Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(extract): per-page extraction watermark; facts and atoms read the appended tail (A7, F24)

garrytan606f9f3d3cac
diff --git a/docs/architecture/key-files/commands-2-continued.md b/docs/architecture/key-files/commands-2-continued.md
index bbd8c861a9..81c4724613 100644
--- a/docs/architecture/key-files/commands-2-continued.md
+++ b/docs/architecture/key-files/commands-2-continued.md
@@ -17,6 +17,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/doctor/checks/search-eval.ts` — search, model, and AI-config health checks. `checkSearchMode` (`search_mode`) reports the resolved mode and its `search.*` overrides; when the only override is an explicit `search.reranker.model` row equal to the mode bundle's own default (a row an init may have written on Voyage installs) it is called redundant with the precise `gbrain config unset search.reranker.model` — never a `--reset`, which would also wipe every other tuned search knob.
- `src/commands/doctor/checks/atom-holds.ts` — `extract_atoms_held_failed` (#6325, BRAIN, registered before `fence_integrity`). Lists `listHeldManagedAtoms` (`persistence/atom-maintenance.ts`): managed atom pages and transcripts held after `MAX_DETERMINISTIC_FAILURES` failed extractions of their current content (code `held_failed`) that no later run completed, each with its last request id, failure, `receipt_command` and `retry_command`. Warns with a paid `fix` (the reviewed `gbrain jobs submit extract-atoms-drain --params '{sourceId, retryRequestId}'` retry of the first item). Local doctor only; `run_doctor` does not include it. Tests: `test/managed-atoms-retry.test.ts`.
+- `src/commands/doctor/checks/extraction-input.ts` — `extraction_input_truncated` (large pages A7, BRAIN, registered after `fence_integrity`, before `search_mode`). Groups the live pages with an `input_truncated` receipt in `page_extraction_state` by pipeline and kind (`facts_backstop/head|tail_window`, `extract_atoms/head|tail_window`, `conversation_facts/skipped_too_large`) with three recent `source:slug` samples and a remedy each. Warns when an atoms or conversation-facts receipt exists; the atoms fix is `gbrain config set cycle.extract_atoms.max_input_chars <n>` (`ask_user`, consent `paid`), otherwise `fix_unavailable_reason: operator_judgement`. Facts-only receipts are `ok` with `severity: info`, `readiness_state: degraded` (no knob raises the facts cap; later appends are read incrementally). Reads the database only. Tests: `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`, `test/conversation-facts-oversized-sidecar.test.ts`.
- `src/commands/doctor/checks/fence-integrity.ts` — `fence_integrity` (#6188, BRAIN, registered before `search_mode`). Each run advances the fence census within `GBRAIN_DOCTOR_FENCE_TIMEOUT_MS` (default 10 s), then reports per source the malformed facts/takes fences still waiting, each counted once (held file, stored page, unsynced file) and split by planned tier (deterministic, resolver, llm, manual), the oldest hold's age, the 7-day `fences_normalized` trend with top writers (warns at `FENCE_NORMALIZATION_WARN_7D` = 20), and the model-repair caps with today's ledger spend. `ok` only when nothing waits, every source's census is complete and no source reaches the trend threshold; a partial census warns with the resume command. The fix is the read-only `gbrain repair fences --source <id>` preview for holds, stored pages and files alike; a warn reads `readFenceAutoRepair` (details `auto_repair`): while a maintenance run is active and `fences.repair.enabled` is on, the non-manual fences are "repaired automatically by the next maintenance run", otherwise the fix's `then` is the apply. Model-tier fences say why they wait (`fences.repair.llm` off with the command that turns it on, or today's budget spent with the cap command), else the caps. `fenceIntegrityCheck(engine, sourceIds?)` is the `WAVE_CHECKS` entry (scoped for a remote caller). Location only. #6278: the check also counts `unrenderable_legacy_facts`: the active `row_num IS NULL` fact rows the fence step leaves unadopted because the fence codec would change their text (or their page already carries the claim), planned read-only per source within the census time budget (`planUnfencedFacts` + `auditUnadoptableFacts`) and listed by page, fact id and reason class, never the claim text. They stay active and searchable, so the finding says nothing is lost, never suggests `forget_fact`, and when it is the only finding its fix carries no command (`next: report`) with the doctor re-count as verify; an incomplete scan asks for a rerun. Test: `test/doctor-fence-integrity.test.ts`.
- `src/commands/doctor/checks/git-convergence.ts` — `git_convergence` (#5063, brain category, after `sync_freshness`): for every non-archived filesystem source root plus `sync.repo_path` (connector sources skipped), `git status --porcelain -z` and `rev-list --left-right --count @{u}...HEAD` against the local upstream ref, never a fetch, each call bounded at 5 s and at most 50 roots. Commits not on the upstream warn after 6 h and fail after 24 h (oldest unpushed commit time); uncommitted changes warn once the oldest changed file is older than 6 h; behind is reported, not judged. Emits nothing when no probed root has an upstream. The same entry emits `tracked_ownership_marker` (#5186): `git ls-files --cached` on each of those checkouts, warn when a path `isPhysicalRootMetadata` recognizes is in the index, with a user-run `git -C <root> rm --cached <paths>` fix (an ignore rule never un-tracks a file; the push deny list is the backstop), ok otherwise, nothing without a checkout. `bootstrap-checks.ts` `bootstrap_push_health` also warns, instead of `ok`, when a recent successful push leaves the receipt workspace ahead of `origin/<branch>`. `scripts/smoke-test.sh` accepts a configured database URL (`engine status` `db_url_source`) and trusts doctor `embedding_provider` over raw OpenAI/Voyage keys. Tests: `doctor-git-convergence-5063.test.ts`, `doctor-ownership-marker.test.ts`, `bootstrap-doctor-checks.test.ts`, `smoke-test-worker.test.ts`.
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 0f935ec235..867dbcc459 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -21,7 +21,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/cycle/extract-atoms-budget-notice.ts` — #6425: `drainBudgetNotice(result)` renders the `atom_drain_budget` notice a `budget`-stopped drain carries in `gbrain dream --drain --json` (spend, per-run cap, pages left; paid fix `gbrain config set cycle.extract_atoms.budget_usd <USD>`, verify `gbrain config get`), and `usd` formats the amounts for the stderr stop line. Dynamically imported by `dream.ts` so its notice-rendering imports stay out of the CLI flag scan. Tests: `test/dream-drain-failure-summary.serial.test.ts`.
-- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).
+- `src/core/cycle/extract-atoms-input.ts` — #6503 the input cap and the partial disposition. `resolveExtractAtomsInputCap` reads `cycle.extract_atoms.max_input_chars` (floor 1000; the older `max_source_chars`, floor 500, loses when both are set; default 50 000) before discovery. `extractAtomsInput(item, cap)` binds the cut once: paste-stripped for a transcript (#5812), UTF-8-safe, with `truncated` measured on the text the cap applied to. A page item also takes its stored `extract_atoms` watermark (`src/core/extraction-watermark.ts`, large pages A7): when the body still starts with the watermarked prefix the model reads only the appended text (its newest `cap` characters when longer), which is still partial input, so the same disposition below applies; `inputTruncatedLine` is null for a complete tail read (not counted, no stderr) and names the window otherwise, and the phase commits the plan once the item's writes committed (a pending managed batch keeps the old watermark). A cut item is extracted once from its head and gets a partial disposition instead of a completion: `input_truncated` counts it on the phase result (and the drain sums it into `input_truncated`, with one `[drain]` line), `inputTruncatedLine` is written to stderr naming the knob, the head atoms publish, no completion stamp is written and nothing is retired. `recordPartialDisposition` stores the cap under (content hash, cap) in `extract_atoms_page_state` / `extract_atoms_transcript_state.partial_input_chars` (migration v240; the page row is pinned to the identity discovery read), and on a managed brain the origin carries `partialInputChars`, which enters the run key, keeps the completion's checkpoint `partial`, skips the page-state stamp and the retirement, and marks the completion outcome `status: 'partial'`. Discovery and the backlog count skip a partial row like a tombstone (`PAGE_SCAN_STATE_EXCLUSION_SQL`, `tombstonedTranscriptsForHashes`, the partial checkpoint); `releasePartialDispositions` runs before discovery with the current cap and clears the rows and checkpoints a raised cap supersedes, so the item is eligible again with zero model calls in between; a content change is a new row. Resumed and budget-skipped items are not counted. `stampTranscriptTombstone` (v146) lives here too. Tests: `test/extract-atoms-input-truncated-6503.test.ts` (PGLite and Postgres, page and transcript, managed and unmanaged).
- `src/core/cycle/extract-atoms.ts` — the extract_atoms lens phase: mines eligible pages into `atoms/<date>/<stem>-<hash>` pages. The input cap, the cut and the partial disposition of a cut item are in `extract-atoms-input.ts` (#6503). Transcript input is paste-stripped before the cut (#5812); discovery skips self-captures (#5820). Discovery and the backlog count append `connectorAtomExclusionSql` (`connector-atoms.ts`), so connector `email`/`meeting` pages stay out only when `cycle.extract_atoms.connector_pages` is false. The type allowlist is `unionExtractableTypes(packExtractable, packExcluded)`: the legacy floor (meeting, source, article, video, book, original) minus the floor types the active pack declares not extractable (`nonExtractableTypesFromPack`, #5756; a declared type without `extractable: true` is a pack decision, an undeclared type keeps the floor), plus the pack's `extractable: true` types, minus synthesis outputs; gbrain-base is unchanged, gbrain-recommended's `source: false` now holds for atoms as it did for facts. Pinned by `test/pack-extractable-floor-5756.test.ts`. A drain attempt passes `opts.attempt` (`budgetTracker`, `writeWait`) so its batches share one budget and one maintenance publish wait. Eligibility reads source-incarnation/page/full-hash-keyed derived scan state; scan and failure markers do not mutate canonical frontmatter. Managed extraction checks source-wide local authority and owner readiness before provider work, admits outputs plus a completion request together, and replays retained output without another model call. A failed managed batch is retried by the next run instead (#6325, `resumeManagedAtoms` in `persistence/atom-maintenance.ts`); an origin held after `MAX_DETERMINISTIC_FAILURES` (now defined in `extract-atoms-page-state.ts`, re-exported here) is skipped with no model call and counted in `details.held_failed`, never in `failures`. Managed atom files keep provisional source hashes; only the source-incarnation/page/full-hash durable completion receipt excludes an item from discovery and backlog counts. Unmanaged atom completion flips and their cardinality check share a transaction after provenance links persist, so a partial match rolls back and stays retryable. A page-derived atom upserts at its locator-folded slug, else a compatible legacy title-only slug; when both miss, the source page's live bound atoms are loaded once per page per run and exactly one JS-lowercased title match is adopted (a case-only title change never mints a duplicate; zero or several matches mint the new slug). Response parsing lives in `extract-atoms-parse.ts`. An undated source dates its atoms by the source page's creation date (`undated` for transcripts), never the run date. After an unmanaged item completes (`completeUnmanagedItem`), `retireStaleAtoms` soft-deletes that source's atoms from earlier extractions (other or provisional `source_hash`) that this extraction did not re-produce; a cut item neither completes nor retires. Hard `opts.signal` (chat call, pacing, checks before each item and commit) leaves no strike, receipt or rollup; soft `opts.stopSignal` stops before the next item.
Managed completion admits revision-pinned `managed_atom_delete` children alongside replacement pages, removes canonical files through the page deletion path, and commits its checkpoint only after every publication and retirement commits.
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.md
index dc0df7664a..9552c60b8c 100644
--- a/docs/architecture/key-files/core-utilities-1.md
+++ b/docs/architecture/key-files/core-utilities-1.md
@@ -33,6 +33,8 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy
- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.
+- `src/core/extraction-watermark.ts` — large pages A7: no silent head-only page extraction. `planExtraction(body, stored, { cap, pipeline, emptyTail })` decides what one extraction reads: the whole body when it fits `cap` (`full`); the text past a stored watermark when the body still starts with exactly the watermarked prefix (`tail`; UTF-8 byte offset + sha256 of the prefix + `EXTRACTION_PIPELINE_VERSION`), its newest `cap` characters when the tail is longer (receipt `tail_window`, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (`truncateUtf8`) with receipt `head` and reason `no_watermark` / `prefix_changed` / `version_changed` / `no_new_text`. An empty tail is a skip (`facts_backstop`) or a head re-read (`extract_atoms`, after a cap rise). `readPageWatermark` (by source + slug, fail-soft), `commitExtractionPlan` (after a successful extraction: the watermark moves to the end of the planned body; a full read clears `input_truncated`, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) and `setExtractionReceipt` (the conversation-facts size skip, no watermark) write `page_extraction_state` (migration v245; hashes, offsets and counts only, rows cascade with the page). Doctor `extraction_input_truncated` reads the receipts. Tests: `test/extraction-watermark.test.ts`, `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`.
+
- `src/core/env-number.ts` — numeric env-var resolution with ONE shared warn-once memo. `resolveEnvNumber(varName, fallback, {unit?})` (positive numbers only; zero/negative/garbage → warn once + fallback), `resolveHoursEnv` (hours unit pre-applied), `warnOnceForEnv(varName, message)` for disabled-unless-set vars that need the same memo without the fallback shape (e.g. `GBRAIN_EXTRACTION_LAG_FAIL_PCT`). Lives in core because `source-health.ts` needs the hours resolver for the staleness ceiling while `doctor.ts` already imports FROM `source-health.ts` — reaching back would cycle, and duplicating would fork the memo so one bad var warns twice. `doctor.ts` re-exports it as `_resolveEnvNumber` for `sync.ts`'s dynamic import. `_resetEnvNumberWarnedForTests()` is a test seam.
- `src/core/errors.ts` — `StructuredAgentError` + `buildError` + `serializeError`. Every agent-facing surface (code-def, code-refs, usage errors) uses this envelope; matches the `CycleReport.PhaseResult.error` shape.
diff --git a/docs/architecture/key-files/google-and-loops-continued.md b/docs/architecture/key-files/google-and-loops-continued.md
index 135d3fc00a..1d48a6a658 100644
--- a/docs/architecture/key-files/google-and-loops-continued.md
+++ b/docs/architecture/key-files/google-and-loops-continued.md
@@ -24,7 +24,7 @@
- `src/core/facts/withdrawal-overlay.ts` — pure legacy-fence enumeration and withdrawal rendering shared by coherent snapshots, stale imports and physical forget mirrors. The shared snapshot overlay and import pre-publication validator recognize canonical prefixed/inline markers and distinguish malformed live segments. Discovery refuses matching ambiguous claims before mutation. Fingerprints match independently in each fence, including inactive history, against both the folded (v174) and exact legacy hashes; parser-recognized markers precede preserved evidence context and earlier expiry remains intact. Regression: `test/withdrawal-overlay-concurrency.test.ts` on both engines.
- **`src/commands/sync-persistence-delegate.ts` + `src/core/persistence/{sync-wire,sync-administration}.ts`** — pre-connect authenticated CLI sync ingress for any resident PGLite owner, including stdio MCP. The CLI JSON renderer shares the direct sync envelope. Strict options preserve source/brain selection and filtering; only current CLI credentials can advance bounded durable cursor slices. Unactivated delegation also forces import-only work and queues the owner embed drain, preserving the inline cost gate; backlogs are per-engine source sets and shutdown waits for actual provider settlement before releasing datastore ownership; the real serve E2E observes a committed receipt before SIGKILL and proves same-ID cursor recovery without breaking locks. The env and default deadlines stay progress-aware across slices (`DelegatedSyncDeadline`): past the deadline the client keeps re-entering while a slice advanced the managed cursor within one progress window, and each slice gets at least one window; `--timeout` and `--hard-deadline` stay strict. Legacy shared-secret sync refuses managed brains. `test/persistence-sync-stdio-owner.test.ts` starts a real stdio owner and exercises CLI import/read/admin, remote-lane denial and revocation without a competing datastore open.
-- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them).
+- `src/core/facts/backstop.ts` + `src/core/entities/resolve-on-save.ts` — saved facts retain their content and provenance but use a NULL entity target when resolution falls back to slugification. Legacy extraction uses the shared exact source/entity/visibility fingerprint decision before identity-gated cosine candidates, so old facts without vector provenance still deduplicate identical text without relabeling their vectors. The conversation save caller also clears the target on ordinary resolution errors, preserves diagnostic counters, and propagates abort/budget failures. It never treats an invented slug as a verified page. #5836: `src/core/facts/subject-infer-write.ts` `inferMissingSubjects` links facts with no or fallback-only entity via `inferFactSubject` (remote callers: written page only, readable pages, caller fences, managed grant), never on the unmanaged DB-only branch, marks `entity_inferred` (context note; exact-text dedup only in both writers); `test/facts-backstop-entity-inference.test.ts`, `test/managed-facts-entity-inference.test.ts`. #6159: every writer (both backstop buckets, the fence writes and `persistence/facts-maintenance.ts`) dates a fact with `facts/event-time.ts` `factEventTime` (extractor date, then `validFrom`, then `turnAt`, then now) and the extraction prompt's observation date falls back to `turnAt`; the sweep's corpus pass sets `turnAt` from the session file's write time, vetted by `context/corpus-windows.ts` `corpusFactTime` (finite, from 2000, at most 60 s ahead; otherwise logged and dated at extraction) (`test/sweep-corpus-fact-time.test.ts`). #6113: `resolveManagedFactsEmbedding` (`persistence/facts-maintenance.ts`) reads the brain's DB-plane model only; a legacy row without a provider refuses `embedding_configuration` naming `gbrain migrate embeddings --to <gateway provider>:<model> --dry-run` (the read-only preview; applying it needs paid authorization). Test: `test/facts-embedding-bare-model.serial.test.ts`. The notability-filter vocabulary (`NOTABILITY_FILTERS`, `coerceNotabilityFilter`) lives in import-light `src/core/facts/notability-filter.ts` (re-exported here) beside the page-write key resolver. The unmanaged pipeline counts entity groups held on a facts fence that does not parse cleanly as `fence_refused` (nothing written for them). Large pages A7: the page entry (`runPipeline`) plans with the `facts_backstop` watermark (`src/core/extraction-watermark.ts`, cap `MAX_TURN_TEXT_CHARS`): past a matching watermark the extractor reads only the appended text (`PipelineInput.extractText`; `turnText` stays the full body, which the managed preparer compares with the page), an unchanged long page makes no model call, and a head or tail-window read returns `input_truncated` on the inline result; the plan commits after an extraction that neither failed nor aborted. Test: `test/extraction-watermark-facts.test.ts`.
- `src/commands/migrations/v0_32_2.ts` + `src/core/facts/unfenced-facts.ts` — Phase B is the shared core pass `planUnfencedFacts` / `fenceUnfencedFacts`, which the `extract_facts` cycle phase also runs on every cycle (#5299). It fences live unfenced facts (`row_num IS NULL`) only onto an existing source-scoped page, and never ontology observations (`dimension IS NOT NULL`, #6264: they belong to the ontology, keyed by their own provenance) and its recorded canonical file; a managed brain publishes each page as one coordinator `managed_maintenance_adopt_fact_fence` request (database-only pages included; a read-only pre-pass of `planManagedPage` counts the pages that will submit for the up-front lifetime-ID check, so suppressed or unadoptable pages never refuse the step, and the submit loop replans each page right before it submits; `test/fact-fence-adoption-exits.test.ts`), and an unmanaged page is written under the source filesystem lock and page lock (`.tmp` + parse + rename), mirrored into `pages` and stamped in one maintenance transaction, and committed when the checkout is durability-hardened. Missing pages/files are counted as `skipped_no_page` (missing files are also listed in `missing_files`), never materialized as stubs. The migration adds a dirty-tree refusal that stays inside the source subdirectory; fence row allocation respects both database-owned row numbers and the parsed fence, preserving idempotent recovery without collisions. Dry runs use the same eligibility checks, and historical drift remains visible rather than silently repaired. #6278: `planFence` uses the fence codec as the oracle (`adoptableClaim`): a legacy row adopts only when `parseFactsFence(renderFactsTable([row]))` hands its claim back active and non-empty with the same kind, visibility, validity and source, differing from the stored text by whitespace and line endings alone (trim, CRLF/CR to LF, NBSP), and the parsed text is written into `facts.fact` with the row number on both the managed and the unmanaged path, so the projection keeps the row's id, vectors and provenance. A row the codec would change further (whitespace-only, `~~x~~`, a literal `<br>`) or a second row whose normalized claim, source and visibility the page already carries stays a legacy row exactly as it is, recorded as an `UnadoptableFactRecord` (source, page, fact id, reason class; never the claim text) and named in `failed_pages` as `FACTS_FENCE_FAILED: <slug> (fence_unrenderable: N row(s), <class>)` in the cycle and the migration output; the page's other rows still adopt. Tests: `test/facts-fence-adoption-roundtrip.test.ts`, `test/extract-facts-unfenced-rows.test.ts`, `test/migrations-v0_32_2-managed.test.ts`.
- `src/core/google/loop-catchup.ts` — open-loop recovery passes the Gmail sweep runs (#5867, #5868). Grace holds: `recordGraceVerdict` keeps each thread `detectThreadLoop` grace-held (and `loopExtractionEligibility` passes) in connector state `loop_grace_holds` (cap `GRACE_HOLDS_CAP` 2,000, oldest pruned and logged; prose sanitized for jsonb), separate from connector item holds, so `connector_held_items` and `waiting` coverage never count them. `settleDueGraceHolds` opens a due hold from its stored spec when the page still carries the newest message id it was computed from (no Gmail read), otherwise re-fetches through `processThread` (at most `GRACE_REFETCH_PER_SWEEP` 100 per sweep; a 404 drops the hold, a failure keeps it due). `seedGraceBackfill` seeds holds once for email pages active in the last 14 days with no open deterministic loop, from stored pages only; the sweep sets `loop_grace_backfill_done` after a non-aborted sweep. Catch-up (managed sources only): `runLoopsCatchup` re-candidates email pages whose newest message is in the last 30 days; a page is settled by a revision-bound outcome (`recordLoopsExtractOutcome`, written by the `loops_extract` handler into `op_checkpoints` op `loops-extract-outcomes`, one statement, pruned past the window), not by job completion. It skips pages this sweep or a pending sweep job already queues, checks eligibility on the live thread, enqueues under its own key `loops-catchup:<source>:<slug>:<rev>` inside the waiting-depth ceiling, retries a dead-lettered job once (`:retry`) then settles it, honors the kill switch and chat availability, and sets `loops_catchup.done` only when every candidate is settled. Tests: `test/google-loops-recovery.serial.test.ts` (+ Postgres twin).
diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.ts
new file mode 100644
index 0000000000..8b18d9ea0c
--- /dev/null
+++ b/src/commands/doctor/checks/extraction-input.ts
@@ -0,0 +1,63 @@
+/**
+ * extraction_input_truncated (large pages A7): pages whose last extraction
+ * read only part of its input, from the durable `input_truncated` receipts in
+ * `page_extraction_state` (src/core/extraction-watermark.ts). Facts read the
+ * first 8,000 characters when no watermark matched (or the newest 8,000 of a
+ * long append); atoms read the first `cycle.extract_atoms.max_input_chars`;
+ * conversation facts skip an input over the size cap. Appends after a
+ * watermark are read incrementally, so the receipt marks text that was never
+ * read. Warn when a receipt has a remedy (the atoms cap, an oversized
+ * conversation input); facts-only receipts are reported as info. Reads the
+ * database only.
+ */
+import type { Check } from '../../doctor.ts';
+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';
+import { agentFix, checkError } from '../check-fix.ts';
+import { EXTRACT_MAX_INPUT_CHARS_KEY } from '../../../core/cycle/extract-atoms-input.ts';
+
+interface ReceiptGroup { pipeline: string; kind: string; pages: number; samples: string[] }
+
+const REMEDY: Record<string, string> = {
+ facts_backstop: 'later appends are extracted from the appended text; for a conversation page, gbrain extract-conversation-facts --slug <slug> reads every window of the body',
+ extract_atoms: `raise the cap so the next cycle reads more of each page: gbrain config set ${EXTRACT_MAX_INPUT_CHARS_KEY} <n>`,
+ conversation_facts: 'the parser input (page body or raw_transcript sidecar) is over the conversation body cap and was not read; trim the sidecar under the cap or remove raw_transcript from the page frontmatter, then gbrain extract-conversation-facts --slug <slug>',
+};
+
+const describe = (g: ReceiptGroup): string =>
+ `${g.pipeline}/${g.kind}: ${g.pages} page(s) (e.g. ${g.samples.join(', ')}); ${REMEDY[g.pipeline] ?? 'see the receipt in page_extraction_state'}`;
+
+async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Check[]> {
+ const checks: Check[] = [];
+ try {
+ const rows = await connectedEngine(ctx).executeRaw<{ pipeline: string; kind: string; pages: number; samples: string[] }>(
+ `SELECT s.pipeline, COALESCE(s.input_truncated->>'kind', 'unknown') AS kind, count(*)::int AS pages,
+ (array_agg(p.source_id || ':' || p.slug ORDER BY s.updated_at DESC))[1:3] AS samples
+ FROM page_extraction_state s JOIN pages p ON p.id = s.page_id AND p.deleted_at IS NULL
+ WHERE s.input_truncated IS NOT NULL
+ GROUP BY 1, 2 ORDER BY 1, 2`);
+ const groups: ReceiptGroup[] = rows.map(r => ({ pipeline: r.pipeline, kind: r.kind, pages: Number(r.pages), samples: r.samples ?? [] }));
+ const details = { groups: groups.map(g => ({ ...g, remedy: REMEDY[g.pipeline] ?? null })) };
+ if (!groups.length) {
+ checks.push({ name: 'extraction_input_truncated', status: 'ok', message: 'Every page extraction read all of its input (no head-only, tail-window or size-skip receipts).', details });
+ return checks;
+ }
+ const summary = `Page extractions that read only part of their input: ${groups.map(describe).join('. ')}.`;
+ const actionable = groups.filter(g => g.pipeline !== 'facts_backstop');
+ if (!actionable.length) {
+ checks.push({ name: 'extraction_input_truncated', status: 'ok', severity: 'info', readiness_state: 'degraded', message: summary, details });
+ return checks;
+ }
+ const atoms = actionable.find(g => g.pipeline === 'extract_atoms');
+ checks.push({ name: 'extraction_input_truncated', status: 'warn', message: summary, details,
+ ...(atoms
+ ? { fix: agentFix(['gbrain', 'config', 'set', EXTRACT_MAX_INPUT_CHARS_KEY, '<n>'],
+ 'A higher cap lets the next extract_atoms cycle read more of each cut page; it raises model spend, so the value is the user\'s call.', 'extraction_input_truncated',
+ { ask_user: true, consent: ['paid'], inputs: [{ name: 'n', how: 'a character count above the cut pages\' sizes, chosen with the user' }] }) }
+ : { fix_unavailable_reason: 'operator_judgement' as const }) });
+ } catch (error) {
+ checks.push(checkError('extraction_input_truncated', 'read the extraction receipts', error, { details: { health: 'unknown' } }));
+ }
+ return checks;
+}
+
+export const extractionInputTruncatedEntry: DoctorEntry = { name: 'extraction_input_truncated', emits: ['extraction_input_truncated'], run: runExtractionInputTruncatedCheck };
diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.ts
index 78a9020c1f..254edf38a6 100644
--- a/src/commands/doctor/registry.ts
+++ b/src/commands/doctor/registry.ts
@@ -110,6 +110,7 @@ import { behaviorChangesEntry } from './checks/behavior-changes.ts';
import { fenceIntegrityEntry } from './checks/fence-integrity.ts';
import { managedSyncMovementEntry } from './checks/managed-sync-movement.ts';
import { atomHeldFailedEntry } from './checks/atom-holds.ts';
+import { extractionInputTruncatedEntry } from './checks/extraction-input.ts';
import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';
import type { Check } from '../doctor.ts';
import { infoCheck } from './check-fix.ts';
@@ -197,6 +198,7 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [
persistenceConsumersEntry,
atomHeldFailedEntry,
fenceIntegrityEntry,
+ extractionInputTruncatedEntry,
searchModeEntry,
];
diff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.ts
index ef0a024b21..ac41c56956 100644
--- a/src/core/cycle/extract-atoms-input.ts
+++ b/src/core/cycle/extract-atoms-input.ts
@@ -21,6 +21,7 @@ import type { SqlEngine } from '../persistence/model.ts';
import { truncateUtf8 } from '../text-safe.ts';
import { corpusTextForExtraction } from '../context/corpus-segments.ts';
import { AtomPageStateError, type AtomPageInput } from './extract-atoms-page-state.ts';
+import { planExtraction, type ExtractionPlan, type StoredWatermark } from '../extraction-watermark.ts';
export const DEFAULT_EXTRACT_MAX_INPUT_CHARS = 50_000;
export const EXTRACT_MAX_INPUT_CHARS_KEY = 'cycle.extract_atoms.max_input_chars';
@@ -49,25 +50,40 @@ export type ExtractAtomsItem =
export interface ExtractAtomsInput {
/** Exactly the text the model receives; quote provenance verifies against it. */
promptContent: string;
- /** The text was longer than the cap: the model does not read its tail. */
+ /** The model does not read the whole item (a head, an appended tail or its newest window): partial disposition. */
truncated: boolean;
/** Characters of the text the cap applied to (post paste-strip for a transcript). */
inputChars: number;
+ /** A page's watermark plan (extraction-watermark.ts), stored once the item's extraction succeeded. */
+ plan?: ExtractionPlan;
}
/**
* Bind the cut once. Pastes are stripped from a transcript first (#5812), the
* cap is applied UTF-8-safely (#4529/#4540: a bare slice can split a
* surrogate pair), and `truncated` is measured on the text the cap applied to.
+ * Large pages A7: a page whose stored watermark still matches its body reads
+ * the text appended since (`watermark`); a tail read is partial input too, so
+ * the #6503 disposition holds (no completion stamp, nothing retired).
*/
-export function extractAtomsInput(item: ExtractAtomsItem, maxInputChars: number): ExtractAtomsInput {
- const text = item.kind === 'transcript' ? corpusTextForExtraction(item.filePath, item.content) : item.content;
+export function extractAtomsInput(item: ExtractAtomsItem, maxInputChars: number, watermark: StoredWatermark | null = null): ExtractAtomsInput {
+ if (item.kind === 'page') {
+ const plan = planExtraction(item.content, watermark, { cap: maxInputChars, pipeline: 'extract_atoms', emptyTail: 'head' });
+ return { promptContent: plan.text, truncated: plan.mode !== 'full', inputChars: item.content.length, plan };
+ }
+ const text = corpusTextForExtraction(item.filePath, item.content);
const promptContent = truncateUtf8(text, maxInputChars);
return { promptContent, truncated: promptContent.length < text.length, inputChars: text.length };
}
-/** The one stderr line per cut item; names the knob that raises the cap. */
-export function inputTruncatedLine(originLabel: string, input: ExtractAtomsInput, maxInputChars: number): string {
+/** The one stderr line per cut item; names the knob that raises the cap. Null for a complete appended-tail read. */
+export function inputTruncatedLine(originLabel: string, input: ExtractAtomsInput, maxInputChars: number): string | null {
+ const cut = input.plan?.truncated;
+ if (input.plan && !cut) return null;
+ if (cut?.kind === 'tail_window') {
+ return `[extract_atoms] ${originLabel}: ${cut.total_chars} chars were appended since the last extraction; the model read the newest ${cut.processed_chars}. `
+ + `Atoms are kept, the item is not marked complete, and doctor's extraction_input_truncated lists it: gbrain config set ${EXTRACT_MAX_INPUT_CHARS_KEY} <n>`;
+ }
return `[extract_atoms] ${originLabel}: input truncated to ${maxInputChars} of ${input.inputChars} chars; the model did not read the tail. ` +
`Atoms from the head are kept, the item is not marked complete and is skipped until the cap rises: gbrain config set ${EXTRACT_MAX_INPUT_CHARS_KEY} <n>`;
}
diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.ts
index f36f7e3243..fb55978328 100644
--- a/src/core/cycle/extract-atoms.ts
+++ b/src/core/cycle/extract-atoms.ts
@@ -69,7 +69,8 @@ import { createGlobalLlmHaltTracker, haltedClassOf, providerContentBlockReason,
import { importFromContent } from '../import-file.ts';
import { derivedWriteThrough } from './derived-write-through.ts';
import { serializeMarkdown } from '../markdown.ts';
-import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone } from './extract-atoms-input.ts';
+import { DEFAULT_EXTRACT_MAX_INPUT_CHARS, extractAtomsInput, inputTruncatedLine, recordPartialDisposition, releasePartialDispositions, resolveExtractAtomsInputCap, stampTranscriptTombstone, type ExtractAtomsInput, type ExtractAtomsItem } from './extract-atoms-input.ts';
+import { commitExtractionPlan, readPageWatermark } from '../extraction-watermark.ts';
import { claudeCliSelfSessionIds } from '../ai/providers/claude-cli-scratch.ts';
import { BudgetExhausted, BudgetTracker, loadPricingOverrides } from '../budget/budget-tracker.ts';
import type { MaintenanceWriteWait } from '../persistence/maintenance-wait.ts';
@@ -996,6 +997,10 @@ export async function runPhaseExtractAtoms(
async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {
await writeAtomPageState(engine, sourceId, item, 'complete');
}
+ /** Large pages A7: a page's watermark moves past the text this item read once its writes committed (a pending batch keeps the old one). */
+ async function commitAtomsWatermark(item: ExtractAtomsItem, input: ExtractAtomsInput, published: readonly { state: string }[]): Promise<void> {
+ if (item.kind === 'page' && item.identity && input.plan && published.every(receipt => receipt.state === 'committed')) await commitExtractionPlan(engine, item.identity.pageId, input.plan);
+ }
/**
* Durable per-item failure count, keyed to the CURRENT content hash so a
@@ -1079,7 +1084,7 @@ export async function runPhaseExtractAtoms(
// item, so a quote can only verify against text the model actually saw.
// #6503: a cut item is extracted once from its head and gets a partial
// disposition instead of a completion stamp (extract-atoms-input.ts).
- const input = extractAtomsInput(item, maxInputChars);
+ const input = extractAtomsInput(item, maxInputChars, item.kind === 'page' ? (await readPageWatermark(engine, sourceId, item.slug, 'extract_atoms')).stored : null);
const { promptContent, truncated } = input;
try {
const origin: AtomOrigin | null = managed ? { ...await readAtomOrigin(engine, managed, item), ...(truncated ? { partialInputChars: maxInputChars } : {}) } : null;
@@ -1089,7 +1094,8 @@ export async function runPhaseExtractAtoms(
const resumed = !opts.dryRun && managed && origin ? await resumeManagedAtoms(engine, managed, origin) : 'run';
if (resumed === 'done') { duplicatesSkipped++; continue; }
if (resumed === 'held') { heldFailed++; continue; } // #6325: settled after repeated failures; doctor lists it
- if (truncated) { inputTruncated++; console.error(inputTruncatedLine(originLabel, input, maxInputChars)); } // counted only for a model call
+ const cutLine = truncated ? inputTruncatedLine(originLabel, input, maxInputChars) : null; // A7: a complete appended-tail read prints nothing
+ if (cutLine) { inputTruncated++; console.error(cutLine); } // counted only for a model call
const result = await chat({
model: extractModel,
@@ -1139,10 +1145,12 @@ export async function runPhaseExtractAtoms(
// row is (source_id, file_path, content_hash)-keyed, so editing the
// file re-eligibilizes it — which is what makes the permanence safe.
if (!opts.dryRun) {
- if (managed && origin) writeRequests.push(...await publishManagedAtoms(engine, managed, origin, []));
- else if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);
- else if (item.kind === 'page') await stampAtomsScanHash(item);
- else await stampTranscriptTombstone(engine, sourceId, item.filePath, item.contentHash);
+ const published = managed && origin ? await publishManagedAtoms(engine, managed, origin, []) : [];
+ writeRequests.push(...published);
+ if (!origin && truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);
+ else if (!origin && item.kind === 'page') await stampAtomsScanHash(item);
+ else if (!origin && item.kind === 'transcript') await stampTranscriptTombstone(engine, sourceId, item.filePath, item.contentHash);
+ await commitAtomsWatermark(item, input, published);
}
if (item.kind === 'transcript') transcriptsProcessed++;
else pagesProcessed++;
@@ -1280,6 +1288,7 @@ export async function runPhaseExtractAtoms(
writeRequests.push(...published);
if (published.some(receipt => receipt.state !== 'committed')) writesPending++;
totalAtomsExtracted += managedAtoms.length;
+ await commitAtomsWatermark(item, input, published);
} else {
if (provenanceLinks.length > 0) {
await engine.addLinksBatch(provenanceLinks, { auditSite: 'cycle.extract_atoms.provenance' }); // gbrain-allow-direct-insert: atom-provenance edges derived from the extraction itself (no markdown body to reconcile from)
@@ -1295,6 +1304,7 @@ export async function runPhaseExtractAtoms(
await atomFiles?.(importedSlugs, retired);
if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);
else if (item.kind === 'page') await stampAtomsScanHash(item);
+ await commitAtomsWatermark(item, input, []);
}
} else {
totalAtomsExtracted += atoms.length; // count for dry-run reporting
diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.ts
index 48ac03ba14..2455bdc1a1 100644
--- a/src/core/deletion-inventory.ts
+++ b/src/core/deletion-inventory.ts
@@ -104,6 +104,7 @@ const ROWS: readonly Row[] = [
['op_checkpoints', 'out_of_scope', 'no_memory_text', 'op fingerprint completed_keys'],
['open_loops', 'swept', 'open_loops', 'source_id dedup_key loop_type counterparty_slug counterparty_source_id counterparty_email summary evidence thread_id page_slug status detector closed_by'],
['page_aliases', 'out_of_scope', 'probed_reported', 'source_id alias_norm slug origin alias_text', 'alias_text'],
+ ['page_extraction_state', 'out_of_scope', 'no_memory_text', 'pipeline watermark_sha256 input_truncated'],
['page_facts_reconcile', 'out_of_scope', 'no_memory_text', 'outcome'],
['page_mention_state', 'out_of_scope', 'no_memory_text', 'source_id'],
['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],
diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.ts
index 9ea609ad42..90ca6ed205 100644
--- a/src/core/doctor-categories.ts
+++ b/src/core/doctor-categories.ts
@@ -118,6 +118,8 @@ export const BRAIN_CHECK_NAMES: ReadonlySet<string> = new Set([
// #6325: managed atom origins held after repeated extraction failures.
'extract_atoms_held_failed',
'extract_health',
+ // Large pages A7: page extractions that read only part of their input.
+ 'extraction_input_truncated',
'facts_embedding_width_consistency',
'facts_extraction_health',
'facts_health',
diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.ts
new file mode 100644
index 0000000000..4f4edc47b4
--- /dev/null
+++ b/src/core/extraction-watermark.ts
@@ -0,0 +1,160 @@
+/**
+ * Large pages A7: no silent head-only extraction.
+ *
+ * Page extractors read a bounded slice of the body (facts: 8,000 chars,
+ * atoms: `cycle.extract_atoms.max_input_chars`). Reading the head every time
+ * means the text appended to a long conversation page is never extracted.
+ * A per-page watermark per pipeline fixes that: the UTF-8 byte offset of the
+ * body the last successful extraction covered, the sha256 of the body up to
+ * that offset, and the pipeline version. When the current body still starts
+ * with exactly that prefix, the next extraction reads only the appended tail
+ * (its newest `cap` characters when the tail itself is longer). Otherwise it
+ * reads the head as before and records the durable receipt `input_truncated`
+ * in `page_extraction_state`, which doctor's `extraction_input_truncated`
+ * check reports. A full read clears the receipt; a tail read keeps it, since
+ * the text skipped earlier is still unread.
+ */
+import { createHash } from 'node:crypto';
+import type { BrainEngine } from './engine.ts';
+import { truncateUtf8 } from './text-safe.ts';
+
+export type ExtractionPipeline = 'facts_backstop' | 'extract_atoms' | 'conversation_facts';
+
+/** Bump a pipeline's version when its extracted body changes shape: every stored watermark then falls back to the head once. */
+export const EXTRACTION_PIPELINE_VERSION: Readonly<Record<ExtractionPipeline, number>> = {
+ facts_backstop: 1, extract_atoms: 1, conversation_facts: 1,
+};
+
+export type HeadFallbackReason = 'no_watermark' | 'prefix_changed' | 'version_changed' | 'no_new_text';
+
+/** The durable receipt of an extraction that did not read all of its input. */
+export interface InputTruncated {
+ kind: 'head' | 'tail_window' | 'skipped_too_large';
+ pipeline: ExtractionPipeline;
+ /** Characters the extractor read (0 for a skipped page). */
+ processed_chars: number;
+ /** Characters of the input the cap applied to: the body for `head`, the appended tail for `tail_window`; absent for an unread input. */
+ total_chars?: number;
+ reason?: HeadFallbackReason;
+ /** `skipped_too_large`: the input's UTF-8 size, the cap it exceeded and where the input came from. */
+ total_bytes?: number;
+ cap_bytes?: number;
+ origin?: 'page' | 'sidecar';
+}
+
+export interface StoredWatermark { pipelineVersion: number; bytes: number; sha256: string }
+
+export interface ExtractionPlan {
+ pipeline: ExtractionPipeline;
+ /** full: the body fits the cap; tail: past the watermark; head: no usable watermark. */
+ mode: 'full' | 'tail' | 'head';
+ /** Exactly what the extractor reads, at most `cap` characters. Empty only for a tail with nothing appended. */
+ text: string;
+ truncated: InputTruncated | null;
+ /** The watermark to store once the extraction succeeded: the whole current body. */
+ next: { bytes: number; sha256: string };
+}
+
+const sha256 = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex');
+
+/** The newest `cap` characters of `text`, never starting inside a surrogate pair, at a line start when one is near. */
+function newestWindow(text: string, cap: number): string {
+ let start = text.length - cap;
+ const code = text.charCodeAt(start);
+ if (code >= 0xdc00 && code <= 0xdfff) start++;
+ const newline = text.indexOf('\n', start);
+ if (newline >= 0 && newline - start < Math.floor(cap / 10)) start = newline + 1;
+ return text.slice(start);
+}
+
+/**
+ * Decide what one extraction reads. `emptyTail` says what a matching
+ * watermark with nothing appended means: `skip` (nothing new to extract) or
+ * `head` (the caller re-reads on purpose, e.g. after the cap rose).
+ */
+export function planExtraction(body: string, stored: StoredWatermark | null,
+ opts: { cap: number; pipeline: ExtractionPipeline; emptyTail: 'skip' | 'head' }): ExtractionPlan {
+ const { cap, pipeline } = opts;
+ const buf = Buffer.from(body, 'utf8');
+ const next = { bytes: buf.length, sha256: sha256(buf) };
+ if (body.length <= cap) return { pipeline, mode: 'full', text: body, truncated: null, next };
+ const head = (reason: HeadFallbackReason): ExtractionPlan => ({ pipeline, mode: 'head', text: truncateUtf8(body, cap), next,
+ truncated: { kind: 'head', pipeline, processed_chars: Math.min(cap, body.length), total_chars: body.length, reason } });
+ if (!stored) return head('no_watermark');
+ if (stored.pipelineVersion !== EXTRACTION_PIPELINE_VERSION[pipeline]) return head('version_changed');
+ const offset = stored.bytes;
+ const onBoundary = offset === buf.length || (offset < buf.length && (buf[offset]! & 0xc0) !== 0x80);
+ if (offset > buf.length || !onBoundary || sha256(buf.subarray(0, offset)) !== stored.sha256) return head('prefix_changed');
+ const tail = buf.subarray(offset).toString('utf8');
+ if (!tail.trim()) return opts.emptyTail === 'skip' ? { pipeline, mode: 'tail', text: '', truncated: null, next } : head('no_new_text');
+ if (tail.length <= cap) return { pipeline, mode: 'tail', text: tail, truncated: null, next };
+ const window = newestWindow(tail, cap);
+ return { pipeline, mode: 'tail', text: window, next,
+ truncated: { kind: 'tail_window', pipeline, processed_chars: window.length, total_chars: tail.length } };
+}
+
+let warnedStorage = false;
+function warnStorageOnce(action: string, error: unknown): void {
+ if (warnedStorage) return;
+ warnedStorage = true;
+ console.error(`[extraction-watermark] could not ${action} (${error instanceof Error ? error.message : String(error)}); `
+ + 'large pages fall back to head-only extraction until gbrain apply-migrations brings the schema to head.');
+}
+
+/** The page's id and stored watermark for `pipeline`; `pageId` is null when no live page has that slug. Fail-soft to no watermark. */
+export async function readPageWatermark(engine: BrainEngine, sourceId: string, slug: string,
+ pipeline: ExtractionPipeline): Promise<{ pageId: number | null; stored: StoredWatermark | null }> {
+ try {
+ const [row] = await engine.executeRaw<{ id: number; pipeline_version: number | null; watermark_bytes: string | number | null; watermark_sha256: string | null }>(
+ `SELECT p.id, s.pipeline_version, s.watermark_bytes, s.watermark_sha256
+ FROM pages p LEFT JOIN page_extraction_state s ON s.page_id = p.id AND s.pipeline = $3
+ WHERE p.source_id = $1 AND p.slug = $2 AND p.deleted_at IS NULL`, [sourceId, slug, pipeline]);
+ if (!row) return { pageId: null, stored: null };
+ const stored = row.pipeline_version !== null && row.watermark_bytes !== null && row.watermark_sha256
+ ? { pipelineVersion: Number(row.pipeline_version), bytes: Number(row.watermark_bytes), sha256: row.watermark_sha256 } : null;
+ return { pageId: Number(row.id), stored };
+ } catch (error) {
+ warnStorageOnce('read the extraction watermark', error);
+ return { pageId: null, stored: null };
+ }
+}
+
+/**
+ * Store a successful extraction: the watermark moves to the end of the body
+ * it planned against. A full read clears the receipt, a truncated read
+ * replaces it, and a complete tail read keeps whatever gap an earlier read left.
+ */
+export async function commitExtractionPlan(engine: BrainEngine, pageId: number, plan: ExtractionPlan): Promise<void> {
+ const receipt = plan.truncated ? JSON.stringify(plan.truncated) : null;
+ try {
+ await engine.executeRaw(
+ `INSERT INTO page_extraction_state (page_id, pipeline, pipeline_version, watermark_bytes, watermark_sha256, input_truncated, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6::text::jsonb, now())
+ ON CONFLICT (page_id, pipeline) DO UPDATE SET pipeline_version = EXCLUDED.pipeline_version,
+ watermark_bytes = EXCLUDED.watermark_bytes, watermark_sha256 = EXCLUDED.watermark_sha256,
+ input_truncated = CASE WHEN $7 THEN page_extraction_state.input_truncated ELSE EXCLUDED.input_truncated END,
+ updated_at = now()`,
+ [pageId, plan.pipeline, EXTRACTION_PIPELINE_VERSION[plan.pipeline], plan.next.bytes, plan.next.sha256, receipt,
+ plan.mode === 'tail' && !plan.truncated]);
+ } catch (error) {
+ warnStorageOnce('store the extraction watermark', error);
+ }
+}
+
+/** Record (receipt) or clear (null) the partial-input receipt of a pipeline that keeps no watermark: the conversation-facts size skip. */
+export async function setExtractionReceipt(engine: BrainEngine, pageId: number, pipeline: ExtractionPipeline,
+ receipt: InputTruncated | null): Promise<void> {
+ try {
+ if (!receipt) {
+ await engine.executeRaw('DELETE FROM page_extraction_state WHERE page_id = $1 AND pipeline = $2', [pageId, pipeline]);
+ return;
+ }
+ await engine.executeRaw(
+ `INSERT INTO page_extraction_state (page_id, pipeline, pipeline_version, input_truncated, updated_at)
+ VALUES ($1, $2, $3, $4::text::jsonb, now())
+ ON CONFLICT (page_id, pipeline) DO UPDATE SET input_truncated = EXCLUDED.input_truncated, updated_at = now()`,
+ [pageId, pipeline, EXTRACTION_PIPELINE_VERSION[pipeline], JSON.stringify(receipt)]);
+ } catch (error) {
+ warnStorageOnce('store the extraction receipt', error);
+ }
+}
diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.ts
index c5567cdfc0..359c5ec74e 100644
--- a/src/core/facts/backstop.ts
+++ b/src/core/facts/backstop.ts
@@ -61,6 +61,7 @@ import { intentContentOrigin } from '../trust/channel.ts';
import { readTaintInputs, derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';
import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';
import { decideFactWrite } from '../write-gate-store.ts';
+import { commitExtractionPlan, planExtraction, readPageWatermark, type InputTruncated } from '../extraction-watermark.ts';
// The notability-filter vocabulary lives in notability-filter.ts; re-exported for existing importers.
export { NOTABILITY_FILTERS, coerceNotabilityFilter, type FactNotabilityFilter } from './notability-filter.ts';
@@ -176,11 +177,15 @@ export type FactsBackstopResult =
would_dedup_same_page?: number;
/** #6506: candidates skipped because the exact claim was forgotten in this source and visibility. */
withdrawn_skipped?: number;
+ /** Large pages A7: the extractor read only part of the page (also stored in page_extraction_state). */
+ input_truncated?: InputTruncated;
};
/** One pipeline run's input: the turn text plus its page provenance and observation date. */
interface PipelineInput {
turnText: string;
+ /** What the extractor reads when it is not `turnText`: the appended tail or a bounded window (extraction-watermark.ts). */
+ extractText?: string;
isDreamGenerated: boolean;
ref?: string;
pageSlug?: string;
@@ -188,6 +193,9 @@ interface PipelineInput {
observationDate?: ObservationDate | null;
}
+/** One page or turn pipeline run's counts (runPipelineWithBody). */
+interface PipelineResult { inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }
+
interface ParsedPageInput {
slug: string;
type: PageType;
@@ -565,10 +573,17 @@ async function runPipeline(
parsedPage: ParsedPageInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }> {
- return runPipelineWithBody(
+): Promise<PipelineResult & { input_truncated?: InputTruncated }> {
+ // Large pages A7: past the watermark the extractor reads only the appended
+ // tail; without a usable one it reads the head and the receipt says so.
+ const { MAX_TURN_TEXT_CHARS } = await import('./extract.ts');
+ const { pageId, stored } = await readPageWatermark(ctx.engine, ctx.sourceId, parsedPage.slug, 'facts_backstop');
+ const plan = planExtraction(parsedPage.compiled_truth, stored, { cap: MAX_TURN_TEXT_CHARS, pipeline: 'facts_backstop', emptyTail: 'skip' });
+ if (!plan.text) return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };
+ const result = await runPipelineWithBody(
{
turnText: parsedPage.compiled_truth,
+ ...(plan.mode === 'full' ? {} : { extractText: plan.text }),
isDreamGenerated: false, // eligibility check already rejected dream pages
ref: parsedPage.slug,
// #4819: page provenance for DB-only rows. The turn-path entry
@@ -579,6 +594,8 @@ async function runPipeline(
ctx,
abortSignal,
);
+ if (pageId !== null && !result.skipped_reason && !abortSignal?.aborted) await commitExtractionPlan(ctx.engine, pageId, plan);
+ return plan.truncated ? { ...result, input_truncated: plan.truncated } : result;
}
/**
@@ -612,7 +629,7 @@ async function runPipelineWithBody(
input: PipelineInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }> {
+): Promise<PipelineResult> {
// #4210: outside a withBudgetTracker scope (extract_facts op, sweep,
// put_page backstop, checkpoint harvest, file/code import) the gateway's
// chat/embed calls were budget no-ops — real spend, zero audit rows.
@@ -683,7 +700,7 @@ async function runPipelineBodyInner(
input: PipelineInput,
ctx: FactsBackstopCtx,
abortSignal?: AbortSignal,
-): Promise<{ inserted: number; duplicate: number; superseded: number; fact_ids: number[]; entity_slugs: string[]; skipped_reason?: import('./extract.ts').ExtractFailureReason; write_gate?: GateTally; fence_refused?: number; would_dedup_same_page?: number; withdrawn_skipped?: number }> {
+): Promise<PipelineResult> {
const { extractFactsFromTurnWithOutcome, FactsExtractionError } = await import('./extract.ts');
const { resolveEntitySlugWithSource } = await import('../entities/resolve.ts');
const { cosineSimilarity } = await import('./classify.ts');
@@ -718,7 +735,7 @@ async function runPipelineBodyInner(
? { allowed: ['high', 'medium'] as const, invalid: 'drop' as const }
: undefined;
const extract = () => extractFactsFromTurnWithOutcome({
- turnText: input.turnText,
+ turnText: input.extractText ?? input.turnText,
sessionId: ctx.sessionId,
entityHints: ctx.entityHints,
source: ctx.source,
diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.ts
index c2834fa565..e09c1ac675 100644
--- a/src/core/persistence/graduation-inventory.ts
+++ b/src/core/persistence/graduation-inventory.ts
@@ -103,6 +103,7 @@ export const GRADUATION_INVENTORY: Inventory = {
carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),
carry('open_loops', 'user_data', 'Open loops and their status.'),
carry('page_aliases', 'user_data', 'Page aliases.'),
+ carry('page_extraction_state', 'operational', 'Extraction watermarks and partial-input receipts per page and pipeline; without them the next extraction of a large page reads its head again and records the receipt anew.'),
carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),
carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),
carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),
diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.ts
index 4a0fe95b8d..e8aac9884b 100644
--- a/src/core/pglite-schema.generated.ts
+++ b/src/core/pglite-schema.generated.ts
@@ -1239,6 +1239,18 @@ CREATE TABLE IF NOT EXISTS dream_synthesis_completions (
completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, idempotency_key)
);
+CREATE TABLE IF NOT EXISTS page_extraction_state (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('facts_backstop','extract_atoms','conversation_facts')),
+ pipeline_version INTEGER NOT NULL,
+ watermark_bytes BIGINT CHECK (watermark_bytes >= 0),
+ watermark_sha256 TEXT,
+ input_truncated JSONB,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline)
+);
+CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idx
+ ON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;
-- Durable concurrent persistence (migration 151).
CREATE TABLE IF NOT EXISTS persistence_brain (
diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.ts
index 03157f03b1..78bc0b7622 100644
--- a/src/core/schema-embedded.generated.ts
+++ b/src/core/schema-embedded.generated.ts
@@ -1958,6 +1958,20 @@ CREATE TABLE IF NOT EXISTS dream_synthesis_completions (
completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, idempotency_key)
);
+-- Large pages A7 (migration v245): per-page extraction watermark and the
+-- durable receipt of a partial-input extraction (src/core/extraction-watermark.ts).
+CREATE TABLE IF NOT EXISTS page_extraction_state (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('facts_backstop','extract_atoms','conversation_facts')),
+ pipeline_version INTEGER NOT NULL,
+ watermark_bytes BIGINT CHECK (watermark_bytes >= 0),
+ watermark_sha256 TEXT,
+ input_truncated JSONB,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline)
+);
+CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idx
+ ON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;
-- Durable concurrent persistence (migration 151).
-- BEGIN GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS). Edit that file, then run: bun run build:schema
diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.ts
index a73fbd1589..d0bb19dbe3 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 = 243;
+export const LATEST_SCHEMA_VERSION = 245;
diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.ts
index 129cf41721..b2fcd8c3f1 100644
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@ -244,6 +244,7 @@ import { v240 } from './v240-pages-name-lookup-indexes.ts';
import { v241 } from './v241-persistence-request-slug-intent-index.ts';
import { v242 } from './v242-extract-atoms-partial-input.ts';
import { v243 } from './v243-persistence-consumer-process-start.ts';
+import { v245 } from './v245-page-extraction-state.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@ -486,4 +487,5 @@ export const MIGRATIONS: Migration[] = [
v241,
v242,
v243,
+ v245,
];
diff --git a/src/core/schema-migrations/v245-page-extraction-state.ts b/src/core/schema-migrations/v245-page-extraction-state.ts
new file mode 100644
index 0000000000..a3c151883a
--- /dev/null
+++ b/src/core/schema-migrations/v245-page-extraction-state.ts
@@ -0,0 +1,34 @@
+import type { Migration } from './types.ts';
+
+// Applied by src/core/migrate.ts on the next initSchema(); the fresh-install
+// copy in src/schema.sql carries the same table.
+//
+// Large pages A7 (src/core/extraction-watermark.ts): one row per page and
+// extraction pipeline. The watermark (UTF-8 byte offset into the extracted
+// body plus the sha256 of the body up to it, under a pipeline version) lets
+// the next extraction of an appended page read only the appended tail.
+// `input_truncated` is the durable receipt of an extraction that read only
+// part of its input (the head, the newest window of a long tail, or a page
+// skipped as too large); doctor's `extraction_input_truncated` reads it.
+// Hashes, offsets and counts only: no page text is stored. Rows go with
+// their page (ON DELETE CASCADE). DDL only, nothing to backfill: a page with
+// no row falls back to today's behavior and records the receipt.
+export const v245: Migration = {
+ version: 245,
+ name: 'page_extraction_state',
+ idempotent: true,
+ sql: `
+ CREATE TABLE IF NOT EXISTS page_extraction_state (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('facts_backstop','extract_atoms','conversation_facts')),
+ pipeline_version INTEGER NOT NULL,
+ watermark_bytes BIGINT CHECK (watermark_bytes >= 0),
+ watermark_sha256 TEXT,
+ input_truncated JSONB,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline)
+ );
+ CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idx
+ ON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;
+ `,
+};
diff --git a/src/schema.sql b/src/schema.sql
index 6afd1c311e..7ed463dee2 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -1954,6 +1954,20 @@ CREATE TABLE IF NOT EXISTS dream_synthesis_completions (
completed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (source_id, idempotency_key)
);
+-- Large pages A7 (migration v245): per-page extraction watermark and the
+-- durable receipt of a partial-input extraction (src/core/extraction-watermark.ts).
+CREATE TABLE IF NOT EXISTS page_extraction_state (
+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,
+ pipeline TEXT NOT NULL CHECK (pipeline IN ('facts_backstop','extract_atoms','conversation_facts')),
+ pipeline_version INTEGER NOT NULL,
+ watermark_bytes BIGINT CHECK (watermark_bytes >= 0),
+ watermark_sha256 TEXT,
+ input_truncated JSONB,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (page_id, pipeline)
+);
+CREATE INDEX IF NOT EXISTS page_extraction_state_truncated_idx
+ ON page_extraction_state (pipeline, page_id) WHERE input_truncated IS NOT NULL;
-- Durable concurrent persistence (migration 151).
-- BEGIN GENERATED from src/core/persistence/schema.ts (PERSISTENCE_SCHEMA_STATEMENTS). Edit that file, then run: bun run build:schema
diff --git a/test/extraction-watermark-atoms.test.ts b/test/extraction-watermark-atoms.test.ts
new file mode 100644
index 0000000000..5f165d1a28
--- /dev/null
+++ b/test/extraction-watermark-atoms.test.ts
@@ -0,0 +1,165 @@
+/**
+ * Large pages A7 (eng F24) with the #6503 partial disposition: extract_atoms
+ * reads the text appended to a page over `cycle.extract_atoms.max_input_chars`
+ * instead of its head again, and a tail read is still partial input.
+ *
+ * 1. Protects: an append past the cap reaches the model; the tail run writes
+ * no completion stamp and retires no atom from earlier reads; a cut read
+ * leaves a receipt that doctor's extraction_input_truncated warns about.
+ * 2. Regression that fails it: re-reading the head on every content change
+ * (pre-A7), or treating a tail read as a complete read (which would stamp
+ * the page and retire the head's atoms).
+ * 3. The #6503 suite covers the head cut only; nothing covers an append.
+ * 4. No new seam: `_chat` and the page discovery are the phase's own inputs.
+ *
+ * PGLite, plus Postgres when DATABASE_URL is set. Stub model ($0).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';
+import { runPhaseExtractAtoms } from '../src/core/cycle/extract-atoms.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { extractionInputTruncatedEntry } from '../src/commands/doctor/checks/extraction-input.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';
+
+const CAP = 2_000;
+const KNOB = 'cycle.extract_atoms.max_input_chars';
+
+const prose = (tag: string, chars: number) =>
+ `${tag}: the team agreed to measure every launch against clear exit criteria before shipping. `.repeat(Math.ceil(chars / 80)).slice(0, chars);
+
+function stubChat(title: string) {
+ const calls: string[] = [];
+ const chat = async (opts: ChatOpts): Promise<ChatResult> => {
+ const last = opts.messages[opts.messages.length - 1];
+ calls.push(typeof last.content === 'string' ? last.content : JSON.stringify(last.content));
+ const text = JSON.stringify([{ title, body: `${title}, decided in the meeting.`, atom_type: 'insight' }]);
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end',
+ usage: { input_tokens: 10, output_tokens: 10, cache_read_tokens: 0, cache_creation_tokens: 0 }, model: 'anthropic:claude-haiku-4-5', providerId: 'anthropic' };
+ };
+ return { calls, chat };
+}
+
+async function captureStderr<T>(run: () => Promise<T>): Promise<{ value: T; lines: string[] }> {
+ const lines: string[] = [];
+ const original = console.error;
+ console.error = (...args: unknown[]) => { lines.push(args.map(String).join(' ')); };
+ try { return { value: await run(), lines }; } finally { console.error = original; }
+}
+
+const liveAtoms = (engine: BrainEngine, sourceId: string, slug: string) =>
+ engine.executeRaw<{ title: string; source_hash: string }>(
+ `SELECT title, frontmatter->>'source_hash' AS source_hash FROM pages
+ WHERE source_id=$1 AND type='atom' AND frontmatter->>'source_slug'=$2 AND deleted_at IS NULL ORDER BY title`, [sourceId, slug]);
+
+const currentState = (engine: BrainEngine, sourceId: string, slug: string) =>
+ engine.executeRaw<{ tombstoned: boolean; partial_input_chars: number | null }>(
+ `SELECT scan.tombstoned, scan.partial_input_chars FROM extract_atoms_page_state scan
+ JOIN pages p ON p.id=scan.page_id AND scan.content_hash=p.content_hash WHERE p.source_id=$1 AND p.slug=$2`, [sourceId, slug]);
+
+async function receipt(engine: BrainEngine, sourceId: string, slug: string): Promise<Record<string, unknown> | null> {
+ const [row] = await engine.executeRaw<{ input_truncated: Record<string, unknown> | string | null }>(
+ `SELECT s.input_truncated FROM page_extraction_state s JOIN pages p ON p.id=s.page_id
+ WHERE p.source_id=$1 AND p.slug=$2 AND s.pipeline='extract_atoms'`, [sourceId, slug]);
+ const value = row?.input_truncated ?? null;
+ return typeof value === 'string' ? JSON.parse(value) : value;
+}
+
+describe('extract_atoms reads the appended tail and keeps the partial disposition (A7, #6503)', () => {
+ const engines: Array<{ backend: string; engine: BrainEngine }> = [];
+ let closePostgres: (() => Promise<void>) | undefined;
+
+ beforeAll(async () => {
+ for (const backend of testBackends()) {
+ if (backend === 'pglite') {
+ const engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ engines.push({ backend, engine });
+ } else {
+ const isolated = await isolatedPersistencePostgres(requirePostgresTestDatabase());
+ engines.push({ backend, engine: isolated.engine });
+ closePostgres = isolated.close;
+ }
+ }
+ }, 120_000);
+ afterAll(async () => {
+ for (const { engine } of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ });
+
+ test('an append past the cap is read from the appended text, never stamped complete, and retires nothing', async () => {
+ for (const { backend, engine } of engines) {
+ await engine.setConfig(KNOB, String(CAP));
+ const sourceId = `a7-atoms-${backend}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const slug = 'notes/a7-growing-log';
+ const head = prose('HEADPART', 3_000);
+ await engine.putPage(slug, { type: 'note', title: 'Growing log', compiled_truth: head, timeline: '' }, { sourceId });
+
+ const first = stubChat('Head decision');
+ await runPhaseExtractAtoms(engine, { sourceId, _chat: first.chat, _transcripts: [] });
+ expect(first.calls, backend).toHaveLength(1);
+ expect(first.calls[0], backend).toContain('HEADPART');
+ expect(await receipt(engine, sourceId, slug), backend).toMatchObject({ kind: 'head', reason: 'no_watermark', processed_chars: CAP });
+
+ const appended = head + prose('TAILPART', 1_000);
+ await engine.putPage(slug, { type: 'note', title: 'Growing log', compiled_truth: appended, timeline: '' }, { sourceId });
+ const second = stubChat('Tail decision');
+ const { value: tailRun, lines } = await captureStderr(() => runPhaseExtractAtoms(engine, { sourceId, _chat: second.chat, _transcripts: [] }));
+ expect(second.calls, backend).toHaveLength(1);
+ expect(second.calls[0], backend).toContain('TAILPART');
+ expect(second.calls[0], backend).not.toContain('HEADPART');
+ // A complete tail read is not a cut: no counter, no stderr line.
+ expect(tailRun.details.input_truncated, backend).toBe(0);
+ expect(lines.filter(line => line.includes('[extract_atoms]') && line.includes(slug)), backend).toEqual([]);
+ // #6503: partial input, so no completion stamp and the head's atom is not retired.
+ expect(await currentState(engine, sourceId, slug), backend).toEqual([{ tombstoned: false, partial_input_chars: CAP }]);
+ const atoms = await liveAtoms(engine, sourceId, slug);
+ expect(atoms.map(atom => atom.title), backend).toEqual(['Head decision', 'Tail decision']);
+ for (const atom of atoms) expect(atom.source_hash, backend).toMatch(/^pending:/);
+ expect(await receipt(engine, sourceId, slug), backend).toMatchObject({ kind: 'head' });
+
+ const longer = appended + prose('OLDAPPEND', 2_000) + prose('NEWAPPEND', 2_000);
+ await engine.putPage(slug, { type: 'note', title: 'Growing log', compiled_truth: longer, timeline: '' }, { sourceId });
+ const third = stubChat('Newest decision');
+ const { value: windowRun, lines: windowLines } = await captureStderr(() => runPhaseExtractAtoms(engine, { sourceId, _chat: third.chat, _transcripts: [] }));
+ expect(third.calls[0], backend).toContain('NEWAPPEND');
+ expect(third.calls[0], backend).not.toContain('TAILPART');
+ expect(windowRun.details.input_truncated, backend).toBe(1);
+ expect(windowLines.some(line => line.includes(slug) && line.includes('appended since the last extraction')), backend).toBe(true);
+ expect(await receipt(engine, sourceId, slug), backend).toMatchObject({ kind: 'tail_window', total_chars: longer.length - appended.length });
+ expect((await liveAtoms(engine, sourceId, slug)).map(atom => atom.title), backend).toEqual(['Head decision', 'Newest decision', 'Tail decision']);
+
+ const checks = await extractionInputTruncatedEntry.run({ engine } as unknown as DoctorContext) as Check[];
+ const check = checks.find(c => c.name === 'extraction_input_truncated')!;
+ expect(check.status, backend).toBe('warn');
+ expect(check.message, backend).toContain(`${sourceId}:${slug}`);
+ expect(check.fix, backend).toMatchObject({ argv: ['gbrain', 'config', 'set', KNOB, '<n>'], ask_user: true });
+ }
+ }, 120_000);
+
+ test('an edit inside the read prefix falls back to the head with a prefix_changed receipt', async () => {
+ for (const { backend, engine } of engines) {
+ await engine.setConfig(KNOB, String(CAP));
+ const sourceId = `a7-atoms-edit-${backend}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [sourceId]);
+ const slug = 'notes/a7-edited-log';
+ const body = prose('ORIGINAL', 3_000);
+ await engine.putPage(slug, { type: 'note', title: 'Edited log', compiled_truth: body, timeline: '' }, { sourceId });
+ await runPhaseExtractAtoms(engine, { sourceId, _chat: stubChat('First decision').chat, _transcripts: [] });
+ const edited = 'REWRITTEN opening line.\n' + body + prose('APPENDED', 500);
+ await engine.putPage(slug, { type: 'note', title: 'Edited log', compiled_truth: edited, timeline: '' }, { sourceId });
+ const second = stubChat('Second decision');
+ await runPhaseExtractAtoms(engine, { sourceId, _chat: second.chat, _transcripts: [] });
+ expect(second.calls[0], backend).toContain('REWRITTEN opening line.');
+ expect(second.calls[0], backend).not.toContain('APPENDED');
+ expect(await receipt(engine, sourceId, slug), backend).toMatchObject({ kind: 'head', reason: 'prefix_changed' });
+ expect(await currentState(engine, sourceId, slug), backend).toEqual([{ tombstoned: false, partial_input_chars: CAP }]);
+ }
+ }, 120_000);
+});
diff --git a/test/extraction-watermark-facts.test.ts b/test/extraction-watermark-facts.test.ts
new file mode 100644
index 0000000000..af3fa53940
--- /dev/null
+++ b/test/extraction-watermark-facts.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Large pages A7 (eng F24): the facts backstop reads the appended tail of a
+ * long page instead of its first 8,000 characters, and a head-only read is a
+ * durable receipt plus a doctor signal instead of a silent cut.
+ *
+ * 1. Protects: text appended to a page past MAX_TURN_TEXT_CHARS reaches the
+ * extractor; a mid-page edit falls back to the head and records
+ * `input_truncated` in page_extraction_state, which doctor lists.
+ * 2. Regression that fails it: the extractor slicing the page head again
+ * (the pre-A7 behavior), or the receipt not being written.
+ * 3. Existing facts tests use bodies under the cap, so no test sees the cut.
+ * 4. No new seam: the chat transport stub is the existing test seam.
+ *
+ * PGLite in-memory, chat stubbed ($0).
+ */
+import { describe, test, expect, beforeAll, afterAll, afterEach } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { runFactsBackstop } from '../src/core/facts/backstop.ts';
+import { MAX_TURN_TEXT_CHARS } from '../src/core/facts/extract.ts';
+import { __setChatTransportForTests, resetGateway, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
+import { __resetFactsQueueForTests } from '../src/core/facts/queue.ts';
+import { extractionInputTruncatedEntry } from '../src/commands/doctor/checks/extraction-input.ts';
+import type { DoctorContext } from '../src/commands/doctor/context.ts';
+import type { Check } from '../src/commands/doctor.ts';
+
+let engine: PGLiteEngine;
+
+beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+});
+
+afterAll(async () => {
+ await engine.disconnect();
+});
+
+afterEach(() => {
+ __setChatTransportForTests(null);
+ resetGateway();
+ __resetFactsQueueForTests();
+});
+
+/** Records every extractor prompt; replies with no facts. */
+function capturePrompts(): string[] {
+ const prompts: string[] = [];
+ __setChatTransportForTests(async (opts: ChatOpts): Promise<ChatResult> => {
+ prompts.push(JSON.stringify(opts.messages));
+ return { text: '{"facts":[]}', blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',
+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ return prompts;
+}
+
+/** iMessage-shaped lines, `tag` planted in each, until the text reaches `chars`. */
+function lines(tag: string, chars: number): string {
+ const out: string[] = [];
+ let n = 0;
+ for (let len = 0; len < chars; n++) {
+ const line = `**alice-example** (2024-03-15 1:04 PM): ${tag} message ${n} about the acme-example rollout plan\n`;
+ out.push(line);
+ len += line.length;
+ }
+ return out.join('');
+}
+
+async function put(slug: string, body: string): Promise<void> {
+ await engine.putPage(slug, { type: 'meeting', title: 'Sync', compiled_truth: body });
+}
+
+async function backstop(slug: string, body: string) {
+ return runFactsBackstop({ slug, type: 'meeting', compiled_truth: body, frontmatter: {} },
+ { engine, sourceId: 'default', sessionId: null, source: 'mcp:put_page', mode: 'inline' });
+}
+
+async function receipt(slug: string): Promise<Record<string, unknown> | null> {
+ const [row] = await engine.executeRaw<{ input_truncated: Record<string, unknown> | string | null }>(
+ `SELECT s.input_truncated FROM page_extraction_state s JOIN pages p ON p.id = s.page_id
+ WHERE p.slug = $1 AND s.pipeline = 'facts_backstop'`, [slug]);
+ const value = row?.input_truncated ?? null;
+ return typeof value === 'string' ? JSON.parse(value) : value;
+}
+
+async function doctor(): Promise<Check> {
+ const checks = await extractionInputTruncatedEntry.run({ engine } as unknown as DoctorContext) as Check[];
+ return checks.find(c => c.name === 'extraction_input_truncated')!;
+}
+
+describe('facts backstop: appended tail instead of the page head (A7)', () => {
+ test('an append to a page over the cap is extracted from the appended text, not the head', async () => {
+ const slug = 'meetings/a7-append';
+ const head = lines('HEADNEEDLE', MAX_TURN_TEXT_CHARS + 2_000);
+ await put(slug, head);
+ const prompts = capturePrompts();
+
+ const first = await backstop(slug, head);
+ expect(prompts).toHaveLength(1);
+ expect(prompts[0]).toContain('HEADNEEDLE message 0 ');
+ expect(first).toMatchObject({ mode: 'inline', input_truncated: { kind: 'head', reason: 'no_watermark', processed_chars: MAX_TURN_TEXT_CHARS } });
+ expect(await receipt(slug)).toMatchObject({ kind: 'head', pipeline: 'facts_backstop', reason: 'no_watermark', total_chars: head.length });
+
+ const appended = head + lines('TAILNEEDLE', 1_500);
+ await put(slug, appended);
+ const second = await backstop(slug, appended);
+ expect(prompts).toHaveLength(2);
+ expect(prompts[1]).toContain('TAILNEEDLE message 0 ');
+ expect(prompts[1]).not.toContain('HEADNEEDLE');
+ expect(second).not.toHaveProperty('input_truncated');
+ // The head the first run skipped is still unread: the receipt stays.
+ expect(await receipt(slug)).toMatchObject({ kind: 'head' });
+
+ // Nothing appended since: no model call at all.
+ await backstop(slug, appended);
+ expect(prompts).toHaveLength(2);
+
+ // An append longer than the cap: the newest window, recorded as such.
+ const long = appended + lines('OLDTAIL', 6_000) + lines('NEWTAIL', 6_000);
+ await put(slug, long);
+ const third = await backstop(slug, long);
+ expect(prompts).toHaveLength(3);
+ expect(prompts[2]).toContain('NEWTAIL');
+ expect(prompts[2]).not.toContain('OLDTAIL message 0 ');
+ expect(prompts[2]).not.toContain('TAILNEEDLE');
+ expect(third).toMatchObject({ input_truncated: { kind: 'tail_window' } });
+ expect(await receipt(slug)).toMatchObject({ kind: 'tail_window', total_chars: long.length - appended.length });
+ });
+
+ test('a mid-page edit falls back to the head, records the receipt and doctor lists the page', async () => {
+ const slug = 'meetings/a7-mid-edit';
+ const body = lines('EARLY', 3_000) + lines('LATER', MAX_TURN_TEXT_CHARS);
+ await put(slug, body);
+ const prompts = capturePrompts();
+ await backstop(slug, body);
+ // The first read leaves the watermark at the end of this body.
+ const edited = body.replace('EARLY message 3 ', 'EDITED message 3 ') + lines('APPENDED', 500);
+ await put(slug, edited);
+ const result = await backstop(slug, edited);
+ expect(prompts).toHaveLength(2);
+ expect(prompts[1]).toContain('EDITED message 3 ');
+ expect(prompts[1]).not.toContain('APPENDED');
+ expect(result).toMatchObject({ input_truncated: { kind: 'head', reason: 'prefix_changed' } });
+ expect(await receipt(slug)).toMatchObject({ kind: 'head', reason: 'prefix_changed', total_chars: edited.length });
+
+ const check = await doctor();
+ expect(check.message).toContain(`default:${slug}`);
+ expect(check.message).toContain('facts_backstop/head');
+ expect(check.details).toMatchObject({ groups: expect.arrayContaining([expect.objectContaining({ pipeline: 'facts_backstop', kind: 'head' })]) });
+ });
+
+ test('a page under the cap is read whole and leaves no receipt', async () => {
+ const slug = 'meetings/a7-short';
+ const body = lines('SHORT', 2_000);
+ await put(slug, body);
+ const prompts = capturePrompts();
+ const result = await backstop(slug, body);
+ expect(prompts[0]).toContain('SHORT message 0 ');
+ expect(result).not.toHaveProperty('input_truncated');
+ expect(await receipt(slug)).toBeNull();
+ });
+});
diff --git a/test/extraction-watermark.test.ts b/test/extraction-watermark.test.ts
new file mode 100644
index 0000000000..517adee319
--- /dev/null
+++ b/test/extraction-watermark.test.ts
@@ -0,0 +1,53 @@
+/**
+ * planExtraction (src/core/extraction-watermark.ts): the watermark decision
+ * on its own, for the cases the pipeline tests do not reach.
+ *
+ * 1. Protects: offsets are UTF-8 bytes, so a multi-byte body resumes exactly
+ * at the appended text; a stale pipeline version or an offset past the body
+ * falls back to the head with the reason; a tail window never starts inside
+ * a surrogate pair.
+ * 2. Regression that fails it: counting the watermark in UTF-16 units, or
+ * trusting a watermark from another pipeline version.
+ * 3. The facts and atoms suites use ASCII bodies and the current version.
+ * 4. No seam: a pure function.
+ */
+import { describe, expect, test } from 'bun:test';
+import { createHash } from 'node:crypto';
+import { EXTRACTION_PIPELINE_VERSION, planExtraction, type StoredWatermark } from '../src/core/extraction-watermark.ts';
+
+const opts = { cap: 40, pipeline: 'facts_backstop' as const, emptyTail: 'skip' as const };
+const mark = (body: string, version = EXTRACTION_PIPELINE_VERSION.facts_backstop): StoredWatermark => {
+ const buf = Buffer.from(body, 'utf8');
+ return { pipelineVersion: version, bytes: buf.length, sha256: createHash('sha256').update(buf).digest('hex') };
+};
+
+describe('planExtraction', () => {
+ test('a multi-byte body resumes at the appended text (offsets are UTF-8 bytes)', () => {
+ const before = 'Grüße aus Zürich — 😀 '.repeat(4);
+ const plan = planExtraction(before + 'appended line', mark(before), opts);
+ expect(plan).toMatchObject({ mode: 'tail', text: 'appended line', truncated: null });
+ expect(plan.next.bytes).toBe(Buffer.byteLength(before + 'appended line', 'utf8'));
+ });
+
+ test('a stale pipeline version and an offset past the body read the head with the reason', () => {
+ const before = 'x'.repeat(60);
+ expect(planExtraction(before + 'more', mark(before, 0), opts).truncated).toMatchObject({ kind: 'head', reason: 'version_changed' });
+ expect(planExtraction(before.slice(0, 50), mark(before), opts).truncated).toMatchObject({ kind: 'head', reason: 'prefix_changed' });
+ });
+
+ test('nothing appended: skip, or re-read the head when the caller asks', () => {
+ const body = 'y'.repeat(60);
+ expect(planExtraction(body, mark(body), opts)).toMatchObject({ mode: 'tail', text: '' });
+ expect(planExtraction(body, mark(body), { ...opts, emptyTail: 'head' }).truncated).toMatchObject({ kind: 'head', reason: 'no_new_text' });
+ });
+
+ test('a tail window never starts inside a surrogate pair', () => {
+ const before = 'z'.repeat(60);
+ const tail = '😀'.repeat(30) + 'end';
+ const plan = planExtraction(before + tail, mark(before), opts);
+ expect(plan.truncated).toMatchObject({ kind: 'tail_window', total_chars: tail.length });
+ expect(plan.text.endsWith('end')).toBe(true);
+ expect(plan.text).not.toMatch(/^[\uDC00-\uDFFF]/);
+ expect(plan.text.length).toBeLessThanOrEqual(opts.cap);
+ });
+});
diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
index f94b5a044f..84b4b2ed61 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@ -205,6 +205,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +680,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1143,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2522,6 +2531,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 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 545b92cf9a..21e53ad20a 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@ -205,6 +205,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +680,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1143,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2522,6 +2531,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 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 5a06338969..eee989bace 100644
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@ -205,6 +205,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +680,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1132,6 +1139,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2518,6 +2527,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 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 f492a7603e..89fc3db86a 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json
@@ -140,6 +140,10 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -481,6 +485,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -810,6 +817,8 @@
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"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)",
@@ -1838,6 +1847,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 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 384e9c888f..edd3e7aee7 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json
@@ -140,6 +140,10 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -481,6 +485,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -810,6 +817,8 @@
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"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)",
@@ -1838,6 +1847,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 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 9e912dbff9..203df1b44e 100644
--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json
@@ -140,6 +140,10 @@
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_uniq": "u UNIQUE (source_id, alias_norm, slug)",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -481,6 +485,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -809,6 +816,8 @@
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
"page_aliases_uniq": "CREATE UNIQUE INDEX page_aliases_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"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)",
@@ -1837,6 +1846,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.json
index 1ef7a9aedf..bbb6c92f9a 100644
--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json
+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json
@@ -151,6 +151,10 @@
"open_loops.open_loops_pkey": "p PRIMARY KEY (id)",
"open_loops.open_loops_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
"open_loops.open_loops_status_check": "c CHECK ((status = ANY (ARRAY['open'::text, 'done'::text, 'dropped'::text, 'stale'::text])))",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_generation_clock.page_generation_clock_id_check": "c CHECK ((id = 1))",
"page_generation_clock.page_generation_clock_pkey": "p PRIMARY KEY (id)",
"page_projection_jobs.page_projection_jobs_pkey": "p PRIMARY KEY (source_incarnation, slug)",
@@ -501,6 +505,9 @@
"open_loops": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_generation_clock": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -838,6 +845,8 @@
"open_loops_pkey": "CREATE UNIQUE INDEX open_loops_pkey ON public.open_loops USING btree (id)",
"open_loops_status_idx": "CREATE INDEX open_loops_status_idx ON public.open_loops USING btree (source_id, status, last_activity_at DESC)",
"open_loops_thread_idx": "CREATE INDEX open_loops_thread_idx ON public.open_loops USING btree (source_id, thread_id) WHERE (status = 'open'::text)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"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)",
@@ -1907,6 +1916,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_generation_clock": {
"columns": [
"1 id integer/int4 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 14f901d232..4499e05bfb 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@ -209,6 +209,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -683,6 +687,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1140,6 +1147,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2534,6 +2543,18 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 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 94fc6a5348..a4deabf2a2 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@ -209,6 +209,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -683,6 +687,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1140,6 +1147,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2534,6 +2543,18 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 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 a9688cbe03..6f600d93df 100644
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@ -209,6 +209,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -683,6 +687,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1143,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2530,6 +2539,18 @@
],
"flags": "relkind=r rls=true force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=true force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.json
index 9178d71e98..3e18094445 100644
--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json
+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json
@@ -535,7 +535,7 @@
},
{
"category": "meta",
- "message": "1115 column(s) verified against live schema",
+ "message": "1122 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
@@ -2203,6 +2203,15 @@
"name": "fence_integrity",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "groups": []
+ },
+ "message": "Every page extraction read all of its input (no head-only, tail-window or size-skip receipts).",
+ "name": "extraction_input_truncated",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.json
index 934b02ace6..ca3c6b92d0 100644
--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json
+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json
@@ -538,7 +538,7 @@
},
{
"category": "meta",
- "message": "1115 column(s) verified against live schema",
+ "message": "1122 column(s) verified against live schema",
"name": "schema_columns",
"status": "ok"
},
@@ -2211,6 +2211,15 @@
"name": "fence_integrity",
"status": "ok"
},
+ {
+ "category": "brain",
+ "details": {
+ "groups": []
+ },
+ "message": "Every page extraction read all of its input (no head-only, tail-window or size-skip receipts).",
+ "name": "extraction_input_truncated",
+ "status": "ok"
+ },
{
"category": "ops",
"message": "Mode: conservative (no per-key overrides — mode bundle is canonical).",
diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.json
index a042813fdc..0906419eeb 100644
--- a/test/fixtures/goldens/doctor/registry-build-checks.json
+++ b/test/fixtures/goldens/doctor/registry-build-checks.json
@@ -781,6 +781,10 @@
"category": "brain",
"name": "fence_integrity"
},
+ {
+ "category": "brain",
+ "name": "extraction_input_truncated"
+ },
{
"category": "ops",
"name": "search_mode"
diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.json
index ef3d235035..f4a051866f 100644
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@ -1,11 +1,12 @@
{
"golden": {
- "count": 238,
+ "count": 239,
"gaps": [
17,
18,
19,
- 100
+ 100,
+ 244
],
"helpers": {
"ALIAS_TABLES": "cddd37c636af42d862c08ca7754a57dfe9d12576b769fa8f74a5f02c803f67a0",
@@ -54,7 +55,7 @@
"sqlQueryForEngine": "71fb1ccec1b22cdc1662876dbd8c17ed81e9ab83485c6965cdf5caa4fc4a4ab5",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
- "latest": 243,
+ "latest": 245,
"records": [
{
"handler": {
@@ -3697,6 +3698,19 @@
"transaction": "absent",
"verify": "absent",
"version": 243
+ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "page_extraction_state",
+ "sql": {
+ "length": 644,
+ "sha256": "f2189cbc318857938dc6d8081c53e93e5ec6372a9402f34029ee9cbf7c376934"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 245
}
],
"versions": [
@@ -3937,7 +3951,8 @@
240,
241,
242,
- 243
+ 243,
+ 245
]
},
"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 57e79115c3..3ba86667eb 100644
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@ -205,6 +205,10 @@
"page_aliases.page_aliases_origin_uniq": "u UNIQUE (source_id, alias_norm, slug, origin)",
"page_aliases.page_aliases_pkey": "p PRIMARY KEY (id)",
"page_aliases.page_aliases_source_fk": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
+ "page_extraction_state.page_extraction_state_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['facts_backstop'::text, 'extract_atoms'::text, 'conversation_facts'::text])))",
+ "page_extraction_state.page_extraction_state_pkey": "p PRIMARY KEY (page_id, pipeline)",
+ "page_extraction_state.page_extraction_state_watermark_bytes_check": "c CHECK ((watermark_bytes >= 0))",
"page_facts_reconcile.page_facts_reconcile_outcome_check": "c CHECK ((outcome = ANY (ARRAY['complete'::text, 'deferred'::text, 'invalid'::text, 'cancelled'::text])))",
"page_facts_reconcile.page_facts_reconcile_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",
"page_facts_reconcile.page_facts_reconcile_pkey": "p PRIMARY KEY (page_id)",
@@ -676,6 +680,9 @@
"page_aliases": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
+ "page_extraction_state": [
+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
+ ],
"page_facts_reconcile": [
"<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"
],
@@ -1136,6 +1143,8 @@
"page_aliases_origin_uniq": "CREATE UNIQUE INDEX page_aliases_origin_uniq ON public.page_aliases USING btree (source_id, alias_norm, slug, origin)",
"page_aliases_pkey": "CREATE UNIQUE INDEX page_aliases_pkey ON public.page_aliases USING btree (id)",
"page_aliases_slug_idx": "CREATE INDEX page_aliases_slug_idx ON public.page_aliases USING btree (source_id, slug)",
+ "page_extraction_state_pkey": "CREATE UNIQUE INDEX page_extraction_state_pkey ON public.page_extraction_state USING btree (page_id, pipeline)",
+ "page_extraction_state_truncated_idx": "CREATE INDEX page_extraction_state_truncated_idx ON public.page_extraction_state USING btree (pipeline, page_id) WHERE (input_truncated IS NOT NULL)",
"page_facts_reconcile_pkey": "CREATE UNIQUE INDEX page_facts_reconcile_pkey ON public.page_facts_reconcile USING btree (page_id)",
"page_generation_clock_pkey": "CREATE UNIQUE INDEX page_generation_clock_pkey ON public.page_generation_clock USING btree (id)",
"page_mention_state_pkey": "CREATE UNIQUE INDEX page_mention_state_pkey ON public.page_mention_state USING btree (page_id)",
@@ -2522,6 +2531,18 @@
],
"flags": "relkind=r rls=false force_rls=false"
},
+ "page_extraction_state": {
+ "columns": [
+ "1 page_id integer/int4 NOT NULL",
+ "2 pipeline text/text NOT NULL",
+ "3 pipeline_version integer/int4 NOT NULL",
+ "4 watermark_bytes bigint/int8 NULL",
+ "5 watermark_sha256 text/text NULL",
+ "6 input_truncated jsonb/jsonb NULL",
+ "7 updated_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"
+ ],
+ "flags": "relkind=r rls=false force_rls=false"
+ },
"page_facts_reconcile": {
"columns": [
"1 page_id integer/int4 NOT NULL",
diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.ts
index 0f2618f67c..c7ac494f1b 100644
--- a/test/graduation-inventory.test.ts
+++ b/test/graduation-inventory.test.ts
@@ -60,7 +60,7 @@ describe('graduation inventory', () => {
expect(new Set(names).size).toBe(names.length);
const counts: Record<string, number> = {};
for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;
- expect(counts).toEqual({ carry: 122, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });
+ expect(counts).toEqual({ carry: 123, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });
for (const e of GRADUATION_INVENTORY.entries) {
expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres })
.toEqual({ relation: e.relation, reason: true, present: true });