Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B lane 1a: segmented page storage schema and engine SQL
garrytan77a9d867d0bb
diff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex c04617a68f..fed80f5157 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -33,6 +33,7 @@ import { FACT_WITHDRAWAL_SCHEMA_STATEMENTS } from '../src/core/facts/withdrawal-import { GRANT_AUDIT_SCHEMA_SQL } from '../src/core/grants/schema.ts';import { LEASE_TOKEN_SCHEMA_SQL } from '../src/core/lease-schema.ts';import { LINK_TEMPORAL_SCHEMA_SQL } from '../src/core/link-temporal-schema.ts';+import { PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL } from '../src/core/page-body/schema.ts';import { PAGE_PROJECTION_SCHEMA_SQL } from '../src/core/page-state/projection-schema.ts';import { PAGE_STATE_SCHEMA_SQL } from '../src/core/page-state/schema.ts';import { POSTGRES_CONCURRENT_PERSISTENCE_INDEXES, PERSISTENCE_SCHEMA_STATEMENTS } from '../src/core/persistence/schema.ts';@@ -75,6 +76,7 @@ export interface Fragment {const persistenceSql = (statements: readonly string[]) => `${statements.join(';\n')};`;export const FRAGMENTS: readonly Fragment[] = [+ { source: 'src/core/page-body/schema.ts', expr: 'PAGE_GENERATION_BUMP_FN_SQL', postgres: PAGE_GENERATION_BUMP_FN_SQL, pglite: PAGE_GENERATION_BUMP_FN_SQL },{ source: 'src/core/fts-language.ts', expr: 'FTS_INPUT_FUNCTION_SQL', postgres: FTS_INPUT_FUNCTION_SQL, pglite: FTS_INPUT_FUNCTION_SQL },{ source: 'src/core/grants/schema.ts', expr: 'GRANT_AUDIT_SCHEMA_SQL', postgres: GRANT_AUDIT_SCHEMA_SQL, pglite: GRANT_AUDIT_SCHEMA_SQL },{@@ -84,6 +86,7 @@ export const FRAGMENTS: readonly Fragment[] = [pglite: `${FACT_WITHDRAWAL_SCHEMA_STATEMENTS[0]};`,},{ source: 'src/core/lease-schema.ts', expr: 'LEASE_TOKEN_SCHEMA_SQL', postgres: LEASE_TOKEN_SCHEMA_SQL, pglite: LEASE_TOKEN_SCHEMA_SQL },+ { source: 'src/core/page-body/schema.ts', expr: 'PAGE_BODY_SCHEMA_SQL', postgres: PAGE_BODY_SCHEMA_SQL, pglite: PAGE_BODY_SCHEMA_SQL },{ source: 'src/core/page-state/schema.ts', expr: 'PAGE_STATE_SCHEMA_SQL', postgres: PAGE_STATE_SCHEMA_SQL, pglite: PAGE_STATE_SCHEMA_SQL },{source: 'src/core/persistence/schema.ts',diff --git a/scripts/engine-sql-baseline.tsv b/scripts/engine-sql-baseline.tsvindex a629bfb264..05cec331b2 100644--- a/scripts/engine-sql-baseline.tsv+++ b/scripts/engine-sql-baseline.tsv@@ -15,6 +15,7 @@ migrated factsmigrated filesmigrated healthmigrated links+migrated page-bodymigrated pagesmigrated saliencemigrated sourcesdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 902ef453cc..7812368dfd 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -20,8 +20,8 @@ src/core/engine.ts 2820 ratchet grown v0.46.26.0 megawave: relational/visibilitysrc/core/import-file.ts 2032 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); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032src/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 nullablesrc/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 3043 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); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import-src/core/postgres-engine.ts 3060 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); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import+src/core/pglite-engine.ts 3065 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); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their imports+src/core/postgres-engine.ts 3082 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); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their importssrc/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 2315 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); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts)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/batch-rows.ts b/src/core/batch-rows.tsindex d634a86516..323040080d 100644--- a/src/core/batch-rows.ts+++ b/src/core/batch-rows.ts@@ -208,15 +208,16 @@ export const ROW_BATCH_MAX_BYTES = 16 * 1024 ** 2;* a time, each at most ROW_BATCH_MAX_ROWS rows and ROW_BATCH_MAX_BYTES bytes (a* single larger row travels alone). Only the batch being built is held as* JSON, so a page's statement size and staging memory stay bounded whatever- * the page size.+ * the page size. `maxBytes` lowers the byte bound (segmented-page staging+ * uses STAGE_BATCH_BYTES, 4 MiB on PGLite).*/-export function* jsonRowBatches<T>(items: Iterable<T>, encode: (item: T) => unknown): Generator<string> {+export function* jsonRowBatches<T>(items: Iterable<T>, encode: (item: T) => unknown, maxBytes = ROW_BATCH_MAX_BYTES): Generator<string> {let rows: string[] = [];let bytes = 2;for (const item of items) {const row = JSON.stringify(encode(item));const size = Buffer.byteLength(row) + 1;- if (rows.length > 0 && (rows.length === ROW_BATCH_MAX_ROWS || bytes + size > ROW_BATCH_MAX_BYTES)) {+ if (rows.length > 0 && (rows.length === ROW_BATCH_MAX_ROWS || bytes + size > maxBytes)) {yield `[${rows.join(',')}]`;rows = [];bytes = 2;diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex f1752febf0..c5c9ba0d87 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -104,15 +104,19 @@ const ROWS: readonly Row[] = [['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_source_id counterparty_email summary evidence thread_id page_slug status detector closed_by'],['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],+ ['page_body_manifest', 'swept', 'segment_manifest', 'region source_id sha256 cut_kind entry_state protected_regions facts_slots outline hash_state'],+ ['page_body_staging_parts', 'swept', 'body_stagings', 'sha256 body', 'body'],+ ['page_body_stagings', 'swept', 'body_stagings', 'kind principal_kind principal_id source_id slug mode declared_sha256 state'],['page_embedding_budget', 'out_of_scope', 'no_memory_text', 'state reason embedding_signature'],['page_extraction_state', 'out_of_scope', 'no_memory_text', 'pipeline watermark_sha256 input_truncated'],['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],['page_mention_state', 'out_of_scope', 'no_memory_text', 'source_id'],['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],['page_purges', 'out_of_scope', 'text_free_ledger', 'source_id content_hash slug'],- ['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin'],+ ['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],+ ['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash'],['page_write_guards', 'out_of_scope', 'no_memory_text', 'slug'],- ['pages', 'swept', 'page_body', 'source_id slug type page_kind title compiled_truth timeline frontmatter content_hash effective_date_source import_filename database_only_reason contextual_retrieval_mode corpus_generation search_vector source_path ingested_via source_uri source_kind embedding_signature revision_principal_kind revision_principal_id trust_tier write_origin'],+ ['pages', 'swept', 'page_body', 'source_id slug type page_kind title compiled_truth timeline frontmatter content_hash effective_date_source import_filename database_only_reason contextual_retrieval_mode corpus_generation search_vector source_path ingested_via source_uri source_kind embedding_signature revision_principal_kind revision_principal_id trust_tier write_origin body_storage body_flags truth_lead timeline_lead'],['persistence_consumers', 'out_of_scope', 'no_memory_text', 'kind mode pool version nonce minted_under persistence_home host_json_path pid_ns boot_id process_start'],['persistence_counters', 'out_of_scope', 'no_memory_text', 'key'],['persistence_effects', 'swept', 'effect_recovery', 'kind data state source_id error_code outcome recovery'],diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.tsnew file mode 100644index 0000000000..bcd222f1ec--- /dev/null+++ b/src/core/engine-sql/page-body.ts@@ -0,0 +1,374 @@+/**+ * Segmented page storage (Wave B): one SQL implementation for both engines.+ * Segment texts, the generation-ranged body manifest, staged chunk rows, the+ * generation flip and garbage collection (docs: wave-b spec 1.2, 3.3-3.5, 4.2).+ *+ * Contracts the callers keep:+ * - Every staged manifest row's `staging_id` names a row `openBodyStaging`+ * recorded; a staging is a GC root while it is open, sealed or prepared, or+ * while a non-terminal persistence request's `intent.body_ref` names it.+ * - Manifest rows are staged before the chunk rows of their occurrences: a+ * staged chunk row no live staging's manifest row owns is garbage.+ * - A writer that dedupes onto an existing text stages its manifest row in the+ * same transaction as the text insert, so the FK lock protects the text from+ * a concurrent sweep (insert-reference-before-GC).+ *+ * Statement sizes stay bounded whatever the page size: texts by+ * STAGE_BATCH_BYTES per engine, manifest and chunk rows by `jsonRowBatches`+ * under the same byte bound; the flip touches O(changed rows).+ */+import type { ManifestRow, ManifestRowInput, BodyFlipInput, BodyFlipResult, BodyRegion, BodyStagingInput, BodyStagingState,+ SegmentChunkInput, SegmentedPageMeta, SegmentSweepOptions, SegmentSweepResult, SegmentTextInput } from '../page-body/types.ts';+import type { ResolvedColumn } from '../types.ts';+import { BODY_STAGING_HARD_MS, SEGMENT_TEXT_GC_GRACE_MS, STAGE_BATCH_BYTES } from '../page-body/limits.ts';+import { jsonRowBatches, sanitizeText } from '../batch-rows.ts';+import { normalizeEngineColumn, quoteIdentifier, resolveWriteColumnFromConfigRows, vectorCastSuffix } from '../search/embedding-column.ts';+import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';+import { validateSlug } from '../utils.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import { jsonbParam, type SqlExecutor } from './executor.ts';+import type { LegacyUnscopedRead } from './brands.ts';+import { joinFragments, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';+import { compileRowNormalizer } from './normalize.ts';++const LIVE_STAGING_STATES = ['open', 'sealed', 'prepared'];+const TERMINAL_STAGING_STATES = ['committed', 'aborted', 'expired'];+const NON_TERMINAL_REQUEST_STATES = ['queued', 'running', 'recovering'];++const hex = (bytes: Uint8Array) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('hex');+const bytes = (value: unknown): Uint8Array => {+ const view = value as Uint8Array;+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);+};+const yieldTurn = () => new Promise<void>(resolve => setTimeout(resolve, 0));+const stageBatchBytes = (exec: SqlExecutor) => STAGE_BATCH_BYTES[exec.dialect];++/** The staging ids a sweep must keep: live stagings and those a non-terminal request's body_ref names. */+const liveStagingIds = sqlFragment`(SELECT s.id::text FROM page_body_stagings s WHERE s.state = ANY(${LIVE_STAGING_STATES}::text[])+ UNION SELECT r.intent->'body_ref'->>'staging_id' FROM persistence_requests r+ WHERE r.state = ANY(${NON_TERMINAL_REQUEST_STATES}::text[]) AND r.intent->'body_ref'->>'staging_id' IS NOT NULL)`;++export async function allocateBodyOccurrenceIds(exec: SqlExecutor, count: number): Promise<number[]> {+ if (count <= 0) return [];+ const { rows } = await exec.run<{ id: unknown }>(sqlFragment`SELECT nextval('page_body_occurrence_id_seq') AS id FROM generate_series(1, ${count}::int)`);+ return rows.map(row => Number(row.id));+}++export async function stageSegmentTexts(exec: SqlExecutor, sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }> {+ const maxBytes = stageBatchBytes(exec);+ const maxRows = Math.floor(exec.capabilities.maxBindParamsPerStatement / 5);+ let inserted = 0;+ let batch: SqlFragment[] = [];+ let batchBytes = 0;+ const flush = async () => {+ if (batch.length === 0) return;+ const { affectedRows } = await exec.run(sqlFragment`INSERT INTO page_segment_texts (source_id, sha256, byte_len, line_count, body)+ VALUES ${joinFragments(batch, ', ')} ON CONFLICT (source_id, sha256) DO NOTHING`);+ inserted += affectedRows;+ batch = [];+ batchBytes = 0;+ await yieldTurn();+ };+ for (const text of texts) {+ if (batch.length > 0 && (batchBytes + text.body.byteLength > maxBytes || batch.length >= maxRows)) await flush();+ batch.push(sqlFragment`(${sourceId}, decode(${hex(text.sha256)}, 'hex'), ${text.body.byteLength}::int, ${text.lineCount}::int,+ ${Buffer.from(text.body.buffer, text.body.byteOffset, text.body.byteLength)}::bytea)`);+ batchBytes += text.body.byteLength;+ }+ await flush();+ return { inserted };+}++export async function readSegmentTexts(exec: LegacyUnscopedRead, sourceId: string, sha256s: readonly Uint8Array[]): Promise<Map<string, Uint8Array>> {+ if (sha256s.length === 0) return new Map();+ const { rows } = await exec.run<{ sha: string; body: unknown }>(sqlFragment`+ SELECT encode(t.sha256, 'hex') AS sha, t.body FROM page_segment_texts t+ WHERE t.source_id = ${sourceId} AND t.sha256 = ANY(SELECT decode(h, 'hex') FROM unnest(${sha256s.map(hex)}::text[]) AS h)`);+ return new Map(rows.map(row => [row.sha, bytes(row.body)]));+}++export async function stageManifestRows(exec: SqlExecutor, rows: readonly ManifestRowInput[]): Promise<void> {+ const batches = jsonRowBatches(rows, row => ({+ page_id: row.pageId, occurrence_id: row.occurrenceId, gen_from: row.genFrom, seq: row.seq, region: row.region,+ source_id: row.sourceId, sha256: hex(row.sha256), byte_start: row.byteStart, byte_len: row.byteLen,+ line_start: row.lineStart, line_count: row.lineCount, cut_kind: row.cutKind, entry_state: row.entryState,+ protected_regions: row.protectedRegions, facts_slots: row.factsSlots, static_proj_bytes: row.staticProjBytes,+ static_proj_lines: row.staticProjLines, outline: row.outline, date_min: row.dateMin, date_max: row.dateMax,+ hash_state: hex(row.hashState), staging_id: row.stagingId,+ }), stageBatchBytes(exec));+ for (const json of batches) {+ await exec.run(sqlFragment`INSERT INTO page_body_manifest (page_id, occurrence_id, gen_from, seq, region, source_id, sha256,+ byte_start, byte_len, line_start, line_count, cut_kind, entry_state, protected_regions, facts_slots, static_proj_bytes,+ static_proj_lines, outline, date_min, date_max, hash_state, staging_id)+ SELECT m.page_id, m.occurrence_id, m.gen_from, m.seq, m.region, m.source_id, decode(m.sha256, 'hex'), m.byte_start, m.byte_len,+ m.line_start, m.line_count, m.cut_kind, m.entry_state, m.protected_regions, m.facts_slots, m.static_proj_bytes,+ m.static_proj_lines, m.outline, m.date_min, m.date_max, decode(m.hash_state, 'hex'), m.staging_id+ FROM jsonb_to_recordset(${json}::text::jsonb) AS m(page_id int, occurrence_id bigint, gen_from bigint, seq int, region text,+ source_id text, sha256 text, byte_start bigint, byte_len int, line_start bigint, line_count int, cut_kind text,+ entry_state jsonb, protected_regions jsonb, facts_slots jsonb, static_proj_bytes bigint, static_proj_lines int,+ outline jsonb, date_min date, date_max date, hash_state text, staging_id uuid)`);+ await yieldTurn();+ }+}++const normalizeManifestRow = compileRowNormalizer<Record<string, unknown>>({+ occurrence_id: 'bigint', gen_from: 'bigint', gen_to: 'bigint', byte_start: 'bigint', line_start: 'bigint', static_proj_bytes: 'bigint',+ entry_state: 'jsonb', protected_regions: 'jsonb', facts_slots: 'jsonb', outline: 'jsonb',+});++function toManifestRow(raw: Record<string, unknown>): ManifestRow {+ const r = normalizeManifestRow(raw);+ return {+ pageId: r.page_id as number, occurrenceId: r.occurrence_id as number, genFrom: r.gen_from as number, genTo: (r.gen_to as number | null) ?? null,+ seq: r.seq as number, region: r.region as BodyRegion, sourceId: r.source_id as string, sha256: bytes(r.sha256),+ byteStart: r.byte_start as number, byteLen: r.byte_len as number, lineStart: r.line_start as number, lineCount: r.line_count as number,+ cutKind: r.cut_kind as ManifestRow['cutKind'], entryState: r.entry_state as ManifestRow['entryState'],+ protectedRegions: r.protected_regions as unknown[], factsSlots: r.facts_slots as unknown[], staticProjBytes: r.static_proj_bytes as number,+ staticProjLines: r.static_proj_lines as number, outline: r.outline as unknown[], dateMin: (r.date_min as string | null) ?? null,+ dateMax: (r.date_max as string | null) ?? null, hashState: bytes(r.hash_state), stagingId: (r.staging_id as string | null) ?? null,+ };+}++export async function readManifest(exec: LegacyUnscopedRead, pageId: number,+ opts: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number } = {}): Promise<ManifestRow[]> {+ const rowsOf = opts.stagingId !== undefined+ ? sqlFragment`m.staging_id = ${opts.stagingId}::uuid`+ : sqlFragment`m.staging_id IS NULL AND m.gen_from <= g.gen AND (m.gen_to IS NULL OR m.gen_to > g.gen)`;+ const region = opts.region ? sqlFragment`AND m.region = ${opts.region}` : sqlFragment``;+ const tail = opts.lastN !== undefined ? sqlFragment`ORDER BY m.seq DESC LIMIT ${opts.lastN}::int` : sqlFragment`ORDER BY m.seq`;+ const { rows } = await exec.run<Record<string, unknown>>(sqlFragment`+ SELECT m.page_id, m.occurrence_id, m.gen_from, m.gen_to, m.seq, m.region, m.source_id, m.sha256, m.byte_start, m.byte_len,+ m.line_start, m.line_count, m.cut_kind, m.entry_state, m.protected_regions, m.facts_slots, m.static_proj_bytes,+ m.static_proj_lines, m.outline, to_char(m.date_min, 'YYYY-MM-DD') AS date_min, to_char(m.date_max, 'YYYY-MM-DD') AS date_max,+ m.hash_state, m.staging_id::text AS staging_id+ FROM page_body_manifest m+ CROSS JOIN (SELECT COALESCE(${opts.generation ?? null}::bigint, (SELECT body_generation FROM pages WHERE id = ${pageId})) AS gen) g+ WHERE m.page_id = ${pageId} AND ${rowsOf} ${region}+ ${tail}`);+ const out = rows.map(toManifestRow);+ return opts.lastN !== undefined ? out.reverse() : out;+}++/** The write column and model label the chunk rows carry, resolved on this executor's handle (as upsertChunks does). */+async function resolveChunkWrite(exec: SqlExecutor, chunks: readonly SegmentChunkInput[], embeddingColumn?: ResolvedColumn): Promise<{ column: ResolvedColumn; model: string }> {+ const { rows } = await exec.run<{ key: string; value: string }>(sqlFragment`SELECT key, value FROM config+ WHERE key IN ('search_embedding_column', 'embedding_columns', 'embedding_model')`);+ const config = new Map(rows.map(row => [row.key, row.value]));+ const column = embeddingColumn ? normalizeEngineColumn(embeddingColumn) : resolveWriteColumnFromConfigRows({+ searchEmbeddingColumn: config.get('search_embedding_column') ?? null, embeddingColumnsJson: config.get('embedding_columns') ?? null });+ const model = column.embeddingModel || config.get('embedding_model') || null;+ if (!model && chunks.some(chunk => chunk.embedding && !chunk.model)) {+ throw new Error('Embedding model provenance is unknown. Supply an explicit chunk model or run gbrain migrate embeddings --status before an explicit migration.');+ }+ return { column, model: model ?? 'unconfigured' };+}++export async function stageSegmentChunks(exec: SqlExecutor, pageId: number, generation: number, chunks: readonly SegmentChunkInput[],+ opts: { embeddingColumn?: ResolvedColumn } = {}): Promise<number[]> {+ if (chunks.length === 0) return [];+ const { column, model } = await resolveChunkWrite(exec, chunks, opts.embeddingColumn);+ const col = quoteIdentifier(column.name);+ const cast = vectorCastSuffix(column);+ return exec.transaction(async tx => {+ if (tx.capabilities.transactionAdvisoryLocks) {+ // Lock-census: COMPLIANT — key is the page id, unique brain-wide.+ await tx.run(sqlFragment`SELECT pg_advisory_xact_lock(hashtextextended('gbrain:page-body-chunks:' || ${pageId}::text, 0))`);+ }+ const { rows } = await tx.run<{ next: unknown }>(sqlFragment`SELECT COALESCE(MAX(chunk_index), -1) + 1 AS next FROM content_chunks WHERE page_id = ${pageId}`);+ const first = Number(rows[0]?.next ?? 0);+ const indexes = chunks.map((_, i) => first + i);+ const batches = jsonRowBatches(chunks.map((chunk, i) => ({ chunk, index: indexes[i]! })), ({ chunk, index }) => {+ const embedding = chunk.embedding ? '[' + Array.from(chunk.embedding).join(',') + ']' : null;+ return {+ chunk_index: index, chunk_text: sanitizeText(chunk.chunk_text), chunk_source: chunk.chunk_source ?? null, embedding,+ model: chunk.model || model, token_count: chunk.token_count || null,+ embedding_input_hash: embedding ? chunk.embedding_input_hash ?? null : null,+ language: chunk.language || null, symbol_name: chunk.symbol_name || null, symbol_type: chunk.symbol_type || null,+ start_line: chunk.start_line ?? null, end_line: chunk.end_line ?? null,+ parent_symbol_path: chunk.parent_symbol_path && chunk.parent_symbol_path.length > 0 ? chunk.parent_symbol_path : null,+ doc_comment: chunk.doc_comment || null, symbol_name_qualified: chunk.symbol_name_qualified || null, modality: chunk.modality ?? 'text',+ embedding_image: chunk.embedding_image ? '[' + Array.from(chunk.embedding_image).join(',') + ']' : null,+ projected_byte_start: chunk.projected_byte_start ?? null, projected_byte_end: chunk.projected_byte_end ?? null,+ occurrence_id: chunk.occurrence_id, local_ordinal: chunk.local_ordinal, raw_byte_start: chunk.raw_byte_start, raw_byte_end: chunk.raw_byte_end,+ };+ }, stageBatchBytes(tx));+ for (const json of batches) {+ await tx.run(sqlFragment`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, ${trustedSql(col)}, model, token_count,+ embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path,+ doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end,+ occurrence_id, local_ordinal, raw_byte_start, raw_byte_end, body_generation)+ SELECT ${pageId}::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding${trustedSql(cast)}, c.model, c.token_count,+ CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END,+ CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,+ c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,+ c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector,+ CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END,+ c.projected_byte_start, c.projected_byte_end, c.occurrence_id, c.local_ordinal, c.raw_byte_start, c.raw_byte_end, ${generation}::bigint+ FROM jsonb_to_recordset(${json}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,+ embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,+ start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text,+ projected_byte_start bigint, projected_byte_end bigint, occurrence_id bigint, local_ordinal int, raw_byte_start bigint, raw_byte_end bigint)`);+ await yieldTurn();+ }+ return indexes;+ });+}++function metaParams(meta: SegmentedPageMeta) {+ const ingested = meta.source_kind || meta.source_uri || meta.ingested_via;+ return {+ pageKind: meta.page_kind || 'markdown', title: sanitizeText(meta.title), frontmatter: jsonbParam(meta.frontmatter || {}),+ effectiveDate: meta.effective_date ?? null, effectiveDateSource: meta.effective_date_source ?? null, importFilename: meta.import_filename ?? null,+ chunkerVersion: meta.chunker_version === undefined || meta.chunker_version === null ? null : Math.min(meta.chunker_version, SAFE_FENCE_CHUNKER_VERSION - 1),+ sourcePath: meta.source_path ?? null, sourceKind: meta.source_kind ?? null, sourceUri: meta.source_uri ?? null, ingestedVia: meta.ingested_via ?? null,+ ingestedAt: ingested ? new Date() : null,+ };+}++export async function createSegmentedPageShell(exec: SqlExecutor, slug: string, meta: SegmentedPageMeta, opts: { sourceId: string }): Promise<{ id: number }> {+ const m = metaParams(meta);+ const { rows } = await exec.run<{ id: number }>(sqlFragment`+ INSERT INTO pages (source_id, slug, type, page_kind, title, compiled_truth, timeline, frontmatter, updated_at, effective_date,+ effective_date_source, import_filename, chunker_version, source_path, source_kind, source_uri, ingested_via, ingested_at,+ body_storage, body_generation, body_bytes)+ VALUES (${opts.sourceId}, ${validateSlug(slug)}, ${meta.type}, ${m.pageKind}, ${m.title}, NULL, NULL, ${m.frontmatter}, now(), ${m.effectiveDate},+ ${m.effectiveDateSource}, ${m.importFilename}, ${m.chunkerVersion ?? 0}::smallint, ${m.sourcePath}, ${m.sourceKind}, ${m.sourceUri},+ ${m.ingestedVia}, ${m.ingestedAt}, 'segmented', 0, 0)+ RETURNING id`);+ return { id: Number(rows[0]!.id) };+}++/**+ * The generation flip (spec 3.4), in the caller's publication transaction (a+ * savepoint when nested). The page row is assigned `compiled_truth` and+ * `timeline` (NULL) on every flip, so `trg_pages_search_vector` (UPDATE OF+ * title,timeline) recomputes the page vector from `timeline_lead`.+ */+export async function flipBodyGeneration(exec: SqlExecutor, input: BodyFlipInput): Promise<BodyFlipResult> {+ if (input.newGeneration !== input.expectedGeneration + 1) throw new TypeError('newGeneration must be expectedGeneration + 1');+ return exec.transaction(async tx => {+ const { rows } = await tx.run<{ body_generation: unknown; slug: string; source_id: string }>(sqlFragment`+ SELECT body_generation, slug, source_id FROM pages WHERE id = ${input.pageId} FOR UPDATE`);+ const page = rows[0];+ if (!page) {+ throw opError('page_identity_changed', `Page ${input.pageId} was deleted while its segmented write was prepared.`,+ 'The page was deleted or recreated while this write was prepared, so nothing was published. Read the page that holds the slug now, then write again.',+ { reason: 'page_deleted' });+ }+ const current = Number(page.body_generation);+ if (current !== input.expectedGeneration) {+ throw opError('revision_changed', `Page ${page.slug} moved to body generation ${current} while this write was prepared at ${input.expectedGeneration}.`,+ 'Another write published first. Read the page again and repeat this write against its current revision.',+ { legacy_error: 'invalid_params', detail: JSON.stringify({ expected_generation: input.expectedGeneration, current_generation: current }),+ fix: readFix('Returns the current revision and size.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],+ mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'none' } } }) });+ }+ const stagedOccurrences = sqlFragment`(SELECT s.occurrence_id FROM page_body_manifest s WHERE s.page_id = ${input.pageId} AND s.staging_id = ${input.stagingId}::uuid)`;+ const retire = sqlFragment`c.page_id = ${input.pageId} AND c.retired_generation IS NULL AND (+ c.occurrence_id = ANY(${[...input.retireChunkOccurrences]}::bigint[])+ OR (${input.retireInlineChunks === true}::boolean AND c.body_generation IS NULL)+ OR (c.body_generation = ${input.newGeneration}::bigint AND c.occurrence_id NOT IN ${stagedOccurrences}))`;+ const { rows: counted } = await tx.run<{ n: unknown }>(sqlFragment`SELECT count(*)::bigint AS n FROM content_chunks c WHERE ${retire}`);+ const toRetire = Number(counted[0]?.n ?? 0);+ const retireDeferred = toRetire > input.retireMaxRows;+ await tx.run(sqlFragment`UPDATE page_body_manifest SET gen_to = ${input.newGeneration}::bigint+ WHERE page_id = ${input.pageId} AND gen_to IS NULL AND staging_id IS NULL AND occurrence_id = ANY(${[...input.closeOccurrences]}::bigint[])`);+ const retired = retireDeferred || toRetire === 0 ? 0 : (await tx.run(sqlFragment`UPDATE content_chunks c+ SET retired_generation = ${input.newGeneration}::bigint, body_generation = COALESCE(c.body_generation, 0) WHERE ${retire}`)).affectedRows;+ await tx.run(sqlFragment`UPDATE page_body_manifest SET staging_id = NULL WHERE page_id = ${input.pageId} AND staging_id = ${input.stagingId}::uuid`);+ const m = metaParams(input.meta);+ const b = input.body;+ await tx.run(sqlFragment`UPDATE pages SET+ body_storage = 'segmented', compiled_truth = NULL, timeline = NULL, body_generation = ${input.newGeneration}::bigint,+ content_hash = ${b.content_hash}, body_bytes = ${b.body_bytes}::bigint, truth_bytes = ${b.truth_bytes}::bigint,+ body_lines = ${b.body_lines}::bigint, segment_count = ${b.segment_count}::int, segmenter_version = ${b.segmenter_version}::int,+ truth_lead = ${sanitizeText(b.truth_lead)}, timeline_lead = ${sanitizeText(b.timeline_lead)}, body_flags = ${jsonbParam(b.body_flags)},+ type = ${input.meta.type}, page_kind = ${m.pageKind}, title = ${m.title}, frontmatter = ${m.frontmatter}, updated_at = now(), deleted_at = NULL,+ effective_date = COALESCE(${m.effectiveDate}::timestamptz, effective_date),+ effective_date_source = COALESCE(${m.effectiveDateSource}::text, effective_date_source),+ import_filename = COALESCE(${m.importFilename}::text, import_filename),+ chunker_version = COALESCE(${m.chunkerVersion}::smallint, chunker_version),+ source_path = COALESCE(${m.sourcePath}::text, source_path), source_kind = COALESCE(${m.sourceKind}::text, source_kind),+ source_uri = COALESCE(${m.sourceUri}::text, source_uri), ingested_via = COALESCE(${m.ingestedVia}::text, ingested_via),+ ingested_at = COALESCE(${m.ingestedAt}::timestamptz, ingested_at)+ WHERE id = ${input.pageId}`);+ return { retiredChunks: retired, retireDeferred };+ });+}++export async function openBodyStaging(exec: SqlExecutor, input: BodyStagingInput): Promise<void> {+ await exec.run(sqlFragment`INSERT INTO page_body_stagings (id, kind, principal_kind, principal_id, client_request_id, source_id,+ source_incarnation, slug, page_id, mode, base_revision, base_generation, declared_bytes, declared_sha256, reserved_bytes,+ idle_expires_at, hard_expires_at)+ VALUES (${input.id}::uuid, ${input.kind}, ${input.principalKind}, ${input.principalId}, ${input.clientRequestId}::uuid, ${input.sourceId},+ ${input.sourceIncarnation}::uuid, ${input.slug}, ${input.pageId}::int, ${input.mode}, ${input.baseRevision}::uuid, ${input.baseGeneration}::bigint,+ ${input.declaredBytes}::bigint, decode(${input.declaredSha256 ? hex(input.declaredSha256) : null}::text, 'hex'), ${input.reservedBytes}::bigint,+ ${input.idleExpiresAt}, ${input.hardExpiresAt})`);+}++export async function setBodyStagingState(exec: SqlExecutor, id: string, state: BodyStagingState, opts: { commitRequestId?: string | null } = {}): Promise<void> {+ await exec.run(sqlFragment`UPDATE page_body_stagings SET state = ${state}, updated_at = now(),+ commit_request_id = COALESCE(${opts.commitRequestId ?? null}::uuid, commit_request_id)+ WHERE id = ${id}::uuid`);+}++/**+ * Garbage collection (spec 3.5). Roots: each segmented page's live generation,+ * every generation a page_versions row references, and staged rows of live+ * stagings (`liveStagingIds`). Deletes retired chunk rows, staged chunk rows+ * no live staging owns, manifest rows outside every root, and unreferenced+ * texts older than the grace window (a text a concurrent writer is+ * referencing is row-locked by its FK check and skipped). With+ * `expireStagings`, stagings past a deadline (and not request-held) become+ * `expired`, every non-live staging loses its parts, and terminal stagings+ * (committed, aborted, expired) are deleted once BODY_STAGING_HARD_MS has+ * passed since their last change: until then a replayed begin or commit finds+ * its row and an expired upload answers `upload_expired`. Staged rows of+ * non-live stagings go whether or not this sweep expired them.+ */+export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptions = {}): Promise<SegmentSweepResult> {+ const now = opts.now ? sqlFragment`${opts.now}::timestamptz` : sqlFragment`now()`;+ const pageScope = joinFragments([+ opts.pageId !== undefined ? sqlFragment`p.id = ${opts.pageId}::int` : sqlFragment`TRUE`,+ opts.sourceId !== undefined ? sqlFragment`p.source_id = ${opts.sourceId}` : sqlFragment`TRUE`,+ ], ' AND ');+ let stagingsExpired = 0;+ if (opts.expireStagings) {+ const stagingScope = joinFragments([+ opts.pageId !== undefined ? sqlFragment`s.page_id = ${opts.pageId}::int` : sqlFragment`TRUE`,+ opts.sourceId !== undefined ? sqlFragment`s.source_id = ${opts.sourceId}` : sqlFragment`TRUE`,+ ], ' AND ');+ const { affectedRows } = await exec.run(sqlFragment`UPDATE page_body_stagings s SET state = 'expired', updated_at = ${now}+ WHERE s.state = ANY(${LIVE_STAGING_STATES}::text[]) AND (s.idle_expires_at <= ${now} OR s.hard_expires_at <= ${now}) AND ${stagingScope}+ AND NOT EXISTS (SELECT 1 FROM persistence_requests r WHERE r.state = ANY(${NON_TERMINAL_REQUEST_STATES}::text[])+ AND r.intent->'body_ref'->>'staging_id' = s.id::text)`);+ stagingsExpired = affectedRows;+ await exec.run(sqlFragment`DELETE FROM page_body_staging_parts p USING page_body_stagings s+ WHERE p.staging_id = s.id AND ${stagingScope} AND s.id::text NOT IN ${liveStagingIds}`);+ await exec.run(sqlFragment`DELETE FROM page_body_stagings s+ WHERE s.state = ANY(${TERMINAL_STAGING_STATES}::text[]) AND s.updated_at <= ${now} - (${BODY_STAGING_HARD_MS}::bigint * interval '1 millisecond')+ AND ${stagingScope} AND s.id::text NOT IN ${liveStagingIds}`);+ }+ const { affectedRows: retiredChunksDeleted } = await exec.run(sqlFragment`DELETE FROM content_chunks c USING pages p+ WHERE c.page_id = p.id AND ${pageScope} AND (+ (c.retired_generation IS NOT NULL AND c.retired_generation <= p.body_generation)+ OR (c.body_generation > p.body_generation AND NOT EXISTS (SELECT 1 FROM page_body_manifest m+ WHERE m.page_id = c.page_id AND m.occurrence_id = c.occurrence_id AND m.staging_id::text IN ${liveStagingIds})))`);+ const { affectedRows: stagedRowsDeleted } = await exec.run(sqlFragment`DELETE FROM page_body_manifest m USING pages p+ WHERE m.page_id = p.id AND ${pageScope} AND m.staging_id IS NOT NULL AND m.staging_id::text NOT IN ${liveStagingIds}`);+ const { affectedRows: closedRowsDeleted } = await exec.run(sqlFragment`DELETE FROM page_body_manifest m USING pages p+ WHERE m.page_id = p.id AND ${pageScope} AND m.staging_id IS NULL+ AND NOT (p.body_storage = 'segmented' AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation))+ AND NOT EXISTS (SELECT 1 FROM page_versions v WHERE v.page_id = m.page_id AND v.body_generation >= m.gen_from+ AND (m.gen_to IS NULL OR v.body_generation < m.gen_to))`);+ const graceMs = opts.graceMs ?? SEGMENT_TEXT_GC_GRACE_MS;+ const textScope = opts.sourceId !== undefined ? sqlFragment`AND t.source_id = ${opts.sourceId}`+ : opts.pageId !== undefined ? sqlFragment`AND t.source_id = (SELECT source_id FROM pages WHERE id = ${opts.pageId}::int)` : sqlFragment``;+ const { affectedRows: textsDeleted } = await exec.run(sqlFragment`DELETE FROM page_segment_texts d+ WHERE (d.source_id, d.sha256) IN (SELECT t.source_id, t.sha256 FROM page_segment_texts t+ WHERE t.created_at < ${now} - (${graceMs}::bigint * interval '1 millisecond') ${textScope}+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id = t.source_id AND m.sha256 = t.sha256)+ FOR UPDATE SKIP LOCKED)`);+ return { retiredChunksDeleted, manifestRowsDeleted: stagedRowsDeleted + closedRowsDeleted, textsDeleted, stagingsExpired };+}diff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 772bd0628b..4e497d87d1 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -75,6 +75,8 @@ async function boundedCount(engine: BrainEngine, sql: string, params: unknown[],const textMatch = (column: string, at: number) => `(strpos(lower(${column}::text),$${at})>0 OR strpos(lower(${column}::text),$${at + 1})>0)`;/** Vector and lexeme columns carry no probe-able text. */const PROBE_SKIP = /embedding|search_vector/;+/** Stores whose probe columns are bytea; their bytes are matched exactly (case-sensitive) against the UTF-8 needle. */+const BINARY_PROBE_TABLES: ReadonlySet<string> = new Set(['minion_attachments', 'page_segment_texts', 'page_body_staging_parts']);/** Probe one inventory table for any of `needles` (exact, case-insensitive; JSON also in its escaped form). Scoped to the source when the table has one. */async function probeTable(engine: BrainEngine, entry: InventoryEntry, sourceId: string, needles: readonly string[], deadline: number): Promise<ProbeResult> {@@ -82,8 +84,7 @@ async function probeTable(engine: BrainEngine, entry: InventoryEntry, sourceId:const list = needles.filter(Boolean).slice(0, 32);if (!columns.length || !list.length) return { count: 0 };const scoped = entry.columns.includes('source_id');- // Bytes are matched exactly (case-sensitive) against the UTF-8 needle.- const binary = entry.table === 'minion_attachments';+ const binary = BINARY_PROBE_TABLES.has(entry.table);const params: unknown[] = [sourceId];const ors: string[] = [];for (const needle of list) {diff --git a/src/core/fts-language.ts b/src/core/fts-language.tsindex 94da29e9fb..0e509b298b 100644--- a/src/core/fts-language.ts+++ b/src/core/fts-language.ts@@ -187,7 +187,9 @@ export function chunkSearchVectorSql(lang: string, row = ''): string {* after a migration leaves the catalog unchanged. #2704: compiled_truth is not* indexed (it overflows the 1MB tsvector cap); the timeline and the joined* entries are cut to their FTS caps for the same reason, the entries in id- * order so the cut is deterministic. `SET search_path = pg_catalog,+ * order so the cut is deterministic. A segmented page (Wave B) has a NULL+ * timeline and indexes its stored `timeline_lead` prefix instead, read only+ * then because the column is migration-only (v248). `SET search_path = pg_catalog,* public` keeps the v120/#1647 hardening, which CREATE OR REPLACE would* otherwise reset.*/@@ -195,15 +197,20 @@ export function pageSearchVectorTriggerFnSql(lang: string): string {return `CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS $$DECLAREtimeline_text TEXT;+ timeline_lead_text TEXT;BEGINSELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')INTO timeline_textFROM timeline_entriesWHERE page_id = NEW.id;+ IF NEW.timeline IS NULL THEN+ timeline_lead_text := NEW.timeline_lead;+ END IF;+NEW.search_vector :=setweight(to_tsvector('${lang}', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||- setweight(to_tsvector('${lang}', gbrain_fts_input(left(coalesce(NEW.timeline, ''), ${PAGE_TIMELINE_FTS_MAX_CHARS}))), 'C') ||+ setweight(to_tsvector('${lang}', gbrain_fts_input(left(coalesce(NEW.timeline, timeline_lead_text, ''), ${PAGE_TIMELINE_FTS_MAX_CHARS}))), 'C') ||setweight(to_tsvector('${lang}', gbrain_fts_input(left(coalesce(timeline_text, ''), ${PAGE_TIMELINE_ENTRIES_FTS_MAX_CHARS}))), 'C');RETURN NEW;diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.tsnew file mode 100644index 0000000000..c47a662eda--- /dev/null+++ b/src/core/page-body/schema.ts@@ -0,0 +1,126 @@+/**+ * Segmented page storage (Wave B) DDL shared by migration v248 and both schema+ * blobs (src/schema.sql regions; `bun run build:schema`).+ *+ * The new tables live in the blob; the columns v248 adds to pages,+ * content_chunks and page_versions do not. Those are migration-only, like the+ * trust-tier columns, so a fresh install (blob, then every migration) and an+ * upgraded brain end with the same column order. Blob triggers therefore read+ * `pages.body_generation` / `timeline_lead` only on a row whose body columns+ * are NULL, which v248's DROP NOT NULL is the first to permit.+ */++/**+ * Query-cache generation bump (migration v91's trigger function). A segmented+ * page's body identity is `body_generation`: its body columns are NULL on both+ * sides of a flip, so the generation moves when body_generation does.+ */+export const PAGE_GENERATION_BUMP_FN_SQL = `CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$+BEGIN+ IF (TG_OP = 'INSERT') THEN+ NEW.generation := COALESCE((SELECT MAX(generation) FROM pages), 0) + 1;+ ELSIF (OLD.compiled_truth IS DISTINCT FROM NEW.compiled_truth)+ OR (OLD.timeline IS DISTINCT FROM NEW.timeline)+ OR (OLD.frontmatter IS DISTINCT FROM NEW.frontmatter)+ OR (OLD.deleted_at IS DISTINCT FROM NEW.deleted_at)+ OR (OLD.contextual_retrieval_mode IS DISTINCT FROM NEW.contextual_retrieval_mode)+ OR (OLD.title IS DISTINCT FROM NEW.title)+ OR (OLD.type IS DISTINCT FROM NEW.type)+ OR (OLD.page_kind IS DISTINCT FROM NEW.page_kind)+ OR (OLD.corpus_generation IS DISTINCT FROM NEW.corpus_generation)+ OR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)+ THEN+ NEW.generation := OLD.generation + 1;+ ELSIF OLD.compiled_truth IS NULL AND NEW.compiled_truth IS NULL THEN+ IF OLD.body_generation IS DISTINCT FROM NEW.body_generation THEN+ NEW.generation := OLD.generation + 1;+ END IF;+ END IF;+ RETURN NEW;+END;+$func$ LANGUAGE plpgsql;`;++/**+ * Segment texts (stored once per source and sha256), the generation-ranged+ * manifest, body stagings and their raw upload parts, and the occurrence id+ * sequence. The manifest's text FK is NO ACTION: a referenced text can't be+ * deleted, and a source delete cascades through pages and texts in one+ * statement before the check runs.+ */+export const PAGE_BODY_SCHEMA_SQL = `CREATE SEQUENCE IF NOT EXISTS page_body_occurrence_id_seq;+CREATE TABLE IF NOT EXISTS page_segment_texts (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ sha256 BYTEA NOT NULL CHECK (octet_length(sha256) = 32),+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 1048576),+ line_count INTEGER NOT NULL CHECK (line_count >= 0),+ body BYTEA NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, sha256)+);+CREATE TABLE IF NOT EXISTS page_body_manifest (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ occurrence_id BIGINT NOT NULL,+ gen_from BIGINT NOT NULL,+ gen_to BIGINT,+ seq INTEGER NOT NULL,+ region TEXT NOT NULL CHECK (region IN ('truth','timeline')),+ source_id TEXT NOT NULL,+ sha256 BYTEA NOT NULL,+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL,+ line_start BIGINT NOT NULL,+ line_count INTEGER NOT NULL,+ cut_kind TEXT NOT NULL CHECK (cut_kind IN ('heading','day','message','blank','forced','region_end','eof')),+ entry_state JSONB NOT NULL,+ protected_regions JSONB NOT NULL DEFAULT '[]',+ facts_slots JSONB NOT NULL DEFAULT '[]',+ static_proj_bytes BIGINT NOT NULL,+ static_proj_lines INTEGER NOT NULL,+ outline JSONB NOT NULL DEFAULT '[]',+ date_min DATE,+ date_max DATE,+ hash_state BYTEA NOT NULL,+ staging_id UUID,+ PRIMARY KEY (page_id, occurrence_id, gen_from),+ FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)+);+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);+CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;+CREATE TABLE IF NOT EXISTS page_body_stagings (+ id UUID PRIMARY KEY,+ kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),+ principal_kind TEXT NOT NULL,+ principal_id TEXT NOT NULL,+ client_request_id UUID NOT NULL,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER REFERENCES pages(id) ON DELETE CASCADE,+ mode TEXT NOT NULL CHECK (mode IN ('create','replace','append')),+ base_revision UUID,+ base_generation BIGINT,+ declared_bytes BIGINT NOT NULL CHECK (declared_bytes >= 0),+ declared_sha256 BYTEA,+ received_bytes BIGINT NOT NULL DEFAULT 0,+ next_part INTEGER NOT NULL DEFAULT 0,+ reserved_bytes BIGINT NOT NULL,+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','sealed','prepared','committed','aborted','expired')),+ commit_request_id UUID,+ idle_expires_at TIMESTAMPTZ NOT NULL,+ hard_expires_at TIMESTAMPTZ NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (principal_kind, principal_id, client_request_id)+);+CREATE INDEX IF NOT EXISTS page_body_stagings_expiry ON page_body_stagings (hard_expires_at) WHERE state IN ('open','sealed','prepared');+CREATE TABLE IF NOT EXISTS page_body_staging_parts (+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,+ part_no INTEGER NOT NULL CHECK (part_no >= 0),+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 4194304),+ sha256 BYTEA NOT NULL,+ body BYTEA NOT NULL,+ PRIMARY KEY (staging_id, part_no)+);`;diff --git a/src/core/page-state/projection-schema.ts b/src/core/page-state/projection-schema.tsindex 6c53c1bec7..ea7526fe49 100644--- a/src/core/page-state/projection-schema.ts+++ b/src/core/page-state/projection-schema.ts@@ -1,10 +1,20 @@+/**+ * The page search-vector trigger fires on the columns its function reads:+ * title, timeline and, once migration v248 added it, the segmented page's+ * timeline_lead (a purge or flip that rewrites only the lead re-indexes it).+ */+export const PAGE_SEARCH_VECTOR_TRIGGER_SQL = `DO $trg$ BEGIN+ EXECUTE format('CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF %s ON pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()',+ CASE WHEN EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'timeline_lead' AND NOT attisdropped)+ THEN 'title,timeline,timeline_lead' ELSE 'title,timeline' END);+ END $trg$`;+/** Durable DB-only text rebuild work; source deletion cancels its old incarnation. */export const PAGE_PROJECTION_SCHEMA_STATEMENTS = [// Metadata/embedding updates must preserve the explicitly sanitized vector.// Canonical body updates remain unsearchable until projection completion.`DROP TRIGGER IF EXISTS trg_pages_search_vector ON pages`,- `CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title,timeline ON pages- FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()`,+ PAGE_SEARCH_VECTOR_TRIGGER_SQL,`CREATE TABLE IF NOT EXISTS page_projection_jobs (source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,slug TEXT NOT NULL,diff --git a/src/core/page-state/schema.ts b/src/core/page-state/schema.tsindex 4888d48006..11e9302073 100644--- a/src/core/page-state/schema.ts+++ b/src/core/page-state/schema.ts@@ -10,6 +10,9 @@ export const PAGE_VERSION_DELETION_SCHEMA_SQL = `ALTER TABLE page_versions ADD C* row needs a value: `sources` is backfilled here (a handful of rows), an* empty `pages` (fresh install) is constrained here, and existing pages are* backfilled in committed batches by page-state/revision-backfill-schema.ts.+ * A segmented page (Wave B) has NULL body columns, so its body identity is+ * `body_generation`, read only when both sides are NULL: the column is+ * migration-only (v248), and before it the body columns are NOT NULL.*/export const PAGE_STATE_SCHEMA_STATEMENTS = [`DO $do$ BEGIN@@ -50,13 +53,17 @@ export const PAGE_STATE_SCHEMA_STATEMENTS = [PRIMARY KEY (source_incarnation, slug))`,`CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$+ DECLARE body_moved boolean := false;BEGINIF OLD.knowledge_revision IS NULL THENNEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());NEW.text_projection_revision := NULL;RETURN NEW;END IF;- IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,+ IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN+ body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;+ END IF;+ IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,NEW.timeline, NEW.frontmatter, NEW.deleted_at)IS DISTINCT FROM(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex c7b7b2fbf2..39145907d2 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -103,6 +103,9 @@ export const GRADUATION_INVENTORY: Inventory = {carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),carry('open_loops', 'user_data', 'Open loops and their status.'),carry('page_aliases', 'user_data', 'Page aliases.'),+ carry('page_body_manifest', 'user_data', 'Segmented page bodies: which segment texts make each body generation, in order; without it a large page has no body.'),+ carry('page_body_staging_parts', 'operational', 'Raw parts of open upload sessions; without them a client resuming an upload starts over.'),+ carry('page_body_stagings', 'operational', 'Body stagings of segmented writes and upload sessions (idempotent begin and commit, expiry deadlines).'),carry('page_embedding_budget', 'operational', 'Large-page embedding spend ledger: per-page spend, holds awaiting approval and caps; without it held pages would embed without consent.'),carry('page_extraction_state', 'operational', 'Extraction watermarks and partial-input receipts per page and pipeline; without them the next extraction of a large page reads its head again and records the receipt anew.'),carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),@@ -111,6 +114,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),carry('page_purges', 'user_data', 'Text-free page purge tombstones (#5575); dropping them would let purged pages re-import.'),carry('page_retrievals', 'operational', 'Retrieval telemetry: when a user-facing read last surfaced each page (stale-page bias, volunteer usage stats).'),+ carry('page_segment_texts', 'user_data', 'Segment texts of segmented page bodies, stored once per source; without them a large page has no body.'),carry('page_versions', 'user_data', 'Page revision history with attribution.'),carry('page_write_guards', 'user_data', 'Page write guards per source incarnation and slug.'),carry('pages', 'user_data', 'Pages with ids, knowledge_revision, revision attribution and timestamps.'),diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.tsindex 756208dd9a..52035ebe27 100644--- a/src/core/persistence/writer-guard-schema.ts+++ b/src/core/persistence/writer-guard-schema.ts@@ -2,7 +2,7 @@ import { ROW_ATTRIBUTION_COLUMNS } from './attribution-schema.ts';const ROW_ATTRIBUTION_KEYS = `ARRAY[${ROW_ATTRIBUTION_COLUMNS.map(column => `'${column}'`).join(',')}]`;/** Guarded tables with no canonical source_id: their source is always their page's (#5983). */export const PAGE_CHILD_TABLES = ['tags', 'timeline_entries', 'takes'];-export const GUARDED_TABLES = ['pages', 'tags', 'slug_aliases', 'page_aliases', 'facts', 'takes', 'timeline_entries', 'sources'];+export const GUARDED_TABLES = ['pages', 'tags', 'slug_aliases', 'page_aliases', 'facts', 'takes', 'timeline_entries', 'sources', 'page_segment_texts', 'page_body_manifest'];const sqlList = (names: string[]) => names.map(name => `'${name}'`).join(',');/** The guard function alone: replacing it takes no table lock (v197). */export const MANAGED_WRITER_GUARD_FUNCTION_SQL = `@@ -12,14 +12,22 @@ BEGINIF NOT EXISTS (SELECT 1 FROM persistence_brain WHERE singleton=1 AND enabled) THENIF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END IF;- row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;- IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ IF TG_TABLE_NAME='page_segment_texts' THEN+ -- Only the source decides; the segment body (up to 1 MiB of bytea) never becomes JSON.+ IF TG_OP='DELETE' THEN row_data := jsonb_build_object('source_id',OLD.source_id); ELSE row_data := jsonb_build_object('source_id',NEW.source_id); END IF;+ IF TG_OP='UPDATE' THEN old_data := jsonb_build_object('source_id',OLD.source_id); END IF;+ ELSE+ row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;+ IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ END IF;IF TG_TABLE_NAME='pages' AND TG_OP='UPDATE' THENIF (NEW.source_id,NEW.slug,NEW.type,NEW.page_kind,NEW.title,NEW.compiled_truth,NEW.timeline,NEW.frontmatter,NEW.deleted_at,NEW.knowledge_revision)IS NOT DISTINCT FROM(OLD.source_id,OLD.slug,OLD.type,OLD.page_kind,OLD.title,OLD.compiled_truth,OLD.timeline,OLD.frontmatter,OLD.deleted_at,OLD.knowledge_revision)-- The trust tier is guarded content (trust/schema.ts); read by key so brains before the column keep working.- AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier' THEN RETURN NEW; END IF;+ AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier'+ -- A segmented page's body identity (page-body/schema.ts); read by key for brains before the column.+ AND row_data->'body_generation' IS NOT DISTINCT FROM old_data->'body_generation' THEN RETURN NEW; END IF;ELSIF TG_TABLE_NAME='sources' THENIF TG_OP='UPDATE' AND (NEW.id,NEW.incarnation,NEW.local_path,NEW.archived)IS NOT DISTINCT FROM (OLD.id,OLD.incarnation,OLD.local_path,OLD.archived) THENdiff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 98349b4bc0..3e57426881 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -151,6 +151,9 @@ import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './seaimport 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 * as pageBodyImpl from './engine-sql/page-body.ts';+import type { BodyFlipInput, BodyFlipResult, BodyRegion, BodyStagingInput, BodyStagingState, ManifestRow, ManifestRowInput, SegmentChunkInput,+ SegmentedPageMeta, SegmentSweepOptions, SegmentSweepResult, SegmentTextInput } from './page-body/types.ts';import { searchKeywordCJK } from './engine-sql/cjk-search.ts';import * as titlesImpl from './engine-sql/titles.ts';import * as keywordPagesImpl from './engine-sql/keyword-pages.ts';@@ -2504,6 +2507,25 @@ export class PGLiteEngine implements BrainEngine {return factsImpl.getFactsHealth(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id);}+ // Segmented page storage (Wave B): SQL in ./engine-sql/page-body.ts.+ async allocateBodyOccurrenceIds(count: number): Promise<number[]> { return pageBodyImpl.allocateBodyOccurrenceIds(this.engineSql, count); }+ async stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }> { return pageBodyImpl.stageSegmentTexts(this.engineSql, sourceId, texts); }+ async readSegmentTexts(sourceId: string, sha256s: readonly Uint8Array[]): Promise<Map<string, Uint8Array>> {+ return pageBodyImpl.readSegmentTexts(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), sourceId, sha256s);+ }+ async stageManifestRows(rows: readonly ManifestRowInput[]): Promise<void> { return pageBodyImpl.stageManifestRows(this.engineSql, rows); }+ async readManifest(pageId: number, opts?: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number }): Promise<ManifestRow[]> {+ return pageBodyImpl.readManifest(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), pageId, opts);+ }+ async stageSegmentChunks(pageId: number, generation: number, chunks: readonly SegmentChunkInput[], opts?: { embeddingColumn?: ResolvedColumn }): Promise<number[]> {+ return pageBodyImpl.stageSegmentChunks(this.engineSql, pageId, generation, chunks, opts);+ }+ async createSegmentedPageShell(slug: string, meta: SegmentedPageMeta, opts: { sourceId: string }): Promise<{ id: number }> { return pageBodyImpl.createSegmentedPageShell(this.engineSql, slug, meta, opts); }+ async flipBodyGeneration(input: BodyFlipInput): Promise<BodyFlipResult> { return pageBodyImpl.flipBodyGeneration(this.engineSql, input); }+ async openBodyStaging(input: BodyStagingInput): Promise<void> { return pageBodyImpl.openBodyStaging(this.engineSql, input); }+ async setBodyStagingState(id: string, state: BodyStagingState, opts?: { commitRequestId?: string | null }): Promise<void> { return pageBodyImpl.setBodyStagingState(this.engineSql, id, state, opts); }+ async sweepSegments(opts?: SegmentSweepOptions): Promise<SegmentSweepResult> { return pageBodyImpl.sweepSegments(this.engineSql, opts); }+// ============================================================// v0.28: Takes (typed/weighted/attributed claims) + synthesis_evidence// ============================================================diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 7e6bfb9b73..2c1f4aa15c 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -70,6 +70,14 @@ CREATE TABLE IF NOT EXISTS pages (CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug));+-- v0.40.3.0 cache invalidation trigger (migration v91; mirrored in+-- src/core/pglite-schema.ts). BEFORE INSERT OR UPDATE so every write path+-- bumps generation per D6 / codex #4. INSERT: pages get+-- COALESCE(MAX(generation), 0) + 1 so the bookmark gate fires for any+-- cache row stored before the new page existed. UPDATE: bumps only when+-- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3+-- to include title/type/page_kind/corpus_generation/content_hash) so+-- read-time mutations don't invalidate every cache row.CREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$BEGINIF (TG_OP = 'INSERT') THEN@@ -86,6 +94,10 @@ BEGINOR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)THENNEW.generation := OLD.generation + 1;+ ELSIF OLD.compiled_truth IS NULL AND NEW.compiled_truth IS NULL THEN+ IF OLD.body_generation IS DISTINCT FROM NEW.body_generation THEN+ NEW.generation := OLD.generation + 1;+ END IF;END IF;RETURN NEW;END;@@ -636,15 +648,20 @@ CREATE INDEX IF NOT EXISTS idx_pages_search ON pages USING GIN(search_vector);CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS \$\$DECLAREtimeline_text TEXT;+ timeline_lead_text TEXT;BEGINSELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')INTO timeline_textFROM timeline_entriesWHERE page_id = NEW.id;+ IF NEW.timeline IS NULL THEN+ timeline_lead_text := NEW.timeline_lead;+ END IF;+NEW.search_vector :=setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||- setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, ''), 65536))), 'C') ||+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, timeline_lead_text, ''), 65536))), 'C') ||setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(timeline_text, ''), 32768))), 'C');RETURN NEW;@@ -1135,13 +1152,17 @@ CREATE TABLE IF NOT EXISTS page_write_guards (PRIMARY KEY (source_incarnation, slug));CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$+ DECLARE body_moved boolean := false;BEGINIF OLD.knowledge_revision IS NULL THENNEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());NEW.text_projection_revision := NULL;RETURN NEW;END IF;- IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,+ IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN+ body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;+ END IF;+ IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,NEW.timeline, NEW.frontmatter, NEW.deleted_at)IS DISTINCT FROM(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,@@ -1264,6 +1285,86 @@ CREATE TABLE IF NOT EXISTS page_extraction_state ();CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idxON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;+-- Wave B segmented page storage (migration v248): segment texts, the+-- generation-ranged body manifest and body stagings (src/core/page-body/).+-- Before the persistence region so the managed-writer guard covers them.+CREATE SEQUENCE IF NOT EXISTS page_body_occurrence_id_seq;+CREATE TABLE IF NOT EXISTS page_segment_texts (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ sha256 BYTEA NOT NULL CHECK (octet_length(sha256) = 32),+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 1048576),+ line_count INTEGER NOT NULL CHECK (line_count >= 0),+ body BYTEA NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, sha256)+);+CREATE TABLE IF NOT EXISTS page_body_manifest (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ occurrence_id BIGINT NOT NULL,+ gen_from BIGINT NOT NULL,+ gen_to BIGINT,+ seq INTEGER NOT NULL,+ region TEXT NOT NULL CHECK (region IN ('truth','timeline')),+ source_id TEXT NOT NULL,+ sha256 BYTEA NOT NULL,+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL,+ line_start BIGINT NOT NULL,+ line_count INTEGER NOT NULL,+ cut_kind TEXT NOT NULL CHECK (cut_kind IN ('heading','day','message','blank','forced','region_end','eof')),+ entry_state JSONB NOT NULL,+ protected_regions JSONB NOT NULL DEFAULT '[]',+ facts_slots JSONB NOT NULL DEFAULT '[]',+ static_proj_bytes BIGINT NOT NULL,+ static_proj_lines INTEGER NOT NULL,+ outline JSONB NOT NULL DEFAULT '[]',+ date_min DATE,+ date_max DATE,+ hash_state BYTEA NOT NULL,+ staging_id UUID,+ PRIMARY KEY (page_id, occurrence_id, gen_from),+ FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)+);+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);+CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;+CREATE TABLE IF NOT EXISTS page_body_stagings (+ id UUID PRIMARY KEY,+ kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),+ principal_kind TEXT NOT NULL,+ principal_id TEXT NOT NULL,+ client_request_id UUID NOT NULL,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER REFERENCES pages(id) ON DELETE CASCADE,+ mode TEXT NOT NULL CHECK (mode IN ('create','replace','append')),+ base_revision UUID,+ base_generation BIGINT,+ declared_bytes BIGINT NOT NULL CHECK (declared_bytes >= 0),+ declared_sha256 BYTEA,+ received_bytes BIGINT NOT NULL DEFAULT 0,+ next_part INTEGER NOT NULL DEFAULT 0,+ reserved_bytes BIGINT NOT NULL,+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','sealed','prepared','committed','aborted','expired')),+ commit_request_id UUID,+ idle_expires_at TIMESTAMPTZ NOT NULL,+ hard_expires_at TIMESTAMPTZ NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (principal_kind, principal_id, client_request_id)+);+CREATE INDEX IF NOT EXISTS page_body_stagings_expiry ON page_body_stagings (hard_expires_at) WHERE state IN ('open','sealed','prepared');+CREATE TABLE IF NOT EXISTS page_body_staging_parts (+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,+ part_no INTEGER NOT NULL CHECK (part_no >= 0),+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 4194304),+ sha256 BYTEA NOT NULL,+ body BYTEA NOT NULL,+ PRIMARY KEY (staging_id, part_no)+);-- Durable concurrent persistence (migration 151).CREATE TABLE IF NOT EXISTS persistence_brain (@@ -1403,14 +1504,22 @@ BEGINIF NOT EXISTS (SELECT 1 FROM persistence_brain WHERE singleton=1 AND enabled) THENIF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END IF;- row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;- IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ IF TG_TABLE_NAME='page_segment_texts' THEN+ -- Only the source decides; the segment body (up to 1 MiB of bytea) never becomes JSON.+ IF TG_OP='DELETE' THEN row_data := jsonb_build_object('source_id',OLD.source_id); ELSE row_data := jsonb_build_object('source_id',NEW.source_id); END IF;+ IF TG_OP='UPDATE' THEN old_data := jsonb_build_object('source_id',OLD.source_id); END IF;+ ELSE+ row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;+ IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ END IF;IF TG_TABLE_NAME='pages' AND TG_OP='UPDATE' THENIF (NEW.source_id,NEW.slug,NEW.type,NEW.page_kind,NEW.title,NEW.compiled_truth,NEW.timeline,NEW.frontmatter,NEW.deleted_at,NEW.knowledge_revision)IS NOT DISTINCT FROM(OLD.source_id,OLD.slug,OLD.type,OLD.page_kind,OLD.title,OLD.compiled_truth,OLD.timeline,OLD.frontmatter,OLD.deleted_at,OLD.knowledge_revision)-- The trust tier is guarded content (trust/schema.ts); read by key so brains before the column keep working.- AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier' THEN RETURN NEW; END IF;+ AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier'+ -- A segmented page's body identity (page-body/schema.ts); read by key for brains before the column.+ AND row_data->'body_generation' IS NOT DISTINCT FROM old_data->'body_generation' THEN RETURN NEW; END IF;ELSIF TG_TABLE_NAME='sources' THENIF TG_OP='UPDATE' AND (NEW.id,NEW.incarnation,NEW.local_path,NEW.archived)IS NOT DISTINCT FROM (OLD.id,OLD.incarnation,OLD.local_path,OLD.archived) THEN@@ -1462,7 +1571,7 @@ END \$fn\$;DO \$body\$DECLARE target text;BEGIN- FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources'] LOOP+ FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources','page_segment_texts','page_body_manifest'] LOOPIF to_regclass(target) IS NOT NULL THENEXECUTE format('DROP TRIGGER IF EXISTS managed_writer_guard ON %I',target);EXECUTE format('CREATE TRIGGER managed_writer_guard BEFORE INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()',target);@@ -1472,8 +1581,11 @@ END \$body\$;;-- Verified text projection work (migration 153).DROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;-CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title,timeline ON pages- FOR EACH ROW EXECUTE FUNCTION update_page_search_vector();+DO \$trg\$ BEGIN+ EXECUTE format('CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF %s ON pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()',+ CASE WHEN EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'timeline_lead' AND NOT attisdropped)+ THEN 'title,timeline,timeline_lead' ELSE 'title,timeline' END);+ END \$trg\$;CREATE TABLE IF NOT EXISTS page_projection_jobs (source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,slug TEXT NOT NULL,diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 129239a575..bea50b9118 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -138,6 +138,9 @@ import type { ChunkWindowRequest, ChunkWindowOpts, ChunkWindowPage } from './seaimport 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 * as pageBodyImpl from './engine-sql/page-body.ts';+import type { BodyFlipInput, BodyFlipResult, BodyRegion, BodyStagingInput, BodyStagingState, ManifestRow, ManifestRowInput, SegmentChunkInput,+ SegmentedPageMeta, SegmentSweepOptions, SegmentSweepResult, SegmentTextInput } from './page-body/types.ts';import { hasCJK } from './cjk.ts';import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-search.ts';import * as titlesImpl from './engine-sql/titles.ts';@@ -2296,6 +2299,25 @@ export class PostgresEngine implements BrainEngine {return factsImpl.getFactsHealth(unscopedExecutor(this.engineSql, 'facts: unscoped on master (EO4 inventory)'), source_id);}+ // Segmented page storage (Wave B): SQL in ./engine-sql/page-body.ts.+ async allocateBodyOccurrenceIds(count: number): Promise<number[]> { return pageBodyImpl.allocateBodyOccurrenceIds(this.engineSql, count); }+ async stageSegmentTexts(sourceId: string, texts: readonly SegmentTextInput[]): Promise<{ inserted: number }> { return pageBodyImpl.stageSegmentTexts(this.engineSql, sourceId, texts); }+ async readSegmentTexts(sourceId: string, sha256s: readonly Uint8Array[]): Promise<Map<string, Uint8Array>> {+ return pageBodyImpl.readSegmentTexts(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), sourceId, sha256s);+ }+ async stageManifestRows(rows: readonly ManifestRowInput[]): Promise<void> { return pageBodyImpl.stageManifestRows(this.engineSql, rows); }+ async readManifest(pageId: number, opts?: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number }): Promise<ManifestRow[]> {+ return pageBodyImpl.readManifest(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), pageId, opts);+ }+ async stageSegmentChunks(pageId: number, generation: number, chunks: readonly SegmentChunkInput[], opts?: { embeddingColumn?: ResolvedColumn }): Promise<number[]> {+ return pageBodyImpl.stageSegmentChunks(this.engineSql, pageId, generation, chunks, opts);+ }+ async createSegmentedPageShell(slug: string, meta: SegmentedPageMeta, opts: { sourceId: string }): Promise<{ id: number }> { return pageBodyImpl.createSegmentedPageShell(this.engineSql, slug, meta, opts); }+ async flipBodyGeneration(input: BodyFlipInput): Promise<BodyFlipResult> { return pageBodyImpl.flipBodyGeneration(this.engineSql, input); }+ async openBodyStaging(input: BodyStagingInput): Promise<void> { return pageBodyImpl.openBodyStaging(this.engineSql, input); }+ async setBodyStagingState(id: string, state: BodyStagingState, opts?: { commitRequestId?: string | null }): Promise<void> { return pageBodyImpl.setBodyStagingState(this.engineSql, id, state, opts); }+ async sweepSegments(opts?: SegmentSweepOptions): Promise<SegmentSweepResult> { return pageBodyImpl.sweepSegments(this.engineSql, opts); }+// ============================================================// v0.28: Takes (typed/weighted/attributed claims) + synthesis_evidence// ============================================================diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex ecb6b2f86f..57fc23cc73 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -162,6 +162,11 @@ CREATE TABLE IF NOT EXISTS pages (-- the content allow-list IS DISTINCT FROM. Read by the per-page snapshot-- check in query-cache-gate.ts.generation BIGINT NOT NULL DEFAULT 1,+ -- Wave B (migration v248): body_storage, body_bytes, truth_bytes, body_lines,+ -- body_generation, segment_count, segmenter_version, body_flags, truth_lead and+ -- timeline_lead, the NULL-able compiled_truth/timeline and pages_body_storage_chk+ -- come from the migration on every install, after the migration-added pages+ -- columns, so fresh and upgraded brains share their ordinals.CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug));@@ -173,6 +178,7 @@ CREATE TABLE IF NOT EXISTS pages (-- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3-- to include title/type/page_kind/corpus_generation/content_hash) so-- read-time mutations don't invalidate every cache row.+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL). Edit that file, then run: bun run build:schemaCREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS \$func\$BEGINIF (TG_OP = 'INSERT') THEN@@ -189,10 +195,15 @@ BEGINOR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)THENNEW.generation := OLD.generation + 1;+ ELSIF OLD.compiled_truth IS NULL AND NEW.compiled_truth IS NULL THEN+ IF OLD.body_generation IS DISTINCT FROM NEW.body_generation THEN+ NEW.generation := OLD.generation + 1;+ END IF;END IF;RETURN NEW;END;\$func\$ LANGUAGE plpgsql;+-- END GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL)DROP TRIGGER IF EXISTS bump_page_generation_trg ON pages;CREATE TRIGGER bump_page_generation_trg@@ -343,6 +354,9 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- content_chunks columns, so fresh and upgraded brains share their ordinals.-- v244: projected_byte_start / projected_byte_end (a prose chunk's UTF-8-- span in its source's read projection) are added the same way.+ -- v248: occurrence_id, local_ordinal, raw_byte_start/end, body_generation and+ -- retired_generation (segmented-page chunks; NULL for inline pages) and+ -- content_chunks_occurrence_idx are added the same way.-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,@@ -651,6 +665,9 @@ CREATE TABLE IF NOT EXISTS page_versions (compiled_truth TEXT NOT NULL,frontmatter JSONB NOT NULL DEFAULT '{}',snapshot_at TIMESTAMPTZ NOT NULL DEFAULT now()+ -- v248: body_storage, body_generation, body_bytes, content_hash, the NULL-able+ -- compiled_truth and page_versions_body_chk come from the migration on every+ -- install (a segmented snapshot references a generation, not a body copy).);CREATE INDEX IF NOT EXISTS idx_versions_page ON page_versions(page_id);@@ -1156,15 +1173,20 @@ CREATE INDEX IF NOT EXISTS idx_pages_search ON pages USING GIN(search_vector);CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS \$\$DECLAREtimeline_text TEXT;+ timeline_lead_text TEXT;BEGINSELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')INTO timeline_textFROM timeline_entriesWHERE page_id = NEW.id;+ IF NEW.timeline IS NULL THEN+ timeline_lead_text := NEW.timeline_lead;+ END IF;+NEW.search_vector :=setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||- setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, ''), 65536))), 'C') ||+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, timeline_lead_text, ''), 65536))), 'C') ||setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(timeline_text, ''), 32768))), 'C');RETURN NEW;@@ -1846,13 +1868,17 @@ CREATE TABLE IF NOT EXISTS page_write_guards (PRIMARY KEY (source_incarnation, slug));CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS \$fn\$+ DECLARE body_moved boolean := false;BEGINIF OLD.knowledge_revision IS NULL THENNEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());NEW.text_projection_revision := NULL;RETURN NEW;END IF;- IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,+ IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN+ body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;+ END IF;+ IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,NEW.timeline, NEW.frontmatter, NEW.deleted_at)IS DISTINCT FROM(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,@@ -1990,6 +2016,88 @@ CREATE TABLE IF NOT EXISTS page_extraction_state ();CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idxON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;+-- Wave B segmented page storage (migration v248): segment texts, the+-- generation-ranged body manifest and body stagings (src/core/page-body/).+-- Before the persistence region so the managed-writer guard covers them.+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE SEQUENCE IF NOT EXISTS page_body_occurrence_id_seq;+CREATE TABLE IF NOT EXISTS page_segment_texts (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ sha256 BYTEA NOT NULL CHECK (octet_length(sha256) = 32),+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 1048576),+ line_count INTEGER NOT NULL CHECK (line_count >= 0),+ body BYTEA NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, sha256)+);+CREATE TABLE IF NOT EXISTS page_body_manifest (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ occurrence_id BIGINT NOT NULL,+ gen_from BIGINT NOT NULL,+ gen_to BIGINT,+ seq INTEGER NOT NULL,+ region TEXT NOT NULL CHECK (region IN ('truth','timeline')),+ source_id TEXT NOT NULL,+ sha256 BYTEA NOT NULL,+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL,+ line_start BIGINT NOT NULL,+ line_count INTEGER NOT NULL,+ cut_kind TEXT NOT NULL CHECK (cut_kind IN ('heading','day','message','blank','forced','region_end','eof')),+ entry_state JSONB NOT NULL,+ protected_regions JSONB NOT NULL DEFAULT '[]',+ facts_slots JSONB NOT NULL DEFAULT '[]',+ static_proj_bytes BIGINT NOT NULL,+ static_proj_lines INTEGER NOT NULL,+ outline JSONB NOT NULL DEFAULT '[]',+ date_min DATE,+ date_max DATE,+ hash_state BYTEA NOT NULL,+ staging_id UUID,+ PRIMARY KEY (page_id, occurrence_id, gen_from),+ FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)+);+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);+CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;+CREATE TABLE IF NOT EXISTS page_body_stagings (+ id UUID PRIMARY KEY,+ kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),+ principal_kind TEXT NOT NULL,+ principal_id TEXT NOT NULL,+ client_request_id UUID NOT NULL,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER REFERENCES pages(id) ON DELETE CASCADE,+ mode TEXT NOT NULL CHECK (mode IN ('create','replace','append')),+ base_revision UUID,+ base_generation BIGINT,+ declared_bytes BIGINT NOT NULL CHECK (declared_bytes >= 0),+ declared_sha256 BYTEA,+ received_bytes BIGINT NOT NULL DEFAULT 0,+ next_part INTEGER NOT NULL DEFAULT 0,+ reserved_bytes BIGINT NOT NULL,+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','sealed','prepared','committed','aborted','expired')),+ commit_request_id UUID,+ idle_expires_at TIMESTAMPTZ NOT NULL,+ hard_expires_at TIMESTAMPTZ NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (principal_kind, principal_id, client_request_id)+);+CREATE INDEX IF NOT EXISTS page_body_stagings_expiry ON page_body_stagings (hard_expires_at) WHERE state IN ('open','sealed','prepared');+CREATE TABLE IF NOT EXISTS page_body_staging_parts (+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,+ part_no INTEGER NOT NULL CHECK (part_no >= 0),+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 4194304),+ sha256 BYTEA NOT NULL,+ body BYTEA NOT NULL,+ PRIMARY KEY (staging_id, part_no)+);+-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)-- Durable concurrent persistence (migration 151).-- BEGIN GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS). Edit that file, then run: bun run build:schema@@ -2118,14 +2226,22 @@ BEGINIF NOT EXISTS (SELECT 1 FROM persistence_brain WHERE singleton=1 AND enabled) THENIF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END IF;- row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;- IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ IF TG_TABLE_NAME='page_segment_texts' THEN+ -- Only the source decides; the segment body (up to 1 MiB of bytea) never becomes JSON.+ IF TG_OP='DELETE' THEN row_data := jsonb_build_object('source_id',OLD.source_id); ELSE row_data := jsonb_build_object('source_id',NEW.source_id); END IF;+ IF TG_OP='UPDATE' THEN old_data := jsonb_build_object('source_id',OLD.source_id); END IF;+ ELSE+ row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;+ IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ END IF;IF TG_TABLE_NAME='pages' AND TG_OP='UPDATE' THENIF (NEW.source_id,NEW.slug,NEW.type,NEW.page_kind,NEW.title,NEW.compiled_truth,NEW.timeline,NEW.frontmatter,NEW.deleted_at,NEW.knowledge_revision)IS NOT DISTINCT FROM(OLD.source_id,OLD.slug,OLD.type,OLD.page_kind,OLD.title,OLD.compiled_truth,OLD.timeline,OLD.frontmatter,OLD.deleted_at,OLD.knowledge_revision)-- The trust tier is guarded content (trust/schema.ts); read by key so brains before the column keep working.- AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier' THEN RETURN NEW; END IF;+ AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier'+ -- A segmented page's body identity (page-body/schema.ts); read by key for brains before the column.+ AND row_data->'body_generation' IS NOT DISTINCT FROM old_data->'body_generation' THEN RETURN NEW; END IF;ELSIF TG_TABLE_NAME='sources' THENIF TG_OP='UPDATE' AND (NEW.id,NEW.incarnation,NEW.local_path,NEW.archived)IS NOT DISTINCT FROM (OLD.id,OLD.incarnation,OLD.local_path,OLD.archived) THEN@@ -2177,7 +2293,7 @@ END \$fn\$;DO \$body\$DECLARE target text;BEGIN- FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources'] LOOP+ FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources','page_segment_texts','page_body_manifest'] LOOPIF to_regclass(target) IS NOT NULL THENEXECUTE format('DROP TRIGGER IF EXISTS managed_writer_guard ON %I',target);EXECUTE format('CREATE TRIGGER managed_writer_guard BEFORE INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()',target);@@ -2189,8 +2305,11 @@ END \$body\$;-- Verified text projection work (migration 153).-- BEGIN GENERATED from src/core/page-state/projection-schema.ts (PAGE_PROJECTION_SCHEMA_SQL). Edit that file, then run: bun run build:schemaDROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;-CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title,timeline ON pages- FOR EACH ROW EXECUTE FUNCTION update_page_search_vector();+DO \$trg\$ BEGIN+ EXECUTE format('CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF %s ON pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()',+ CASE WHEN EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'timeline_lead' AND NOT attisdropped)+ THEN 'title,timeline,timeline_lead' ELSE 'title,timeline' END);+ END \$trg\$;CREATE TABLE IF NOT EXISTS page_projection_jobs (source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,slug TEXT NOT NULL,diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 26c3e6c86c..284286cf7d 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 247;+export const LATEST_SCHEMA_VERSION = 248;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex a4842230dd..6c14de5c01 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -248,6 +248,7 @@ import { v244 } from './v244-chunk-projected-spans.ts';import { v245 } from './v245-page-search-vector-bounded-timeline.ts';import { v246 } from './v246-page-embedding-budget.ts';import { v247 } from './v247-page-extraction-state.ts';+import { v248 } from './v248-segmented-page-storage.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -494,4 +495,5 @@ export const MIGRATIONS: Migration[] = [v245,v246,v247,+ v248,];diff --git a/src/core/schema-migrations/v248-segmented-page-storage.ts b/src/core/schema-migrations/v248-segmented-page-storage.tsnew file mode 100644index 0000000000..67395ed3c8--- /dev/null+++ b/src/core/schema-migrations/v248-segmented-page-storage.ts@@ -0,0 +1,111 @@+import type { Migration } from './types.ts';+import { PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL } from '../page-body/schema.ts';+import { PAGE_SEARCH_VECTOR_TRIGGER_SQL } from '../page-state/projection-schema.ts';+import { buildIndexOnline, migrationNotice } from './helpers.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Wave B segmented page storage (src/core/page-body/): a page body over 1 MiB+// is stored as content-addressed segment texts plus a manifest versioned by+// generation range, behind `pages.segmented_storage` (default off, so no row+// changes class until it is turned on). Nothing to backfill: every existing+// page reads `body_storage = 'inline'`.+//+// - pages: body class, size, generation and bounded leads; compiled_truth and+// timeline become nullable (still DEFAULT ''), and pages_body_storage_chk+// makes them NULL exactly for segmented pages, so an older binary's+// whole-body write to a segmented page fails instead of truncating it.+// - content_chunks: segment identity, stored span and generation range (NULL+// for every inline chunk); page_versions: a segmented snapshot references a+// generation instead of copying the body.+// - The new tables and the occurrence id sequence (also in both blobs).+// - bump_page_generation_fn is re-created so a fresh install (where v91+// re-created it after the blob) ends with the blob's text, and+// trg_pages_search_vector so it also fires on timeline_lead (the blob's+// statement adds that column whenever pages has it).+//+// The pages, content_chunks and page_versions columns are migration-only (not+// in schema.sql's CREATE TABLEs), so fresh and upgraded brains share column+// ordinals; blob triggers read them only on a row whose body columns are NULL.+// CHECKs are added NOT VALID and validated in their own statements, and the+// chunk occurrence index is built online (CONCURRENTLY on Postgres), so no+// whole-table scan runs under an exclusive lock. Segment text storage: lz4 on+// Postgres (EXTERNAL when the server lacks lz4), EXTERNAL on PGLite, whose+// WASM pglz makes deep window reads about 4x slower.+const COMMON_SQL = `+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS body_storage TEXT NOT NULL DEFAULT 'inline';+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS body_bytes BIGINT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS truth_bytes BIGINT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS body_lines BIGINT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS body_generation BIGINT NOT NULL DEFAULT 0;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS segment_count INTEGER;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS segmenter_version INTEGER;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS body_flags JSONB;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS truth_lead TEXT;+ ALTER TABLE pages ADD COLUMN IF NOT EXISTS timeline_lead TEXT;+ ALTER TABLE pages ALTER COLUMN compiled_truth DROP NOT NULL;+ ALTER TABLE pages ALTER COLUMN timeline DROP NOT NULL;+ DO $do$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'pages_body_storage_chk' AND conrelid = 'pages'::regclass) THEN+ ALTER TABLE pages ADD CONSTRAINT pages_body_storage_chk CHECK (+ (body_storage = 'inline' AND compiled_truth IS NOT NULL AND timeline IS NOT NULL AND truth_lead IS NULL)+ OR (body_storage = 'segmented' AND compiled_truth IS NULL AND timeline IS NULL AND body_bytes IS NOT NULL)+ ) NOT VALID;+ END IF;+ END $do$;+ ${PAGE_BODY_SCHEMA_SQL}+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS occurrence_id BIGINT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS local_ordinal INTEGER;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS raw_byte_start BIGINT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS raw_byte_end BIGINT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS body_generation BIGINT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS retired_generation BIGINT;+ ALTER TABLE page_versions ALTER COLUMN compiled_truth DROP NOT NULL;+ ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS body_storage TEXT NOT NULL DEFAULT 'inline';+ ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS body_generation BIGINT;+ ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS body_bytes BIGINT;+ ALTER TABLE page_versions ADD COLUMN IF NOT EXISTS content_hash TEXT;+ DO $do$ BEGIN+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'page_versions_body_chk' AND conrelid = 'page_versions'::regclass) THEN+ ALTER TABLE page_versions ADD CONSTRAINT page_versions_body_chk CHECK (+ (body_storage = 'inline' AND compiled_truth IS NOT NULL)+ OR (body_storage = 'segmented' AND compiled_truth IS NULL AND timeline IS NULL AND body_generation IS NOT NULL)+ ) NOT VALID;+ END IF;+ END $do$;+ ${PAGE_GENERATION_BUMP_FN_SQL}+ DROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;+ ${PAGE_SEARCH_VECTOR_TRIGGER_SQL};+`;++const CONTENT_CHUNKS_OCCURRENCE_INDEX = {+ name: 'content_chunks_occurrence_idx',+ table: 'content_chunks',+ sql: 'CREATE INDEX IF NOT EXISTS content_chunks_occurrence_idx ON content_chunks (page_id, occurrence_id) WHERE occurrence_id IS NOT NULL',+};++export const v248: Migration = {+ version: 248,+ name: 'segmented_page_storage',+ idempotent: true,+ transaction: false,+ sql: '',+ sqlFor: {+ postgres: `${COMMON_SQL}+ DO $do$ BEGIN+ EXECUTE 'ALTER TABLE page_segment_texts ALTER COLUMN body SET COMPRESSION lz4';+ EXCEPTION WHEN feature_not_supported OR syntax_error OR invalid_parameter_value THEN+ ALTER TABLE page_segment_texts ALTER COLUMN body SET STORAGE EXTERNAL;+ END $do$;+ `,+ pglite: `${COMMON_SQL}+ ALTER TABLE page_segment_texts ALTER COLUMN body SET STORAGE EXTERNAL;+ `,+ },+ handler: async engine => {+ await engine.runMigration(248, 'ALTER TABLE pages VALIDATE CONSTRAINT pages_body_storage_chk;');+ await engine.runMigration(248, 'ALTER TABLE page_versions VALIDATE CONSTRAINT page_versions_body_chk;');+ await buildIndexOnline(engine, 248, CONTENT_CHUNKS_OCCURRENCE_INDEX, { notice: migrationNotice });+ },+};diff --git a/src/core/search-vector-backfill.ts b/src/core/search-vector-backfill.tsindex a49c31f04d..5e68d87702 100644--- a/src/core/search-vector-backfill.ts+++ b/src/core/search-vector-backfill.ts@@ -83,7 +83,8 @@ export async function backfillChunkVectors(engine: BrainEngine, opts: VectorBack/*** #6374: page vectors rebuilt with the seal's own expression. The pages- * trigger fires only on `UPDATE OF title,timeline` and indexes the RAW+ * trigger fires only on `UPDATE OF title,timeline` (and a segmented page's+ * timeline_lead) and indexes the RAW* timeline, so neither an UPDATE-to-self nor re-firing it is right. Each batch* reads its rows through an UPDATE-to-self (row locks held for that statement* only, never across the TypeScript sanitize), sanitizes the timeline exactlydiff --git a/src/schema.sql b/src/schema.sqlindex 725b1dd027..3d5a7a6346 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -158,6 +158,11 @@ CREATE TABLE IF NOT EXISTS pages (-- the content allow-list IS DISTINCT FROM. Read by the per-page snapshot-- check in query-cache-gate.ts.generation BIGINT NOT NULL DEFAULT 1,+ -- Wave B (migration v248): body_storage, body_bytes, truth_bytes, body_lines,+ -- body_generation, segment_count, segmenter_version, body_flags, truth_lead and+ -- timeline_lead, the NULL-able compiled_truth/timeline and pages_body_storage_chk+ -- come from the migration on every install, after the migration-added pages+ -- columns, so fresh and upgraded brains share their ordinals.CONSTRAINT pages_source_slug_key UNIQUE (source_id, slug));@@ -169,6 +174,7 @@ CREATE TABLE IF NOT EXISTS pages (-- content columns IS DISTINCT FROM (allow-list widened per D6 + codex #3-- to include title/type/page_kind/corpus_generation/content_hash) so-- read-time mutations don't invalidate every cache row.+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL). Edit that file, then run: bun run build:schemaCREATE OR REPLACE FUNCTION bump_page_generation_fn() RETURNS trigger SET search_path = pg_catalog, public AS $func$BEGINIF (TG_OP = 'INSERT') THEN@@ -185,10 +191,15 @@ BEGINOR (OLD.content_hash IS DISTINCT FROM NEW.content_hash)THENNEW.generation := OLD.generation + 1;+ ELSIF OLD.compiled_truth IS NULL AND NEW.compiled_truth IS NULL THEN+ IF OLD.body_generation IS DISTINCT FROM NEW.body_generation THEN+ NEW.generation := OLD.generation + 1;+ END IF;END IF;RETURN NEW;END;$func$ LANGUAGE plpgsql;+-- END GENERATED from src/core/page-body/schema.ts (PAGE_GENERATION_BUMP_FN_SQL)DROP TRIGGER IF EXISTS bump_page_generation_trg ON pages;CREATE TRIGGER bump_page_generation_trg@@ -339,6 +350,9 @@ CREATE TABLE IF NOT EXISTS content_chunks (-- content_chunks columns, so fresh and upgraded brains share their ordinals.-- v244: projected_byte_start / projected_byte_end (a prose chunk's UTF-8-- span in its source's read projection) are added the same way.+ -- v248: occurrence_id, local_ordinal, raw_byte_start/end, body_generation and+ -- retired_generation (segmented-page chunks; NULL for inline pages) and+ -- content_chunks_occurrence_idx are added the same way.-- #4246 (v133): md5(chunk_text) at embed time. NULL = no embedding or-- pre-v133 row (grandfathered by invalidateContentDriftEmbeddings).embedded_text_hash TEXT,@@ -647,6 +661,9 @@ CREATE TABLE IF NOT EXISTS page_versions (compiled_truth TEXT NOT NULL,frontmatter JSONB NOT NULL DEFAULT '{}',snapshot_at TIMESTAMPTZ NOT NULL DEFAULT now()+ -- v248: body_storage, body_generation, body_bytes, content_hash, the NULL-able+ -- compiled_truth and page_versions_body_chk come from the migration on every+ -- install (a segmented snapshot references a generation, not a body copy).);CREATE INDEX IF NOT EXISTS idx_versions_page ON page_versions(page_id);@@ -1152,15 +1169,20 @@ CREATE INDEX IF NOT EXISTS idx_pages_search ON pages USING GIN(search_vector);CREATE OR REPLACE FUNCTION update_page_search_vector() RETURNS trigger SET search_path = pg_catalog, public AS $$DECLAREtimeline_text TEXT;+ timeline_lead_text TEXT;BEGINSELECT coalesce(string_agg(summary || ' ' || detail, ' ' ORDER BY id), '')INTO timeline_textFROM timeline_entriesWHERE page_id = NEW.id;+ IF NEW.timeline IS NULL THEN+ timeline_lead_text := NEW.timeline_lead;+ END IF;+NEW.search_vector :=setweight(to_tsvector('english', gbrain_fts_input(coalesce(NEW.title, ''))), 'A') ||- setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, ''), 65536))), 'C') ||+ setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(NEW.timeline, timeline_lead_text, ''), 65536))), 'C') ||setweight(to_tsvector('english', gbrain_fts_input(left(coalesce(timeline_text, ''), 32768))), 'C');RETURN NEW;@@ -1842,13 +1864,17 @@ CREATE TABLE IF NOT EXISTS page_write_guards (PRIMARY KEY (source_incarnation, slug));CREATE OR REPLACE FUNCTION gbrain_advance_page_revision() RETURNS trigger LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$+ DECLARE body_moved boolean := false;BEGINIF OLD.knowledge_revision IS NULL THENNEW.knowledge_revision := COALESCE(NEW.knowledge_revision, gen_random_uuid());NEW.text_projection_revision := NULL;RETURN NEW;END IF;- IF (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,+ IF NEW.compiled_truth IS NULL AND OLD.compiled_truth IS NULL THEN+ body_moved := NEW.body_generation IS DISTINCT FROM OLD.body_generation;+ END IF;+ IF body_moved OR (NEW.source_id, NEW.slug, NEW.type, NEW.page_kind, NEW.title, NEW.compiled_truth,NEW.timeline, NEW.frontmatter, NEW.deleted_at)IS DISTINCT FROM(OLD.source_id, OLD.slug, OLD.type, OLD.page_kind, OLD.title, OLD.compiled_truth,@@ -1986,6 +2012,88 @@ CREATE TABLE IF NOT EXISTS page_extraction_state ();CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idxON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;+-- Wave B segmented page storage (migration v248): segment texts, the+-- generation-ranged body manifest and body stagings (src/core/page-body/).+-- Before the persistence region so the managed-writer guard covers them.+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE SEQUENCE IF NOT EXISTS page_body_occurrence_id_seq;+CREATE TABLE IF NOT EXISTS page_segment_texts (+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ sha256 BYTEA NOT NULL CHECK (octet_length(sha256) = 32),+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 1048576),+ line_count INTEGER NOT NULL CHECK (line_count >= 0),+ body BYTEA NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ PRIMARY KEY (source_id, sha256)+);+CREATE TABLE IF NOT EXISTS page_body_manifest (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ occurrence_id BIGINT NOT NULL,+ gen_from BIGINT NOT NULL,+ gen_to BIGINT,+ seq INTEGER NOT NULL,+ region TEXT NOT NULL CHECK (region IN ('truth','timeline')),+ source_id TEXT NOT NULL,+ sha256 BYTEA NOT NULL,+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL,+ line_start BIGINT NOT NULL,+ line_count INTEGER NOT NULL,+ cut_kind TEXT NOT NULL CHECK (cut_kind IN ('heading','day','message','blank','forced','region_end','eof')),+ entry_state JSONB NOT NULL,+ protected_regions JSONB NOT NULL DEFAULT '[]',+ facts_slots JSONB NOT NULL DEFAULT '[]',+ static_proj_bytes BIGINT NOT NULL,+ static_proj_lines INTEGER NOT NULL,+ outline JSONB NOT NULL DEFAULT '[]',+ date_min DATE,+ date_max DATE,+ hash_state BYTEA NOT NULL,+ staging_id UUID,+ PRIMARY KEY (page_id, occurrence_id, gen_from),+ FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)+);+CREATE UNIQUE INDEX IF NOT EXISTS page_body_manifest_live_seq ON page_body_manifest (page_id, seq) WHERE gen_to IS NULL AND staging_id IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_live_bytes ON page_body_manifest (page_id, byte_start) WHERE gen_to IS NULL;+CREATE INDEX IF NOT EXISTS page_body_manifest_text ON page_body_manifest (source_id, sha256);+CREATE INDEX IF NOT EXISTS page_body_manifest_staging ON page_body_manifest (staging_id) WHERE staging_id IS NOT NULL;+CREATE TABLE IF NOT EXISTS page_body_stagings (+ id UUID PRIMARY KEY,+ kind TEXT NOT NULL CHECK (kind IN ('upload','import','sync','put','append','edit','resegment')),+ principal_kind TEXT NOT NULL,+ principal_id TEXT NOT NULL,+ client_request_id UUID NOT NULL,+ source_id TEXT NOT NULL REFERENCES sources(id) ON DELETE CASCADE,+ source_incarnation UUID NOT NULL,+ slug TEXT NOT NULL,+ page_id INTEGER REFERENCES pages(id) ON DELETE CASCADE,+ mode TEXT NOT NULL CHECK (mode IN ('create','replace','append')),+ base_revision UUID,+ base_generation BIGINT,+ declared_bytes BIGINT NOT NULL CHECK (declared_bytes >= 0),+ declared_sha256 BYTEA,+ received_bytes BIGINT NOT NULL DEFAULT 0,+ next_part INTEGER NOT NULL DEFAULT 0,+ reserved_bytes BIGINT NOT NULL,+ state TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open','sealed','prepared','committed','aborted','expired')),+ commit_request_id UUID,+ idle_expires_at TIMESTAMPTZ NOT NULL,+ hard_expires_at TIMESTAMPTZ NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ UNIQUE (principal_kind, principal_id, client_request_id)+);+CREATE INDEX IF NOT EXISTS page_body_stagings_expiry ON page_body_stagings (hard_expires_at) WHERE state IN ('open','sealed','prepared');+CREATE TABLE IF NOT EXISTS page_body_staging_parts (+ staging_id UUID NOT NULL REFERENCES page_body_stagings(id) ON DELETE CASCADE,+ part_no INTEGER NOT NULL CHECK (part_no >= 0),+ byte_start BIGINT NOT NULL,+ byte_len INTEGER NOT NULL CHECK (byte_len BETWEEN 1 AND 4194304),+ sha256 BYTEA NOT NULL,+ body BYTEA NOT NULL,+ PRIMARY KEY (staging_id, part_no)+);+-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)-- Durable concurrent persistence (migration 151).-- BEGIN GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS). Edit that file, then run: bun run build:schema@@ -2114,14 +2222,22 @@ BEGINIF NOT EXISTS (SELECT 1 FROM persistence_brain WHERE singleton=1 AND enabled) THENIF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END IF;- row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;- IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ IF TG_TABLE_NAME='page_segment_texts' THEN+ -- Only the source decides; the segment body (up to 1 MiB of bytea) never becomes JSON.+ IF TG_OP='DELETE' THEN row_data := jsonb_build_object('source_id',OLD.source_id); ELSE row_data := jsonb_build_object('source_id',NEW.source_id); END IF;+ IF TG_OP='UPDATE' THEN old_data := jsonb_build_object('source_id',OLD.source_id); END IF;+ ELSE+ row_data := CASE WHEN TG_OP='DELETE' THEN to_jsonb(OLD) ELSE to_jsonb(NEW) END;+ IF TG_OP='UPDATE' THEN old_data := to_jsonb(OLD); END IF;+ END IF;IF TG_TABLE_NAME='pages' AND TG_OP='UPDATE' THENIF (NEW.source_id,NEW.slug,NEW.type,NEW.page_kind,NEW.title,NEW.compiled_truth,NEW.timeline,NEW.frontmatter,NEW.deleted_at,NEW.knowledge_revision)IS NOT DISTINCT FROM(OLD.source_id,OLD.slug,OLD.type,OLD.page_kind,OLD.title,OLD.compiled_truth,OLD.timeline,OLD.frontmatter,OLD.deleted_at,OLD.knowledge_revision)-- The trust tier is guarded content (trust/schema.ts); read by key so brains before the column keep working.- AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier' THEN RETURN NEW; END IF;+ AND row_data->'trust_tier' IS NOT DISTINCT FROM old_data->'trust_tier'+ -- A segmented page's body identity (page-body/schema.ts); read by key for brains before the column.+ AND row_data->'body_generation' IS NOT DISTINCT FROM old_data->'body_generation' THEN RETURN NEW; END IF;ELSIF TG_TABLE_NAME='sources' THENIF TG_OP='UPDATE' AND (NEW.id,NEW.incarnation,NEW.local_path,NEW.archived)IS NOT DISTINCT FROM (OLD.id,OLD.incarnation,OLD.local_path,OLD.archived) THEN@@ -2173,7 +2289,7 @@ END $fn$;DO $body$DECLARE target text;BEGIN- FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources'] LOOP+ FOREACH target IN ARRAY ARRAY['pages','tags','slug_aliases','page_aliases','facts','takes','timeline_entries','sources','page_segment_texts','page_body_manifest'] LOOPIF to_regclass(target) IS NOT NULL THENEXECUTE format('DROP TRIGGER IF EXISTS managed_writer_guard ON %I',target);EXECUTE format('CREATE TRIGGER managed_writer_guard BEFORE INSERT OR UPDATE OR DELETE ON %I FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()',target);@@ -2185,8 +2301,11 @@ END $body$;-- Verified text projection work (migration 153).-- BEGIN GENERATED from src/core/page-state/projection-schema.ts (PAGE_PROJECTION_SCHEMA_SQL). Edit that file, then run: bun run build:schemaDROP TRIGGER IF EXISTS trg_pages_search_vector ON pages;-CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title,timeline ON pages- FOR EACH ROW EXECUTE FUNCTION update_page_search_vector();+DO $trg$ BEGIN+ EXECUTE format('CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF %s ON pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()',+ CASE WHEN EXISTS (SELECT 1 FROM pg_attribute WHERE attrelid = 'pages'::regclass AND attname = 'timeline_lead' AND NOT attisdropped)+ THEN 'title,timeline,timeline_lead' ELSE 'title,timeline' END);+ END $trg$;CREATE TABLE IF NOT EXISTS page_projection_jobs (source_incarnation UUID NOT NULL REFERENCES sources(incarnation) ON DELETE CASCADE,slug TEXT NOT NULL,diff --git a/test/e2e/segment-gc-parity.test.ts b/test/e2e/segment-gc-parity.test.tsnew file mode 100644index 0000000000..80ae0b0428--- /dev/null+++ b/test/e2e/segment-gc-parity.test.ts@@ -0,0 +1,18 @@+/**+ * Segment garbage collection on Postgres (spec 3.5): the shared cases plus+ * the two-connection races (a sweep skips a text an open writer references;+ * a writer re-staging a text an open sweep deletes waits and re-inserts it),+ * and the JSONB double-encoding check PGLite can't catch. PGLite arm:+ * test/large-pages/segment-gc.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { defineSegmentGcCases } from '../helpers/segment-gc-cases.ts';+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';++(hasDatabase() ? describe : describe.skip)('segment GC [postgres]', () => {+ let engine: PostgresEngine;+ beforeAll(async () => { engine = await setupDB(); }, 120_000);+ afterAll(async () => { await teardownDB(); });+ defineSegmentGcCases({ getEngine: () => engine, concurrentConnections: true });+});diff --git a/test/engine-sql-page-body.test.ts b/test/engine-sql-page-body.test.tsnew file mode 100644index 0000000000..f8e31993b0--- /dev/null+++ b/test/engine-sql-page-body.test.ts@@ -0,0 +1,280 @@+/**+ * Segmented page storage engine SQL (engine-sql/page-body.ts) on PGLite: every+ * Wave B engine member, the manifest generation reads, the flip (happy path,+ * revision_changed, retire bound, two preparers), the body CHECK and the page+ * triggers on a body_generation-only flip. GC: test/large-pages/segment-gc.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { STAGE_BATCH_BYTES } from '../src/core/page-body/limits.ts';+import { chunk, flipInput, hexOf, pageMeta, publishSegmentedPage, segmentText, stageGeneration, stagingInput } from './helpers/page-body-fixtures.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.executeRaw("INSERT INTO sources (id, name) VALUES ('other', 'other') ON CONFLICT DO NOTHING");+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++async function pageRow(pageId: number) {+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT body_storage, compiled_truth, timeline, body_generation::int AS body_generation,+ body_bytes::int AS body_bytes, segment_count, truth_lead, timeline_lead, body_flags, content_hash, generation::int AS generation,+ knowledge_revision::text AS knowledge_revision, text_projection_revision::text AS text_projection_revision, search_vector::text AS search_vector, title+ FROM pages WHERE id = $1`, [pageId]);+ return rows[0]!;+}++async function chunkRows(pageId: number) {+ return engine.executeRaw<{ chunk_index: number; occurrence_id: number | null; body_generation: number | null; retired_generation: number | null; chunk_text: string }>(+ `SELECT chunk_index, occurrence_id::int AS occurrence_id, body_generation::int AS body_generation, retired_generation::int AS retired_generation, chunk_text+ FROM content_chunks WHERE page_id = $1 ORDER BY chunk_index`, [pageId]);+}++describe('allocateBodyOccurrenceIds', () => {+ test('returns distinct increasing ids and nothing for a zero count', async () => {+ const ids = await engine.allocateBodyOccurrenceIds(3);+ expect(ids.length).toBe(3);+ expect(ids[1]).toBeGreaterThan(ids[0]!);+ expect(ids[2]).toBeGreaterThan(ids[1]!);+ const more = await engine.allocateBodyOccurrenceIds(1);+ expect(more[0]).toBeGreaterThan(ids[2]!);+ expect(await engine.allocateBodyOccurrenceIds(0)).toEqual([]);+ });+});++describe('segment texts', () => {+ test('dedupe per source and round-trip bytes exactly', async () => {+ const a = segmentText('alpha segment ☃ with a NUL \u0000 byte\n');+ const b = segmentText('beta segment\nsecond line\n');+ const c = segmentText('gamma segment\n');+ expect(await engine.stageSegmentTexts('default', [a, b])).toEqual({ inserted: 2 });+ expect(await engine.stageSegmentTexts('default', [a, c])).toEqual({ inserted: 1 });+ expect(await engine.stageSegmentTexts('other', [a])).toEqual({ inserted: 1 });+ const read = await engine.readSegmentTexts('default', [a.sha256, b.sha256, segmentText('never staged').sha256]);+ expect([...read.keys()].sort()).toEqual([hexOf(a.sha256), hexOf(b.sha256)].sort());+ expect(Buffer.from(read.get(hexOf(a.sha256))!).equals(Buffer.from(a.body))).toBe(true);+ expect(read.get(hexOf(b.sha256))).toBeInstanceOf(Uint8Array);+ expect(await engine.readSegmentTexts('default', [])).toEqual(new Map());+ });++ test('a stage larger than one statement batch inserts every text', async () => {+ const segmentBytes = 300 * 1024;+ const count = Math.ceil((STAGE_BATCH_BYTES.pglite * 2) / segmentBytes);+ const texts = Array.from({ length: count }, (_, i) => segmentText(`${i}:`.padEnd(segmentBytes, 'x')));+ expect(await engine.stageSegmentTexts('default', texts)).toEqual({ inserted: count });+ const read = await engine.readSegmentTexts('default', texts.map(t => t.sha256));+ expect(read.size).toBe(count);+ });+});++describe('manifest and flip', () => {+ test('a published page reads generation 1 in seq order; staged rows stay invisible until the flip', async () => {+ const t = [segmentText('# Intro\none\n'), segmentText('## Two\ntwo\n'), segmentText('## Three\nthree\n')];+ const page = await publishSegmentedPage(engine, 'notes/manifest-reads', t);+ const live = await engine.readManifest(page.pageId);+ expect(live.map(r => r.seq)).toEqual([0, 1, 2]);+ expect(live.map(r => r.genFrom)).toEqual([1, 1, 1]);+ expect(live.every(r => r.genTo === null && r.stagingId === null)).toBe(true);+ expect(hexOf(live[1]!.sha256)).toBe(hexOf(t[1]!.sha256));+ expect(live[0]!.entryState).toEqual({ fence: null, depth: 0, heading: ['Intro'] });+ expect(live[0]!.outline).toEqual([{ level: 2, text: 'Intro', byte: 0 }]);+ expect(live[0]!.dateMin).toBe('2026-01-02');++ const replacement = segmentText('## Three, edited\nthree!\n');+ const staged = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/manifest-reads', genFrom: 2, texts: [replacement] });+ await engine.executeRaw('UPDATE page_body_manifest SET seq = 2 WHERE staging_id = $1::uuid', [staged.stagingId]);+ expect((await engine.readManifest(page.pageId)).length).toBe(3);+ const stagedRows = await engine.readManifest(page.pageId, { stagingId: staged.stagingId });+ expect(stagedRows.map(r => r.occurrenceId)).toEqual(staged.occurrences);++ const before = await pageRow(page.pageId);+ const result = await engine.flipBodyGeneration(flipInput(page.pageId, 1, staged.stagingId, [t[0]!, t[1]!, replacement],+ { closeOccurrences: [page.occurrences[2]!], retireChunkOccurrences: [page.occurrences[2]!] }));+ expect(result).toEqual({ retiredChunks: 0, retireDeferred: false });+ const gen2 = await engine.readManifest(page.pageId);+ expect(gen2.map(r => r.occurrenceId)).toEqual([page.occurrences[0], page.occurrences[1], staged.occurrences[0]]);+ const gen1 = await engine.readManifest(page.pageId, { generation: 1 });+ expect(gen1.map(r => r.occurrenceId)).toEqual(page.occurrences);+ expect(gen1[2]!.genTo).toBe(2);+ const tail = await engine.readManifest(page.pageId, { region: 'truth', lastN: 2 });+ expect(tail.map(r => r.seq)).toEqual([1, 2]);+ expect(await engine.readManifest(page.pageId, { region: 'timeline' })).toEqual([]);++ const after = await pageRow(page.pageId);+ expect(after.body_generation).toBe(2);+ expect(after.compiled_truth).toBeNull();+ expect(after.timeline).toBeNull();+ expect(after.body_storage).toBe('segmented');+ expect(after.segment_count).toBe(3);+ expect(after.body_flags).toEqual({ has_fences: false, regions: ['truth'] });+ expect(after.generation).toBeGreaterThan(before.generation as number);+ expect(after.knowledge_revision).not.toBe(before.knowledge_revision);+ expect(String(after.search_vector)).toContain('zephyrwind');+ });++ test('a flip against a moved generation refuses revision_changed with a read fix and changes nothing', async () => {+ const t = [segmentText('# Moved\nbody\n')];+ const page = await publishSegmentedPage(engine, 'notes/flip-moved', t);+ const staged = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/flip-moved', genFrom: 2, texts: [segmentText('# Moved\nnew\n')] });+ const before = await pageRow(page.pageId);+ const err = await engine.flipBodyGeneration(flipInput(page.pageId, 0, staged.stagingId, t)).then(() => null, (e: unknown) => e);+ expect(err).toBeInstanceOf(OperationError);+ const op = err as OperationError;+ expect(op.canonical ?? op.code).toBe('revision_changed');+ expect(op.fix?.mcp).toEqual({ tool: 'get_page', arguments: { slug: 'notes/flip-moved', source_id: 'default', body: 'none' } });+ expect(JSON.parse(op.detail!)).toEqual({ expected_generation: 0, current_generation: 1 });+ expect(await pageRow(page.pageId)).toEqual(before);+ expect((await engine.readManifest(page.pageId, { stagingId: staged.stagingId })).length).toBe(1);+ const gone = await engine.flipBodyGeneration(flipInput(2_000_000_000, 0, staged.stagingId, t)).then(() => null, (e: unknown) => e);+ expect((gone as OperationError).code).toBe('page_identity_changed');+ expect(() => engine.flipBodyGeneration(flipInput(page.pageId, 1, staged.stagingId, t, { newGeneration: 3 }))).toThrow(TypeError);+ });++ test('retirement above retireMaxRows retires none and reports retireDeferred; within the bound it retires them', async () => {+ const t = [segmentText('# A\na\n'), segmentText('# B\nb\n'), segmentText('# C\nc\n')];+ const page = await publishSegmentedPage(engine, 'notes/flip-retire-bound', t, { chunkTexts: true });+ const replacement = [segmentText('# A2\na\n'), segmentText('# B2\nb\n'), segmentText('# C2\nc\n')];+ const staged = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/flip-retire-bound', genFrom: 2, texts: replacement, chunkTexts: true });+ const deferred = await engine.transaction(tx => tx.flipBodyGeneration(flipInput(page.pageId, 1, staged.stagingId, replacement,+ { closeOccurrences: page.occurrences, retireChunkOccurrences: page.occurrences, retireMaxRows: 2 })));+ expect(deferred).toEqual({ retiredChunks: 0, retireDeferred: true });+ const rows = await chunkRows(page.pageId);+ expect(rows.filter(r => r.body_generation === 1).every(r => r.retired_generation === null)).toBe(true);+ expect((await pageRow(page.pageId)).body_generation).toBe(2);++ const next = [segmentText('# A3\na\n')];+ const staged3 = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/flip-retire-bound', genFrom: 3, texts: next, chunkTexts: true });+ const retired = await engine.flipBodyGeneration(flipInput(page.pageId, 2, staged3.stagingId, next,+ { closeOccurrences: staged.occurrences, retireChunkOccurrences: [...page.occurrences, ...staged.occurrences], retireMaxRows: 6 }));+ expect(retired).toEqual({ retiredChunks: 6, retireDeferred: false });+ const after = await chunkRows(page.pageId);+ expect(after.filter(r => r.retired_generation === 3).length).toBe(6);+ expect(after.filter(r => r.retired_generation === null).map(r => r.occurrence_id)).toEqual(staged3.occurrences);+ });++ test('two preparers at one generation: the loser\'s staged chunk rows retire with the winner\'s flip', async () => {+ const t = [segmentText('# Race\nbase\n')];+ const page = await publishSegmentedPage(engine, 'notes/flip-two-stagings', t, { chunkTexts: true });+ const winner = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/flip-two-stagings', genFrom: 2, texts: [segmentText('# Race\nwinner\n')], chunkTexts: true });+ const loser = await stageGeneration(engine, { pageId: page.pageId, slug: 'notes/flip-two-stagings', genFrom: 2, texts: [segmentText('# Race\nloser\n')], chunkTexts: true });+ const result = await engine.flipBodyGeneration(flipInput(page.pageId, 1, winner.stagingId, [segmentText('# Race\nwinner\n')],+ { closeOccurrences: page.occurrences, retireChunkOccurrences: page.occurrences }));+ expect(result).toEqual({ retiredChunks: 2, retireDeferred: false });+ const rows = await chunkRows(page.pageId);+ const byOccurrence = new Map(rows.map(r => [r.occurrence_id, r]));+ expect(byOccurrence.get(winner.occurrences[0]!)?.retired_generation).toBeNull();+ expect(byOccurrence.get(loser.occurrences[0]!)?.retired_generation).toBe(2);+ expect(byOccurrence.get(page.occurrences[0]!)?.retired_generation).toBe(2);+ expect((await engine.readManifest(page.pageId)).map(r => r.occurrenceId)).toEqual(winner.occurrences);+ });++ test('promotion from inline retires the inline chunk rows (body_generation 0) and NULLs the body columns', async () => {+ await engine.putPage('notes/promote-inline', { type: 'note', title: 'Promote', compiled_truth: 'inline body', timeline: '' });+ const [{ id: pageId }] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = 'notes/promote-inline' AND source_id = 'default'");+ await engine.upsertChunks('notes/promote-inline', [{ chunk_index: 0, chunk_text: 'inline body', chunk_source: 'compiled_truth' }]);+ const t = [segmentText('# Promoted\nbody\n')];+ const staged = await stageGeneration(engine, { pageId, slug: 'notes/promote-inline', genFrom: 1, texts: t, chunkTexts: true });+ const result = await engine.flipBodyGeneration(flipInput(pageId, 0, staged.stagingId, t, { retireInlineChunks: true }));+ expect(result).toEqual({ retiredChunks: 1, retireDeferred: false });+ const rows = await chunkRows(pageId);+ expect(rows.map(r => [r.chunk_index, r.body_generation, r.retired_generation])).toEqual([[0, 0, 1], [1, 1, null]]);+ const page = await pageRow(pageId);+ expect([page.body_storage, page.compiled_truth, page.timeline, page.body_generation]).toEqual(['segmented', null, null, 1]);+ });+});++describe('stageSegmentChunks and the page shell', () => {+ test('chunk indexes continue past the page maximum and carry segment identity and generation', async () => {+ const t = [segmentText('# Chunks\nbody\n')];+ const page = await publishSegmentedPage(engine, 'notes/stage-chunks', t, { chunkTexts: true });+ const [occ] = await engine.allocateBodyOccurrenceIds(1);+ const vector = new Float32Array(await embeddingDims());+ vector[0] = 1;+ const indexes = await engine.stageSegmentChunks(page.pageId, 2, [chunk(occ!, 0, 'first staged'), { ...chunk(occ!, 1, 'second staged'), embedding: vector, model: 'test-model' }]);+ expect(indexes).toEqual([1, 2]);+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT chunk_index, local_ordinal, raw_byte_start::int AS raw_byte_start, raw_byte_end::int AS raw_byte_end,+ body_generation::int AS body_generation, embedding IS NULL AS no_vector, embedding_pending_since IS NOT NULL AS pending, embedded_at IS NOT NULL AS embedded,+ embedded_text_hash, model FROM content_chunks WHERE page_id = $1 AND occurrence_id = $2 ORDER BY chunk_index`, [page.pageId, occ]);+ expect(rows.map(r => [r.chunk_index, r.local_ordinal, r.body_generation, r.no_vector, r.pending, r.embedded])).toEqual([+ [1, 0, 2, true, true, false], [2, 1, 2, false, false, true]]);+ expect(rows[1]!.model).toBe('test-model');+ expect(rows[1]!.embedded_text_hash).not.toBeNull();+ expect([rows[0]!.raw_byte_start, rows[0]!.raw_byte_end]).toEqual([0, 'first staged'.length]);+ expect(await engine.stageSegmentChunks(page.pageId, 2, [])).toEqual([]);+ });++ test('createSegmentedPageShell inserts a segmented row at generation 0 with the meta columns', async () => {+ const { id } = await engine.createSegmentedPageShell('notes/shell-probe', { ...pageMeta('Shell'), source_path: 'notes/shell-probe.md', ingested_via: 'test' }, { sourceId: 'default' });+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT body_storage, body_generation::int AS g, body_bytes::int AS b, compiled_truth, timeline,+ title, frontmatter, source_path, ingested_via, ingested_at IS NOT NULL AS ingested FROM pages WHERE id = $1`, [id]);+ expect(rows[0]).toEqual({ body_storage: 'segmented', g: 0, b: 0, compiled_truth: null, timeline: null, title: 'Shell',+ frontmatter: { status: 'probe', nested: { a: 1 } }, source_path: 'notes/shell-probe.md', ingested_via: 'test', ingested: true });+ expect(() => engine.createSegmentedPageShell('../bad slug', pageMeta(), { sourceId: 'default' })).toThrow();+ });+});++describe('stagings', () => {+ test('openBodyStaging records the row; setBodyStagingState moves it and keeps the commit request id', async () => {+ const input = stagingInput({ slug: 'notes/staging-probe', declaredBytes: 12, declaredSha256: segmentText('x').sha256 });+ await engine.openBodyStaging(input);+ const read = async () => (await engine.executeRaw<Record<string, unknown>>(`SELECT state, kind, mode, declared_bytes::int AS declared,+ encode(declared_sha256, 'hex') AS sha, commit_request_id::text AS req FROM page_body_stagings WHERE id = $1::uuid`, [input.id]))[0];+ expect(await read()).toEqual({ state: 'open', kind: 'put', mode: 'create', declared: 12, sha: hexOf(input.declaredSha256!), req: null });+ const req = crypto.randomUUID();+ await engine.setBodyStagingState(input.id, 'committed', { commitRequestId: req });+ await engine.setBodyStagingState(input.id, 'committed');+ expect(await read()).toMatchObject({ state: 'committed', req });+ await expect(engine.openBodyStaging({ ...input, id: crypto.randomUUID() })).rejects.toThrow();+ });+});++describe('schema guards', () => {+ test('the body CHECK refuses an old-shape body write to a segmented page and a NULL body on an inline page', async () => {+ const page = await publishSegmentedPage(engine, 'notes/check-probe', [segmentText('# Check\nbody\n')]);+ await expect(engine.executeRaw("UPDATE pages SET compiled_truth = 'x' WHERE id = $1", [page.pageId])).rejects.toThrow(/pages_body_storage_chk/);+ await engine.putPage('notes/check-inline', { type: 'note', title: 'Inline', compiled_truth: 'inline', timeline: '' });+ await expect(engine.executeRaw("UPDATE pages SET compiled_truth = NULL WHERE slug = 'notes/check-inline'")).rejects.toThrow(/pages_body_storage_chk/);+ await expect(engine.executeRaw(`INSERT INTO page_versions (page_id, compiled_truth, body_storage) VALUES ($1, NULL, 'inline')`, [page.pageId])).rejects.toThrow(/page_versions_body_chk/);+ });++ test('a body_generation-only update moves generation and knowledge_revision and clears the projection seal', async () => {+ const page = await publishSegmentedPage(engine, 'notes/revision-probe', [segmentText('# Rev\nbody\n')]);+ await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE id = $1', [page.pageId]);+ const before = await pageRow(page.pageId);+ await engine.executeRaw('UPDATE pages SET body_generation = body_generation + 1 WHERE id = $1', [page.pageId]);+ const after = await pageRow(page.pageId);+ expect(after.generation).toBe((before.generation as number) + 1);+ expect(after.knowledge_revision).not.toBe(before.knowledge_revision);+ expect(after.text_projection_revision).toBeNull();+ });++ test('the page search vector trigger fires on a timeline_lead-only update', async () => {+ const page = await publishSegmentedPage(engine, 'notes/lead-probe', [segmentText('# Lead\nbody\n')]);+ await engine.executeRaw("UPDATE pages SET timeline_lead = 'quixotically renamed lead' WHERE id = $1", [page.pageId]);+ expect(String((await pageRow(page.pageId)).search_vector)).toContain('quixot');+ const [trigger] = await engine.executeRaw<{ cols: string }>(`SELECT string_agg(a.attname, ',' ORDER BY a.attname) AS cols FROM pg_trigger t+ JOIN pg_attribute a ON a.attrelid = t.tgrelid AND a.attnum = ANY(t.tgattr::int2[]) WHERE t.tgname = 'trg_pages_search_vector'`);+ expect(trigger!.cols).toBe('timeline,timeline_lead,title');+ });++ test('JSONB manifest and page columns are stored as objects and arrays, not strings', async () => {+ const page = await publishSegmentedPage(engine, 'notes/jsonb-probe', [segmentText('# Json\nbody\n')]);+ const [types] = await engine.executeRaw<Record<string, string>>(`SELECT jsonb_typeof(m.entry_state) AS entry_state, jsonb_typeof(m.protected_regions) AS protected_regions,+ jsonb_typeof(m.outline) AS outline, jsonb_typeof(p.body_flags) AS body_flags+ FROM page_body_manifest m JOIN pages p ON p.id = m.page_id WHERE m.page_id = $1`, [page.pageId]);+ expect(types).toEqual({ entry_state: 'object', protected_regions: 'array', outline: 'array', body_flags: 'object' });+ });+});++async function embeddingDims(): Promise<number> {+ const rows = await engine.executeRaw<{ dim: number }>(+ `SELECT atttypmod AS dim FROM pg_attribute WHERE attrelid = 'content_chunks'::regclass AND attname = 'embedding' AND attnum > 0`);+ return Number(rows[0]!.dim);+}diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 310c6239a7..23a1ea2299 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -205,6 +205,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -230,11 +247,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -446,9 +470,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -469,7 +493,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -477,7 +501,7 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -687,6 +711,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -714,6 +747,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -918,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1153,6 +1190,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1164,6 +1210,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1350,6 +1397,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1579,7 +1627,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2545,6 +2599,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2631,11 +2752,22 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2652,7 +2784,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2671,8 +2807,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2706,7 +2842,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3667,7 +3813,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3682,7 +3830,7 @@"pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex aab3a2b1b6..f9475c3c60 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -205,6 +205,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -230,11 +247,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -446,9 +470,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -469,7 +493,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -477,7 +501,7 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=991bcae3f032fbda5fabdb1276d77e51d324ce062c1785d966de6ecc92747335"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"},"grants": {"access_tokens": [@@ -687,6 +711,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -714,6 +747,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -918,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1153,6 +1190,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1164,6 +1210,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1350,6 +1397,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1579,7 +1627,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2545,6 +2599,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2631,11 +2752,22 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2652,7 +2784,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2671,8 +2807,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2706,7 +2842,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3667,7 +3813,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3682,7 +3830,7 @@"pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 64be9b2714..736e513026 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -205,6 +205,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -230,11 +247,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -446,9 +470,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -469,7 +493,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -477,7 +501,7 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -687,6 +711,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -714,6 +747,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -918,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1149,6 +1186,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1160,6 +1206,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1346,6 +1393,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1575,7 +1623,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2541,6 +2595,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2627,11 +2748,22 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2648,7 +2780,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2667,8 +2803,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2702,7 +2838,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3663,7 +3809,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3678,7 +3826,7 @@"pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex e118b680df..db1fbf7c1b 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -140,6 +140,23 @@"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -158,6 +175,11 @@"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)","page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -322,9 +344,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",@@ -334,9 +356,9 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -492,6 +514,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -513,6 +544,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -827,6 +861,15 @@"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)","page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -835,6 +878,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))",@@ -982,6 +1026,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1859,6 +1904,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -1920,6 +2032,17 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)",@@ -2693,6 +2816,8 @@"triggers": {"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()","pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()","pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex af34ede931..415ae0ec2c 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -140,6 +140,23 @@"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -158,6 +175,11 @@"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)","page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -322,9 +344,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",@@ -334,9 +356,9 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=991bcae3f032fbda5fabdb1276d77e51d324ce062c1785d966de6ecc92747335"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"},"grants": {"access_tokens": [@@ -492,6 +514,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -513,6 +544,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -827,6 +861,15 @@"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)","page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -835,6 +878,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))",@@ -982,6 +1026,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1859,6 +1904,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -1920,6 +2032,17 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)",@@ -2693,6 +2816,8 @@"triggers": {"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()","pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()","pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex 244b3cbc03..e508668395 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -140,6 +140,23 @@"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -158,6 +175,11 @@"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)","page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -322,9 +344,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",@@ -334,9 +356,9 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -492,6 +514,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -513,6 +544,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -826,6 +860,15 @@"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)","page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -834,6 +877,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))",@@ -981,6 +1025,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1858,6 +1903,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -1919,6 +2031,17 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)",@@ -2692,6 +2815,8 @@"triggers": {"minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()","pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()","pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 1f48a3a01e..d412cab007 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -151,6 +151,23 @@"open_loops.open_loops_pkey": "p PRIMARY KEY (id)","open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -169,6 +186,11 @@"page_purges.page_purges_pkey": "p PRIMARY KEY (source_id, content_hash)","page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)",@@ -331,9 +353,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_forget_page_retrievals()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=0f053c08f9d5a4512d10406f7b20b9c60ec43d9bbea48b28b7e4cf7187ee191b","gbrain_fts_input(t text)": "RETURNS text kind=f lang=sql volatility=i secdef=false config=[search_path=pg_catalog] body_sha256=c73d0dbc333c6dccc9714a6b8d1b7785f48170556b9024002ddca1c80b25d87d",@@ -343,11 +365,11 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -512,6 +534,15 @@"open_loops": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -530,6 +561,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -855,6 +889,15 @@"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)","open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)","open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -863,6 +906,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_coalesce_date_idx": "CREATE INDEX pages_coalesce_date_idx ON public.pages USING btree (COALESCE(effective_date, updated_at))",@@ -1003,6 +1047,7 @@"minion_jobs_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=minion_jobs.id","oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1928,6 +1973,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -1989,6 +2101,17 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)",@@ -2756,6 +2879,8 @@"content_chunks.chunk_search_vector_trigger": "CREATE TRIGGER chunk_search_vector_trigger BEFORE INSERT OR UPDATE OF chunk_text, doc_comment, symbol_name_qualified ON public.content_chunks FOR EACH ROW EXECUTE FUNCTION update_chunk_search_vector()","minion_jobs.minion_job_notify": "CREATE TRIGGER minion_job_notify AFTER INSERT OR UPDATE OF status ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION notify_minion_job_change()","minion_jobs.minion_queue_protocol": "CREATE TRIGGER minion_queue_protocol BEFORE INSERT OR UPDATE ON public.minion_jobs FOR EACH ROW EXECUTE FUNCTION enforce_minion_queue_protocol()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()","pages.bump_page_generation_trg": "CREATE TRIGGER bump_page_generation_trg BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION bump_page_generation_fn()","pages.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 088fd7662b..0f8b036ed5 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -209,6 +209,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -234,11 +251,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -450,9 +474,9 @@"functions": {"auto_enable_rls()": "RETURNS event_trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e5e0a0ee902f481f07da929c5fd39c2a16671869535b12a1e2270543a5a30eb","bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -472,7 +496,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -481,7 +505,7 @@"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -694,6 +718,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -721,6 +754,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -919,6 +955,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1157,6 +1194,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1168,6 +1214,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1352,6 +1399,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1580,7 +1628,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -2557,6 +2611,73 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2643,11 +2764,22 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2664,7 +2796,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -2683,8 +2819,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2718,7 +2854,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3654,7 +3800,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3666,7 +3814,7 @@"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()","pages.pages_refuse_purged": "CREATE TRIGGER pages_refuse_purged BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_page()","pages.pages_revision_attribution": "CREATE TRIGGER pages_revision_attribution BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_revision_attribution()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex a627a0db8e..e4814f326b 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -209,6 +209,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -234,11 +251,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -450,9 +474,9 @@"functions": {"auto_enable_rls()": "RETURNS event_trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e5e0a0ee902f481f07da929c5fd39c2a16671869535b12a1e2270543a5a30eb","bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -472,7 +496,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -481,7 +505,7 @@"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=991bcae3f032fbda5fabdb1276d77e51d324ce062c1785d966de6ecc92747335"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"},"grants": {"access_tokens": [@@ -694,6 +718,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -721,6 +754,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -919,6 +955,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1157,6 +1194,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1168,6 +1214,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1352,6 +1399,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1580,7 +1628,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -2557,6 +2611,73 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2643,11 +2764,22 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2664,7 +2796,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -2683,8 +2819,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2718,7 +2854,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3654,7 +3800,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3666,7 +3814,7 @@"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()","pages.pages_refuse_purged": "CREATE TRIGGER pages_refuse_purged BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_page()","pages.pages_revision_attribution": "CREATE TRIGGER pages_revision_attribution BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_revision_attribution()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 778c42c6e4..e1837fa723 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -209,6 +209,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -234,11 +251,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -450,9 +474,9 @@"functions": {"auto_enable_rls()": "RETURNS event_trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=5e5e0a0ee902f481f07da929c5fd39c2a16671869535b12a1e2270543a5a30eb","bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d3359bcd09cccd881585abd9eee81c3dcf4161d935164f7953f2e9fdef73ed3e",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=78059745996cfbb72586a2e0e161635b96a62a5db9d0be5c710f4d437d994431",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -472,7 +496,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -481,7 +505,7 @@"gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -694,6 +718,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -721,6 +754,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -919,6 +955,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1153,6 +1190,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1164,6 +1210,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1348,6 +1395,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1576,7 +1624,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -2553,6 +2607,73 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2639,11 +2760,22 @@],"flags": "relkind=r rls=true force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2660,7 +2792,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -2679,8 +2815,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2714,7 +2850,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},@@ -3650,7 +3796,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3662,7 +3810,7 @@"pages.pages_projection_queue": "CREATE TRIGGER pages_projection_queue AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_queue_page_projection()","pages.pages_refuse_purged": "CREATE TRIGGER pages_refuse_purged BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_page()","pages.pages_revision_attribution": "CREATE TRIGGER pages_revision_attribution BEFORE INSERT OR UPDATE ON public.pages FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_revision_attribution()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex abdfc2d495..f812dc4426 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 242,+ "count": 243,"gaps": [17,18,@@ -11,6 +11,7 @@"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0","BOUNDED_TIMELINE_CHECKPOINT": "385c4da3e28732343148795d6e9a86670813a7a7cfa1e52f8a5bb494680a3c0d","CHECKPOINT": "3c6ff909363c4ba1c9d730e748654ab90aa07549ddf4bf36b8f93c5f4ea3680b",+ "CONTENT_CHUNKS_OCCURRENCE_INDEX": "7b692ba777b30399ab5a3b100eb40b3b9d1b3fb2322dc4dc808ba8a4d667912c","FACT_PURGES_ALL_SUBJECTS_INDEX": "99e2eb6c24134b539cb4cfd6e5ff66a724463525d09e9ba1fdde3c13f5787b6c","FACT_PURGES_SUBJECT_INDEX": "f4fba07082f2e26da3fa51b0b689f3fe78a3d09afd20c1924dbc2fbe6b1560f1","FACT_RELINK_TABLE_SQL": "1fdde4b99d0077365274096f294be64a992961c7b4544af794224de238b03630",@@ -46,7 +47,7 @@"migrateConnectorCheckpoints": "e0403022a56559556c82a9fa1e90d928f36e1d09c7db570e1d788a87d2dc9521","migrateLegacyTokens": "6e4abe3670127e7a495b56ecbf9f5789edd3a7362d45704656c2210a85b27f4c","migrationNotice": "9a6607b26a9719ef1833571b137bc8ebfcd1e16d545e89ff8728cf3ccbcbb409",- "pageSearchVectorTriggerFnSql": "f9f083978d2a5cd756a889781ee07a921132c4db9d3cfa1b041da2af95a4a4b5",+ "pageSearchVectorTriggerFnSql": "c78074a731ae571c508ca0a84c6bb19ac34a933a7f4ab2068b47124aabb87435","quietMigrationNotices": "4045c32034a8f46204dd5d89e185ff5c35e8073f560f14caa8b127f8a695957c","readExistingEmbeddingShape": "16d92d7cd52d8ebd7e89982f02e1bbdd8e8d08a6712a4ce57fbcf0952b7a6ca5","repairLegacyClientGrants": "c1dc6b1d0c4933c041583aa1c4eacaefc0ff0ae2a67f56cfad7534f87a5ab309",@@ -56,7 +57,7 @@"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5","verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"},- "latest": 247,+ "latest": 248,"records": [{"handler": {@@ -2237,8 +2238,8 @@"idempotent": true,"name": "canonical_page_revisions_and_guards","sql": {- "length": 4724,- "sha256": "c04f8117c2e6c7b9d3c3328acd27f56aa0c2eeddcc32843bec7caf0fb5f9a29b"+ "length": 4945,+ "sha256": "abf706276e26714a3cb322ca1d99cc3cd939bc4b2414c35f5fdaf0e4812fb539"},"sqlFor": "absent","transaction": "absent",@@ -2250,8 +2251,8 @@"idempotent": true,"name": "durable_concurrent_persistence","sql": {- "length": 11791,- "sha256": "34fa2dd7def982037e8c04ef6914fe16e0c87f8d73927d99e3dd13b221697d75"+ "length": 12437,+ "sha256": "0127e709523d8c08a045edb74f69365cbcc4cd83f21e5bd78c4c681f528a8afc"},"sqlFor": "absent","transaction": "absent",@@ -2276,8 +2277,8 @@"idempotent": true,"name": "verified_text_projection_activation","sql": {- "length": 2545,- "sha256": "0ce686d328e43d51c806c62161ceafaf6724957fa1652a7b9855b3a4b9c0547f"+ "length": 2788,+ "sha256": "b968f743f66a2c0fe71da28a9a949c2a1404438942788de4d24f71840d7d86e9"},"sqlFor": "absent","transaction": "absent",@@ -2289,8 +2290,8 @@"idempotent": true,"name": "preserve_sanitized_page_search_vectors","sql": {- "length": 2109,- "sha256": "a03fa150bbe0f7a5414bbc15b644f4bc67ba1bbef1e16081f7b293de6f1968a4"+ "length": 2352,+ "sha256": "cdf64cada2597a3f367390136661a7ff699c7921b04e41df2e2c522394d8c8b1"},"sqlFor": "absent","transaction": "absent",@@ -2315,8 +2316,8 @@"idempotent": true,"name": "managed_alias_and_source_checkpoint_guards","sql": {- "length": 5632,- "sha256": "7cdd67f6734a0f3963b243420d4c0097700d756339e86b36dd8a19a39a20b0b2"+ "length": 6278,+ "sha256": "b4e6169bf100ed36973cececf7fa611f8c26f7b1995f0a085d8b7d76d74b5e77"},"sqlFor": "absent","transaction": "absent",@@ -2474,8 +2475,8 @@"idempotent": true,"name": "fact_embedding_identity","sql": {- "length": 5777,- "sha256": "9b2ba4919832da41e48e8688bb31c24ea2d27197b9143cde1077b7701621ea40"+ "length": 6423,+ "sha256": "f95330837bc60e5a73191a93e17d6503d7ef2d1ee294a861ff4c438e975facec"},"sqlFor": "absent","transaction": "absent",@@ -2873,8 +2874,8 @@"idempotent": true,"name": "take_embedding_identity","sql": {- "length": 5777,- "sha256": "f859485119a29379245109e95303a7de53584c023633f38d0287804138b00282"+ "length": 6423,+ "sha256": "739d2dfe3f5d4e0b68511a27478f877381aa2455af3389976e03974eebfc4240"},"sqlFor": "absent","transaction": "absent",@@ -2886,8 +2887,8 @@"idempotent": true,"name": "f1_write_attribution","sql": {- "length": 14623,- "sha256": "ad09591c350cddb3d863c3d36c8b6784b41dafc526cf9eb3023504eec7f8e1c6"+ "length": 15269,+ "sha256": "6ed235b09ce8b18a25cf065fa32321472485ad16b2af17f90e292d01881b3ead"},"sqlFor": "absent","transaction": "absent",@@ -2944,8 +2945,8 @@"idempotent": true,"name": "managed_guard_null_source_fallback","sql": {- "length": 5134,- "sha256": "6d014f2104fe4f938d470329a75320f13a1a0153f21076f315ba6c85e6f84d04"+ "length": 5738,+ "sha256": "bf17d089ce9f8473be13d541be18136e4f7b0ac12b68f8b2f7e87d5e5b396efc"},"sqlFor": "absent","transaction": "absent",@@ -2957,8 +2958,8 @@"idempotent": true,"name": "publication_failure_detail","sql": {- "length": 5225,- "sha256": "8e6bd0354bd0334b1dd3fb443c1a92d3e1397ffbf3162c4eea6dbd03fbf12da3"+ "length": 5829,+ "sha256": "00788e42366bb2dd3f546d1eb586b4ad5f1951f3f99abfaf71e82dfebccdd289"},"sqlFor": "absent","transaction": "absent",@@ -3387,8 +3388,8 @@"idempotent": true,"name": "trust_tiers","sql": {- "length": 21064,- "sha256": "e970169acfdd98bfc4b51d361522f0137341b67988d0db3cf4b1c0f7f9433eca"+ "length": 21668,+ "sha256": "f6cf6e708adf48bf130320153f8f8fe9308ca3f57b883b6b739840ff464f115b"},"sqlFor": "absent","transaction": "absent",@@ -3764,6 +3765,38 @@"transaction": "absent","verify": "absent","version": 247+ },+ {+ "handler": {+ "form": "arrow",+ "helpers": [+ "CONTENT_CHUNKS_OCCURRENCE_INDEX",+ "buildIndexOnline",+ "dropInvalidConcurrentIndex",+ "migrationNotice",+ "quietMigrationNotices"+ ],+ "sha256": "6ec7d293bcc8086bf46702b5f522519d7634db1451aa7f30fe5375da2484ccc1"+ },+ "idempotent": true,+ "name": "segmented_page_storage",+ "sql": {+ "length": 0,+ "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"+ },+ "sqlFor": {+ "pglite": {+ "length": 8386,+ "sha256": "3ae3ac5bb5ea2699157ca82f87fd83bad42f941304979a8f06c48b5c9f0c3c38"+ },+ "postgres": {+ "length": 8595,+ "sha256": "312f51807d49e623fe35dfae180c3f6e5a4dbefb6abf9fd83213938b8bb61bca"+ }+ },+ "transaction": false,+ "verify": "absent",+ "version": 248}],"versions": [@@ -4008,7 +4041,8 @@244,245,246,- 247+ 247,+ 248]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex c8d9d3e695..fc5cf85f94 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -205,6 +205,23 @@"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)","page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)","page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_cut_kind_check": "c CHECK ((cut_kind = ANY (ARRAY['heading'::text, 'day'::text, 'message'::text, 'blank'::text, 'forced'::text, 'region_end'::text, 'eof'::text])))",+ "page_body_manifest.page_body_manifest_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_manifest.page_body_manifest_pkey": "p PRIMARY KEY (page_id, occurrence_id, gen_from)",+ "page_body_manifest.page_body_manifest_region_check": "c CHECK ((region = ANY (ARRAY['truth'::text, 'timeline'::text])))",+ "page_body_manifest.page_body_manifest_source_id_sha256_fkey": "f FOREIGN KEY (source_id, sha256) REFERENCES page_segment_texts(source_id, sha256)",+ "page_body_staging_parts.page_body_staging_parts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 4194304)))",+ "page_body_staging_parts.page_body_staging_parts_part_no_check": "c CHECK ((part_no >= 0))",+ "page_body_staging_parts.page_body_staging_parts_pkey": "p PRIMARY KEY (staging_id, part_no)",+ "page_body_staging_parts.page_body_staging_parts_staging_id_fkey": "f FOREIGN KEY (staging_id) REFERENCES page_body_stagings(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_declared_bytes_check": "c CHECK ((declared_bytes >= 0))",+ "page_body_stagings.page_body_stagings_kind_check": "c CHECK ((kind = ANY (ARRAY['upload'::text, 'import'::text, 'sync'::text, 'put'::text, 'append'::text, 'edit'::text, 'resegment'::text])))",+ "page_body_stagings.page_body_stagings_mode_check": "c CHECK ((mode = ANY (ARRAY['create'::text, 'replace'::text, 'append'::text])))",+ "page_body_stagings.page_body_stagings_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_pkey": "p PRIMARY KEY (id)",+ "page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)",+ "page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))","page_embedding_budget.page_embedding_budget_cap_usd_check": "c CHECK (((cap_usd IS NULL) OR (cap_usd >= (0)::double precision)))","page_embedding_budget.page_embedding_budget_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_embedding_budget.page_embedding_budget_pkey": "p PRIMARY KEY (page_id)",@@ -230,11 +247,18 @@"page_purges.page_purges_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_purges.trust_generation_insert": "t TRIGGER DEFERRABLE INITIALLY DEFERRED","page_retrievals.page_retrievals_pkey": "p PRIMARY KEY (page_id)",+ "page_segment_texts.page_segment_texts_byte_len_check": "c CHECK (((byte_len >= 1) AND (byte_len <= 1048576)))",+ "page_segment_texts.page_segment_texts_line_count_check": "c CHECK ((line_count >= 0))",+ "page_segment_texts.page_segment_texts_pkey": "p PRIMARY KEY (source_id, sha256)",+ "page_segment_texts.page_segment_texts_sha256_check": "c CHECK ((octet_length(sha256) = 32))",+ "page_segment_texts.page_segment_texts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",+ "page_versions.page_versions_body_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_generation IS NOT NULL))))","page_versions.page_versions_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_versions.page_versions_pkey": "p PRIMARY KEY (id)","page_versions.page_versions_trust_tier_check": "c CHECK (((trust_tier IS NULL) OR (trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text]))))","page_write_guards.page_write_guards_pkey": "p PRIMARY KEY (source_incarnation, slug)","page_write_guards.page_write_guards_source_incarnation_fkey": "f FOREIGN KEY (source_incarnation) REFERENCES sources(incarnation) ON DELETE CASCADE",+ "pages.pages_body_storage_chk": "c CHECK ((((body_storage = 'inline'::text) AND (compiled_truth IS NOT NULL) AND (timeline IS NOT NULL) AND (truth_lead IS NULL)) OR ((body_storage = 'segmented'::text) AND (compiled_truth IS NULL) AND (timeline IS NULL) AND (body_bytes IS NOT NULL))))","pages.pages_page_kind_check": "c CHECK ((page_kind = ANY (ARRAY['markdown'::text, 'code'::text, 'image'::text])))","pages.pages_pkey": "p PRIMARY KEY (id)","pages.pages_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -446,9 +470,9 @@],"functions": {"bump_page_generation_clock_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c40a0a3b86e640b6c8979976173dd93ae92c8c1b9a9e3595cae2af1e265328fe",- "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c4135ae3f74177aa71313a6c73f22bda7a298bbf12435a8def390212ae11466a",+ "bump_page_generation_fn()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=314d4775d7c90f8ed650ea12ae3687f388f714ed3d30582dc8ff678dfea1dc97","enforce_minion_queue_protocol()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=be82640d1979fc81dc812efb78bb3596ef536f656d20750e5e4aa19016bf4784",- "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=ae793ff5263f7b76311e0c22593fb658db9f82e7b3781914421d9508b6da0e88",+ "gbrain_advance_page_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c0f3daff20ad45ba89d7cb5cc295156d36a4ebcfa30cb07ff19aaca91124a8d5","gbrain_advance_tag_revision()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7807b26b4933148aa63c67fca824a60d3492396728205d04e16c48c81174cbd5","gbrain_bump_trust_generation()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4708a89d166ac0999a8922ad8ee8f69fea3213c59e0782d96220f93b0c001a62","gbrain_clear_atom_page_state()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7db0ef05d1220a579e64428b2dd7cf5183191da186fbe64b6496433a7a713d11",@@ -469,7 +493,7 @@"gbrain_refuse_purged_fact()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d1d584b91ceea7f4e63c235b790ef89c958c578e635f77ddd644918bc36d33f1","gbrain_refuse_purged_page()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8aaaf7c22fc9acb4b1e84fe75f11ae6c889949b78de1ef6bdba1db54ef43844e","gbrain_refuse_purged_take()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4a291b0448ab7a31926aa482b5222e0595d31a6bfad81b851b13e4bf581a0d83",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d444fd431abe188062c7266caa9ab41327336c916805d7dd02a362affe2f26a7",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f29ded3a50b998bbe342052444996675f57ddf2de3fd786b2373015d35e6d859","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_snapshot_version_trust()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=7452350236ed4c68a6cd1f4d78a1381a4ef44cc70e8a032141f01bba4a704702","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",@@ -477,7 +501,7 @@"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10","gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2","update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",- "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=a2a8cb721548b59c270080ad486950ea523bb6331ab085e0d543e243f2999360"+ "update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"},"grants": {"access_tokens": [@@ -687,6 +711,15 @@"page_aliases": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_body_manifest": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_staging_parts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],+ "page_body_stagings": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_embedding_budget": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -714,6 +747,9 @@"page_retrievals": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "page_segment_texts": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"page_versions": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -918,6 +954,7 @@"code_traversal_cache_pkey": "CREATE UNIQUE INDEX code_traversal_cache_pkey ON public.code_traversal_cache USING btree (id)","code_traversal_cache_source_idx": "CREATE INDEX code_traversal_cache_source_idx ON public.code_traversal_cache USING btree (source_id)","config_pkey": "CREATE UNIQUE INDEX config_pkey ON public.config USING btree (key)",+ "content_chunks_occurrence_idx": "CREATE INDEX content_chunks_occurrence_idx ON public.content_chunks USING btree (page_id, occurrence_id) WHERE (occurrence_id IS NOT NULL)","content_chunks_pkey": "CREATE UNIQUE INDEX content_chunks_pkey ON public.content_chunks USING btree (id)","content_chunks_stale_idx": "CREATE INDEX content_chunks_stale_idx ON public.content_chunks USING btree (page_id, chunk_index) WHERE (embedding IS NULL)","context_volunteer_events_pkey": "CREATE UNIQUE INDEX context_volunteer_events_pkey ON public.context_volunteer_events USING btree (id)",@@ -1153,6 +1190,15 @@"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)","page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)","page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",+ "page_body_manifest_live_bytes": "CREATE INDEX page_body_manifest_live_bytes ON public.page_body_manifest USING btree (page_id, byte_start) WHERE (gen_to IS NULL)",+ "page_body_manifest_live_seq": "CREATE UNIQUE INDEX page_body_manifest_live_seq ON public.page_body_manifest USING btree (page_id, seq) WHERE ((gen_to IS NULL) AND (staging_id IS NULL))",+ "page_body_manifest_pkey": "CREATE UNIQUE INDEX page_body_manifest_pkey ON public.page_body_manifest USING btree (page_id, occurrence_id, gen_from)",+ "page_body_manifest_staging": "CREATE INDEX page_body_manifest_staging ON public.page_body_manifest USING btree (staging_id) WHERE (staging_id IS NOT NULL)",+ "page_body_manifest_text": "CREATE INDEX page_body_manifest_text ON public.page_body_manifest USING btree (source_id, sha256)",+ "page_body_staging_parts_pkey": "CREATE UNIQUE INDEX page_body_staging_parts_pkey ON public.page_body_staging_parts USING btree (staging_id, part_no)",+ "page_body_stagings_expiry": "CREATE INDEX page_body_stagings_expiry ON public.page_body_stagings USING btree (hard_expires_at) WHERE (state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text]))",+ "page_body_stagings_pkey": "CREATE UNIQUE INDEX page_body_stagings_pkey ON public.page_body_stagings USING btree (id)",+ "page_body_stagings_principal_kind_principal_id_client_reque_key": "CREATE UNIQUE INDEX page_body_stagings_principal_kind_principal_id_client_reque_key ON public.page_body_stagings USING btree (principal_kind, principal_id, client_request_id)","page_embedding_budget_pkey": "CREATE UNIQUE INDEX page_embedding_budget_pkey ON public.page_embedding_budget USING btree (page_id)","page_embedding_budget_state_idx": "CREATE INDEX page_embedding_budget_state_idx ON public.page_embedding_budget USING btree (state) WHERE (state <> 'open'::text)","page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",@@ -1164,6 +1210,7 @@"page_projection_jobs_pkey": "CREATE UNIQUE INDEX page_projection_jobs_pkey ON public.page_projection_jobs USING btree (source_incarnation, slug)","page_purges_pkey": "CREATE UNIQUE INDEX page_purges_pkey ON public.page_purges USING btree (source_id, content_hash)","page_retrievals_pkey": "CREATE UNIQUE INDEX page_retrievals_pkey ON public.page_retrievals USING btree (page_id)",+ "page_segment_texts_pkey": "CREATE UNIQUE INDEX page_segment_texts_pkey ON public.page_segment_texts USING btree (source_id, sha256)","page_versions_pkey": "CREATE UNIQUE INDEX page_versions_pkey ON public.page_versions USING btree (id)","page_write_guards_pkey": "CREATE UNIQUE INDEX page_write_guards_pkey ON public.page_write_guards USING btree (source_incarnation, slug)","pages_atom_source_hash_idx": "CREATE INDEX pages_atom_source_hash_idx ON public.pages USING btree (((frontmatter ->> 'source_hash'::text))) WHERE ((type = 'atom'::text) AND (deleted_at IS NULL))",@@ -1350,6 +1397,7 @@"oauth_grant_audit_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=oauth_grant_audit.id","open_loops_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=open_loops.id","page_aliases_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=page_aliases.id",+ "page_body_occurrence_id_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_generation_clock_seq": "bigint start=1 min=1 max=9223372036854775807 increment=1 cycle=false cache=1 owned_by=-","page_versions_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=page_versions.id","pages_id_seq": "integer start=1 min=1 max=2147483647 increment=1 cycle=false cache=1 owned_by=pages.id",@@ -1579,7 +1627,13 @@"25 edges_backfilled_at timestamp with time zone/timestamptz NULL","26 embedding_pending_since timestamp with time zone/timestamptz NULL","27 projected_byte_start bigint/int8 NULL",- "28 projected_byte_end bigint/int8 NULL"+ "28 projected_byte_end bigint/int8 NULL",+ "29 occurrence_id bigint/int8 NULL",+ "30 local_ordinal integer/int4 NULL",+ "31 raw_byte_start bigint/int8 NULL",+ "32 raw_byte_end bigint/int8 NULL",+ "33 body_generation bigint/int8 NULL",+ "34 retired_generation bigint/int8 NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2545,6 +2599,73 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_body_manifest": {+ "columns": [+ "1 page_id integer/int4 NOT NULL",+ "2 occurrence_id bigint/int8 NOT NULL",+ "3 gen_from bigint/int8 NOT NULL",+ "4 gen_to bigint/int8 NULL",+ "5 seq integer/int4 NOT NULL",+ "6 region text/text NOT NULL",+ "7 source_id text/text NOT NULL",+ "8 sha256 bytea/bytea NOT NULL",+ "9 byte_start bigint/int8 NOT NULL",+ "10 byte_len integer/int4 NOT NULL",+ "11 line_start bigint/int8 NOT NULL",+ "12 line_count integer/int4 NOT NULL",+ "13 cut_kind text/text NOT NULL",+ "14 entry_state jsonb/jsonb NOT NULL",+ "15 protected_regions jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "16 facts_slots jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "17 static_proj_bytes bigint/int8 NOT NULL",+ "18 static_proj_lines integer/int4 NOT NULL",+ "19 outline jsonb/jsonb NOT NULL DEFAULT '[]'::jsonb",+ "20 date_min date/date NULL",+ "21 date_max date/date NULL",+ "22 hash_state bytea/bytea NOT NULL",+ "23 staging_id uuid/uuid NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_staging_parts": {+ "columns": [+ "1 staging_id uuid/uuid NOT NULL",+ "2 part_no integer/int4 NOT NULL",+ "3 byte_start bigint/int8 NOT NULL",+ "4 byte_len integer/int4 NOT NULL",+ "5 sha256 bytea/bytea NOT NULL",+ "6 body bytea/bytea NOT NULL"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },+ "page_body_stagings": {+ "columns": [+ "1 id uuid/uuid NOT NULL",+ "2 kind text/text NOT NULL",+ "3 principal_kind text/text NOT NULL",+ "4 principal_id text/text NOT NULL",+ "5 client_request_id uuid/uuid NOT NULL",+ "6 source_id text/text NOT NULL",+ "7 source_incarnation uuid/uuid NOT NULL",+ "8 slug text/text NOT NULL",+ "9 page_id integer/int4 NULL",+ "10 mode text/text NOT NULL",+ "11 base_revision uuid/uuid NULL",+ "12 base_generation bigint/int8 NULL",+ "13 declared_bytes bigint/int8 NOT NULL",+ "14 declared_sha256 bytea/bytea NULL",+ "15 received_bytes bigint/int8 NOT NULL DEFAULT 0",+ "16 next_part integer/int4 NOT NULL DEFAULT 0",+ "17 reserved_bytes bigint/int8 NOT NULL",+ "18 state text/text NOT NULL DEFAULT 'open'::text",+ "19 commit_request_id uuid/uuid NULL",+ "20 idle_expires_at timestamp with time zone/timestamptz NOT NULL",+ "21 hard_expires_at timestamp with time zone/timestamptz NOT NULL",+ "22 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",+ "23 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_embedding_budget": {"columns": ["1 page_id integer/int4 NOT NULL",@@ -2631,11 +2752,22 @@],"flags": "relkind=r rls=false force_rls=false"},+ "page_segment_texts": {+ "columns": [+ "1 source_id text/text NOT NULL",+ "2 sha256 bytea/bytea NOT NULL",+ "3 byte_len integer/int4 NOT NULL",+ "4 line_count integer/int4 NOT NULL",+ "5 body bytea/bytea NOT NULL",+ "6 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=false force_rls=false"+ },"page_versions": {"columns": ["1 id integer/int4 NOT NULL DEFAULT nextval('page_versions_id_seq'::regclass)","2 page_id integer/int4 NOT NULL",- "3 compiled_truth text/text NOT NULL",+ "3 compiled_truth text/text NULL","4 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","5 snapshot_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()","6 knowledge_revision uuid/uuid NULL",@@ -2652,7 +2784,11 @@"17 archived_principal_kind text/text NULL","18 archived_principal_id text/text NULL","19 trust_tier text/text NULL",- "20 write_origin jsonb/jsonb NULL"+ "20 write_origin jsonb/jsonb NULL",+ "21 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "22 body_generation bigint/int8 NULL",+ "23 body_bytes bigint/int8 NULL",+ "24 content_hash text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -2671,8 +2807,8 @@"4 type text/text NOT NULL","5 page_kind text/text NOT NULL DEFAULT 'markdown'::text","6 title text/text NOT NULL",- "7 compiled_truth text/text NOT NULL DEFAULT ''::text",- "8 timeline text/text NOT NULL DEFAULT ''::text",+ "7 compiled_truth text/text NULL DEFAULT ''::text",+ "8 timeline text/text NULL DEFAULT ''::text","9 frontmatter jsonb/jsonb NOT NULL DEFAULT '{}'::jsonb","10 content_hash text/text NULL","11 emotional_weight real/float4 NOT NULL DEFAULT 0.0",@@ -2706,7 +2842,17 @@"39 revision_principal_kind text/text NULL","40 revision_principal_id text/text NULL","41 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",- "42 write_origin jsonb/jsonb NULL"+ "42 write_origin jsonb/jsonb NULL",+ "43 body_storage text/text NOT NULL DEFAULT 'inline'::text",+ "44 body_bytes bigint/int8 NULL",+ "45 truth_bytes bigint/int8 NULL",+ "46 body_lines bigint/int8 NULL",+ "47 body_generation bigint/int8 NOT NULL DEFAULT 0",+ "48 segment_count integer/int4 NULL",+ "49 segmenter_version integer/int4 NULL",+ "50 body_flags jsonb/jsonb NULL",+ "51 truth_lead text/text NULL",+ "52 timeline_lead text/text NULL"],"flags": "relkind=r rls=false force_rls=false"},@@ -3667,7 +3813,9 @@"needs_rederive.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.needs_rederive DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()","oauth_clients.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.oauth_clients DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((old.min_trust IS DISTINCT FROM new.min_trust)) EXECUTE FUNCTION gbrain_bump_trust_generation()","page_aliases.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_aliases FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()",+ "page_body_manifest.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_body_manifest FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_purges.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.page_purges DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (true) EXECUTE FUNCTION gbrain_bump_trust_generation()",+ "page_segment_texts.managed_writer_guard": "CREATE TRIGGER managed_writer_guard BEFORE INSERT OR DELETE OR UPDATE ON public.page_segment_texts FOR EACH ROW EXECUTE FUNCTION gbrain_require_managed_writer()","page_versions.page_versions_trust_snapshot": "CREATE TRIGGER page_versions_trust_snapshot BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_snapshot_version_trust()","page_versions.page_versions_write_attribution": "CREATE TRIGGER page_versions_write_attribution BEFORE INSERT ON public.page_versions FOR EACH ROW EXECUTE FUNCTION gbrain_stamp_version_attribution()","pages.bump_page_generation_clock_trg": "CREATE TRIGGER bump_page_generation_clock_trg AFTER INSERT OR DELETE OR UPDATE ON public.pages FOR EACH STATEMENT EXECUTE FUNCTION bump_page_generation_clock_fn()",@@ -3682,7 +3830,7 @@"pages.planner_stats_del": "CREATE TRIGGER planner_stats_del AFTER DELETE ON public.pages REFERENCING OLD TABLE AS old_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_ins": "CREATE TRIGGER planner_stats_ins AFTER INSERT ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()","pages.planner_stats_upd": "CREATE TRIGGER planner_stats_upd AFTER UPDATE ON public.pages REFERENCING NEW TABLE AS new_rows FOR EACH STATEMENT EXECUTE FUNCTION gbrain_count_modifications()",- "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()",+ "pages.trg_pages_search_vector": "CREATE TRIGGER trg_pages_search_vector BEFORE INSERT OR UPDATE OF title, timeline, timeline_lead ON public.pages FOR EACH ROW EXECUTE FUNCTION update_page_search_vector()","pages.trust_generation_delete": "CREATE CONSTRAINT TRIGGER trust_generation_delete AFTER DELETE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_insert": "CREATE CONSTRAINT TRIGGER trust_generation_insert AFTER INSERT ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) EXECUTE FUNCTION gbrain_bump_trust_generation()","pages.trust_generation_update": "CREATE CONSTRAINT TRIGGER trust_generation_update AFTER UPDATE ON public.pages DEFERRABLE INITIALLY DEFERRED FOR EACH ROW WHEN (((old.trust_tier IS DISTINCT FROM new.trust_tier) OR ((COALESCE(old.frontmatter, '{}'::jsonb) ? 'quarantine'::text) IS DISTINCT FROM (COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text)) OR ((COALESCE(new.frontmatter, '{}'::jsonb) ? 'quarantine'::text) AND (((old.deleted_at IS DISTINCT FROM new.deleted_at) OR (old.source_id IS DISTINCT FROM new.source_id)) OR (old.slug IS DISTINCT FROM new.slug))))) EXECUTE FUNCTION gbrain_bump_trust_generation()",diff --git a/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json b/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.jsonindex d958cfebbe..ea7bd0867c 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/repeat-boot-recreated-objects.json@@ -3,6 +3,8 @@"trg:facts.managed_writer_guard","trg:minion_jobs.minion_queue_protocol","trg:page_aliases.managed_writer_guard",+ "trg:page_body_manifest.managed_writer_guard",+ "trg:page_segment_texts.managed_writer_guard","trg:pages.bump_page_generation_clock_trg","trg:pages.bump_page_generation_trg","trg:pages.managed_writer_guard",diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 680a6d2133..546fcc9dee 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -3593,6 +3593,7 @@"addTakesBatch": "none","addTimelineEntriesBatch": "none","addTimelineEntry": "none",+ "allocateBodyOccurrenceIds": "none","applyForwardReferenceBootstrap": "none","batchLoadEmotionalInputs": "none","batchRetry": "none",@@ -3606,6 +3607,7 @@"countStalePagesForExtraction": "direct","countStaleTakes": "none","countUnconsolidatedFacts": "none",+ "createSegmentedPageShell": "none","createVersion": "none","deleteChunks": "none","deleteCodeEdgesForChunks": "none",@@ -3630,6 +3632,7 @@"findOntologyConflicts": "none","findOrphanPages": "none","findTrajectory": "none",+ "flipBodyGeneration": "none","getAdjacencyBoosts": "none","getAllConfig": "none","getAllSlugs": "direct",@@ -3714,14 +3717,17 @@"mergeOntologyFact": "none","migrateFactsToCanonical": "none","onCheckout": "none",+ "openBodyStaging": "none","purgeDeletedPages": "none","putContradictionCacheEntry": "none","putDreamVerdict": "none","putPage": "none","putRawData": "none","readEmbeddingStateCounts": "direct",+ "readManifest": "none","readPageSnapshot": "direct","readPageSnapshotsBatch": "direct",+ "readSegmentTexts": "none","reconnect": "none","refreshPageBody": "none","registerBeforeDisconnect": "none",@@ -3753,6 +3759,7 @@"searchTakesVector": "none","searchTitles": "direct","searchVector": "direct",+ "setBodyStagingState": "none","setConfig": "none","setEmotionalWeightBatch": "none","setPageAliases": "none",@@ -3760,11 +3767,15 @@"softDeletePage": "none","softDeletePages": "none","sql": "none",+ "stageManifestRows": "none",+ "stageSegmentChunks": "none",+ "stageSegmentTexts": "none","stripStaleFrontmatterKeys": "none","sumStaleChunkChars": "none","supersedeTake": "none","sweepContradictionCache": "none","sweepDreamVerdicts": "none",+ "sweepSegments": "none","transaction": "none","transactionDirect": "none","transactionOn": "none",diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 1e55c04f69..9c65c39233 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 124, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });+ expect(counts).toEqual({ carry: 128, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });diff --git a/test/helpers/engine-sql-rollback-cases.ts b/test/helpers/engine-sql-rollback-cases.tsindex 46a2491660..5ff4993fdb 100644--- a/test/helpers/engine-sql-rollback-cases.ts+++ b/test/helpers/engine-sql-rollback-cases.ts@@ -20,6 +20,7 @@ import { invalidateStaleSignatureEmbeddingsGuarded } from '../../src/core/embeddimport { reconcileContextualEmbeddingInputs } from '../../src/core/page-state/contextual-proof.ts';import { installPageProjection, readProjectionSnapshot } from '../../src/core/page-state/projections.ts';import { installFixtureChunks } from './page-projection.ts';+import { chunk, flipInput, hexOf, manifestRow, pageMeta, publishSegmentedPage, segmentText, stageGeneration, stagingInput } from './page-body-fixtures.ts';export interface RollbackCase {domain: string;@@ -364,8 +365,135 @@ export const ROLLBACK_CASES: RollbackCase[] = [return (await engine.getTimeline(SLUG, { sourceId: 'default' })).map((e) => e.summary).sort();},},+ {+ domain: 'page-body (stageSegmentTexts)',+ async seed(engine) { await seedSegmentedPage(engine, SEGMENTED_SLUG); },+ async write(tx) { expect(await tx.stageSegmentTexts('default', [ROLLBACK_TEXT])).toEqual({ inserted: 1 }); },+ observe: engine => segmentTextExists(engine, ROLLBACK_TEXT),+ },+ {+ domain: 'page-body (stageManifestRows)',+ async seed(engine) {+ await seedSegmentedPage(engine, SEGMENTED_SLUG);+ await engine.stageSegmentTexts('default', [MANIFEST_TEXT]);+ await seedStaging(engine, MANIFEST_STAGING_ID);+ },+ async write(tx) {+ const [occurrenceId] = await tx.allocateBodyOccurrenceIds(1);+ await tx.stageManifestRows([manifestRow({ pageId: await segmentedPageId(tx, SEGMENTED_SLUG), occurrenceId: occurrenceId!, genFrom: 2, seq: 0,+ text: MANIFEST_TEXT, byteStart: 0, stagingId: MANIFEST_STAGING_ID })]);+ },+ async observe(engine) { return (await engine.readManifest(await segmentedPageId(engine, SEGMENTED_SLUG), { stagingId: MANIFEST_STAGING_ID })).length; },+ },+ {+ domain: 'page-body (stageSegmentChunks)',+ async seed(engine) { await seedSegmentedPage(engine, SEGMENTED_SLUG); },+ async write(tx) {+ const [occurrenceId] = await tx.allocateBodyOccurrenceIds(1);+ await tx.stageSegmentChunks(await segmentedPageId(tx, SEGMENTED_SLUG), 99, [chunk(occurrenceId!, 0, 'rolled-back staged chunk')]);+ },+ async observe(engine) {+ const rows = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM content_chunks WHERE page_id = $1 AND body_generation = 99',+ [await segmentedPageId(engine, SEGMENTED_SLUG)]);+ return Number(rows[0]?.n ?? 0);+ },+ },+ {+ domain: 'page-body (createSegmentedPageShell)',+ async seed() {},+ async write(tx) { await tx.createSegmentedPageShell(SHELL_SLUG, pageMeta(), { sourceId: 'default' }); },+ async observe(engine) {+ const rows = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM pages WHERE slug = $1 AND source_id = 'default'", [SHELL_SLUG]);+ return Number(rows[0]?.n ?? 0);+ },+ },+ {+ domain: 'page-body (flipBodyGeneration)',+ async seed(engine) {+ await seedSegmentedPage(engine, FLIP_SLUG);+ const pageId = await segmentedPageId(engine, FLIP_SLUG);+ if (await openStagingOf(engine, FLIP_SLUG)) return;+ await stageGeneration(engine, { pageId, slug: FLIP_SLUG, genFrom: 2, texts: [FLIP_TEXT] });+ },+ async write(tx) {+ const pageId = await segmentedPageId(tx, FLIP_SLUG);+ const live = await tx.readManifest(pageId);+ expect(await tx.flipBodyGeneration(flipInput(pageId, 1, (await openStagingOf(tx, FLIP_SLUG))!, [FLIP_TEXT],+ { closeOccurrences: live.map(r => r.occurrenceId) }))).toEqual({ retiredChunks: 0, retireDeferred: false });+ },+ async observe(engine) {+ const rows = await engine.executeRaw<{ g: number }>("SELECT body_generation::int AS g FROM pages WHERE slug = $1 AND source_id = 'default'", [FLIP_SLUG]);+ return Number(rows[0]?.g ?? -1);+ },+ },+ {+ domain: 'page-body (openBodyStaging)',+ async seed(engine) { await seedSegmentedPage(engine, SEGMENTED_SLUG); },+ async write(tx) { await tx.openBodyStaging(stagingInput({ id: OPENED_STAGING_ID, slug: SEGMENTED_SLUG })); },+ observe: engine => stagingState(engine, OPENED_STAGING_ID),+ },+ {+ domain: 'page-body (setBodyStagingState)',+ async seed(engine) { await seedStaging(engine, STATE_STAGING_ID); },+ async write(tx) { await tx.setBodyStagingState(STATE_STAGING_ID, 'aborted'); },+ observe: engine => stagingState(engine, STATE_STAGING_ID),+ },+ {+ domain: 'page-body (sweepSegments)',+ async seed(engine) {+ await seedSegmentedPage(engine, SEGMENTED_SLUG);+ await engine.stageSegmentTexts('default', [ORPHAN_TEXT]);+ await engine.executeRaw("UPDATE page_segment_texts SET created_at = now() - interval '2 hours' WHERE source_id = 'default' AND sha256 = decode($1, 'hex')",+ [hexOf(ORPHAN_TEXT.sha256)]);+ },+ async write(tx) {+ expect((await tx.sweepSegments({ pageId: await segmentedPageId(tx, SEGMENTED_SLUG) })).textsDeleted).toBeGreaterThanOrEqual(1);+ },+ observe: engine => segmentTextExists(engine, ORPHAN_TEXT),+ },];+const SEGMENTED_SLUG = 'notes/engine-sql-rollback-segmented-alice-example';+const FLIP_SLUG = 'notes/engine-sql-rollback-flip-alice-example';+const SHELL_SLUG = 'notes/engine-sql-rollback-shell-alice-example';+const ROLLBACK_TEXT = segmentText('# Rollback\nstaged text that never commits\n');+const MANIFEST_TEXT = segmentText('# Rollback\nmanifest probe text\n');+const FLIP_TEXT = segmentText('# Rollback\nflipped body\n');+const ORPHAN_TEXT = segmentText('# Rollback\nunreferenced aged text\n');+const MANIFEST_STAGING_ID = '6d1f1c2a-8b6e-4a59-9c39-2f0b6d4a0001';+const OPENED_STAGING_ID = '6d1f1c2a-8b6e-4a59-9c39-2f0b6d4a0002';+const STATE_STAGING_ID = '6d1f1c2a-8b6e-4a59-9c39-2f0b6d4a0003';++async function segmentedPageId(engine: BrainEngine, slug: string): Promise<number> {+ const rows = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = $1 AND source_id = 'default'", [slug]);+ return Number(rows[0]?.id ?? 0);+}++async function seedSegmentedPage(engine: BrainEngine, slug: string): Promise<void> {+ if (await segmentedPageId(engine, slug)) return;+ await publishSegmentedPage(engine, slug, [segmentText(`# ${slug}\nbase body\n`)]);+}++async function seedStaging(engine: BrainEngine, id: string): Promise<void> {+ await seedSegmentedPage(engine, SEGMENTED_SLUG);+ if (await stagingState(engine, id)) return;+ await engine.openBodyStaging(stagingInput({ id, slug: SEGMENTED_SLUG, pageId: await segmentedPageId(engine, SEGMENTED_SLUG) }));+}++async function stagingState(engine: BrainEngine, id: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id = $1::uuid', [id]);+ return rows[0]?.state ?? null;+}++async function openStagingOf(engine: BrainEngine, slug: string): Promise<string | null> {+ const rows = await engine.executeRaw<{ id: string }>("SELECT id::text AS id FROM page_body_stagings WHERE slug = $1 AND state = 'open' ORDER BY created_at LIMIT 1", [slug]);+ return rows[0]?.id ?? null;+}++async function segmentTextExists(engine: BrainEngine, text: { sha256: Uint8Array }): Promise<boolean> {+ return (await engine.readSegmentTexts('default', [text.sha256])).has(hexOf(text.sha256));+}+async function chunkTexts(engine: BrainEngine): Promise<string[]> {const rows = await engine.executeRaw<{ t: string }>(`SELECT cc.chunk_text AS t FROM content_chunks cc JOIN pages p ON p.id = cc.page_iddiff --git a/test/helpers/page-body-fixtures.ts b/test/helpers/page-body-fixtures.tsnew file mode 100644index 0000000000..8f63c17c7d--- /dev/null+++ b/test/helpers/page-body-fixtures.ts@@ -0,0 +1,100 @@+/**+ * Builders for segmented page storage tests (engine-sql/page-body.ts): segment+ * texts with their sha256, manifest rows, stagings, page metadata and body+ * columns, plus a one-call publish of a segmented page at generation 1.+ */+import { createHash, randomUUID } from 'crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { BodyFlipInput, BodyRegion, BodyStagingInput, ManifestRowInput, SegmentChunkInput, SegmentedBodyColumns,+ SegmentedPageMeta, SegmentTextInput } from '../../src/core/page-body/types.ts';+import { BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, DEFAULT_FLIP_RETIRE_MAX_ROWS } from '../../src/core/page-body/limits.ts';++export const sha256 = (body: Uint8Array | string): Uint8Array => new Uint8Array(createHash('sha256').update(body).digest());+export const hexOf = (bytes: Uint8Array): string => Buffer.from(bytes).toString('hex');++export function segmentText(text: string): SegmentTextInput {+ const body = new TextEncoder().encode(text);+ return { sha256: sha256(body), body, lineCount: text.split('\n').length - (text.endsWith('\n') ? 1 : 0) };+}++export function manifestRow(input: { pageId: number; occurrenceId: number; genFrom: number; seq: number; text: SegmentTextInput;+ byteStart: number; stagingId: string | null; region?: BodyRegion; sourceId?: string; lineStart?: number }): ManifestRowInput {+ return {+ pageId: input.pageId, occurrenceId: input.occurrenceId, genFrom: input.genFrom, seq: input.seq, region: input.region ?? 'truth',+ sourceId: input.sourceId ?? 'default', sha256: input.text.sha256, byteStart: input.byteStart, byteLen: input.text.body.byteLength,+ lineStart: input.lineStart ?? 0, lineCount: input.text.lineCount, cutKind: 'heading',+ entryState: { fence: null, depth: 0, heading: ['Intro'] }, protectedRegions: [{ kind: 'facts', start: 0, end: 4 }],+ factsSlots: [], staticProjBytes: input.text.body.byteLength, staticProjLines: input.text.lineCount,+ outline: [{ level: 2, text: 'Intro', byte: 0 }], dateMin: '2026-01-02', dateMax: '2026-01-03',+ hashState: sha256(`state:${input.occurrenceId}:${input.genFrom}`), stagingId: input.stagingId,+ };+}++export function stagingInput(overrides: Partial<BodyStagingInput> & { slug: string }): BodyStagingInput {+ const now = Date.now();+ return {+ id: randomUUID(), kind: 'put', principalKind: 'local', principalId: 'test', clientRequestId: randomUUID(), sourceId: 'default',+ sourceIncarnation: randomUUID(), pageId: null, mode: 'create', baseRevision: null, baseGeneration: null, declaredBytes: 0,+ declaredSha256: null, reservedBytes: 0, idleExpiresAt: new Date(now + BODY_STAGING_IDLE_MS), hardExpiresAt: new Date(now + BODY_STAGING_HARD_MS),+ ...overrides,+ };+}++export const pageMeta = (title = 'Segmented probe'): SegmentedPageMeta => ({ type: 'note', title, frontmatter: { status: 'probe', nested: { a: 1 } } });++export function bodyColumns(texts: readonly SegmentTextInput[], overrides: Partial<SegmentedBodyColumns> = {}): SegmentedBodyColumns {+ const bytes = texts.reduce((n, t) => n + t.body.byteLength, 0);+ return {+ content_hash: hexOf(sha256(texts.map(t => new TextDecoder().decode(t.body)).join(''))), body_bytes: bytes, truth_bytes: bytes,+ body_lines: texts.reduce((n, t) => n + t.lineCount, 0), segment_count: texts.length, segmenter_version: 1,+ truth_lead: new TextDecoder().decode(texts[0]?.body ?? new Uint8Array()), timeline_lead: 'timeline lead mentions zephyrwinds',+ body_flags: { has_fences: false, regions: ['truth'] }, ...overrides,+ };+}++export function chunk(occurrenceId: number, localOrdinal: number, text: string): SegmentChunkInput {+ return { chunk_text: text, chunk_source: 'compiled_truth', occurrence_id: occurrenceId, local_ordinal: localOrdinal, raw_byte_start: 0, raw_byte_end: text.length };+}++export function flipInput(pageId: number, expectedGeneration: number, stagingId: string, texts: readonly SegmentTextInput[],+ overrides: Partial<BodyFlipInput> = {}): BodyFlipInput {+ return {+ pageId, expectedGeneration, newGeneration: expectedGeneration + 1, stagingId, closeOccurrences: [], retireChunkOccurrences: [],+ retireMaxRows: DEFAULT_FLIP_RETIRE_MAX_ROWS, body: bodyColumns(texts), meta: pageMeta(), ...overrides,+ };+}++/** Stage `texts` as consecutive manifest rows of a new staging at `genFrom` (texts, staging and rows in one transaction). */+export async function stageGeneration(engine: BrainEngine, input: { pageId: number; slug: string; genFrom: number; texts: readonly SegmentTextInput[];+ sourceId?: string; chunkTexts?: boolean }): Promise<{ stagingId: string; occurrences: number[] }> {+ const sourceId = input.sourceId ?? 'default';+ const staging = stagingInput({ slug: input.slug, pageId: input.pageId, sourceId, mode: input.genFrom === 1 ? 'create' : 'replace' });+ const occurrences = await engine.allocateBodyOccurrenceIds(input.texts.length);+ await engine.transaction(async tx => {+ await tx.openBodyStaging(staging);+ await tx.stageSegmentTexts(sourceId, input.texts);+ let byteStart = 0;+ await tx.stageManifestRows(input.texts.map((text, seq) => {+ const row = manifestRow({ pageId: input.pageId, occurrenceId: occurrences[seq]!, genFrom: input.genFrom, seq, text, byteStart, stagingId: staging.id, sourceId });+ byteStart += text.body.byteLength;+ return row;+ }));+ if (input.chunkTexts) {+ await tx.stageSegmentChunks(input.pageId, input.genFrom, input.texts.map((text, i) => chunk(occurrences[i]!, 0, new TextDecoder().decode(text.body))));+ }+ });+ return { stagingId: staging.id, occurrences };+}++/** Create a segmented page and publish `texts` as generation 1. */+export async function publishSegmentedPage(engine: BrainEngine, slug: string, texts: readonly SegmentTextInput[],+ opts: { sourceId?: string; chunkTexts?: boolean } = {}): Promise<{ pageId: number; stagingId: string; occurrences: number[] }> {+ const sourceId = opts.sourceId ?? 'default';+ const { id: pageId } = await engine.createSegmentedPageShell(slug, pageMeta(), { sourceId });+ const staged = await stageGeneration(engine, { pageId, slug, genFrom: 1, texts, sourceId, chunkTexts: opts.chunkTexts });+ await engine.transaction(async tx => {+ await tx.flipBodyGeneration(flipInput(pageId, 0, staged.stagingId, texts));+ await tx.setBodyStagingState(staged.stagingId, 'committed');+ });+ return { pageId, ...staged };+}diff --git a/test/helpers/segment-gc-cases.ts b/test/helpers/segment-gc-cases.tsnew file mode 100644index 0000000000..d36ae30bb6--- /dev/null+++ b/test/helpers/segment-gc-cases.ts@@ -0,0 +1,219 @@+/**+ * Segment garbage collection cases (engine-sql/page-body.ts sweepSegments,+ * spec 3.5), shared by the PGLite arm (test/large-pages/segment-gc.test.ts)+ * and the Postgres arm (test/e2e/segment-gc-parity.test.ts). Each case runs in+ * its own source so a sweep never reaches another case's rows. The concurrent+ * cases need two connections and run on Postgres only.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { BODY_STAGING_HARD_MS } from '../../src/core/page-body/limits.ts';+import { chunk, flipInput, hexOf, manifestRow, publishSegmentedPage, segmentText, stageGeneration, stagingInput } from './page-body-fixtures.ts';++async function freshSource(engine: BrainEngine): Promise<string> {+ const id = `gc-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [id]);+ return id;+}++async function textExists(engine: BrainEngine, sourceId: string, text: { sha256: Uint8Array }): Promise<boolean> {+ return (await engine.readSegmentTexts(sourceId, [text.sha256])).has(hexOf(text.sha256));+}++async function ageTexts(engine: BrainEngine, sourceId: string): Promise<void> {+ await engine.executeRaw("UPDATE page_segment_texts SET created_at = now() - interval '2 hours' WHERE source_id = $1", [sourceId]);+}++const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));++export function defineSegmentGcCases(opts: { getEngine: () => BrainEngine; concurrentConnections: boolean }): void {+ test('a text referenced in the same transaction as its ON CONFLICT insert survives a sweep', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const shared = segmentText('# Shared\nsegment text reused by a second page\n');+ await publishSegmentedPage(engine, `notes/gc-first-${sourceId}`, [shared], { sourceId });+ await engine.executeRaw('DELETE FROM pages WHERE source_id = $1', [sourceId]);+ await ageTexts(engine, sourceId);+ const { id: pageId } = await engine.createSegmentedPageShell(`notes/gc-second-${sourceId}`, { type: 'note', title: 'Second', frontmatter: {} }, { sourceId });+ const staging = stagingInput({ slug: `notes/gc-second-${sourceId}`, pageId, sourceId });+ const [occ] = await engine.allocateBodyOccurrenceIds(1);+ await engine.transaction(async tx => {+ await tx.openBodyStaging(staging);+ expect(await tx.stageSegmentTexts(sourceId, [shared])).toEqual({ inserted: 0 });+ await tx.stageManifestRows([manifestRow({ pageId, occurrenceId: occ!, genFrom: 1, seq: 0, text: shared, byteStart: 0, stagingId: staging.id, sourceId })]);+ const swept = await tx.sweepSegments({ sourceId, graceMs: 0 });+ expect(swept.textsDeleted).toBe(0);+ });+ expect(await textExists(engine, sourceId, shared)).toBe(true);+ });++ if (opts.concurrentConnections) {+ test('a sweep on another connection skips a text an open writer transaction references', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const shared = segmentText('# Shared\nreferenced while a sweep runs\n');+ expect(await engine.stageSegmentTexts(sourceId, [shared])).toEqual({ inserted: 1 });+ await ageTexts(engine, sourceId);+ const { id: pageId } = await engine.createSegmentedPageShell(`notes/gc-race-${sourceId}`, { type: 'note', title: 'Race', frontmatter: {} }, { sourceId });+ const staging = stagingInput({ slug: `notes/gc-race-${sourceId}`, pageId, sourceId });+ const [occ] = await engine.allocateBodyOccurrenceIds(1);+ await engine.transaction(async tx => {+ await tx.openBodyStaging(staging);+ await tx.stageSegmentTexts(sourceId, [shared]);+ await tx.stageManifestRows([manifestRow({ pageId, occurrenceId: occ!, genFrom: 1, seq: 0, text: shared, byteStart: 0, stagingId: staging.id, sourceId })]);+ const swept = await engine.sweepSegments({ sourceId, graceMs: 0 });+ expect(swept.textsDeleted).toBe(0);+ });+ expect(await textExists(engine, sourceId, shared)).toBe(true);+ }, 30_000);++ test('a writer that re-stages a text an open sweep is deleting waits and re-inserts it', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const orphan = segmentText('# Orphan\nunreferenced, then referenced mid-sweep\n');+ await engine.stageSegmentTexts(sourceId, [orphan]);+ await ageTexts(engine, sourceId);+ const { id: pageId } = await engine.createSegmentedPageShell(`notes/gc-late-${sourceId}`, { type: 'note', title: 'Late', frontmatter: {} }, { sourceId });+ const staging = stagingInput({ slug: `notes/gc-late-${sourceId}`, pageId, sourceId });+ await engine.openBodyStaging(staging);+ const [occ] = await engine.allocateBodyOccurrenceIds(1);+ let writer: Promise<unknown> | null = null;+ let writerSettled = false;+ await engine.transaction(async gc => {+ expect((await gc.sweepSegments({ sourceId, graceMs: 0 })).textsDeleted).toBe(1);+ writer = engine.transaction(async tx => {+ await tx.stageSegmentTexts(sourceId, [orphan]);+ await tx.stageManifestRows([manifestRow({ pageId, occurrenceId: occ!, genFrom: 1, seq: 0, text: orphan, byteStart: 0, stagingId: staging.id, sourceId })]);+ }).finally(() => { writerSettled = true; });+ await sleep(300);+ expect(writerSettled).toBe(false);+ });+ await writer;+ expect(await textExists(engine, sourceId, orphan)).toBe(true);+ expect((await engine.readManifest(pageId, { stagingId: staging.id })).length).toBe(1);+ }, 30_000);+ }++ test('deleting a referenced text is refused by the manifest foreign key', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const t = segmentText('# Referenced\nlive text\n');+ await publishSegmentedPage(engine, `notes/gc-fk-${sourceId}`, [t], { sourceId });+ await expect(engine.executeRaw('DELETE FROM page_segment_texts WHERE source_id = $1', [sourceId])).rejects.toThrow(/foreign key/i);+ expect(await textExists(engine, sourceId, t)).toBe(true);+ });++ test('young unreferenced texts wait out the grace window; old ones go', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const t = segmentText('# Orphan\nnever referenced\n');+ await engine.stageSegmentTexts(sourceId, [t]);+ expect((await engine.sweepSegments({ sourceId })).textsDeleted).toBe(0);+ await ageTexts(engine, sourceId);+ expect((await engine.sweepSegments({ sourceId })).textsDeleted).toBe(1);+ expect(await textExists(engine, sourceId, t)).toBe(false);+ });++ test('staging expiry deletes the staged rows and parts; a request-held staging stays', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const page = await publishSegmentedPage(engine, `notes/gc-expiry-${sourceId}`, [segmentText('# Base\nbody\n')], { sourceId });+ const staged = await stageGeneration(engine, { pageId: page.pageId, slug: `notes/gc-expiry-${sourceId}`, genFrom: 2, sourceId,+ texts: [segmentText('# Base\nabandoned edit\n')], chunkTexts: true });+ await engine.executeRaw(`INSERT INTO page_body_staging_parts (staging_id, part_no, byte_start, byte_len, sha256, body)+ VALUES ($1::uuid, 0, 0, 3, decode(repeat('00', 32), 'hex'), convert_to('abc', 'UTF8'))`, [staged.stagingId]);+ const held = await stageGeneration(engine, { pageId: page.pageId, slug: `notes/gc-expiry-${sourceId}`, genFrom: 2, sourceId,+ texts: [segmentText('# Base\nqueued edit\n')], chunkTexts: true });+ await engine.executeRaw("UPDATE page_body_stagings SET idle_expires_at = now() - interval '1 minute' WHERE id = ANY($1::uuid[])", [[staged.stagingId, held.stagingId]]);+ const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id = $1', [sourceId]);+ await engine.executeRaw(`INSERT INTO persistence_requests (principal_kind, principal_id, request_id, operation, source_id, source_incarnation, slug, digest,+ authority, intent_bytes, terminal_reservation, intent)+ VALUES ('local_cli', 'test', $1::uuid, 'put_page', $2, $3::uuid, $4, 'digest', '{}'::jsonb, 0, 0, $5::text::jsonb)`,+ [randomUUID(), sourceId, incarnation, `notes/gc-expiry-${sourceId}`, JSON.stringify({ body_ref: { staging_id: held.stagingId } })]);++ const result = await engine.sweepSegments({ sourceId, expireStagings: true });+ expect(result.stagingsExpired).toBe(1);+ const states = await engine.executeRaw<{ id: string; state: string }>('SELECT id::text AS id, state FROM page_body_stagings WHERE source_id = $1', [sourceId]);+ expect(new Map(states.map(s => [s.id, s.state]))).toEqual(new Map([[page.stagingId, 'committed'], [staged.stagingId, 'expired'], [held.stagingId, 'open']]));+ expect(await engine.readManifest(page.pageId, { stagingId: staged.stagingId })).toEqual([]);+ expect((await engine.readManifest(page.pageId, { stagingId: held.stagingId })).length).toBe(1);+ const chunks = await engine.executeRaw<{ occurrence_id: number }>('SELECT occurrence_id::int AS occurrence_id FROM content_chunks WHERE page_id = $1 AND body_generation = 2', [page.pageId]);+ expect(chunks.map(c => c.occurrence_id)).toEqual(held.occurrences);+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_staging_parts WHERE staging_id = $1::uuid', [staged.stagingId]);+ expect(n).toBe(0);+ expect((await engine.readManifest(page.pageId)).length).toBe(1);++ const later = new Date(Date.now() + BODY_STAGING_HARD_MS + 60_000);+ await engine.executeRaw("UPDATE persistence_requests SET state = 'failed' WHERE source_id = $1", [sourceId]);+ await engine.sweepSegments({ sourceId, expireStagings: true, now: later });+ const left = await engine.executeRaw<{ id: string; state: string }>('SELECT id::text AS id, state FROM page_body_stagings WHERE source_id = $1', [sourceId]);+ expect(left).toEqual([{ id: held.stagingId, state: 'expired' }]);+ });++ test('a closed manifest row a retained version references survives; unreferenced closed rows and retired chunks go', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const v1 = [segmentText('# One\nfirst\n'), segmentText('# Two\nsecond\n')];+ const page = await publishSegmentedPage(engine, `notes/gc-versions-${sourceId}`, v1, { sourceId, chunkTexts: true });+ await engine.executeRaw(`INSERT INTO page_versions (page_id, compiled_truth, timeline, frontmatter, body_storage, body_generation, body_bytes, content_hash)+ VALUES ($1, NULL, NULL, '{}'::jsonb, 'segmented', 1, 10, 'h1')`, [page.pageId]);+ const v2 = [segmentText('# Two\nsecond, edited\n')];+ const s2 = await stageGeneration(engine, { pageId: page.pageId, slug: `notes/gc-versions-${sourceId}`, genFrom: 2, texts: v2, sourceId, chunkTexts: true });+ await engine.executeRaw('UPDATE page_body_manifest SET seq = 1 WHERE staging_id = $1::uuid', [s2.stagingId]);+ await engine.flipBodyGeneration(flipInput(page.pageId, 1, s2.stagingId, v2, { closeOccurrences: [page.occurrences[1]!], retireChunkOccurrences: [page.occurrences[1]!] }));+ const v3 = [segmentText('# Two\nsecond, edited again\n')];+ const s3 = await stageGeneration(engine, { pageId: page.pageId, slug: `notes/gc-versions-${sourceId}`, genFrom: 3, texts: v3, sourceId, chunkTexts: true });+ await engine.executeRaw('UPDATE page_body_manifest SET seq = 1 WHERE staging_id = $1::uuid', [s3.stagingId]);+ await engine.flipBodyGeneration(flipInput(page.pageId, 2, s3.stagingId, v3, { closeOccurrences: s2.occurrences, retireChunkOccurrences: s2.occurrences }));+ await ageTexts(engine, sourceId);++ const first = await engine.sweepSegments({ pageId: page.pageId, graceMs: 0 });+ expect(first.manifestRowsDeleted).toBe(1);+ expect(first.retiredChunksDeleted).toBe(2);+ expect(first.textsDeleted).toBe(1);+ expect(await textExists(engine, sourceId, v2[0]!)).toBe(false);+ expect((await engine.readManifest(page.pageId, { generation: 1 })).map(r => r.occurrenceId)).toEqual(page.occurrences);+ expect(await textExists(engine, sourceId, v1[1]!)).toBe(true);++ await engine.executeRaw('DELETE FROM page_versions WHERE page_id = $1', [page.pageId]);+ const second = await engine.sweepSegments({ pageId: page.pageId, graceMs: 0 });+ expect(second.manifestRowsDeleted).toBe(1);+ expect(second.textsDeleted).toBe(1);+ expect(await textExists(engine, sourceId, v1[1]!)).toBe(false);+ expect((await engine.readManifest(page.pageId)).map(r => r.occurrenceId)).toEqual([page.occurrences[0], s3.occurrences[0]]);+ });++ test('staged chunk rows no live staging owns are swept; a live staging keeps its rows', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const page = await publishSegmentedPage(engine, `notes/gc-orphan-chunks-${sourceId}`, [segmentText('# Base\nbody\n')], { sourceId });+ const live = await stageGeneration(engine, { pageId: page.pageId, slug: `notes/gc-orphan-chunks-${sourceId}`, genFrom: 2, sourceId,+ texts: [segmentText('# Base\nlive staging\n')], chunkTexts: true });+ const [orphanOcc] = await engine.allocateBodyOccurrenceIds(1);+ await engine.stageSegmentChunks(page.pageId, 2, [chunk(orphanOcc!, 0, 'chunk row without a manifest row')]);+ const result = await engine.sweepSegments({ pageId: page.pageId });+ expect(result.retiredChunksDeleted).toBe(1);+ const rows = await engine.executeRaw<{ occurrence_id: number }>('SELECT occurrence_id::int AS occurrence_id FROM content_chunks WHERE page_id = $1 AND body_generation = 2', [page.pageId]);+ expect(rows.map(r => r.occurrence_id)).toEqual(live.occurrences);+ });++ test('JSONB columns round-trip as objects and arrays and bytea round-trips exactly', async () => {+ const engine = opts.getEngine();+ const sourceId = await freshSource(engine);+ const t = segmentText('# Bytes ☃\n\u0000 and multibyte ü text\n');+ const page = await publishSegmentedPage(engine, `notes/gc-jsonb-${sourceId}`, [t], { sourceId });+ const [types] = await engine.executeRaw<Record<string, string>>(`SELECT jsonb_typeof(m.entry_state) AS entry_state, jsonb_typeof(m.protected_regions) AS protected_regions,+ jsonb_typeof(m.outline) AS outline, jsonb_typeof(p.body_flags) AS body_flags, jsonb_typeof(p.frontmatter) AS frontmatter+ FROM page_body_manifest m JOIN pages p ON p.id = m.page_id WHERE m.page_id = $1`, [page.pageId]);+ expect(types).toEqual({ entry_state: 'object', protected_regions: 'array', outline: 'array', body_flags: 'object', frontmatter: 'object' });+ const [row] = await engine.readManifest(page.pageId);+ expect(row!.entryState).toEqual({ fence: null, depth: 0, heading: ['Intro'] });+ expect(row!.protectedRegions).toEqual([{ kind: 'facts', start: 0, end: 4 }]);+ expect(hexOf(row!.hashState).length).toBe(64);+ const read = await engine.readSegmentTexts(sourceId, [t.sha256]);+ expect(Buffer.from(read.get(hexOf(t.sha256))!).equals(Buffer.from(t.body))).toBe(true);+ const [{ hex }] = await engine.executeRaw<{ hex: string }>('SELECT encode(body, \'hex\') AS hex FROM page_segment_texts WHERE source_id = $1', [sourceId]);+ expect(hex).toBe(Buffer.from(t.body).toString('hex'));+ });+}diff --git a/test/large-pages/segment-gc.test.ts b/test/large-pages/segment-gc.test.tsnew file mode 100644index 0000000000..0d8698fc98--- /dev/null+++ b/test/large-pages/segment-gc.test.ts@@ -0,0 +1,25 @@+/**+ * Segment garbage collection on PGLite (spec 3.5): text grace and the+ * manifest foreign key, staging expiry, versions as roots, orphan staged+ * chunks, JSONB and bytea round-trips. Postgres arm (adds the two-connection+ * races): test/e2e/segment-gc-parity.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { defineSegmentGcCases } from '../helpers/segment-gc-cases.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);++afterAll(async () => {+ await engine.disconnect();+});++describe('segment GC [pglite]', () => {+ defineSegmentGcCases({ getEngine: () => engine, concurrentConnections: false });+});diff --git a/test/pglite-upgrade-replay.test.ts b/test/pglite-upgrade-replay.test.tsindex dd49346fcc..451a34ac8a 100644--- a/test/pglite-upgrade-replay.test.ts+++ b/test/pglite-upgrade-replay.test.ts@@ -75,11 +75,12 @@ import {const FRESH_GOLDEN = 'pglite-upgrade-replay/catalog-before-boot';/*** Master finding (see header): functions whose body text on an upgraded brain- * differs from a fresh install by whitespace only.+ * differs from a fresh install by whitespace only. v248 re-creates+ * bump_page_generation_fn from the same fragment the schema blob embeds, so its+ * drift is gone.*/const WHITESPACE_ONLY_FUNCTION_DRIFT = ['bump_page_generation_clock_fn()',- 'bump_page_generation_fn()',];/** The OID-churn list is already sorted identity keys; nothing volatile to scrub. */const recreatedObjectsNormalizer = defineNormalizer<string[]>('oid-churn-keys-v1', (keys) => [...keys].sort());diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 3c49bacfcc..2ad854d444 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -1121,6 +1121,34 @@ const COLUMN_EXEMPTIONS = new Set<string>([// doctor reader probes for the column on older brains.'pages.links_attendance_blocked_revision','pages.links_attendance_blocked_at',+ // Wave B segmented page storage (migration v248). Deliberately absent from+ // both schema blobs so fresh and upgraded brains share their ordinals; no+ // index in either blob references them (content_chunks_occurrence_idx is+ // migration-built), and the blob functions that read them+ // (bump_page_generation_fn, gbrain_advance_page_revision,+ // update_page_search_vector) reach them only when compiled_truth/timeline is+ // NULL, which no brain before v248 can hold; the writer guard reads+ // body_generation by key.+ 'pages.body_storage',+ 'pages.body_bytes',+ 'pages.truth_bytes',+ 'pages.body_lines',+ 'pages.body_generation',+ 'pages.segment_count',+ 'pages.segmenter_version',+ 'pages.body_flags',+ 'pages.truth_lead',+ 'pages.timeline_lead',+ 'content_chunks.occurrence_id',+ 'content_chunks.local_ordinal',+ 'content_chunks.raw_byte_start',+ 'content_chunks.raw_byte_end',+ 'content_chunks.body_generation',+ 'content_chunks.retired_generation',+ 'page_versions.body_storage',+ 'page_versions.body_generation',+ 'page_versions.body_bytes',+ 'page_versions.content_hash',]);test('every ALTER TABLE ADD COLUMN in MIGRATIONS is covered by applyForwardReferenceBootstrap (column-only class)', async () => {