Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(large-pages): Wave B PR 4 interface: page_segment_derivations, facts.source_window (v265 placeholder) and the segment-derivation engine surface

garrytan5572de1ad4dc
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index fcf1e51c6d..1022eda4cf 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -253,8 +253,9 @@ live in `test/postgres-engine-rls-scope.test.ts`.
keeps its text in `page_segment_texts`, its layout and headings in
`page_body_manifest`, uploads in progress in `page_body_stagings` /
`page_body_staging_parts` (with the segment texts each one holds in
-`page_body_staging_texts`), and view sizes in `page_view_digests`. gbrain
-enables RLS on all six on every schema replay, as it does on `pages` and
+`page_body_staging_texts`), view sizes in `page_view_digests`, and per-segment
+derivation results (link candidates, window anchors) in `page_segment_derivations`.
+gbrain enables RLS on all seven on every schema replay, as it does on `pages` and
`content_chunks`, so with no policy a role that does not bypass RLS reads no row
of them. Title search, the source-scoped vector scan, the chunk windows search
reads around its hits, `get_chunks` and get_page check a chunk of a page stored
@@ -297,6 +298,9 @@ CREATE POLICY page_body_staging_parts_scope_filter ON page_body_staging_parts
CREATE POLICY page_view_digests_scope_filter ON page_view_digests
USING (current_setting('app.scopes', true) = '*'
OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
+CREATE POLICY page_segment_derivations_scope_filter ON page_segment_derivations
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
CREATE POLICY content_chunks_scope_filter ON content_chunks
USING (current_setting('app.scopes', true) = '*'
OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
@@ -313,6 +317,7 @@ ALTER TABLE page_body_stagings FORCE ROW LEVEL SECURITY;
ALTER TABLE page_body_staging_parts FORCE ROW LEVEL SECURITY;
ALTER TABLE page_body_staging_texts FORCE ROW LEVEL SECURITY;
ALTER TABLE page_view_digests FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_segment_derivations FORCE ROW LEVEL SECURITY;
ALTER TABLE content_chunks FORCE ROW LEVEL SECURITY;
```
<!-- gbrain:segmented-rls-recipe:end -->
diff --git a/llms-full.txt b/llms-full.txt
index f131df560f..2c84dd896f 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -5539,8 +5539,9 @@ live in `test/postgres-engine-rls-scope.test.ts`.
keeps its text in `page_segment_texts`, its layout and headings in
`page_body_manifest`, uploads in progress in `page_body_stagings` /
`page_body_staging_parts` (with the segment texts each one holds in
-`page_body_staging_texts`), and view sizes in `page_view_digests`. gbrain
-enables RLS on all six on every schema replay, as it does on `pages` and
+`page_body_staging_texts`), view sizes in `page_view_digests`, and per-segment
+derivation results (link candidates, window anchors) in `page_segment_derivations`.
+gbrain enables RLS on all seven on every schema replay, as it does on `pages` and
`content_chunks`, so with no policy a role that does not bypass RLS reads no row
of them. Title search, the source-scoped vector scan, the chunk windows search
reads around its hits, `get_chunks` and get_page check a chunk of a page stored
@@ -5583,6 +5584,9 @@ CREATE POLICY page_body_staging_parts_scope_filter ON page_body_staging_parts
CREATE POLICY page_view_digests_scope_filter ON page_view_digests
USING (current_setting('app.scopes', true) = '*'
OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
+CREATE POLICY page_segment_derivations_scope_filter ON page_segment_derivations
+ USING (current_setting('app.scopes', true) = '*'
+ OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
CREATE POLICY content_chunks_scope_filter ON content_chunks
USING (current_setting('app.scopes', true) = '*'
OR EXISTS (SELECT 1 FROM pages p WHERE p.id = page_id));
@@ -5599,6 +5603,7 @@ ALTER TABLE page_body_stagings FORCE ROW LEVEL SECURITY;
ALTER TABLE page_body_staging_parts FORCE ROW LEVEL SECURITY;
ALTER TABLE page_body_staging_texts FORCE ROW LEVEL SECURITY;
ALTER TABLE page_view_digests FORCE ROW LEVEL SECURITY;
+ALTER TABLE page_segment_derivations FORCE ROW LEVEL SECURITY;
ALTER TABLE content_chunks FORCE ROW LEVEL SECURITY;
```
<!-- gbrain:segmented-rls-recipe:end -->
diff --git a/scripts/build-schema.ts b/scripts/build-schema.ts
index 2d74b19d02..c57c828883 100644
--- a/scripts/build-schema.ts
+++ b/scripts/build-schema.ts
@@ -33,7 +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_RLS_SQL, PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL } from '../src/core/page-body/schema.ts';
+import { PAGE_BODY_RLS_SQL, PAGE_BODY_SCHEMA_SQL, PAGE_GENERATION_BUMP_FN_SQL, PAGE_SEGMENT_DERIVATIONS_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';
@@ -88,6 +88,7 @@ export const FRAGMENTS: readonly Fragment[] = [
},
{ 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-body/schema.ts', expr: 'PAGE_SEGMENT_DERIVATIONS_SQL', postgres: PAGE_SEGMENT_DERIVATIONS_SQL, pglite: PAGE_SEGMENT_DERIVATIONS_SQL },
// Capability rule: PGLite has no role system and enables RLS on no core table, so the segment tables' RLS block is Postgres-only.
{ source: 'src/core/page-body/schema.ts', expr: 'PAGE_BODY_RLS_SQL', postgres: PAGE_BODY_RLS_SQL, pglite: '' },
{ source: 'src/core/page-state/schema.ts', expr: 'PAGE_STATE_SCHEMA_SQL', postgres: PAGE_STATE_SCHEMA_SQL, pglite: PAGE_STATE_SCHEMA_SQL },
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 1da2fb613d..d1a0bf67ec 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -16,12 +16,12 @@ src/commands/sync.ts 548 ratchet refactor wave 1 split target (W4 sync); ceiling
src/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads an owned clone's pull block and reports it as pull_blocked (logic in url-clone.ts urlClonePullBlock/urlClonePullBlockSummary); +6 GBRA-130 A-1: the extract phase warns on failed or breaker-stopped stale drain pages (logic in cycle/connector-extract.ts staleDrainFailures); +1 W1 belief ledger: the extract phase runs the sampled belief drift reconcile (logic in belief/coverage-report.ts); +2 System One v1 S9: extract_facts phase tail runs the conflict sweep (ai/decide/sweep.ts) only when the slot is not off; +2 System One v1: purge phase prunes decision receipts (ai/decide/store.ts); grown v0.46.26.0 megawave (#4102 #2608) + master v0.46.26.0 cycle-start orphan recovery; +10 wave G #3974: cycle-sync uncommitted-drift warn; grown wave-g (#4416): synthesize_concepts source threading; grown wave-g (#4416): synthesize_concepts source threading (same fix absorbed as #4417 on wave-k); wave-k: ); +7: #4077 abort threading; +10: #4745 fullImplicitSourceCycle opt-in contract; +3: #4890 extract phase jsonMode/quiet + pages-not-links totals; +1: wave review — extract phase passes quiet:true + jsonMode:false; +1: extract_facts pagesFailed detail; +8 fix wave 3: one cycle date resolved in runCycle and threaded to synthesize/patterns/drift (C-15); +1 #5632: cycle sync resumes an unfinished managed cursor with its stored options; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +1 at the merge; -41 #5809: anyAbortSignal peeled to abort-signals.ts; +5 #5809: extract_atoms phase gets a real abort signal; +4 #5809: cycle_already_running names the lock holder; +7 #5255: cycle sync runs a managed pull request as no-pull and reports upstream_refresh; +1 #4578: a lock steal during the last selected phase reports lock_stolen, not aborted; +3 #5536: keyless embed phase clean-skips when embedding_disabled is set; +5 F4b: planner-stats refresh after the freshness phases (logic in planner-stats.ts); +2 agent operator wave A1: PhaseResult sibling code/fix; +20 #5876: Life Chronicle phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block; v0.60.46.0 merge: re-summed to the merged line count (3224); +3 retrieval feedback retention in the purge phase (logic in feedback/store.ts pruneRetrievalFeedback); 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); P3 x foundations-2 composition: deltas re-summed at the merge; 12 Lane D: facts_drain phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch line (logic in cycle/facts-drain.ts); +15 GBRA-49 temporal typed edges: edge_contradictions phase registration + dispatch block + extract-phase relationship sweep call (logic in cycle/edge-contradictions.ts, link-relationships.ts); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; +1 fix wave 9 lane P (#5151): extract_facts phase passes drain so the facts watermark drain runs (logic in facts/reconcile-watermark.ts); +10 #6188: fence_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in cycle/fence-repair.ts); +19 fix wave 12 #6242: source cycles with brain-wide phases also take the shared gbrain-cycle lease (acquireDbCycleLock lease set, needsMaintenanceLease, skipBrainWidePhases, all-skipped deriveStatus case; lease logic in cycle/lock-set.ts); +16 #6377: content_repair phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK), the REPAIR_LANE_PHASES dispatch helper shared with fence_repair (logic in cycle/content-repair.ts); +10 C4 pinned questions: standing_questions phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its runCycle dispatch block (logic in questions/phase.ts); +11 #6696 (A5, A4): runCycle becomes the background-origin wrapper over runCycleUnscoped and adds the capacity notices (logic in persistence/admission-origin.ts, capacity-snapshot.ts) plus the CycleReport.notices interface field; +2 #6297: CycleOpts.directPhases (operator-named phases skip the patterns cadence); +5 #6865: unindexed_files phase registration (CyclePhase, ALL_PHASES, NEEDS_LOCK) and its line in the REPAIR_LANE_PHASES dispatch helper (logic in cycle/unindexed-files.ts); +2 fix wave 20 #6954: the extract phase warns on extract_write_lost and its stale drain retries the pages left due
src/core/cycle/synthesize.ts 3230 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)
src/core/cycle/extract-atoms.ts 1658 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guard
-src/core/engine.ts 2832 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9
+src/core/engine.ts 2839 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9; +7 Wave B PR 4 interface: readSegmentDerivations/upsertSegmentDerivations/retireSegmentDerivations members + derivations type import (SQL in engine-sql/page-body.ts, types in page-body/derivations.ts)
src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +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 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation
src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullable
src/core/operations.ts 242 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); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)
-src/core/pglite-engine.ts 3085 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; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)
-src/core/postgres-engine.ts 3107 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 imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107)
+src/core/pglite-engine.ts 3093 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; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085); +8 Wave B PR 4 interface: segment-derivation delegations + type import (SQL in engine-sql/page-body.ts)
+src/core/postgres-engine.ts 3115 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 imports; +3 wave 18b lane 2 (#6495): keywordTimeouts negative-cache field and the searchKeyword runner wrap (logic in postgres-engine/keyword-timeout-cache.ts); integrated at wave 18b: master 3082 + 3; +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3085 + 3; +3 PR2 fix lane E (E1): getChunks/getChunkPage/getChunkWindows run the manifest privilege probe in their scoped transaction (chunkManifestReads in search/safe-chunks.ts); integrated at the lane E merge onto b75a69a6d: 3088 + 3; +6 PR2 fix lane X: searchVector, explainVectorSearch, the hasMore witness and runVectorAttempt pick the chunk-manifest statement form inside each bounded attempt transaction, so its statement_timeout bounds the probe (form memo vectorStatementForms in search/vector-statement.ts; engine methods cannot move): 3091 + 6; +5 PR2 fix lane X: keywordBoundedRead runs the read in withScopedReadTransaction under the keyword statement timeout setting (engine methods cannot move): 3097 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3102 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3107); +8 Wave B PR 4 interface: segment-derivation delegations + type import (SQL in engine-sql/page-body.ts)
src/core/search/hybrid.ts 1562 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); lowered to 1562: LHF wave 2 item 3 peeled cosineReScore into search/cosine-rescore.ts
src/core/types.ts 2325 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +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); +4 wave 18b lane 2 (#6495): SearchOpts.keywordTimeoutCache, the skipped_after_timeout degraded reason and the useCache doc line; integrated at wave 18b: master 2319 + 4; +2 LHF wave 2 item 3: retrieval meta cosine_rescore field (js_fallback disclosure; logic in search/cosine-rescore.ts)
src/core/minions/queue.ts 2533 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); +5 GBRA-130 A-30: claim excludeWatchdogSuspects option (signature, doc and the mark parameter), the releaseWatchdogClaim delegate, and the co-runner stall call site in handleStalled (logic in minions/watchdog-attribution.ts)
diff --git a/src/commands/doctor/checks/managed-guard.ts b/src/commands/doctor/checks/managed-guard.ts
index c3b18bfe8d..18d47ccddf 100644
--- a/src/commands/doctor/checks/managed-guard.ts
+++ b/src/commands/doctor/checks/managed-guard.ts
@@ -23,7 +23,7 @@ export const GUARDED_TABLE_COLUMNS: Readonly<Record<string, readonly string[]>>
facts: ['attributed_to', 'claim_metric', 'claim_period', 'claim_unit', 'claim_value', 'confidence', 'consolidated_at', 'consolidated_into', 'context', 'created_at',
'dim_status', 'dimension', 'embedded_at', 'embedded_text_hash', 'embedding', 'embedding_model', 'entity_slug', 'event_type', 'expired_at', 'fact',
'id', 'kind', 'last_write_principal_id', 'last_write_principal_kind', 'last_write_request_id', 'last_written_at', 'notability', 'row_num', 'source',
- 'source_id', 'source_markdown_slug', 'source_session', 'superseded_by', 'trust_tier', 'valid_from', 'valid_until', 'value', 'value_hash', 'visibility',
+ 'source_id', 'source_markdown_slug', 'source_session', 'source_window', 'superseded_by', 'trust_tier', 'valid_from', 'valid_until', 'value', 'value_hash', 'visibility',
'write_origin', 'write_principal_id', 'write_principal_kind', 'write_request_id'],
takes: ['active', 'claim', 'created_at', 'embedded_at', 'embedded_text_hash', 'embedding', 'embedding_model', 'holder', 'id', 'kind',
'last_write_principal_id', 'last_write_principal_kind', 'last_write_request_id', 'last_written_at', 'page_id', 'resolved_at', 'resolved_by',
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 2cbac77b73..7de177c373 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -78,7 +78,7 @@ const ROWS: readonly Row[] = [
['fact_purges', 'out_of_scope', 'text_free_ledger', 'source_id visibility subject fact_hash actor reason'],
['fact_relink_attempts', 'out_of_scope', 'probed_reported', 'source_id outcome reason tier model target_slug run_id', 'reason'],
['fact_withdrawals', 'out_of_scope', 'text_free_ledger', 'source_id visibility subject fact_hash'],
- ['facts', 'swept', 'fact', 'source_id entity_slug fact kind visibility notability context source source_session embedding source_markdown_slug claim_metric claim_unit claim_period event_type dimension value value_hash dim_status embedding_model embedded_text_hash write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id attributed_to trust_tier write_origin'],
+ ['facts', 'swept', 'fact', 'source_id entity_slug fact kind visibility notability context source source_session embedding source_markdown_slug claim_metric claim_unit claim_period event_type dimension value value_hash dim_status embedding_model embedded_text_hash write_principal_kind write_principal_id last_write_principal_kind last_write_principal_id attributed_to trust_tier write_origin source_window'],
['files', 'swept', 'page_files', 'source_id page_slug filename storage_path mime_type content_hash metadata'],
['gbrain_cycle_locks', 'out_of_scope', 'no_memory_text', 'id holder_host'],
['ingest_log', 'out_of_scope', 'probed_reported', 'source_id source_type source_ref pages_updated summary writer_version', 'summary pages_updated'],
@@ -118,6 +118,7 @@ const ROWS: readonly Row[] = [
['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_segment_derivations', 'out_of_scope', 'probed_reported', 'pipeline segment_sha256 context_hash state output receipt', 'output receipt'],
['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],
['page_view_digests', 'out_of_scope', 'no_memory_text', 'revision view audience sha256'],
['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'],
diff --git a/src/core/engine-sql/page-body.ts b/src/core/engine-sql/page-body.ts
index cfb308fb6b..60bd8f9a2f 100644
--- a/src/core/engine-sql/page-body.ts
+++ b/src/core/engine-sql/page-body.ts
@@ -35,6 +35,7 @@ import type { LegacyUnscopedRead } from './brands.ts';
import { joinFragments, sqlFragment, trustedSql, type SqlFragment } from './fragment.ts';
import { compileRowNormalizer } from './normalize.ts';
import { stagingNeedsTextSql } from '../page-body/schema.ts';
+import type { SegmentDerivationInput, SegmentDerivationKind, SegmentDerivationRow, SegmentDerivationState } from '../page-body/derivations.ts';
import { RELEASE_STAGED_CTE } from '../persistence/limits.ts';
export const LIVE_STAGING_STATES = ['open', 'sealed', 'prepared'];
@@ -458,3 +459,64 @@ export async function sweepSegments(exec: SqlExecutor, opts: SegmentSweepOptions
FOR UPDATE SKIP LOCKED)`)).affectedRows;
return { retiredChunksDeleted: retiredChunksDeleted + orphanedChunksDeleted, manifestRowsDeleted: stagedRowsDeleted + closedRowsDeleted, textsDeleted, stagingsExpired };
}
+
+const normalizeDerivationRow = compileRowNormalizer<Record<string, unknown>>({ occurrence_id: 'bigint', output: 'jsonb', receipt: 'jsonb' });
+
+/** A page's per-segment derivation rows (every kind, or `kind`; optionally only `occurrenceIds`), by kind then occurrence. */
+export async function readSegmentDerivations(exec: LegacyUnscopedRead, pageId: number,
+ opts: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[] } = {}): Promise<SegmentDerivationRow[]> {
+ if (opts.occurrenceIds !== undefined && opts.occurrenceIds.length === 0) return [];
+ const kind = opts.kind !== undefined ? sqlFragment`AND d.pipeline = ${opts.kind}` : sqlFragment``;
+ const occurrences = opts.occurrenceIds !== undefined ? sqlFragment`AND d.occurrence_id = ANY(${[...opts.occurrenceIds]}::bigint[])` : sqlFragment``;
+ const { rows } = await exec.run<Record<string, unknown>>(sqlFragment`
+ SELECT d.page_id, d.pipeline, d.occurrence_id, d.pipeline_version, d.segment_sha256, d.context_hash, d.state, d.output, d.receipt,
+ to_char(d.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS created_at,
+ to_char(d.updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at
+ FROM page_segment_derivations d
+ WHERE d.page_id = ${pageId}::int ${kind} ${occurrences}
+ ORDER BY d.pipeline, d.occurrence_id`);
+ return rows.map(raw => {
+ const r = normalizeDerivationRow(raw);
+ return {
+ pageId: r.page_id as number, kind: r.pipeline as SegmentDerivationKind, occurrenceId: r.occurrence_id as number,
+ version: r.pipeline_version as number, segmentSha256: bytes(r.segment_sha256), contextHash: bytes(r.context_hash),
+ state: r.state as SegmentDerivationState, output: r.output ?? null, receipt: r.receipt ?? null,
+ createdAt: r.created_at as string, updatedAt: r.updated_at as string,
+ };
+ });
+}
+
+/**
+ * Insert or replace rows keyed (page, kind, occurrence), in statements bounded like manifest rows. A replaced row
+ * keeps its created_at and moves updated_at. Outputs and receipts travel inside the batch's JSON text, never as a
+ * `::jsonb` bind of a stringified value.
+ */
+export async function upsertSegmentDerivations(exec: SqlExecutor, rows: readonly SegmentDerivationInput[]): Promise<void> {
+ const batches = jsonRowBatches(rows, row => ({
+ page_id: row.pageId, pipeline: row.kind, occurrence_id: row.occurrenceId, pipeline_version: row.version,
+ segment_sha256: hex(row.segmentSha256), context_hash: hex(row.contextHash), state: row.state,
+ output: row.output ?? null, receipt: row.receipt ?? null,
+ }), stageBatchBytes(exec));
+ for (const json of batches) {
+ await exec.run(sqlFragment`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256,
+ context_hash, state, output, receipt)
+ SELECT d.page_id, d.pipeline, d.occurrence_id, d.pipeline_version, decode(d.segment_sha256, 'hex'), decode(d.context_hash, 'hex'),
+ d.state, d.output, d.receipt
+ FROM jsonb_to_recordset(${json}::text::jsonb) AS d(page_id int, pipeline text, occurrence_id bigint, pipeline_version int,
+ segment_sha256 text, context_hash text, state text, output jsonb, receipt jsonb)
+ ON CONFLICT (page_id, pipeline, occurrence_id) DO UPDATE SET pipeline_version = EXCLUDED.pipeline_version,
+ segment_sha256 = EXCLUDED.segment_sha256, context_hash = EXCLUDED.context_hash, state = EXCLUDED.state,
+ output = EXCLUDED.output, receipt = EXCLUDED.receipt, updated_at = now()`);
+ await yieldTurn();
+ }
+}
+
+/** Delete a page's rows (every kind, or `kind`) whose occurrence is not in `liveOccurrenceIds`; returns the count. */
+export async function retireSegmentDerivations(exec: SqlExecutor, pageId: number, liveOccurrenceIds: readonly number[],
+ opts: { kind?: SegmentDerivationKind } = {}): Promise<number> {
+ const kind = opts.kind !== undefined ? sqlFragment`AND pipeline = ${opts.kind}` : sqlFragment``;
+ const { affectedRows } = await exec.run(sqlFragment`DELETE FROM page_segment_derivations
+ WHERE page_id = ${pageId}::int ${kind} AND NOT (occurrence_id = ANY(${[...liveOccurrenceIds]}::bigint[]))`);
+ return affectedRows;
+}
+
diff --git a/src/core/engine.ts b/src/core/engine.ts
index 154bd6c9c5..daa96d7923 100644
--- a/src/core/engine.ts
+++ b/src/core/engine.ts
@@ -351,6 +351,7 @@ export interface TakeHit {
import type { StaleTakeOpts, StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';
import type { BodyFlipInput, BodyFlipResult, BodyRegion, BodyStagingInput, BodyStagingState, ManifestRow, ManifestRowInput, SegmentChunkInput,
SegmentedPageMeta, SegmentSweepOptions, SegmentSweepResult, SegmentTextInput } from './page-body/types.ts';
+import type { SegmentDerivationInput, SegmentDerivationKind, SegmentDerivationRow } from './page-body/derivations.ts';
export type { StaleTakeOpts, StaleTakeRow, TakeEmbeddingInput } from './takes-row-types.ts';
/** Resolution metadata for resolveTake. */
@@ -2395,6 +2396,13 @@ export interface BrainEngine {
setBodyStagingState(id: string, state: BodyStagingState, opts?: { commitRequestId?: string | null }): Promise<void>;
/** Garbage collection: retired chunks and dead manifest rows (versions are roots), unreferenced texts past the grace window, expired stagings. */
sweepSegments(opts?: SegmentSweepOptions): Promise<SegmentSweepResult>;
+ // Per-segment derivation watermarks (Wave B PR 4; types in page-body/derivations.ts, SQL in engine-sql/page-body.ts).
+ /** A page's rows (every kind, or `kind`; optionally only `occurrenceIds`), by kind then occurrence. */
+ readSegmentDerivations(pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[] }): Promise<SegmentDerivationRow[]>;
+ /** Insert or replace rows keyed (page, kind, occurrence) in bounded statements; a replaced row keeps created_at. */
+ upsertSegmentDerivations(rows: readonly SegmentDerivationInput[]): Promise<void>;
+ /** Delete a page's rows (every kind, or `kind`) whose occurrence is not in `liveOccurrenceIds`; returns the count. */
+ retireSegmentDerivations(pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind }): Promise<number>;
// Versions
/**
diff --git a/src/core/page-body/derivations.ts b/src/core/page-body/derivations.ts
new file mode 100644
index 0000000000..13384a79ef
--- /dev/null
+++ b/src/core/page-body/derivations.ts
@@ -0,0 +1,117 @@
+/**
+ * Per-segment derivation watermarks (Wave B PR 4, wave-b spec 8.1-8.6): the shared types and pure helpers every
+ * incremental pipeline codes against. Rows live in page_segment_derivations (DDL in page-body/schema.ts, migration
+ * v265); the engine reads and writes them through readSegmentDerivations / upsertSegmentDerivations /
+ * retireSegmentDerivations (SQL in engine-sql/page-body.ts).
+ *
+ * A row says: pipeline `kind` at `version` ran on occurrence `occurrenceId` of a page while the occurrence held the
+ * segment text `segmentSha256` in the context `contextHash`, and settled in `state`. The work left for a pipeline is
+ * every live occurrence without a settled row whose three inputs match (planSegmentDerivations), so the set is found
+ * from manifest metadata without reading a body. 'done' and 'skipped' are settled (a skip is a decision made for those
+ * exact inputs); 'partial' and 'failed' are retried.
+ *
+ * facts.source_window anchors a conversation fact to the window it was extracted from (SourceWindow), so an append
+ * extracts only new windows and deletes only the facts of retired ones.
+ */
+import { createHash } from 'node:crypto';
+import { canonicalJson } from '../belief/keys.ts';
+import { SEGMENT_DERIVATION_KINDS, SEGMENT_DERIVATION_STATES } from './schema.ts';
+
+export { SEGMENT_DERIVATION_KINDS, SEGMENT_DERIVATION_STATES };
+export type SegmentDerivationKind = typeof SEGMENT_DERIVATION_KINDS[number];
+export type SegmentDerivationState = typeof SEGMENT_DERIVATION_STATES[number];
+export const SETTLED_DERIVATION_STATES: readonly SegmentDerivationState[] = ['done', 'skipped'];
+
+/** What a pipeline records for one occurrence. `output` stays bounded per segment (candidates, keys, anchors, never text). */
+export interface SegmentDerivationInput {
+ pageId: number;
+ kind: SegmentDerivationKind;
+ occurrenceId: number;
+ version: number;
+ segmentSha256: Uint8Array;
+ contextHash: Uint8Array;
+ state: SegmentDerivationState;
+ output: unknown;
+ receipt: unknown;
+}
+
+/** A stored row: the input plus its timestamps (ISO-8601 UTC). */
+export interface SegmentDerivationRow extends SegmentDerivationInput {
+ createdAt: string;
+ updatedAt: string;
+}
+
+/**
+ * The context hash of one segment for one pipeline: SHA-256 over the canonical JSON of the pipeline kind, the
+ * segment's manifest `entry_state` and every page-level input the pipeline reads (title, type, pack fingerprint,
+ * gazetteer generation, gap settings, ...). Canonical JSON sorts keys at every depth, so an entry state read back
+ * from JSONB hashes the same as the one the segmenter built. The pipeline version is stored beside the hash, not in it.
+ */
+export function segmentDerivationContextHash(kind: SegmentDerivationKind, input: { entryState: unknown; page: Record<string, unknown> }): Uint8Array {
+ const digest = createHash('sha256').update(canonicalJson(['gbrain.segment_derivation.v1', kind, input.entryState ?? null, input.page])).digest();
+ return new Uint8Array(digest.buffer, digest.byteOffset, digest.byteLength);
+}
+
+/** A live occurrence as a pipeline sees it: identity, segment text hash and its context hash for that pipeline. */
+export interface LiveSegment {
+ occurrenceId: number;
+ sha256: Uint8Array;
+ contextHash: Uint8Array;
+}
+
+export interface SegmentDerivationPlan {
+ /** Live occurrences to (re)derive, in input order. */
+ todo: LiveSegment[];
+ /** Settled rows whose inputs still match a live occurrence: their outputs are the page aggregate's inputs. */
+ current: SegmentDerivationRow[];
+ /** Rows whose occurrence is no longer live: delete them (retireSegmentDerivations) and undo their effects. */
+ retired: SegmentDerivationRow[];
+}
+
+const sameBytes = (a: Uint8Array, b: Uint8Array) => a.byteLength === b.byteLength && Buffer.from(a).equals(Buffer.from(b));
+
+/** Split one pipeline's rows of a page against its live occurrences at `version` (rows of another kind are ignored). */
+export function planSegmentDerivations(kind: SegmentDerivationKind, version: number, live: readonly LiveSegment[],
+ rows: readonly SegmentDerivationRow[]): SegmentDerivationPlan {
+ const byOccurrence = new Map<number, SegmentDerivationRow>();
+ for (const row of rows) if (row.kind === kind) byOccurrence.set(row.occurrenceId, row);
+ const liveIds = new Set(live.map(segment => segment.occurrenceId));
+ const plan: SegmentDerivationPlan = { todo: [], current: [], retired: [] };
+ for (const segment of live) {
+ const row = byOccurrence.get(segment.occurrenceId);
+ const settled = row !== undefined && SETTLED_DERIVATION_STATES.includes(row.state) && row.version === version
+ && sameBytes(row.segmentSha256, segment.sha256) && sameBytes(row.contextHash, segment.contextHash);
+ if (settled) plan.current.push(row);
+ else plan.todo.push(segment);
+ }
+ for (const row of byOccurrence.values()) if (!liveIds.has(row.occurrenceId)) plan.retired.push(row);
+ return plan;
+}
+
+/** facts.source_window: the conversation window a fact came from. Snake-case keys: it is stored as JSONB as-is. */
+export interface SourceWindow {
+ occurrence_id: number;
+ window_ordinal: number;
+ /** Lowercase hex SHA-256 of the rendered window text the extractor saw. */
+ window_text_sha: string;
+}
+
+export function sourceWindowFor(occurrenceId: number, windowOrdinal: number, windowText: string): SourceWindow {
+ return { occurrence_id: occurrenceId, window_ordinal: windowOrdinal, window_text_sha: createHash('sha256').update(windowText).digest('hex') };
+}
+
+/** One string per window identity, for set membership (live windows vs a page's stored facts). */
+export function sourceWindowKey(window: SourceWindow): string {
+ return `${window.occurrence_id}:${window.window_ordinal}:${window.window_text_sha}`;
+}
+
+/** A stored source_window (already JSONB-decoded), or null for NULL; throws on a value the column CHECK would refuse. */
+export function parseSourceWindow(value: unknown): SourceWindow | null {
+ if (value === null || value === undefined) return null;
+ const w = value as Record<string, unknown>;
+ if (typeof value !== 'object' || Array.isArray(value) || !Number.isSafeInteger(w.occurrence_id) || !Number.isSafeInteger(w.window_ordinal)
+ || typeof w.window_text_sha !== 'string' || !/^[0-9a-f]{64}$/.test(w.window_text_sha)) {
+ throw new Error(`malformed facts.source_window: ${JSON.stringify(value)}`);
+ }
+ return { occurrence_id: w.occurrence_id as number, window_ordinal: w.window_ordinal as number, window_text_sha: w.window_text_sha };
+}
diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.ts
index bb676f2e57..b374906f3b 100644
--- a/src/core/page-body/schema.ts
+++ b/src/core/page-body/schema.ts
@@ -168,9 +168,42 @@ CREATE TABLE IF NOT EXISTS page_body_staging_parts (
);
${PAGE_BODY_STAGING_TEXTS_SQL}`;
+/**
+ * The derivation pipelines whose per-segment results page_segment_derivations records (wave-b spec 8.1-8.6, PR 4), and
+ * the states a row can settle in. One list feeds the table's CHECKs and the TS types (page-body/derivations.ts).
+ */
+export const SEGMENT_DERIVATION_KINDS = ['links', 'mentions', 'timeline', 'fences', 'conversation_facts', 'extract_atoms', 'facts_backstop', 'synopsis'] as const;
+export const SEGMENT_DERIVATION_STATES = ['done', 'partial', 'failed', 'skipped'] as const;
+const sqlList = (values: readonly string[]) => values.map(v => `'${v}'`).join(',');
+
+/**
+ * Per-segment derivation watermarks (migration v265): one row per page, pipeline and manifest occurrence, recording
+ * the segment text and the context (`context_hash`: entry state plus the page-level inputs the pipeline reads) it was
+ * derived from, the pipeline version, the outcome and a bounded per-segment output. A pipeline's work on a page is the
+ * live occurrences without a settled row whose segment sha, context hash and version match, found from metadata alone.
+ * Rows of an occurrence that left the live generation are deleted by their pipeline (retireSegmentDerivations); a page
+ * delete cascades. The output holds link context and window anchors, so the table gets the segment tables' RLS posture.
+ */
+export const PAGE_SEGMENT_DERIVATIONS_SQL = `CREATE TABLE IF NOT EXISTS page_segment_derivations (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN (${sqlList(SEGMENT_DERIVATION_KINDS)})),
+ occurrence_id BIGINT NOT NULL,
+ pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),
+ segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),
+ context_hash BYTEA NOT NULL CHECK (octet_length(context_hash) = 32),
+ state TEXT NOT NULL CHECK (state IN (${sqlList(SEGMENT_DERIVATION_STATES)})),
+ output JSONB,
+ receipt JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline, occurrence_id)
+);
+CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');`;
+
/**
* The segment tables hold page text (`page_segment_texts`, `page_body_staging_parts`) or a page's shape and
- * headings (`page_body_manifest`, `page_body_stagings`, `page_view_digests`), so they get the posture of `pages`
+ * headings (`page_body_manifest`, `page_body_stagings`, `page_view_digests`) or derived link context
+ * (`page_segment_derivations`), so they get the posture of `pages`
* and `content_chunks`: RLS on, re-asserted on every schema replay like the core list in src/schema.sql, so a brain
* the auto-RLS event trigger (v35) missed, or one where it was dropped or disabled, never serves segment text to a
* role `pages` returns no rows to. Only under a role that bypasses RLS (else the runtime role would lock itself out),
@@ -178,7 +211,7 @@ ${PAGE_BODY_STAGING_TEXTS_SQL}`;
* `page_view_digests` is absent while migration v248 runs. Postgres only: PGLite has no role system, and its
* bootstrap enables RLS on no core table either. Source-scoped policies are operator SQL (docs/ENGINES.md).
*/
-export const PAGE_BODY_RLS_TABLES = ['page_segment_texts', 'page_body_manifest', 'page_body_stagings', 'page_body_staging_parts', 'page_view_digests', 'page_body_staging_texts'] as const;
+export const PAGE_BODY_RLS_TABLES = ['page_segment_texts', 'page_body_manifest', 'page_body_stagings', 'page_body_staging_parts', 'page_view_digests', 'page_body_staging_texts', 'page_segment_derivations'] as const;
export const PAGE_BODY_RLS_SQL = `DO $rls$
DECLARE target TEXT;
BEGIN
diff --git a/src/core/persistence/attribution-schema.ts b/src/core/persistence/attribution-schema.ts
index 3b8b4aee97..87c38ddb91 100644
--- a/src/core/persistence/attribution-schema.ts
+++ b/src/core/persistence/attribution-schema.ts
@@ -54,7 +54,7 @@ export const WRITE_ATTRIBUTION_CONTENT_COLUMNS: Record<AttributedTable, readonly
* content rewrite, so it does not move last_write_*).
*/
export const WRITE_ATTRIBUTION_PROJECTION_COLUMNS: Record<AttributedTable, readonly string[]> = {
- facts: ['embedding', 'embedded_at', 'embedding_model', 'embedded_text_hash', ...TRUST_ROW_COLUMNS],
+ facts: ['embedding', 'embedded_at', 'embedding_model', 'embedded_text_hash', 'source_window', ...TRUST_ROW_COLUMNS],
takes: ['embedding', 'embedded_at', 'updated_at', 'embedding_model', 'embedded_text_hash', ...TRUST_ROW_COLUMNS],
timeline_entries: [...TRUST_ROW_COLUMNS],
};
diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.ts
index 066d197824..dcb5c9ac2f 100644
--- a/src/core/pglite-engine.ts
+++ b/src/core/pglite-engine.ts
@@ -158,6 +158,7 @@ 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 type { SegmentDerivationInput, SegmentDerivationKind, SegmentDerivationRow } from './page-body/derivations.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';
@@ -2532,6 +2533,13 @@ export class PGLiteEngine implements BrainEngine {
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); }
+ async readSegmentDerivations(pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[] }): Promise<SegmentDerivationRow[]> {
+ return pageBodyImpl.readSegmentDerivations(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), pageId, opts);
+ }
+ async upsertSegmentDerivations(rows: readonly SegmentDerivationInput[]): Promise<void> { return pageBodyImpl.upsertSegmentDerivations(this.engineSql, rows); }
+ async retireSegmentDerivations(pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind }): Promise<number> {
+ return pageBodyImpl.retireSegmentDerivations(this.engineSql, pageId, liveOccurrenceIds, 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.ts
index 34ac28d9ea..44220d101a 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1388,6 +1388,23 @@ CREATE TABLE IF NOT EXISTS page_body_staging_texts (
);
CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);
+-- Wave B per-segment derivation watermarks (migration v265; src/core/page-body/derivations.ts).
+CREATE TABLE IF NOT EXISTS page_segment_derivations (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','extract_atoms','facts_backstop','synopsis')),
+ occurrence_id BIGINT NOT NULL,
+ pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),
+ segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),
+ context_hash BYTEA NOT NULL CHECK (octet_length(context_hash) = 32),
+ state TEXT NOT NULL CHECK (state IN ('done','partial','failed','skipped')),
+ output JSONB,
+ receipt JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline, occurrence_id)
+);
+CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+
-- Durable concurrent persistence (migration 151).
diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.ts
index af1b260aba..3301dc2353 100644
--- a/src/core/postgres-engine.ts
+++ b/src/core/postgres-engine.ts
@@ -145,6 +145,7 @@ 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 type { SegmentDerivationInput, SegmentDerivationKind, SegmentDerivationRow } from './page-body/derivations.ts';
import { hasCJK } from './cjk.ts';
import { searchKeywordCJK as searchKeywordCJKImpl } from './engine-sql/cjk-search.ts';
import { KeywordTimeoutNegativeCache } from './postgres-engine/keyword-timeout-cache.ts';
@@ -2333,6 +2334,13 @@ export class PostgresEngine implements BrainEngine {
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); }
+ async readSegmentDerivations(pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[] }): Promise<SegmentDerivationRow[]> {
+ return pageBodyImpl.readSegmentDerivations(unscopedExecutor(this.engineSql, 'page-body: page-id keyed internal read'), pageId, opts);
+ }
+ async upsertSegmentDerivations(rows: readonly SegmentDerivationInput[]): Promise<void> { return pageBodyImpl.upsertSegmentDerivations(this.engineSql, rows); }
+ async retireSegmentDerivations(pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind }): Promise<number> {
+ return pageBodyImpl.retireSegmentDerivations(this.engineSql, pageId, liveOccurrenceIds, 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.ts
index defc56577d..75b6c73ff8 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -2131,12 +2131,31 @@ CREATE TABLE IF NOT EXISTS page_body_staging_texts (
CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)
+-- Wave B per-segment derivation watermarks (migration v265; src/core/page-body/derivations.ts).
+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL). Edit that file, then run: bun run build:schema
+CREATE TABLE IF NOT EXISTS page_segment_derivations (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','extract_atoms','facts_backstop','synopsis')),
+ occurrence_id BIGINT NOT NULL,
+ pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),
+ segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),
+ context_hash BYTEA NOT NULL CHECK (octet_length(context_hash) = 32),
+ state TEXT NOT NULL CHECK (state IN ('done','partial','failed','skipped')),
+ output JSONB,
+ receipt JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline, occurrence_id)
+);
+CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+-- END GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL)
+
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema
DO \$rls\$
DECLARE target TEXT;
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
- FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts'] LOOP
+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations'] LOOP
IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index 7c10d71c56..d776960602 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 = 263;
+export const LATEST_SCHEMA_VERSION = 265;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 4d376fcd12..56f9b7063f 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -264,6 +264,7 @@ import { v260 } from './v260-segmented-page-size-index.ts';
import { v261 } from './v261-persistence-request-transient-retries.ts';
import { v262 } from './v262-commit-notifier.ts';
import { v263 } from './v263-try-jsonb-function.ts';
+import { v265 } from './v265-segment-derivations.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -526,4 +527,5 @@ export const MIGRATIONS: Migration[] = [
v261,
v262,
v263,
+ v265,
];
diff --git a/src/core/schema-migrations/v265-segment-derivations.ts b/src/core/schema-migrations/v265-segment-derivations.ts
new file mode 100644
index 0000000000..d4031e1e20
--- /dev/null
+++ b/src/core/schema-migrations/v265-segment-derivations.ts
@@ -0,0 +1,48 @@
+import type { Migration } from './types.ts';
+import { PAGE_SEGMENT_DERIVATIONS_SQL } from '../page-body/schema.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md
+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.
+//
+// Wave B PR 4, incremental derivation (wave-b spec 1.2 item 7, 8.1, 8.2):
+// - page_segment_derivations: per page, pipeline and manifest occurrence, the
+// segment sha, context hash and pipeline version a derivation ran on, its
+// outcome and a bounded output (also in both blobs; the blob's RLS block,
+// replayed on every initSchema, covers it on Postgres).
+// - facts.source_window: the conversation window a fact was extracted from,
+// {occurrence_id, window_ordinal, window_text_sha} (page-body/derivations.ts
+// SourceWindow), so an append re-extracts only new windows and deletes only
+// the facts of retired ones. NULL for every existing fact and every fact not
+// extracted from a segmented conversation window. Migration-only, like every
+// facts column (v045 creates the table). Classified as a projection column
+// for write attribution: it locates the fact's source text and is not
+// asserted content, so the attribution trigger is unchanged.
+//
+// Nothing to backfill. facts_source_window_chk keeps a malformed anchor (a
+// double-encoded JSON string included) out; it is added NOT VALID and
+// validated in its own statement, so no facts scan runs under the exclusive
+// lock of the ALTER. Per-page window reads use the existing
+// (source_id, source_markdown_slug, row_num) index.
+export const v265: Migration = {
+ version: 265,
+ name: 'segment_derivations',
+ idempotent: true,
+ transaction: false,
+ sql: `
+ ${PAGE_SEGMENT_DERIVATIONS_SQL}
+ ALTER TABLE facts ADD COLUMN IF NOT EXISTS source_window JSONB;
+ DO $do$ BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'facts_source_window_chk' AND conrelid = 'facts'::regclass) THEN
+ ALTER TABLE facts ADD CONSTRAINT facts_source_window_chk CHECK (source_window IS NULL OR (
+ jsonb_typeof(source_window) = 'object'
+ AND jsonb_typeof(source_window->'occurrence_id') = 'number'
+ AND jsonb_typeof(source_window->'window_ordinal') = 'number'
+ AND jsonb_typeof(source_window->'window_text_sha') = 'string'
+ )) NOT VALID;
+ END IF;
+ END $do$;
+ `,
+ handler: async engine => {
+ await engine.runMigration(265, 'ALTER TABLE facts VALIDATE CONSTRAINT facts_source_window_chk;');
+ },
+};
diff --git a/src/schema.sql b/src/schema.sql
index b5cb777853..1b0f51c53a 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -2127,12 +2127,31 @@ CREATE TABLE IF NOT EXISTS page_body_staging_texts (
CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_texts (source_id, sha256);
-- END GENERATED from src/core/page-body/schema.ts (PAGE_BODY_SCHEMA_SQL)
+-- Wave B per-segment derivation watermarks (migration v265; src/core/page-body/derivations.ts).
+-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL). Edit that file, then run: bun run build:schema
+CREATE TABLE IF NOT EXISTS page_segment_derivations (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','extract_atoms','facts_backstop','synopsis')),
+ occurrence_id BIGINT NOT NULL,
+ pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),
+ segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),
+ context_hash BYTEA NOT NULL CHECK (octet_length(context_hash) = 32),
+ state TEXT NOT NULL CHECK (state IN ('done','partial','failed','skipped')),
+ output JSONB,
+ receipt JSONB,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline, occurrence_id)
+);
+CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');
+-- END GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL)
+
-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_BODY_RLS_SQL). Edit that file, then run: bun run build:schema
DO $rls$
DECLARE target TEXT;
BEGIN
IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN
- FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts'] LOOP
+ FOREACH target IN ARRAY ARRAY['page_segment_texts','page_body_manifest','page_body_stagings','page_body_staging_parts','page_view_digests','page_body_staging_texts','page_segment_derivations'] LOOP
IF EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = current_schema() AND c.relname = target AND c.relkind = 'r' AND NOT c.relrowsecurity) THEN
EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', target);
diff --git a/test/e2e/segment-derivations-postgres.test.ts b/test/e2e/segment-derivations-postgres.test.ts
new file mode 100644
index 0000000000..0235dca888
--- /dev/null
+++ b/test/e2e/segment-derivations-postgres.test.ts
@@ -0,0 +1,15 @@
+/**
+ * Per-segment derivation rows and facts.source_window on Postgres (Wave B PR 4 interface, migration v265): the shared
+ * cases, including the JSONB double-encoding checks PGLite can't catch. PGLite arm: test/engine-sql-segment-derivations.test.ts.
+ */
+import { afterAll, beforeAll, describe } from 'bun:test';
+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { defineSegmentDerivationCases } from '../helpers/segment-derivation-cases.ts';
+import { hasDatabase, setupDB, teardownDB } from './helpers.ts';
+
+(hasDatabase() ? describe : describe.skip)('segment derivations [postgres]', () => {
+ let engine: PostgresEngine;
+ beforeAll(async () => { engine = await setupDB(); }, 120_000);
+ afterAll(async () => { await teardownDB(); });
+ defineSegmentDerivationCases({ getEngine: () => engine });
+});
diff --git a/test/e2e/segmented-rls-scope.test.ts b/test/e2e/segmented-rls-scope.test.ts
index 809441cceb..01e7a90b8f 100644
--- a/test/e2e/segmented-rls-scope.test.ts
+++ b/test/e2e/segmented-rls-scope.test.ts
@@ -34,7 +34,7 @@ const LEGACY = `gbrain_seg_rls_legacy_${tag}`;
const WRITER = `gbrain_seg_rls_writer_${tag}`;
const SOURCES = { 'src-a': 'alphaneedle', 'src-b': 'bravoneedle' } as const;
const slugOf = (id: string) => `notes/ledger-${id}`;
-const PAGE_BODY_RLS_TABLES = ['page_body_manifest', 'page_body_staging_parts', 'page_body_staging_texts', 'page_body_stagings', 'page_segment_texts', 'page_view_digests'];
+const PAGE_BODY_RLS_TABLES = ['page_body_manifest', 'page_body_staging_parts', 'page_body_staging_texts', 'page_body_stagings', 'page_segment_derivations', 'page_segment_texts', 'page_view_digests'];
/** What a search and a body read touch besides the recipe's tables, opened to the reader. */
const SEARCH_SIDE_TABLES = ['config', 'timeline_entries'];
diff --git a/test/engine-sql-segment-derivations.test.ts b/test/engine-sql-segment-derivations.test.ts
new file mode 100644
index 0000000000..902fb29b10
--- /dev/null
+++ b/test/engine-sql-segment-derivations.test.ts
@@ -0,0 +1,23 @@
+/**
+ * Per-segment derivation rows and facts.source_window on PGLite (Wave B PR 4 interface, migration v265). Postgres arm:
+ * test/e2e/segment-derivations-postgres.test.ts. Pure planning and hashing helpers: test/large-pages/segment-derivations-plan.test.ts.
+ */
+import { afterAll, beforeAll, describe } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { defineSegmentDerivationCases } from './helpers/segment-derivation-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 derivations [pglite]', () => {
+ defineSegmentDerivationCases({ getEngine: () => engine });
+});
diff --git a/test/engine-surface-coverage.test.ts b/test/engine-surface-coverage.test.ts
index 1fc9c4ee6b..d45ec2c0fe 100644
--- a/test/engine-surface-coverage.test.ts
+++ b/test/engine-surface-coverage.test.ts
@@ -117,6 +117,8 @@ const INTERFACE_METHODS: readonly string[] = [
// Wave B segmented page bodies (src/core/engine-sql/page-body.ts; covered by test/large-pages/ and test/engine-sql-page-body.test.ts)
'allocateBodyOccurrenceIds', 'stageSegmentTexts', 'readSegmentTexts', 'stageManifestRows', 'readManifest', 'stageSegmentChunks',
'createSegmentedPageShell', 'flipBodyGeneration', 'openBodyStaging', 'setBodyStagingState', 'sweepSegments',
+ // Wave B PR 4 per-segment derivation rows (same SQL module; covered by test/engine-sql-segment-derivations.test.ts and its Postgres arm)
+ 'readSegmentDerivations', 'upsertSegmentDerivations', 'retireSegmentDerivations',
];
/**
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 582c55accb..cf620a5f82 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -258,6 +259,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -794,6 +802,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1295,6 +1306,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2282,7 +2295,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2937,6 +2951,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index c24e21978b..2cca7d6043 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -258,6 +259,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -794,6 +802,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1295,6 +1306,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2282,7 +2295,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2937,6 +2951,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 6a6095e121..e3f66a4a65 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -258,6 +259,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -794,6 +802,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1291,6 +1302,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2278,7 +2291,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2933,6 +2947,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
index d961e5c719..02f1c206a8 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -186,6 +186,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -588,6 +595,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -952,6 +962,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2202,6 +2214,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
index e00cd83152..e615c9fe52 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -186,6 +186,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -588,6 +595,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -952,6 +962,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2202,6 +2214,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
index bec1d2cc76..b5e42fa8a3 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -186,6 +186,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -588,6 +595,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -951,6 +961,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2201,6 +2213,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 80c8d46a27..3df780b38c 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -197,6 +197,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -605,6 +612,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -980,6 +990,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2270,6 +2282,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
index b482e71c74..7aac5f4900 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -262,6 +263,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -801,6 +809,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1299,6 +1310,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2283,7 +2296,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2949,6 +2963,22 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 9ea57a2ebc..b31d21769e 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -262,6 +263,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -801,6 +809,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1299,6 +1310,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2283,7 +2296,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2949,6 +2963,22 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index dc450522e7..950c52c273 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -262,6 +263,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -801,6 +809,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1295,6 +1306,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2279,7 +2292,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=true force_rls=false"
},
@@ -2945,6 +2959,22 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 9d81061774..906a0c569f 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -913,7 +913,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1296 column(s) verified against live schema",
+ "message": "1307 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index bae03e6967..125fdbb462 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -960,7 +960,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1296 column(s) verified against live schema",
+ "message": "1307 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.json
index 618aa8698f..898283c788 100644
--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json
+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json
@@ -942,7 +942,7 @@
{
"category": "ops",
"elapsed_ms": "<volatile>",
- "message": "RLS enabled on 151/151 public tables",
+ "message": "RLS enabled on 152/152 public tables",
"name": "rls",
"status": "ok"
},
@@ -956,7 +956,7 @@
{
"category": "meta",
"elapsed_ms": "<volatile>",
- "message": "1302 column(s) verified against live schema",
+ "message": "1313 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
diff --git a/test/fixtures/goldens/exports/runtime.json b/test/fixtures/goldens/exports/runtime.json
index 99e549e65f..63ac09fbe8 100644
--- a/test/fixtures/goldens/exports/runtime.json
+++ b/test/fixtures/goldens/exports/runtime.json
@@ -149,6 +149,7 @@
"readManifest",
"readPageSnapshot",
"readPageSnapshotsBatch",
+ "readSegmentDerivations",
"readSegmentTexts",
"reconnect",
"refreshPageBody",
@@ -167,6 +168,7 @@
"resolveSlugsByPaths",
"resolveTake",
"restorePage",
+ "retireSegmentDerivations",
"revertToVersion",
"rewriteLinks",
"runMigration",
@@ -207,6 +209,7 @@
"upsertChunks",
"upsertEventProjection",
"upsertFile",
+ "upsertSegmentDerivations",
"withReservedConnection",
"writeContradictionsRun"
],
@@ -357,6 +360,7 @@
"readManifest",
"readPageSnapshot",
"readPageSnapshotsBatch",
+ "readSegmentDerivations",
"readSegmentTexts",
"reconnect",
"refreshPageBody",
@@ -376,6 +380,7 @@
"resolveSlugsByPaths",
"resolveTake",
"restorePage",
+ "retireSegmentDerivations",
"revertToVersion",
"rewriteLinks",
"rlsScopeBindingEnabled",
@@ -421,6 +426,7 @@
"upsertChunks",
"upsertEventProjection",
"upsertFile",
+ "upsertSegmentDerivations",
"vectorIterativeScanSupported",
"withReservedConnection",
"withScopedReadTransaction",
diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.json
index de6eb6e6a5..0d8da1c45b 100644
--- a/test/fixtures/goldens/exports/types.json
+++ b/test/fixtures/goldens/exports/types.json
@@ -185,6 +185,7 @@
"readManifest: (pageId: number, opts?: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number; }) => Promise<ManifestRow[]>",
"readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>",
"readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>",
+ "readSegmentDerivations: (pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[]; }) => Promise<SegmentDerivationRow[]>",
"readSegmentTexts: (sourceId: string, sha256s: readonly Uint8Array[]) => Promise<Map<string, Uint8Array>>",
"readonly kind: \"postgres\" | \"pglite\"",
"reconnect: (ctx?: { error?: unknown; }) => Promise<void>",
@@ -204,6 +205,7 @@
"resolveSlugsByPaths: (paths: string[], opts: { sourceId: string; }) => Promise<Map<string, string>>",
"resolveTake: (pageId: number, rowNum: number, resolution: TakeResolution) => Promise<void>",
"restorePage: (slug: string, opts?: { sourceId?: string; }) => Promise<boolean>",
+ "retireSegmentDerivations: (pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind; }) => Promise<number>",
"revertToVersion: (slug: string, versionId: number, opts?: { sourceId?: string; }) => Promise<void>",
"rewriteLinks: (oldSlug: string, newSlug: string) => Promise<void>",
"runMigration: (version: number, sql: string) => Promise<void>",
@@ -244,6 +246,7 @@
"upsertChunks: (slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true; } & BatchOpts) => Promise<void>",
"upsertEventProjection: (opts: { depthSlug: string; eventSlug: string; date: string; summary: string; detail?: string; sourceId?: string; }) => Promise<{ projected: boolean; }>",
"upsertFile: (spec: FileSpec) => Promise<{ id: number; created: boolean; }>",
+ "upsertSegmentDerivations: (rows: readonly SegmentDerivationInput[]) => Promise<void>",
"withReservedConnection: <T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: \"ordinary\"; selfContained?: boolean; }) => Promise<T>",
"writeContradictionsRun: (row: { run_id: string; judge_model: string; prompt_version: string; queries_evaluated: number; queries_with_contradiction: number; total_contradictions_flagged: number; wilson_ci_lower: number; wilson_ci_upper: number; judge_errors_total: number; cost_usd_total: number; duration_ms: number; source_tier_breakdown: Record<string, unknown>; report_json: Record<string, unknown>; }) => Promise<boolean>"
],
@@ -1228,6 +1231,7 @@
"readManifest: (pageId: number, opts?: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number; }) => Promise<ManifestRow[]>",
"readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>",
"readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>",
+ "readSegmentDerivations: (pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[]; }) => Promise<SegmentDerivationRow[]>",
"readSegmentTexts: (sourceId: string, sha256s: readonly Uint8Array[]) => Promise<Map<string, Uint8Array>>",
"readonly kind: \"postgres\"",
"reconnect: (ctx?: { error?: unknown; }) => Promise<void>",
@@ -1247,6 +1251,7 @@
"resolveSlugsByPaths: (paths: string[], opts: { sourceId: string; }) => Promise<Map<string, string>>",
"resolveTake: (pageId: number, rowNum: number, resolution: TakeResolution) => Promise<void>",
"restorePage: (slug: string, opts?: { sourceId?: string; }) => Promise<boolean>",
+ "retireSegmentDerivations: (pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind; }) => Promise<number>",
"revertToVersion: (slug: string, versionId: number, opts?: { sourceId?: string; }) => Promise<void>",
"rewriteLinks: (_oldSlug: string, _newSlug: string) => Promise<void>",
"runMigration: (_version: number, sqlStr: string) => Promise<void>",
@@ -1288,6 +1293,7 @@
"upsertChunks: (slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true; } & BatchOpts) => Promise<void>",
"upsertEventProjection: (opts: { depthSlug: string; eventSlug: string; date: string; summary: string; detail?: string; sourceId?: string; }) => Promise<{ projected: boolean; }>",
"upsertFile: (spec: FileSpec) => Promise<{ id: number; created: boolean; }>",
+ "upsertSegmentDerivations: (rows: readonly SegmentDerivationInput[]) => Promise<void>",
"withReservedConnection: <T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: \"ordinary\"; selfContained?: boolean; }) => Promise<T>",
"writeContradictionsRun: (row: { run_id: string; judge_model: string; prompt_version: string; queries_evaluated: number; queries_with_contradiction: number; total_contradictions_flagged: number; wilson_ci_lower: number; wilson_ci_upper: number; judge_errors_total: number; cost_usd_total: number; duration_ms: number; source_tier_breakdown: Record<string, unknown>; report_json: Record<string, unknown>; }) => Promise<boolean>"
],
@@ -3483,6 +3489,7 @@
"readManifest: (pageId: number, opts?: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number; }) => Promise<ManifestRow[]>",
"readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>",
"readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>",
+ "readSegmentDerivations: (pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[]; }) => Promise<SegmentDerivationRow[]>",
"readSegmentTexts: (sourceId: string, sha256s: readonly Uint8Array[]) => Promise<Map<string, Uint8Array>>",
"readonly kind: \"postgres\" | \"pglite\"",
"reconnect: (ctx?: { error?: unknown; }) => Promise<void>",
@@ -3502,6 +3509,7 @@
"resolveSlugsByPaths: (paths: string[], opts: { sourceId: string; }) => Promise<Map<string, string>>",
"resolveTake: (pageId: number, rowNum: number, resolution: TakeResolution) => Promise<void>",
"restorePage: (slug: string, opts?: { sourceId?: string; }) => Promise<boolean>",
+ "retireSegmentDerivations: (pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind; }) => Promise<number>",
"revertToVersion: (slug: string, versionId: number, opts?: { sourceId?: string; }) => Promise<void>",
"rewriteLinks: (oldSlug: string, newSlug: string) => Promise<void>",
"runMigration: (version: number, sql: string) => Promise<void>",
@@ -3542,6 +3550,7 @@
"upsertChunks: (slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true; } & BatchOpts) => Promise<void>",
"upsertEventProjection: (opts: { depthSlug: string; eventSlug: string; date: string; summary: string; detail?: string; sourceId?: string; }) => Promise<{ projected: boolean; }>",
"upsertFile: (spec: FileSpec) => Promise<{ id: number; created: boolean; }>",
+ "upsertSegmentDerivations: (rows: readonly SegmentDerivationInput[]) => Promise<void>",
"withReservedConnection: <T>(fn: (conn: ReservedConnection) => Promise<T>, opts?: { route?: \"ordinary\"; selfContained?: boolean; }) => Promise<T>",
"writeContradictionsRun: (row: { run_id: string; judge_model: string; prompt_version: string; queries_evaluated: number; queries_with_contradiction: number; total_contradictions_flagged: number; wilson_ci_lower: number; wilson_ci_upper: number; judge_errors_total: number; cost_usd_total: number; duration_ms: number; source_tier_breakdown: Record<string, unknown>; report_json: Record<string, unknown>; }) => Promise<boolean>"
],
@@ -4345,7 +4354,7 @@
"dryRun?: boolean | undefined",
"includeFrontmatter?: boolean | undefined",
"jsonMode?: boolean | undefined",
- "mode: \"timeline\" | \"all\" | \"links\"",
+ "mode: \"timeline\" | \"links\" | \"all\"",
"quiet?: boolean | undefined",
"signal?: AbortSignal | undefined",
"slugs?: string[] | undefined",
@@ -6795,6 +6804,7 @@
"readManifest: (pageId: number, opts?: { generation?: number; stagingId?: string; region?: BodyRegion; lastN?: number; }) => Promise<ManifestRow[]>",
"readPageSnapshot: (slug: string, opts?: PageSnapshotOptions) => Promise<PageSnapshot | null>",
"readPageSnapshotsBatch: (refs: ReadonlyArray<{ slug: string; sourceId: string; }>, opts?: { maxBytes?: number; includeDeleted?: boolean; absentIsNull?: boolean; }) => Promise<PageSnapshotBatch>",
+ "readSegmentDerivations: (pageId: number, opts?: { kind?: SegmentDerivationKind; occurrenceIds?: readonly number[]; }) => Promise<SegmentDerivationRow[]>",
"readSegmentTexts: (sourceId: string, sha256s: readonly Uint8Array[]) => Promise<Map<string, Uint8Array>>",
"readonly kind: \"pglite\"",
"reconnect: (_ctx?: { error?: unknown; }) => Promise<void>",
@@ -6814,6 +6824,7 @@
"resolveSlugsByPaths: (paths: string[], opts: { sourceId: string; }) => Promise<Map<string, string>>",
"resolveTake: (pageId: number, rowNum: number, resolution: TakeResolution) => Promise<void>",
"restorePage: (slug: string, opts?: { sourceId?: string; }) => Promise<boolean>",
+ "retireSegmentDerivations: (pageId: number, liveOccurrenceIds: readonly number[], opts?: { kind?: SegmentDerivationKind; }) => Promise<number>",
"revertToVersion: (slug: string, versionId: number, opts?: { sourceId?: string; }) => Promise<void>",
"rewriteLinks: (_oldSlug: string, _newSlug: string) => Promise<void>",
"runMigration: (_version: number, sql: string) => Promise<void>",
@@ -6854,6 +6865,7 @@
"upsertChunks: (slug: string, chunks: ChunkInput[], opts?: { sourceId?: string; embeddingColumn?: ResolvedColumn; expectedRevision?: string; sealChunkerVersion?: number; pageId?: number; deferSeal?: true; } & BatchOpts) => Promise<void>",
"upsertEventProjection: (opts: { depthSlug: string; eventSlug: string; date: string; summary: string; detail?: string; sourceId?: string; }) => Promise<{ projected: boolean; }>",
"upsertFile: (spec: FileSpec) => Promise<{ id: number; created: boolean; }>",
+ "upsertSegmentDerivations: (rows: readonly SegmentDerivationInput[]) => Promise<void>",
"walRepairReceipt: WalRepairReceipt | null",
"withReservedConnection: <T>(fn: (conn: ReservedConnection) => Promise<T>) => Promise<T>",
"writeContradictionsRun: (row: { run_id: string; judge_model: string; prompt_version: string; queries_evaluated: number; queries_with_contradiction: number; total_contradictions_flagged: number; wilson_ci_lower: number; wilson_ci_upper: number; judge_errors_total: number; cost_usd_total: number; duration_ms: number; source_tier_breakdown: Record<string, unknown>; report_json: Record<string, unknown>; }) => Promise<boolean>"
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index 0d27d340dd..92dd72f220 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,11 +1,12 @@
{
"golden": {
- "count": 258,
+ "count": 259,
"gaps": [
17,
18,
19,
- 100
+ 100,
+ 264
],
"helpers": {
"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",
@@ -72,7 +73,7 @@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 263,
+ "latest": 265,
"records": [
{
"handler": {
@@ -4188,6 +4189,23 @@
"transaction": "absent",
"verify": "absent",
"version": 263
+ },
+ {
+ "handler": {
+ "form": "arrow",
+ "helpers": [],
+ "sha256": "bfe715b8aacdf09fc7b396f6fedfd37b19044764232fa0837facb37b405bd1ef"
+ },
+ "idempotent": true,
+ "name": "segment_derivations",
+ "sql": {
+ "length": 1640,
+ "sha256": "b3ca53ee2f2e2a30fde6d9b6219e08edaefaa9daccbffdc3676644e580aaacad"
+ },
+ "sqlFor": "absent",
+ "transaction": false,
+ "verify": "absent",
+ "version": 265
}
],
"versions": [
@@ -4448,7 +4466,8 @@
260,
261,
262,
- 263
+ 263,
+ 265
]
},
"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.json
index 6e744b2f69..274f0e7907 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -100,6 +100,7 @@
"facts.facts_notability_check": "c CHECK ((notability = ANY (ARRAY['high'::text, 'medium'::text, 'low'::text])))",
"facts.facts_pkey": "p PRIMARY KEY (id)",
"facts.facts_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "facts.facts_source_window_chk": "c CHECK (((source_window IS NULL) OR ((jsonb_typeof(source_window) = 'object'::text) AND (jsonb_typeof((source_window -> 'occurrence_id'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_ordinal'::text)) = 'number'::text) AND (jsonb_typeof((source_window -> 'window_text_sha'::text)) = 'string'::text))))",
"facts.facts_superseded_by_fkey": "f FOREIGN KEY (superseded_by) REFERENCES facts(id) ON DELETE SET NULL",
"facts.facts_trust_tier_check": "c CHECK ((trust_tier = ANY (ARRAY['user_confirmed'::text, 'operator_curated'::text, 'tool_observed'::text, 'agent_written'::text, 'unknown'::text, 'external_untrusted'::text])))",
"facts.facts_visibility_check": "c CHECK ((visibility = ANY (ARRAY['private'::text, 'world'::text])))",
@@ -258,6 +259,13 @@
"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_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))",
+ "page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",
+ "page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))",
+ "page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",
+ "page_segment_derivations.page_segment_derivations_state_check": "c CHECK ((state = ANY (ARRAY['done'::text, 'partial'::text, 'failed'::text, 'skipped'::text])))",
"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)",
@@ -794,6 +802,9 @@
"page_retrievals": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_segment_derivations": [
+ "<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"
],
@@ -1295,6 +1306,8 @@
"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_derivations_pkey": "CREATE UNIQUE INDEX page_segment_derivations_pkey ON public.page_segment_derivations USING btree (page_id, pipeline, occurrence_id)",
+ "page_segment_derivations_unsettled": "CREATE INDEX page_segment_derivations_unsettled ON public.page_segment_derivations USING btree (pipeline, page_id) WHERE (state = ANY (ARRAY['partial'::text, 'failed'::text]))",
"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_view_digests_pkey": "CREATE UNIQUE INDEX page_view_digests_pkey ON public.page_view_digests USING btree (page_id, revision, view, audience)",
@@ -2282,7 +2295,8 @@
"40 last_written_at timestamp with time zone/timestamptz NULL",
"41 attributed_to text/text NULL",
"42 trust_tier text/text NOT NULL DEFAULT 'unknown'::text",
- "43 write_origin jsonb/jsonb NULL"
+ "43 write_origin jsonb/jsonb NULL",
+ "44 source_window jsonb/jsonb NULL"
],
"flags": "relkind=r rls=false force_rls=false"
},
@@ -2937,6 +2951,22 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_segment_derivations": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 occurrence_id bigint/int8 NOT NULL",
+ "4 pipeline_version integer/int4 NOT NULL",
+ "5 segment_sha256 bytea/bytea NOT NULL",
+ "6 context_hash bytea/bytea NOT NULL",
+ "7 state text/text NOT NULL",
+ "8 output jsonb/jsonb NULL",
+ "9 receipt jsonb/jsonb NULL",
+ "10 created_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()",
+ "11 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_segment_texts": {
"columns": [
"1 source_id text/text NOT NULL",
diff --git a/test/fixtures/goldens/sql-text/_classification.json b/test/fixtures/goldens/sql-text/_classification.json
index a0cd35f1de..1bda00bb67 100644
--- a/test/fixtures/goldens/sql-text/_classification.json
+++ b/test/fixtures/goldens/sql-text/_classification.json
@@ -14,7 +14,7 @@
"out-of-scope:internal-helper (private; exercised through public callers)": 19,
"out-of-scope:lifecycle (connection, pool, transaction, raw seams)": 16,
"out-of-scope:no-sql-stub": 1,
- "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)": 11,
+ "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)": 14,
"out-of-scope:raw-data": 2,
"out-of-scope:search (FTS/vector hot paths, dialect-specific, not a W1 domain)": 5,
"out-of-scope:shared-read-enrichment (already one SQL copy in search/read-enrichment.ts)": 9,
@@ -174,6 +174,7 @@
"readManifest": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",
"readPageSnapshot": "pages",
"readPageSnapshotsBatch": "pages",
+ "readSegmentDerivations": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",
"readSegmentTexts": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",
"reconnect": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
"refreshPageBody": "pages",
@@ -193,6 +194,7 @@
"resolveSlugsByPaths": "pages",
"resolveTake": "takes",
"restorePage": "pages",
+ "retireSegmentDerivations": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",
"revertToVersion": "pages",
"rewriteLinks": "out-of-scope:no-sql-stub",
"rlsScopeBindingEnabled": "out-of-scope:internal-helper (private; exercised through public callers)",
@@ -238,6 +240,7 @@
"upsertChunks": "chunks",
"upsertEventProjection": "timeline",
"upsertFile": "files",
+ "upsertSegmentDerivations": "out-of-scope:page-body (Wave B segmented storage, born in engine-sql/page-body.ts; pinned by test/engine-sql-page-body.test.ts)",
"vectorIterativeScanSupported": "out-of-scope:internal-helper (private; exercised through public callers)",
"withReservedConnection": "out-of-scope:lifecycle (connection, pool, transaction, raw seams)",
"withScopedReadTransaction": "out-of-scope:internal-helper (private; exercised through public callers)",
diff --git a/test/helpers/engine-sql-rollback-cases.ts b/test/helpers/engine-sql-rollback-cases.ts
index 78d0e7f352..e2a08fcbcb 100644
--- a/test/helpers/engine-sql-rollback-cases.ts
+++ b/test/helpers/engine-sql-rollback-cases.ts
@@ -20,7 +20,8 @@ import { invalidateStaleSignatureEmbeddingsGuarded } from '../../src/core/embedd
import { 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';
+import { chunk, flipInput, hexOf, manifestRow, pageMeta, publishSegmentedPage, segmentText, sha256, stageGeneration, stagingInput } from './page-body-fixtures.ts';
+import type { SegmentDerivationInput, SegmentDerivationKind, SegmentDerivationState } from '../../src/core/page-body/derivations.ts';
export interface RollbackCase {
domain: string;
@@ -451,8 +452,36 @@ export const ROLLBACK_CASES: RollbackCase[] = [
},
observe: engine => segmentTextExists(engine, ORPHAN_TEXT),
},
+ {
+ domain: 'page-body (upsertSegmentDerivations)',
+ async seed(engine) {
+ await seedSegmentedPage(engine, SEGMENTED_SLUG);
+ await engine.upsertSegmentDerivations([derivationRow(await segmentedPageId(engine, SEGMENTED_SLUG), 'links', 1, 'partial')]);
+ },
+ async write(tx) { await tx.upsertSegmentDerivations([derivationRow(await segmentedPageId(tx, SEGMENTED_SLUG), 'links', 1, 'done')]); },
+ async observe(engine) {
+ return (await engine.readSegmentDerivations(await segmentedPageId(engine, SEGMENTED_SLUG), { kind: 'links' })).map(r => r.state);
+ },
+ },
+ {
+ domain: 'page-body (retireSegmentDerivations)',
+ async seed(engine) {
+ await seedSegmentedPage(engine, SEGMENTED_SLUG);
+ const pageId = await segmentedPageId(engine, SEGMENTED_SLUG);
+ await engine.upsertSegmentDerivations([derivationRow(pageId, 'mentions', 1, 'done'), derivationRow(pageId, 'mentions', 2, 'done')]);
+ },
+ async write(tx) { expect(await tx.retireSegmentDerivations(await segmentedPageId(tx, SEGMENTED_SLUG), [1], { kind: 'mentions' })).toBe(1); },
+ async observe(engine) {
+ return (await engine.readSegmentDerivations(await segmentedPageId(engine, SEGMENTED_SLUG), { kind: 'mentions' })).map(r => r.occurrenceId);
+ },
+ },
];
+function derivationRow(pageId: number, kind: SegmentDerivationKind, occurrenceId: number, state: SegmentDerivationState): SegmentDerivationInput {
+ return { pageId, kind, occurrenceId, version: 1, segmentSha256: sha256(`segment ${occurrenceId}`), contextHash: sha256(`context ${occurrenceId}`),
+ state, output: { n: occurrenceId }, receipt: null };
+}
+
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';
diff --git a/test/helpers/postgres-engine-sql-cases.ts b/test/helpers/postgres-engine-sql-cases.ts
index faf4d6ffbc..65d29ee1d5 100644
--- a/test/helpers/postgres-engine-sql-cases.ts
+++ b/test/helpers/postgres-engine-sql-cases.ts
@@ -116,6 +116,7 @@ export const DOMAIN_OF: Record<string, string> = {
'countChunklessPagesWithContent': 'chunks', 'listChunklessPagesWithContent': 'chunks', 'deleteChunks': 'chunks',
'readEmbeddingStateCounts': 'chunks', 'listEmbeddingStateRows': 'chunks',
'allocateBodyOccurrenceIds': OOS.pageBody, 'stageSegmentTexts': OOS.pageBody, 'readSegmentTexts': OOS.pageBody, 'stageManifestRows': OOS.pageBody, 'readManifest': OOS.pageBody, 'stageSegmentChunks': OOS.pageBody, 'createSegmentedPageShell': OOS.pageBody, 'flipBodyGeneration': OOS.pageBody, 'openBodyStaging': OOS.pageBody, 'setBodyStagingState': OOS.pageBody, 'sweepSegments': OOS.pageBody,
+ 'readSegmentDerivations': OOS.pageBody, 'upsertSegmentDerivations': OOS.pageBody, 'retireSegmentDerivations': OOS.pageBody,
'getEmbeddingsByChunkIds': 'chunks', 'getChunksWithEmbeddings': 'chunks',
// facts (incl. the ontology rows of the facts table)
'insertFact': 'facts', 'expireFact': 'facts', 'insertFacts': 'facts', 'deleteFactsForPage': 'facts',
diff --git a/test/helpers/segment-derivation-cases.ts b/test/helpers/segment-derivation-cases.ts
new file mode 100644
index 0000000000..01f669392d
--- /dev/null
+++ b/test/helpers/segment-derivation-cases.ts
@@ -0,0 +1,136 @@
+/**
+ * Per-segment derivation rows (engine-sql/page-body.ts readSegmentDerivations / upsertSegmentDerivations /
+ * retireSegmentDerivations, migration v265) and the facts.source_window column, shared by the PGLite arm
+ * (test/engine-sql-segment-derivations.test.ts) and the Postgres arm (test/e2e/segment-derivations-postgres.test.ts).
+ * The JSONB checks matter on Postgres, where a stringified `::jsonb` bind would store a string scalar.
+ */
+import { expect, test } from 'bun:test';
+import { randomUUID } from 'crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { ROW_BATCH_MAX_ROWS } from '../../src/core/batch-rows.ts';
+import { parseSourceWindow, sourceWindowFor, type SegmentDerivationInput, type SegmentDerivationKind,
+ type SegmentDerivationState } from '../../src/core/page-body/derivations.ts';
+import { hexOf, sha256 } from './page-body-fixtures.ts';
+
+async function freshPage(engine: BrainEngine): Promise<number> {
+ const slug = `notes/derivations-${randomUUID().slice(0, 8)}`;
+ await engine.putPage(slug, { type: 'note', title: 'Derivation probe', compiled_truth: 'body' });
+ const rows = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE slug = $1 AND source_id = 'default'", [slug]);
+ return Number(rows[0]!.id);
+}
+
+function row(pageId: number, kind: SegmentDerivationKind, occurrenceId: number, overrides: Partial<SegmentDerivationInput> = {}): SegmentDerivationInput {
+ return { pageId, kind, occurrenceId, version: 1, segmentSha256: sha256(`segment ${occurrenceId}`), contextHash: sha256(`context ${kind} ${occurrenceId}`),
+ state: 'done' as SegmentDerivationState, output: { links: [{ to: 'people/alice-example', at: occurrenceId }] }, receipt: null, ...overrides };
+}
+
+export function defineSegmentDerivationCases(opts: { getEngine: () => BrainEngine }): void {
+ test('rows round-trip bytes, JSONB objects and timestamps, ordered by kind then occurrence', async () => {
+ const engine = opts.getEngine();
+ const pageId = await freshPage(engine);
+ const output = { candidates: [{ slug: 'people/alice-example', context: 'met ☃ "quoted"' }], nested: { b: 2, a: [1, null] } };
+ await engine.upsertSegmentDerivations([
+ row(pageId, 'timeline', 20, { state: 'skipped', output: null, receipt: { reason: 'no_entries' } }),
+ row(pageId, 'links', 20, { output, version: 3 }),
+ row(pageId, 'links', 10, { state: 'failed', output: null, receipt: { error: 'timeout' } }),
+ ]);
+ const rows = await engine.readSegmentDerivations(pageId);
+ expect(rows.map(r => [r.kind, r.occurrenceId, r.state, r.version])).toEqual([['links', 10, 'failed', 1], ['links', 20, 'done', 3], ['timeline', 20, 'skipped', 1]]);
+ const links20 = rows[1]!;
+ expect(links20.pageId).toBe(pageId);
+ expect(hexOf(links20.segmentSha256)).toBe(hexOf(sha256('segment 20')));
+ expect(hexOf(links20.contextHash)).toBe(hexOf(sha256('context links 20')));
+ expect(links20.output).toEqual(output);
+ expect(links20.receipt).toBeNull();
+ expect(rows[2]!.receipt).toEqual({ reason: 'no_entries' });
+ expect(links20.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$/);
+ const kinds = await engine.executeRaw<{ o: string; r: string }>(
+ 'SELECT jsonb_typeof(output) AS o, jsonb_typeof(receipt) AS r FROM page_segment_derivations WHERE page_id = $1 AND pipeline = $2 AND occurrence_id = 10',
+ [pageId, 'links']);
+ expect(kinds).toEqual([{ o: null as unknown as string, r: 'object' }]);
+ const stored = await engine.executeRaw<{ t: string }>(
+ "SELECT jsonb_typeof(output) AS t FROM page_segment_derivations WHERE page_id = $1 AND pipeline = 'links' AND occurrence_id = 20", [pageId]);
+ expect(stored).toEqual([{ t: 'object' }]);
+ });
+
+ test('an upsert replaces the row under the same key, keeps created_at and moves updated_at', async () => {
+ const engine = opts.getEngine();
+ const pageId = await freshPage(engine);
+ await engine.upsertSegmentDerivations([row(pageId, 'mentions', 7, { state: 'partial' })]);
+ await engine.executeRaw("UPDATE page_segment_derivations SET created_at = now() - interval '1 hour', updated_at = now() - interval '1 hour' WHERE page_id = $1", [pageId]);
+ const [before] = await engine.readSegmentDerivations(pageId);
+ await engine.upsertSegmentDerivations([row(pageId, 'mentions', 7, { state: 'done', version: 2, segmentSha256: sha256('new text'), output: { found: ['acme-example'] } })]);
+ const after = await engine.readSegmentDerivations(pageId);
+ expect(after.length).toBe(1);
+ expect(after[0]!.state).toBe('done');
+ expect(after[0]!.version).toBe(2);
+ expect(hexOf(after[0]!.segmentSha256)).toBe(hexOf(sha256('new text')));
+ expect(after[0]!.output).toEqual({ found: ['acme-example'] });
+ expect(after[0]!.createdAt).toBe(before!.createdAt);
+ expect(after[0]!.updatedAt > before!.updatedAt).toBe(true);
+ });
+
+ test('reads filter by kind and occurrence; an empty occurrence list reads nothing', async () => {
+ const engine = opts.getEngine();
+ const pageId = await freshPage(engine);
+ await engine.upsertSegmentDerivations([row(pageId, 'links', 1), row(pageId, 'links', 2), row(pageId, 'synopsis', 1)]);
+ expect((await engine.readSegmentDerivations(pageId, { kind: 'links' })).map(r => r.occurrenceId)).toEqual([1, 2]);
+ expect((await engine.readSegmentDerivations(pageId, { occurrenceIds: [1] })).map(r => r.kind)).toEqual(['links', 'synopsis']);
+ expect((await engine.readSegmentDerivations(pageId, { kind: 'synopsis', occurrenceIds: [2] }))).toEqual([]);
+ expect(await engine.readSegmentDerivations(pageId, { occurrenceIds: [] })).toEqual([]);
+ expect(await engine.readSegmentDerivations(pageId + 100_000)).toEqual([]);
+ });
+
+ test('retire deletes only rows of occurrences outside the live set, per kind or for every kind', async () => {
+ const engine = opts.getEngine();
+ const pageId = await freshPage(engine);
+ const other = await freshPage(engine);
+ await engine.upsertSegmentDerivations([row(pageId, 'links', 1), row(pageId, 'links', 2), row(pageId, 'links', 3),
+ row(pageId, 'timeline', 2), row(pageId, 'timeline', 4), row(other, 'links', 2)]);
+ expect(await engine.retireSegmentDerivations(pageId, [1, 3], { kind: 'links' })).toBe(1);
+ expect((await engine.readSegmentDerivations(pageId)).map(r => `${r.kind}:${r.occurrenceId}`)).toEqual(['links:1', 'links:3', 'timeline:2', 'timeline:4']);
+ expect(await engine.retireSegmentDerivations(pageId, [1])).toBe(3);
+ expect((await engine.readSegmentDerivations(pageId)).map(r => `${r.kind}:${r.occurrenceId}`)).toEqual(['links:1']);
+ expect(await engine.retireSegmentDerivations(pageId, [])).toBe(1);
+ expect((await engine.readSegmentDerivations(other)).length).toBe(1);
+ });
+
+ test('more rows than one statement batch all land', async () => {
+ const engine = opts.getEngine();
+ const pageId = await freshPage(engine);
+ const count = ROW_BATCH_MAX_ROWS * 2 + 7;
+ await engine.upsertSegmentDerivations(Array.from({ length: count }, (_, i) => row(pageId, 'fences', i + 1)));
+ expect((await engine.readSegmentDerivations(pageId, { kind: 'fences' })).length).toBe(count);
+ });
+
+ test('the table refuses an unknown pipeline, a short hash and an unknown state, and goes with its page', async () => {
+ const engine = opts.getEngine();
+ const pageId = await freshPage(engine);
+ await expect(engine.upsertSegmentDerivations([row(pageId, 'nope' as SegmentDerivationKind, 1)])).rejects.toThrow();
+ await expect(engine.upsertSegmentDerivations([row(pageId, 'links', 1, { segmentSha256: new Uint8Array(31) })])).rejects.toThrow();
+ await expect(engine.upsertSegmentDerivations([row(pageId, 'links', 1, { state: 'pending' as SegmentDerivationState })])).rejects.toThrow();
+ await engine.upsertSegmentDerivations([row(pageId, 'links', 1)]);
+ await engine.executeRaw('DELETE FROM pages WHERE id = $1', [pageId]);
+ const left = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_segment_derivations WHERE page_id = $1', [pageId]);
+ expect(Number(left[0]!.n)).toBe(0);
+ });
+
+ test('facts.source_window stores a window anchor as a JSONB object and refuses a malformed one', async () => {
+ const engine = opts.getEngine();
+ const window = sourceWindowFor(42, 3, 'user: hello\nassistant: hi\n');
+ const slug = `conversations/window-${randomUUID().slice(0, 8)}`;
+ const inserted = await engine.executeRaw<{ id: number }>(
+ "INSERT INTO facts (fact, source, source_markdown_slug, source_window) VALUES ('likes tea', 'test:window', $1, $2::text::jsonb) RETURNING id",
+ [slug, JSON.stringify(window)]);
+ const read = await engine.executeRaw<{ w: unknown; t: string }>('SELECT source_window AS w, jsonb_typeof(source_window) AS t FROM facts WHERE id = $1', [inserted[0]!.id]);
+ expect(read[0]!.t).toBe('object');
+ const value = typeof read[0]!.w === 'string' ? JSON.parse(read[0]!.w as string) : read[0]!.w;
+ expect(parseSourceWindow(value)).toEqual(window);
+ const nulls = await engine.executeRaw<{ n: number }>("INSERT INTO facts (fact, source) VALUES ('no window', 'test:window') RETURNING (source_window IS NULL)::int AS n");
+ expect(Number(nulls[0]!.n)).toBe(1);
+ await expect(engine.executeRaw("INSERT INTO facts (fact, source, source_window) VALUES ('bad', 'test:window', $1::text::jsonb)",
+ [JSON.stringify(JSON.stringify(window))])).rejects.toThrow();
+ await expect(engine.executeRaw("INSERT INTO facts (fact, source, source_window) VALUES ('bad', 'test:window', $1::text::jsonb)",
+ [JSON.stringify({ occurrence_id: '42', window_ordinal: 3, window_text_sha: window.window_text_sha })])).rejects.toThrow();
+ });
+}
diff --git a/test/large-pages/segment-derivations-plan.test.ts b/test/large-pages/segment-derivations-plan.test.ts
new file mode 100644
index 0000000000..92647d0d2c
--- /dev/null
+++ b/test/large-pages/segment-derivations-plan.test.ts
@@ -0,0 +1,84 @@
+/**
+ * Pure helpers of the per-segment derivation interface (page-body/derivations.ts): the work plan from manifest
+ * metadata, the context hash and the facts.source_window identity. Engine rows: test/engine-sql-segment-derivations.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'crypto';
+import { parseSourceWindow, planSegmentDerivations, segmentDerivationContextHash, sourceWindowFor, sourceWindowKey,
+ SEGMENT_DERIVATION_KINDS, type LiveSegment, type SegmentDerivationRow } from '../../src/core/page-body/derivations.ts';
+
+const h = (s: string) => new Uint8Array(createHash('sha256').update(s).digest());
+const live = (occurrenceId: number, text = `t${occurrenceId}`, context = 'c'): LiveSegment => ({ occurrenceId, sha256: h(text), contextHash: h(context) });
+function stored(occurrenceId: number, overrides: Partial<SegmentDerivationRow> = {}): SegmentDerivationRow {
+ return { pageId: 1, kind: 'links', occurrenceId, version: 2, segmentSha256: h(`t${occurrenceId}`), contextHash: h('c'), state: 'done',
+ output: null, receipt: null, createdAt: '', updatedAt: '', ...overrides };
+}
+
+describe('planSegmentDerivations', () => {
+ test('settled rows with matching text, context and version are current; new occurrences are todo; gone ones are retired', () => {
+ const plan = planSegmentDerivations('links', 2, [live(1), live(2), live(5)], [stored(1), stored(2), stored(3)]);
+ expect(plan.current.map(r => r.occurrenceId)).toEqual([1, 2]);
+ expect(plan.todo.map(s => s.occurrenceId)).toEqual([5]);
+ expect(plan.retired.map(r => r.occurrenceId)).toEqual([3]);
+ });
+
+ test('a changed text, a changed context or another version is redone; partial and failed are redone; skipped is settled', () => {
+ const rows = [stored(1), stored(2), stored(3, { version: 1 }), stored(4, { state: 'partial' }), stored(5, { state: 'failed' }), stored(6, { state: 'skipped' })];
+ const plan = planSegmentDerivations('links', 2, [live(1, 'edited'), live(2, 't2', 'title changed'), live(3), live(4), live(5), live(6)], rows);
+ expect(plan.todo.map(s => s.occurrenceId)).toEqual([1, 2, 3, 4, 5]);
+ expect(plan.current.map(r => r.occurrenceId)).toEqual([6]);
+ expect(plan.retired).toEqual([]);
+ });
+
+ test('rows of another pipeline never count', () => {
+ const plan = planSegmentDerivations('timeline', 2, [live(1)], [stored(1), stored(9)]);
+ expect(plan.todo.map(s => s.occurrenceId)).toEqual([1]);
+ expect(plan.current).toEqual([]);
+ expect(plan.retired).toEqual([]);
+ });
+});
+
+describe('segmentDerivationContextHash', () => {
+ test('is 32 bytes and ignores key order at every depth, as a JSONB round trip reorders keys', () => {
+ const a = segmentDerivationContextHash('links', { entryState: { fence: { depth: 1, open: false }, date: '2026-01-02' }, page: { title: 'T', type: 'note' } });
+ const b = segmentDerivationContextHash('links', { entryState: { date: '2026-01-02', fence: { open: false, depth: 1 } }, page: { type: 'note', title: 'T' } });
+ expect(a.byteLength).toBe(32);
+ expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true);
+ });
+
+ test('moves with the pipeline, the entry state and each page-level input', () => {
+ const base = { entryState: { fence: null }, page: { title: 'T', gazetteer_generation: 4 } };
+ const hex = (x: Uint8Array) => Buffer.from(x).toString('hex');
+ const hashes = new Set([
+ hex(segmentDerivationContextHash('links', base)),
+ hex(segmentDerivationContextHash('mentions', base)),
+ hex(segmentDerivationContextHash('links', { ...base, entryState: { fence: 'open' } })),
+ hex(segmentDerivationContextHash('links', { ...base, page: { title: 'T2', gazetteer_generation: 4 } })),
+ hex(segmentDerivationContextHash('links', { ...base, page: { title: 'T', gazetteer_generation: 5 } })),
+ ]);
+ expect(hashes.size).toBe(5);
+ });
+
+ test('every kind the table accepts is a distinct hash domain', () => {
+ const seen = new Set(SEGMENT_DERIVATION_KINDS.map(k => Buffer.from(segmentDerivationContextHash(k, { entryState: null, page: {} })).toString('hex')));
+ expect(seen.size).toBe(SEGMENT_DERIVATION_KINDS.length);
+ });
+});
+
+describe('source windows', () => {
+ test('identity is occurrence, ordinal and the text hash', () => {
+ const w = sourceWindowFor(42, 3, 'user: hi\n');
+ expect(w).toEqual({ occurrence_id: 42, window_ordinal: 3, window_text_sha: createHash('sha256').update('user: hi\n').digest('hex') });
+ expect(sourceWindowKey(w)).toBe(`42:3:${w.window_text_sha}`);
+ expect(sourceWindowKey(sourceWindowFor(42, 3, 'user: hi!\n'))).not.toBe(sourceWindowKey(w));
+ });
+
+ test('parse accepts a stored anchor and NULL, and throws on what the column CHECK refuses', () => {
+ const w = sourceWindowFor(1, 0, 'x');
+ expect(parseSourceWindow({ ...w })).toEqual(w);
+ expect(parseSourceWindow(null)).toBeNull();
+ for (const bad of [JSON.stringify(w), [w], { ...w, occurrence_id: '1' }, { ...w, window_ordinal: 1.5 }, { ...w, window_text_sha: 'ABC' }]) {
+ expect(() => parseSourceWindow(bad)).toThrow('malformed facts.source_window');
+ }
+ });
+});
diff --git a/test/migrations-golden.test.ts b/test/migrations-golden.test.ts
index 5eb1bcd0e9..49b23f8911 100644
--- a/test/migrations-golden.test.ts
+++ b/test/migrations-golden.test.ts
@@ -33,7 +33,8 @@ describe('migrations full-record golden', () => {
expect(new Set(versions).size).toBe(versions.length);
const sorted = [...versions].sort((a, b) => a - b);
const golden = buildMigrationsGolden(MIGRATIONS);
- expect(golden.gaps).toEqual([17, 18, 19, 100]);
+ // 264: Wave B PR 4's placeholder v265 leaves room for the follow-up wave's v264; release:restamp renumbers it at merge.
+ expect(golden.gaps).toEqual([17, 18, 19, 100, 264]);
expect(sorted[0]).toBe(2);
expect(sorted[sorted.length - 1]).toBe(LATEST_VERSION);
}, 60_000);
diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.ts
index eac300c7be..c0216ad9a1 100644
--- a/test/schema-bootstrap-coverage.test.ts
+++ b/test/schema-bootstrap-coverage.test.ts
@@ -1005,6 +1005,9 @@ const COLUMN_EXEMPTIONS = new Set<string>([
// (absent from PGLITE_SCHEMA_SQL), so no schema-blob forward reference can
// exist; nullable column only, no index or FK.
'facts.attributed_to',
+ // migration v265 (Wave B PR 4) — conversation window anchor. Same precedent: the facts table is migration-created,
+ // so no schema-blob forward reference can exist; nullable column plus a CHECK, no index or FK.
+ 'facts.source_window',
// v0.42.56.0 (migration v122, #2390) — Life Chronicle ontology columns.
// Same precedent as facts.claim_metric et al: the `facts` table itself is
// migration-created (absent from PGLITE_SCHEMA_SQL), so no schema-blob