Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(extract-atoms): segmented pages are not offered to extract_atoms (git is the parent: atom pages are written to the database before git)
garrytan8f43d6f3288e
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsvindex 95e1f59292..51a86744e6 100644--- a/docs/architecture/canonical-writers.tsv+++ b/docs/architecture/canonical-writers.tsv@@ -45,9 +45,9 @@ src/core/company-brain/demo.ts 2 isolated_eval Fictional source registration usesrc/core/company-brain/profile.ts 2 engine_guard Company-profile legacy deletes use withCompanyBrainSource to lock and validate source incarnation, path, receipt and policy; calls without that context retain engine guards, and managed sync routes to the coordinator before this legacy path. Direct importFromContent calls without prepare refuse on managed brains before any write (assertUnmanagedCanonicalWriter).src/core/company-brain/runtime.ts 1 projection Only source policy metadata advances under the company-source lock and brain/source row locks; the same transaction validates immutable approval and creates a receipt with source-incarnation and managed owner/topology fences, without source-file writes.src/core/cycle/drift.ts 1 coordinator A managed brain preflights maintenance authority before judge spend and publishes the report through publishMaintenancePage; the unmanaged putPage stays behind the canonical table trigger.-src/core/cycle/extract-atoms.ts 2 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication. PR 4 (Wave B incremental derivation, transcripts): stale atom retirement moved to extract-atoms-page-state.ts; what remains is the atom write through importFromContent and its mention in the module comment.+src/core/cycle/extract-atoms.ts 3 engine_guard Canonical table SQL trigger requires coordinator capability; legacy calls fail before canonical DB publication.src/core/cycle/extract-facts.ts 7 coordinator Managed and unmanaged reconciliation key rows by fence row number, update matched rows in place, expire and detach removed rows instead of deleting them, and expire fence-owned rows of soft-deleted pages; on a managed brain each changed page publishes a managed_maintenance_fence_facts request and each soft-deleted page a managed_maintenance_deleted_page_facts_expire request, whose preparers replan or recheck the deletion under the page key inside the coordinator publication.-src/core/cycle/extract-atoms-page-state.ts 3 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately. PR 4 (Wave B incremental derivation, transcripts): stale atom retirement (softDeletePages of an origin's non-current, non-imported, non-managed atoms) lives here, in 500-page maintenanceTransaction chunks for a whole-page extraction (retireStaleAtoms, moved from extract-atoms.ts) and, for a segmented page, in the caller's maintenanceTransaction right after the scan-state revision check (retireStaleAtomsIn, extract-atoms-segments.ts settlePage); managed brains skip segmented atom extraction and the trigger refuses an uncoordinated soft-delete.+src/core/cycle/extract-atoms-page-state.ts 1 engine_guard Atom completion updates and cardinality checks share one transaction; managed canonical SQL remains fenced and scan/failure bookkeeping is stored separately.src/core/cycle/extract-takes.ts 4 coordinator On a managed brain the DB-source walk publishes each fenced page that needs a change as a managed_maintenance_takes_reextract request whose preparer re-reads the page under its key and writes the canonical projection's superseded_by while leaving resolution columns untouched; the file walk and unmanaged brains keep direct SQL, which the trigger refuses on managed brains. Stale-row pruning deletes only takes whose rows left a cleanly parsed fence on a live page in the same source.src/core/cycle/grade-takes.ts 1 coordinator A managed brain applies auto-resolutions through the coordinated takes_resolve page mutation; the unmanaged resolveTake stays behind the canonical table trigger.src/core/cycle/patterns.ts 2 coordinator Managed local patterns use admitted page operations and validate canonical outputs; the legacy reverse-file path runs only unmanaged. Quote grounding writes verified pattern pages back through publishMaintenancePage (revision-checked) on a managed brain; the unmanaged importFromContent write-back stays behind the canonical table trigger. #6302: on that unmanaged path only, the timeline row of a quarantined appended entry is deleted in the same transaction as the import (an import does not reconcile timeline rows; a managed publish projects them from the Markdown).diff --git a/docs/architecture/system-of-record.md b/docs/architecture/system-of-record.mdindex 2b8c489221..a1b99fe374 100644--- a/docs/architecture/system-of-record.md+++ b/docs/architecture/system-of-record.md@@ -232,7 +232,8 @@ or a physical projection that leaves attribution untouched):- `src/core/cycle/dream-provenance.ts` (1): the dream provenance frontmatter stamp runs per page in `maintenanceTransaction`, or `derivedMaintenanceTransaction` at the child's derived tier when the ref carries its taint (unmanaged brains only; managed synthesis publishes through maintenance requests).- `src/core/cycle/dream-taint.ts` (3): the unmanaged dream summary page, its frontmatter tags, and the page_versions row of the different body it replaces (#6982), run in `derivedMaintenanceTransaction` at the tier of the pages it indexes; managed brains publish it through a maintenance request.- `src/core/cycle/drift.ts` (1): the unmanaged drift report page runs in `maintenanceTransaction`; managed brains publish it through a maintenance request.-- `src/core/cycle/extract-atoms-page-state.ts` (3): the atom completion stamp runs in `maintenanceTransaction`; stale atom retirement soft-deletes in 500-page `maintenanceTransaction` chunks after a whole-page extraction, and for a segmented page in the caller's `maintenanceTransaction` right after its scan-state revision check.+- `src/core/cycle/extract-atoms-page-state.ts` (1): the atom completion stamp runs in `maintenanceTransaction`.+- `src/core/cycle/extract-atoms.ts` (1): stale atom retirement soft-deletes in 500-page `maintenanceTransaction` chunks.- `src/core/cycle/extract-facts.ts` (7): the unmanaged page reconcile and the expiry of fence facts whose page was soft-deleted run in `maintenanceTransaction`; managed brains publish `managed_maintenance_fence_facts` and `managed_maintenance_deleted_page_facts_expire` requests whose preparers write inside the coordinator publication. Both reconcile paths write at the page's tier and gate new rows.- `src/core/cycle/extract-takes.ts` (1): one projected-takes writer stamps each page's tier and runs the write gate: inside a receipted `managed_maintenance_takes_reextract` request per changed page on managed brains, one `maintenanceTransaction` per page tier for the unmanaged batch upsert.- `src/core/enrichment-service.ts` (2): the enrichment stub fallback write and its auto-timeline entry run in `maintenanceTransaction` at the source page's derived tier (the stub import is lowered to it afterwards).diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex e9b8a63e5f..66fb9745c3 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -119,8 +119,8 @@ src/core/cycle/edge-contradictions.ts removeTimelineLine call:serializeMarkdownsrc/core/cycle/edge-contradictions.ts removeTimelineLine field SEGWsrc/core/cycle/extract-atoms-page-state.ts transferLegacyAtomPageState field META compares two snapshots; segmented page: getter throws page_body_segmentedsrc/core/cycle/extract-atoms.ts discoverExtractablePages field STREAM see sql row; CAS is on content_hash + knowledge_revision-src/core/cycle/extract-atoms.ts discoverExtractablePages sql STREAM segmented pages are matched by body_storage instead and extracted per occurrence window (extract-atoms-segments.ts, PR 4 4b)-src/core/cycle/extract-atoms.ts minCompiledTruthChars sql STREAM false for a segmented page (NULL body); discovery ORs body_storage = 'segmented' (PR 4 4b)+src/core/cycle/extract-atoms.ts discoverExtractablePages sql STREAM minCompiledTruthChars is false for NULL: segmented pages are never discovered (skip until per-segment extraction, PR 4)+src/core/cycle/extract-atoms.ts minCompiledTruthChars sql STREAM false for a segmented page (NULL body): skipsrc/core/cycle/extract-atoms.ts runPhaseExtractAtoms call:serializeMarkdown SEGWsrc/core/cycle/extract-facts.ts canonicalCacheState field INLINE inline arm; a segmented page compares its stored regions with the canonical file by length and SHA-256 (segmentedBodyMatchesFile)src/core/cycle/extract-facts.ts planFenceReconcile field NONE view.timeline is the parsed facts fence of the timeline section (FactsFenceView); a segmented page reads it from its marker segments (segmentedFactsFenceView)diff --git a/src/commands/doctor/checks/derivation-pricing.ts b/src/commands/doctor/checks/derivation-pricing.tsindex a0075c8096..2a94f7ce1e 100644--- a/src/commands/doctor/checks/derivation-pricing.ts+++ b/src/commands/doctor/checks/derivation-pricing.ts@@ -1,6 +1,6 @@/*** derivation_unpriced_model (PR 4, Wave B incremental derivation): segmented pages whose paid derivation (facts,- * conversation facts, atoms, synopsis) stopped or booked its whole reservation because the model has no price. An+ * conversation facts, synopsis) stopped or booked its whole reservation because the model has no price. An* unpriced model reserves a ceiling estimate (no default changes and no price is invented), so under the per-page cap it* gets about one window per page and every call books that ceiling. The receipts on page_segment_derivations say so* (reason or kind `unpriced_model`, with the model; unpricedModelReceipt); this check groups them by model and namesdiff --git a/src/commands/doctor/checks/derivation-purge-sweeps.ts b/src/commands/doctor/checks/derivation-purge-sweeps.tsindex 9aeca8b74e..0e7600052c 100644--- a/src/commands/doctor/checks/derivation-purge-sweeps.ts+++ b/src/commands/doctor/checks/derivation-purge-sweeps.ts@@ -1,7 +1,7 @@/*** Wave B PR 4 (lane 4a): doctor `derivation_purge_sweeps`. A fact purge records a sweep of the stored derivation* results holding its claim and deletes them after it commits (segment-derive.ts continueDerivationPurges). While a- * sweep is recorded, paid atom, synopsis and fact extraction makes no call on the pages it covers (receipts say+ * sweep is recorded, paid synopsis and fact extraction makes no call on the pages it covers (receipts say* `purge_sweep_pending`), so a sweep left pending or stalled holds that work back. This check names each one with its* purge request id and the command that continues it.*/@@ -38,7 +38,7 @@ async function runDerivationPurgeSweeps(ctx: DoctorContext): Promise<Check[]> {checks.push({name: 'derivation_purge_sweeps', status: 'warn', details: { sweeps: rows.length, truncated: rows.length > sweeps.length, records: sweeps },message: `${rows.length} fact purge sweep(s) of stored derivation results are not finished: ${listed}${rows.length > sweeps.length ? ` (first ${sweeps.length} of ${rows.length} shown)` : ''}. `- + 'Until each ends, paid atom, synopsis and fact extraction makes no call on the pages it covers (purge_sweep_pending). '+ + 'Until each ends, paid synopsis and fact extraction makes no call on the pages it covers (purge_sweep_pending). '+ (busy ? 'A sweep marked scope_lock_busy has walked to its end and waits only for a write in its source that is still open (an import, sync or page edit): let that write finish, then continue it. ' : '')+ `Continue each with gbrain forget --purge --status --request-id <request_id> --continue.`,...(first ? { fix: { argv: continueSweepArgv(first), consent: [], actor: 'agent' as const, requires_exclusive: false, verify: doctorVerify('derivation_purge_sweeps'),diff --git a/src/commands/doctor/checks/extraction-input.ts b/src/commands/doctor/checks/extraction-input.tsindex b1dbd6ecce..927e54bdd8 100644--- a/src/commands/doctor/checks/extraction-input.ts+++ b/src/commands/doctor/checks/extraction-input.ts@@ -19,8 +19,8 @@* are read; a page counts once per pipeline and receipt kind. A derivation receipt* without a `kind` (the synopsis pass's tier fallback or refused reservation), or of* kind `unpriced_model` (doctor derivation_unpriced_model), is not an input-truncation- * receipt and is not counted. A receipt whose reason is `purge_sweep_pending` (atoms,- * synopsis or fact extraction made no paid call because a fact purge's sweep covers the+ * receipt and is not counted. A receipt whose reason is `purge_sweep_pending` (synopsis+ * or fact extraction made no paid call because a fact purge's sweep covers the* page) counts under that kind, whatever its own: its remedy is finishing the sweep* (doctor derivation_purge_sweeps), not a higher spend cap.*@@ -118,7 +118,7 @@ async function runExtractionInputTruncatedCheck(ctx: DoctorContext): Promise<Chechecks.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' && g.kind !== UNREAD_WINDOWS && g.kind !== PURGE_SWEEP);+ const atoms = actionable.find(g => g.pipeline === 'extract_atoms');const capped = actionable.some(g => g.kind === UNREAD_WINDOWS);const sweeping = actionable.some(g => g.kind === PURGE_SWEEP);checks.push({ name: 'extraction_input_truncated', status: 'warn', message: summary, details,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 33482db76d..a6624f4a00 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1063,8 +1063,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// PR 4 (Wave B incremental derivation, transcripts)// PR 4 4b{ since: 'TBD', text: 'Appending to a long conversation now re-extracts facts only for the new messages.' },- { since: 'TBD', text: 'Atom extraction now covers very large pages, and after an append reads only the new text.' },- { since: 'TBD', text: 'Fact, atom and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls, the synopsis step\'s embedding included, turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped. A model with no price still reserves its ceiling estimate (about one window per page at the default cap; no default changed and no price is assumed), and its receipt now says `unpriced_model` with the model; doctor `derivation_unpriced_model` warns and names the fix, `gbrain pricing set <model> --input <usd> --output <usd>`, which writes `pricing.overrides`.' },+ { since: 'TBD', text: 'Fact and synopsis extraction on a large page now each have their own per-page spend cap, `derive.max_usd_per_page` (default $2 per kind over the page\'s lifetime; unlimited under `spend.posture tokenmax` when unset; `off` disables it), separate from `embed.max_usd_per_page`, which now counts embeddings only, so extraction never uses up a page\'s embedding budget and a new embedding model does not reset extraction spend. Each call reserves its worst case (every retry) and books what the provider reported; a call that failed after the provider answered is still booked, a call the provider may have billed (a timeout, an abort, a dropped connection, a server or gateway error, each retry the provider SDK made) books its worst case, and only one the provider refused outright (a rate limit, an auth or request error, with no usage reported) or a failed embedding books nothing; metered calls, the synopsis step\'s embedding included, turn the SDK\'s hidden retries off. Doctor lists the pages a cap stopped. A model with no price still reserves its ceiling estimate (about one window per page at the default cap; no default changed and no price is assumed), and its receipt now says `unpriced_model` with the model; doctor `derivation_unpriced_model` warns and names the fix, `gbrain pricing set <model> --input <usd> --output <usd>`, which writes `pricing.overrides`.' },{ since: 'TBD', text: 'A conversation window whose fact extraction fails for a reason of its own (malformed or truncated output, a refusal, input too long) in three runs in a row is now skipped with a receipt, so the older windows of the page still get extracted, and the facts it had before stay; provider outages, auth errors and rate limits never count. `gbrain doctor` names the window and `gbrain extract-conversation-facts --slug <slug> --force` tries it again. Incremental runs on a large conversation page only add or replace facts window by window; facts are removed only when their exact window is extracted again or when a run finishes the whole page with no failed window, no cap, no window limit and no `--since`, which then clears the facts of windows no longer on the page. The page\'s chat format is detected over the whole page (not its first 64 KB) whenever it is not already known; a page whose format is no longer detected over the whole page (text added around a transcript can outweigh its message lines, or it quotes another format) while some conversation format still parses a message in it is now held instead of guessed: no model call, no fact added or removed, so stale facts on such a page wait for the operator\'s call. `gbrain doctor` lists it as `conversation_detection_ambiguous` with each format\'s message count, and `gbrain extract-conversation-facts --source-id <source> --slug <slug> --grammar <format> --dry-run` previews what a run under that format would extract and remove; without `--dry-run` it runs, and `--grammar none` settles the page as not a transcript and clears its conversation facts. `--grammar` applies to one page: a slug in more than one source needs `--source-id`, and the command refuses without it. The choice holds until the page changes; then the page is detected again, and when still no format is detected it is held for a new choice. A page no conversation format parses a message in (facts an older extractor left included) is no longer a transcript: it is marked non-extractable and its conversation facts are cleared, even under `--force`. A page that reads as a transcript yet parses no message keeps every fact and leaves a `no_messages` receipt doctor lists. A run settles and clears only if the page is still the version it read when the publication locks it, so a write that lands during the run leaves the page for the next run with every fact kept. Until a run settles, a page can briefly hold more facts than a settled extraction would: a run that stops partway (an abort, a crash, a limit) adds the facts of the windows it finished, and the facts of windows those replaced on the page stay until a later run extracts their exact window again or settles the page.' },// PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.{ since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s synopsis cap (`derive.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. After `gbrain reindex --segmented --apply` re-chunks a page, the next pass synopsizes its new chunks. Pages read whole are unchanged.' },@@ -1076,8 +1075,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: 'TBD', text: 'A fact purge now also finds stored link, mention, timeline and fence results that spell a Greek claim with a final sigma (ς) where the claim has σ or Σ, or the other way round, or a Turkish dotted capital İ the way JavaScript lowercases it (i̇). It normalizes only the results that contain the claim\'s words in order, so the search costs about what the plain substring search did. When that search still runs past the purge transaction\'s statement budget, the purge fails with `purge_lookup_timeout` and nothing is purged, instead of being retried until the transaction gives up.' },{ since: 'TBD', text: 'A fact purge now searches stored link, mention, timeline and fence results in batches of 500 rows per statement, and its receipt checks them the same way, so a claim whose words appear in tens of thousands of stored results can be purged instead of always failing with `purge_lookup_timeout`. The purge still commits all at once. It fails with `purge_lookup_timeout`, purging nothing, only when the search runs past two minutes.' },{ since: 'TBD', text: 'A fact purge no longer searches stored link, mention, timeline and fence results inside its transaction, so other writes to the source are no longer blocked while it walks them. The purge records the claim and commits; it then deletes the results holding the claim in batches of 500 stored results, each in a short transaction of its own, for up to two minutes. From the commit on, a result holding the claim cannot be written back into what the purge covers. When the walk does not finish in that time, the purge still commits, but its receipt reports `page_segment_derivations` as `incomplete`, `completion: incomplete` (exit 75) and `derivation_sweep: pending`. Running the same purge again with its request id, or purging another fact in the source, continues from where the walk stopped. The walk no longer fails a purge with `purge_lookup_timeout` (this replaces the two-minute failure above).' },- { since: 'TBD', text: 'A fact purge\'s sweep of stored link, mention, timeline and fence results no longer stops for good on large results: a batch that runs past its 5-second statement budget is retried in half as many results, down to one, and a single result that still runs past it is deleted without being read (stored results are rebuilt from the page). Only when even that delete runs past the budget does the sweep stop; its receipt then says `derivation_sweep: stalled`, and other sweeps in the source go on. A purge now sweeps for its own claim first, so an earlier slow sweep no longer holds it back. `gbrain forget --purge --status --request-id <id> --continue` (new) continues a pending or stalled sweep after the fact is gone, and the receipt\'s `next` names it. Before a sweep ends it walks the stored results again until a walk deletes nothing, and walks again the pages where a result entered its scope meanwhile (a segment replaced, a page deleted), so no result holding the claim is left behind. While a sweep is pending, paid atom, synopsis and fact extraction makes no call on a page it covers (receipts say `purge_sweep_pending`), instead of paying again for results the sweep would refuse to store.' },- { since: 'TBD', text: 'A fact purge now returns once it has recorded the sweep of stored link, mention, timeline and fence results and run it for up to 5 seconds, instead of up to two minutes; when the sweep has not finished by then, the receipt says `derivation_sweep: pending` (exit 75) and `gbrain forget --purge --status --request-id <id> --continue` finishes it. A sweep never deletes a stored atom, synopsis or conversation-fact result without reading it: when one alone runs past the statement budget, the sweep stops with `derivation_sweep: stalled` and `derivation_sweep_reason: paid_row_unreadable`; a result whose page was restored while the sweep was deleting it unread is kept. A sweep no longer ends while a page delete or segment replacement that brought a result into its scope is still uncommitted; it checks that page after the write commits. When the receipt\'s check of stored results runs out of time after the purge\'s own sweep finished verified, the store reports the sweep\'s result (`reason: verified_by_sweep`, with `probe` naming the deadline) instead of `unverified`. New doctor check `derivation_purge_sweeps` names each pending or stalled sweep with its request id and the command that continues it. Doctor `extraction_input_truncated` reports atom, synopsis and fact receipts a pending sweep blocked as `purge_sweep_pending`, pointing at that check instead of `derive.max_usd_per_page`, and a per-chunk synopsis re-embed job a sweep blocked no longer reports `ok`.' },+ { since: 'TBD', text: 'A fact purge\'s sweep of stored link, mention, timeline and fence results no longer stops for good on large results: a batch that runs past its 5-second statement budget is retried in half as many results, down to one, and a single result that still runs past it is deleted without being read (stored results are rebuilt from the page). Only when even that delete runs past the budget does the sweep stop; its receipt then says `derivation_sweep: stalled`, and other sweeps in the source go on. A purge now sweeps for its own claim first, so an earlier slow sweep no longer holds it back. `gbrain forget --purge --status --request-id <id> --continue` (new) continues a pending or stalled sweep after the fact is gone, and the receipt\'s `next` names it. Before a sweep ends it walks the stored results again until a walk deletes nothing, and walks again the pages where a result entered its scope meanwhile (a segment replaced, a page deleted), so no result holding the claim is left behind. While a sweep is pending, paid synopsis and fact extraction makes no call on a page it covers (receipts say `purge_sweep_pending`), instead of paying again for results the sweep would refuse to store.' },+ { since: 'TBD', text: 'A fact purge now returns once it has recorded the sweep of stored link, mention, timeline and fence results and run it for up to 5 seconds, instead of up to two minutes; when the sweep has not finished by then, the receipt says `derivation_sweep: pending` (exit 75) and `gbrain forget --purge --status --request-id <id> --continue` finishes it. A sweep never deletes a stored synopsis or conversation-fact result without reading it: when one alone runs past the statement budget, the sweep stops with `derivation_sweep: stalled` and `derivation_sweep_reason: paid_row_unreadable`; a result whose page was restored while the sweep was deleting it unread is kept. A sweep no longer ends while a page delete or segment replacement that brought a result into its scope is still uncommitted; it checks that page after the write commits. When the receipt\'s check of stored results runs out of time after the purge\'s own sweep finished verified, the store reports the sweep\'s result (`reason: verified_by_sweep`, with `probe` naming the deadline) instead of `unverified`. New doctor check `derivation_purge_sweeps` names each pending or stalled sweep with its request id and the command that continues it. Doctor `extraction_input_truncated` reports synopsis and fact receipts a pending sweep blocked as `purge_sweep_pending`, pointing at that check instead of `derive.max_usd_per_page`, and a per-chunk synopsis re-embed job a sweep blocked no longer reports `ok`.' },{ since: 'TBD', text: 'When a fact purge\'s receipt check counts a stored link, mention, timeline or fence result still holding the claim, it now reports it even if it then runs out of time: a result the sweep covers makes `page_segment_derivations` `incomplete` (with `probe` naming where it stopped) instead of `verified_by_sweep`. A result found after the purge\'s sweep had already ended records that sweep again, so the receipt says `derivation_sweep: pending` and `gbrain forget --purge --status --request-id <id> --continue` deletes it. A sweep that reaches its end while a page delete or segment replacement in the source is still uncommitted no longer starts its walk over: it waits up to 1.5 seconds for those writes (writes that arrive meanwhile wait behind it, briefly), then ends after checking only the pages they touched; when they are still open after that, a later call tries again, so steady imports no longer keep a sweep from ending. A sweep also waits for writes that were already open when the purge recorded it before it starts its verifying walk, so one that commits during that walk can no longer leave a result holding the claim behind. Doctor `derivation_purge_sweeps` now says that continuing a sweep can also delete, without reading it, an unpaid stored result in its scope that is too large to read within the statement budget.' },{ since: 'TBD', text: 'When a fact purge\'s sweep of stored link, mention, timeline and fence results has walked to its end but cannot finish because a write in the source (an import, sync or page edit) is still open past its 1.5-second wait, the receipt now says `derivation_sweep_reason: scope_lock_busy` and its `next` says to let that write finish before continuing with `gbrain forget --purge --status --request-id <id> --continue`, instead of only saying to continue again. Doctor `derivation_purge_sweeps` lists the same reason for that sweep. The reason clears once the sweep moves on.' },// GBRA-159 visibility hotfix.diff --git a/src/core/config-runtime-keys.ts b/src/core/config-runtime-keys.tsindex 89fe901fd0..3ef72bf01c 100644--- a/src/core/config-runtime-keys.ts+++ b/src/core/config-runtime-keys.ts@@ -7,7 +7,7 @@*/export const RUNTIME_READER_CONFIG_KEYS: readonly string[] = ['embed.max_usd_per_page', // page-embedding-budget.ts: large-page embedding cap, default $2 (unlimited under spend.posture tokenmax)- 'derive.max_usd_per_page', // page-spend.ts: large-page cap per paid derivation (facts, atoms, synopsis), default $2 (unlimited under spend.posture tokenmax)+ 'derive.max_usd_per_page', // page-spend.ts: large-page cap per paid derivation (facts, synopsis), default $2 (unlimited under spend.posture tokenmax)'embed.content_drift.pass_interval_hours', // content-drift-sweep.ts: hours between completed content-drift passes, default 24 (0 = every run)'facts.absorb_warn_threshold', // doctor facts_extraction_health absorb-refusal warn threshold, default 10 per 24 h'think.trajectory_enabled', // think/index.ts: trajectory substrate on temporal intents, default ondiff --git a/src/core/cycle/extract-atoms-input.ts b/src/core/cycle/extract-atoms-input.tsindex ac18f52c5a..83d9583d41 100644--- a/src/core/cycle/extract-atoms-input.ts+++ b/src/core/cycle/extract-atoms-input.ts@@ -67,7 +67,6 @@ export interface ExtractAtomsInput {* the #6503 disposition holds (no completion stamp, nothing retired).*/export function extractAtomsInput(item: ExtractAtomsItem, maxInputChars: number, watermark: StoredWatermark | null = null): ExtractAtomsInput {- if (item.kind === 'page' && item.window) return { promptContent: item.content, truncated: false, inputChars: item.content.length };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 };diff --git a/src/core/cycle/extract-atoms-page-state.ts b/src/core/cycle/extract-atoms-page-state.tsindex 0589cf6b12..f6bbf52149 100644--- a/src/core/cycle/extract-atoms-page-state.ts+++ b/src/core/cycle/extract-atoms-page-state.ts@@ -23,19 +23,6 @@ export interface AtomPageInput {content: string;contentHash: string;identity?: AtomPageIdentity;- /** Discovery found a segmented page: `content` is empty until extract-atoms-segments.ts expands it into windows. */- segmented?: boolean;- /** PR 4 4b: `content` is one window of a segmented page's occurrence, not the page. */- window?: AtomPageWindow;-}--// PR 4 (Wave B incremental derivation, transcripts)-/** One window of a segmented page (extract-atoms-segments.ts); its methods are bound to the page's derivation plan. */-export interface AtomPageWindow {- /** Run this window's model call metered against the page's atoms cap. Null: refused, the page's remaining windows are skipped and the receipt recorded. */- run<T>(model: string, maxOutputTokens: number, call: () => Promise<T>): Promise<{ value: T } | null>;- /** Record the window extracted with these atoms. Returns the atom slugs retired when this settles the page. */- settle(atomSlugs: string[]): Promise<string[]>;}export class AtomPageStateError extends Error {@@ -155,58 +142,3 @@ export async function transferLegacyAtomPageState(engine: SqlEngine, before: Pag[after.page.id, after.sourceIncarnation, after.page.content_hash, after.revision, state.fail_count, state.tombstoned]);return rows.length > 0;}--/**- * Soft-delete an origin's atoms that are not current, inside the caller's transaction (errors propagate, so the caller's- * transaction rolls back). PR 4 (Wave B incremental derivation, transcripts): a segmented page settles with its scan- * state's revision check first, then this, in one transaction.- */-export async function retireStaleAtomsIn(- tx: BrainEngine,- sourceId: string,- origin: { key: 'source_slug' | 'source_path'; value: string },- hash16: string,- currentSlugs: string[],-): Promise<string[]> {- const stale = await staleAtomSlugs(tx, sourceId, origin, hash16, currentSlugs);- for (let i = 0; i < stale.length; i += 500) await tx.softDeletePages(stale.slice(i, i + 500), { sourceId });- return stale;-}--async function staleAtomSlugs(engine: BrainEngine, sourceId: string, origin: { key: 'source_slug' | 'source_path'; value: string },- hash16: string, currentSlugs: string[]): Promise<string[]> {- const rows = await engine.executeRaw<{ slug: string }>(- `SELECT slug FROM pages- WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL- AND frontmatter->>'${origin.key}' = $2- AND COALESCE(frontmatter->>'source_hash', '') <> $3- AND (frontmatter->>'imported_from') IS NULL- AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'- AND NOT (slug = ANY($4::text[]))`,- [sourceId, origin.value, hash16, currentSlugs],- );- return rows.map(r => r.slug);-}--/**- * Soft-delete a source's atoms from earlier extractions (a different or- * provisional source_hash) that the current, completed extraction did not- * re-produce. Imported atoms (`imported_from`) and managed atoms are left- * alone. Best-effort: a failure leaves duplicates, never loses current atoms.- */-export async function retireStaleAtoms(- engine: BrainEngine,- sourceId: string,- origin: { key: 'source_slug' | 'source_path'; value: string },- hash16: string,- currentSlugs: string[],-): Promise<string[]> {- try {- const stale = await staleAtomSlugs(engine, sourceId, origin, hash16, currentSlugs);- for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));- return stale;- } catch (err) {- console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);- return [];- }-}diff --git a/src/core/cycle/extract-atoms-segments.ts b/src/core/cycle/extract-atoms-segments.tsdeleted file mode 100644index d7e11d7e15..0000000000--- a/src/core/cycle/extract-atoms-segments.ts+++ /dev/null@@ -1,142 +0,0 @@-/**- * extract_atoms over a segmented page (wave-b spec 8.2 "extract_atoms", 8.3; PR 4 lane 4b). Discovery finds a- * segmented page with no complete scan state for its content hash; expandSegmentedAtomPages turns it into work items- * that are <= input-cap windows of its new or changed occurrences, cut at line starts, newest first. The phase loop- * extracts each window like a page item and, instead of the page completion stamp, settles the window on the- * occurrence's page_segment_derivations row (kind extract_atoms: segment sha, context hash, each window's text sha and- * the atom slugs it produced). An append offers only the new text's windows; a window whose text an earlier run- * extracted under the same context is never offered again, so a rewritten tail keeps its earlier windows' atoms.- *- * Each window's call is metered against the page's atoms cap (meterPaidCall, atoms:<model>: reserved first, the- * provider-reported cost booked); a refusal skips the page's remaining windows and records an unread_windows receipt on- * each unfinished occurrence's row. When every live occurrence is settled, the page's scan state is stamped complete- * for its content hash (the revision check) and then, in the same transaction, atoms of windows that left the page (and- * atoms of an earlier whole-page extraction) are retired, so a page that changed meanwhile retires nothing.- * The completion CAS stays on content_hash + knowledge_revision (completeAtomReceipts). Managed brains do not extract- * segmented pages (their publication path is whole-page).- */-import { createHash } from 'node:crypto';-import type { BrainEngine } from '../engine.ts';-import { loadPricingOverrides } from '../budget/budget-tracker.ts';-import { maintenanceTransaction } from '../persistence/attribution.ts';-import { estimateChatCallUsd, meterPaidCall, unpricedModelReceipt } from '../page-embedding-budget.ts';-import { planSegmentDerivations, segmentDerivationContextHash, type SegmentDerivationInput, type SegmentDerivationRow } from '../page-body/derivations.ts';-import { readConversationOccurrences, readOccurrenceText } from '../page-body/segment-conversation.ts';-import { lineWindows } from '../facts/backstop-segments.ts';-import { retireStaleAtomsIn, writeAtomPageState, type AtomPageInput, type AtomPageWindow } from './extract-atoms-page-state.ts';--const KIND = 'extract_atoms';-/** Bump when the windowing or the row output changes shape: every occurrence is extracted again once. */-export const EXTRACT_ATOMS_DERIVATION_VERSION = 1;-/** Windows one run offers per page; the rest wait for the next run (the page is not stamped complete). */-export const MAX_ATOM_WINDOWS_PER_PAGE_RUN = 16;--interface WindowRecord { ordinal: number; sha: string; atoms: string[] }-interface OccurrenceState { occurrenceId: number; sha256: Uint8Array; contextHash: Uint8Array; total: number; done: Map<number, WindowRecord> }--const records = (row: SegmentDerivationRow | undefined): WindowRecord[] => {- const windows = (row?.output as { windows?: unknown } | null)?.windows;- return Array.isArray(windows) ? windows as WindowRecord[] : [];-};-const sha = (text: string) => createHash('sha256').update(text).digest('hex');-const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');--/** Segmented pages become their windows; other pages pass through. Returns the atoms retired by pages that settled with nothing left to extract. */-export async function expandSegmentedAtomPages(engine: BrainEngine, sourceId: string, pages: readonly AtomPageInput[],- opts: { managed: boolean; cap: number; dryRun: boolean }): Promise<{ pages: AtomPageInput[]; retired: string[] }> {- const out: AtomPageInput[] = [];- const retired: string[] = [];- for (const page of pages) {- if (!page.segmented) { out.push(page); continue; }- if (opts.managed || !page.identity) continue;- const windows = await planPage(engine, sourceId, page, opts);- if (windows.items.length) out.push(...windows.items);- else if (windows.settled && !opts.dryRun) retired.push(...await windows.settle());- }- return { pages: out, retired };-}--async function planPage(engine: BrainEngine, sourceId: string, page: AtomPageInput, opts: { cap: number; dryRun: boolean }) {- const pageId = page.identity!.pageId;- const { body, occurrences } = await readConversationOccurrences(engine, pageId);- const live = occurrences.map(o => ({ occurrenceId: o.row.occurrenceId, sha256: o.row.sha256,- contextHash: segmentDerivationContextHash(KIND, { entryState: { region: o.row.region }, page: { cap: opts.cap } }) }));- const prior = await engine.readSegmentDerivations(pageId, { kind: KIND });- const plan = planSegmentDerivations(KIND, EXTRACT_ATOMS_DERIVATION_VERSION, live, prior);- const priorRow = new Map(prior.map(row => [row.occurrenceId, row]));- const extracted = new Map<string, string[]>();- for (const row of [...plan.retired, ...prior]) {- if (row.version === EXTRACT_ATOMS_DERIVATION_VERSION) for (const w of records(row)) extracted.set(`${hex(row.contextHash)}:${w.sha}`, w.atoms ?? []);- }- const states = new Map<number, OccurrenceState>();- const items: AtomPageInput[] = [];- let unread = false;- let stop: 'cap_reached' | 'purge_sweep_pending' | null = null;- let unpricedModel: string | null = null;- let open = 0;- const todo = new Map(plan.todo.map(segment => [segment.occurrenceId, segment]));- const row = (state: OccurrenceState): SegmentDerivationInput => {- const finished = state.done.size === state.total;- return { pageId, kind: KIND, occurrenceId: state.occurrenceId, version: EXTRACT_ATOMS_DERIVATION_VERSION, segmentSha256: state.sha256,- contextHash: state.contextHash, state: finished ? 'done' : 'partial', output: { windows: [...state.done.values()].sort((a, b) => a.ordinal - b.ordinal) },- receipt: unpricedModelReceipt(KIND, unpricedModel, stop, finished || !stop ? null : { windows_read: state.done.size, windows_total: state.total }) };- };- const settlePage = async (): Promise<string[]> => {- const keep = new Set<string>();- for (const current of plan.current) for (const w of records(current)) for (const slug of w.atoms ?? []) keep.add(slug);- for (const state of states.values()) for (const w of state.done.values()) for (const slug of w.atoms) keep.add(slug);- // PR 4 (Wave B incremental derivation, transcripts): the revision check, then the retire, in one transaction.- return maintenanceTransaction(engine, async tx => {- await writeAtomPageState(tx, sourceId, page, 'complete');- return retireStaleAtomsIn(tx, sourceId, { key: 'source_slug', value: page.slug }, '', [...keep]);- });- };- for (const occurrence of [...occurrences].reverse()) {- const segment = todo.get(occurrence.row.occurrenceId);- if (!segment) continue;- if (items.length >= MAX_ATOM_WINDOWS_PER_PAGE_RUN) { unread = true; break; }- const old = priorRow.get(segment.occurrenceId);- const same = old && old.version === EXTRACT_ATOMS_DERIVATION_VERSION && hex(old.contextHash) === hex(segment.contextHash);- const texts = lineWindows(await readOccurrenceText(engine, body, occurrence.row), opts.cap);- const state: OccurrenceState = { occurrenceId: segment.occurrenceId, sha256: segment.sha256, contextHash: segment.contextHash, total: texts.length,- done: new Map((same ? records(old) : []).map(w => [w.ordinal, { ...w, atoms: w.atoms ?? [] }])) };- states.set(segment.occurrenceId, state);- for (let ordinal = texts.length - 1; ordinal >= 0; ordinal--) {- const text = texts[ordinal]!;- const key = sha(text);- if (state.done.get(ordinal)?.sha === key) continue;- state.done.delete(ordinal);- const reused = extracted.get(`${hex(segment.contextHash)}:${key}`);- if (reused || !text.trim()) { state.done.set(ordinal, { ordinal, sha: key, atoms: reused ?? [] }); continue; }- if (items.length >= MAX_ATOM_WINDOWS_PER_PAGE_RUN) { unread = true; continue; }- open++;- const window: AtomPageWindow = {- async run(model, maxOutputTokens, call) {- if (opts.dryRun) return { value: await call() };- if (stop) return null;- const pricingOverrides = await loadPricingOverrides(engine);- const metered = await meterPaidCall(engine, { id: pageId, body_storage: 'segmented' }, `atoms:${model}`,- estimateChatCallUsd(model, text.length, maxOutputTokens, pricingOverrides), call, { pricingOverrides });- unpricedModel = metered.unpricedModel ?? unpricedModel;- if (!('refused' in metered)) return metered;- stop = metered.refused.reason === 'purge_sweep_pending' ? 'purge_sweep_pending' : 'cap_reached';- const unfinished = [...states.values()].filter(s => s.done.size < s.total);- if (unfinished.length) await engine.upsertSegmentDerivations(unfinished.map(row));- return null;- },- async settle(atomSlugs) {- state.done.set(ordinal, { ordinal, sha: key, atoms: atomSlugs });- await engine.upsertSegmentDerivations([row(state)]);- open--;- return open === 0 && !unread && !stop ? settlePage() : [];- },- };- items.push({ ...page, segmented: false, content: text, window });- }- }- if (!opts.dryRun) {- if (states.size) await engine.upsertSegmentDerivations([...states.values()].map(row));- await engine.retireSegmentDerivations(pageId, live.map(segment => segment.occurrenceId), { kind: KIND });- }- return { items, settled: !unread && open === 0, settle: settlePage };-}diff --git a/src/core/cycle/extract-atoms.ts b/src/core/cycle/extract-atoms.tsindex af8ee3bfec..130fb4ac66 100644--- a/src/core/cycle/extract-atoms.ts+++ b/src/core/cycle/extract-atoms.ts@@ -71,7 +71,6 @@ import { derivedWriteThrough, reportFileHolds } from './derived-write-through.tsimport { serializeMarkdown } from '../markdown.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 { expandSegmentedAtomPages } from './extract-atoms-segments.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';@@ -95,7 +94,8 @@ import { OperationError } from '../ops/contract.ts';import { isOpPageSlug } from '../ops/context.ts';import type { WriteReceipt } from '../persistence/types.ts';import { acceptedPendingReceipt } from '../persistence/accepted-pending.ts';-import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, retireStaleAtoms, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';+import { AtomPageStateError, completeAtomReceipts, MAX_DETERMINISTIC_FAILURES, readAtomPageIdentity, writeAtomPageState, type AtomPageInput } from './extract-atoms-page-state.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';import { deriveTrust, lowerDerivedPage } from '../trust/taint.ts';import { derivedGateInput } from '../trust/derived-gate.ts';import { ATOM_TYPES, ATOMS_RESPONSE_SCHEMA } from './extract-atoms-schema.ts';@@ -409,7 +409,7 @@ export async function discoverExtractablePages((SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation,p.slug,p.compiled_truth,- p.content_hash, p.body_storage+ p.content_hashFROM pages pWHERE p.source_id = $1AND p.type = ANY($2::text[])@@ -418,12 +418,12 @@ export async function discoverExtractablePages(AND COALESCE(p.frontmatter->>'imported_from', '') <> 'markdown-greenfield'AND COALESCE(p.frontmatter->>'dream_generated', '') <> 'true'${RAW_SOURCE_HOLDER_EXCLUSION_SQL}- AND (p.body_storage = 'segmented' OR ${minCompiledTruthChars('$3')})+ AND ${minCompiledTruthChars('$3')}${MANAGED_ATOM_DISCOVERY_SQL}${PAGE_SCAN_STATE_EXCLUSION_SQL}${connectorExclusion}${hasFilter ? "AND p.slug = ANY($5::text[])" : ''}- AND (p.body_storage = 'segmented' OR NOT EXISTS (+ AND NOT EXISTS (SELECT 1FROM pages atomWHERE atom.type = 'atom'@@ -431,7 +431,7 @@ export async function discoverExtractablePages(AND atom.frontmatter->>'source_hash' = substring(p.content_hash from 1 for 16)AND COALESCE(atom.frontmatter->>'managed_extraction', '') <> 'true'AND atom.deleted_at IS NULL- ))+ )ORDER BY p.updated_at DESCLIMIT $4`;@@ -451,14 +451,12 @@ export async function discoverExtractablePages(slug: string;compiled_truth: string;content_hash: string;- body_storage: string | null;}>(sql, params);return rows.map((r) => ({slug: r.slug,- content: r.compiled_truth ?? '',+ content: r.compiled_truth,contentHash: r.content_hash,- identity: { pageId: Number(r.id), sourceIncarnation: r.source_incarnation, revision: r.knowledge_revision },- ...(r.body_storage === 'segmented' ? { segmented: true } : {}),+ identity: { pageId: r.id, sourceIncarnation: r.source_incarnation, revision: r.knowledge_revision },}));} catch (err) {const msg = err instanceof Error ? err.message : String(err);@@ -763,9 +761,6 @@ export async function runPhaseExtractAtoms(await resolvePageDiscoveryLimit(engine),);}- const segmented = await expandSegmentedAtomPages(engine, sourceId, pages, { managed: managed !== null, cap: maxInputChars, dryRun: opts.dryRun ?? false });- pages = segmented.pages;- if (segmented.retired.length) await atomFiles?.write([], segmented.retired);// 2. Apply transcript-side source-hash idempotency in ONE batch query// instead of N per-hash round trips. Page-side idempotency lives in@@ -833,7 +828,7 @@ export async function runPhaseExtractAtoms(}const pageItems: WorkItem[] = [];for (const p of pages) {- if (!p.window && seenHashes.has(p.contentHash)) { duplicatesSkipped++; continue; }+ if (seenHashes.has(p.contentHash)) { duplicatesSkipped++; continue; }seenHashes.add(p.contentHash);pageItems.push({ kind: 'page', ...p });}@@ -1000,14 +995,7 @@ export async function runPhaseExtractAtoms(let inputTruncated = 0; // #6503: items cut at the input cap this run (partial disposition, see extract-atoms-input.ts)async function stampAtomsScanHash(item: AtomPageInput): Promise<void> {- if (item.window) await atomFiles?.write([], await item.window.settle([])); // PR 4 4b: a segmented page's window settles on its derivation row- else await writeAtomPageState(engine, sourceId, item, 'complete');- }- /** PR 4 4b: a segmented page's window reserves its call against the page's spend cap first; null: refused, the item is skipped. */- async function chatWithinPageCap<T>(item: WorkItem, call: () => Promise<T>): Promise<T | null> {- const metered = item.kind === 'page' && item.window ? await item.window.run(extractModel, maxOutputTokens, call) : { value: await call() };- if (!metered) pagesSkipped++;- return metered ? metered.value : null;+ 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> {@@ -1111,15 +1099,15 @@ export async function runPhaseExtractAtoms(const cutLine = truncated ? inputTruncatedLine(originLabel, input, maxInputChars) : null; // A7: a complete appended-tail read prints nothingif (cutLine) { inputTruncated++; console.error(cutLine); } // counted only for a model call- const result = await chatWithinPageCap(item, () => chat({+ const result = await chat({model: extractModel,...atomsPrompt(dateGrounding, originLabel, promptContent),maxTokens: maxOutputTokens, responseSchema: ATOMS_RESPONSE_SCHEMA,abortSignal: opts.signal,- }));- if (!result) continue;- // Post-await yield: closes the "long LLM call past TTL" hazard codex flagged. The 30s throttle- // inside maybeYield bounds the actual refresh rate so this is cheap when calls are fast.+ });+ // Post-await yield: closes the "long LLM call past TTL" hazard+ // codex flagged. The 30s throttle inside maybeYield bounds the+ // actual refresh rate so this is cheap when calls are fast.await maybeYield();llmHalt.reset();// #4540: optional per-item pacing between successful LLM calls.@@ -1316,7 +1304,7 @@ export async function runPhaseExtractAtoms(const retired = truncated ? [] : await completeUnmanagedItem(engine, sourceId, item, hash16, importedSlugs);await atomFiles?.write(importedSlugs, retired);if (truncated) await recordPartialDisposition(engine, sourceId, item, maxInputChars);- else if (item.kind === 'page' && !item.window) await stampAtomsScanHash(item);+ else if (item.kind === 'page') await stampAtomsScanHash(item);await commitAtomsWatermark(item, input, []);}} else {@@ -1480,11 +1468,43 @@ export async function runPhaseExtractAtoms(async function completeUnmanagedItem(engine: BrainEngine, sourceId: string,item: { kind: 'transcript'; filePath: string } | ({ kind: 'page' } & AtomPageInput), hash16: string, importedSlugs: string[]): Promise<string[]> {await completeAtomReceipts(engine, sourceId, importedSlugs, hash16, item.kind === 'page' ? item : undefined);- if (item.kind === 'page' && item.window) return item.window.settle(importedSlugs);return retireStaleAtoms(engine, sourceId, item.kind === 'page'? { key: 'source_slug', value: item.slug } : { key: 'source_path', value: item.filePath }, hash16, importedSlugs);}+/**+ * Soft-delete a source's atoms from earlier extractions (a different or+ * provisional source_hash) that the current, completed extraction did not+ * re-produce. Imported atoms (`imported_from`) and managed atoms are left+ * alone. Best-effort: a failure leaves duplicates, never loses current atoms.+ */+async function retireStaleAtoms(+ engine: BrainEngine,+ sourceId: string,+ origin: { key: 'source_slug' | 'source_path'; value: string },+ hash16: string,+ currentSlugs: string[],+): Promise<string[]> {+ try {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT slug FROM pages+ WHERE source_id = $1 AND type = 'atom' AND deleted_at IS NULL+ AND frontmatter->>'${origin.key}' = $2+ AND COALESCE(frontmatter->>'source_hash', '') <> $3+ AND (frontmatter->>'imported_from') IS NULL+ AND COALESCE(frontmatter->>'managed_extraction', '') <> 'true'+ AND NOT (slug = ANY($4::text[]))`,+ [sourceId, origin.value, hash16, currentSlugs],+ );+ const stale = rows.map(r => r.slug);+ for (let i = 0; i < stale.length; i += 500) await maintenanceTransaction(engine, tx => tx.softDeletePages(stale.slice(i, i + 500), { sourceId }));+ return stale;+ } catch (err) {+ console.error(`[extract_atoms] stale atom cleanup failed for ${origin.value} (non-fatal): ${err instanceof Error ? err.message : String(err)}`);+ return [];+ }+}+/*** Canonical slug stem for an atom title. Routes through slugifySegment (the* same normalizer the FS-import path uses) and RE-STRIPS a trailing dash afterdiff --git a/src/core/facts/purge-verify.ts b/src/core/facts/purge-verify.tsindex 5979c5aaba..4ab422b6ba 100644--- a/src/core/facts/purge-verify.ts+++ b/src/core/facts/purge-verify.ts@@ -728,6 +728,6 @@ export async function purgeCompletion(engine: BrainEngine, row: Pick<WriteReques: sweep.state === 'pending'? `Stored derivation results are still being swept for the claim (derivation_sweep: pending). Continue the sweep with gbrain forget --purge --status --request-id ${row.request_id} --continue until completion is complete.`: sweep.reason === 'paid_row_unreadable'- ? `The sweep of stored derivation results stopped on a paid result (atoms, synopsis or conversation facts) it could not read within its statement budget (derivation_sweep: stalled, paid_row_unreadable); paid results are never deleted unread, and other sweeps go on. Retry it with gbrain forget --purge --status --request-id ${row.request_id} --continue; if it stalls again, report it with the output of gbrain doctor --json.`+ ? `The sweep of stored derivation results stopped on a paid result (synopsis or conversation facts) it could not read within its statement budget (derivation_sweep: stalled, paid_row_unreadable); paid results are never deleted unread, and other sweeps go on. Retry it with gbrain forget --purge --status --request-id ${row.request_id} --continue; if it stalls again, report it with the output of gbrain doctor --json.`: `The sweep of stored derivation results stopped on a result it could not read or delete within its statement budget (derivation_sweep: stalled); other sweeps go on. Retry it with gbrain forget --purge --status --request-id ${row.request_id} --continue; if it stalls again, report it with the output of gbrain doctor --json.`] } : {}) };}diff --git a/src/core/page-body/schema.ts b/src/core/page-body/schema.tsindex b6e28e0904..74897f67cd 100644--- a/src/core/page-body/schema.ts+++ b/src/core/page-body/schema.ts@@ -172,7 +172,7 @@ ${PAGE_BODY_STAGING_TEXTS_SQL}`;* The derivation pipelines whose per-segment results page_segment_derivations records (wave-b spec 8.1-8.6, PR 4), and* the states a row can settle in. One list feeds the table's CHECKs and the TS types (page-body/derivations.ts).*/-export const SEGMENT_DERIVATION_KINDS = ['links', 'mentions', 'timeline', 'fences', 'conversation_facts', 'extract_atoms', 'facts_backstop', 'synopsis'] as const;+export const SEGMENT_DERIVATION_KINDS = ['links', 'mentions', 'timeline', 'fences', 'conversation_facts', 'facts_backstop', 'synopsis'] as const;export const SEGMENT_DERIVATION_STATES = ['done', 'partial', 'failed', 'skipped'] as const;const sqlList = (values: readonly string[]) => values.map(v => `'${v}'`).join(',');@@ -260,7 +260,7 @@ export function derivationScopeLockSql(sourceId: string): string {* before it ends.** PR 4 (Wave B incremental derivation, transcripts): page_derivation_spend is the per-page lifetime spend ledger of each- * paid derivation family (`facts`, `atoms`, `synopsis`; page-spend.ts), each capped by `derive.max_usd_per_page` on its own,+ * paid derivation family (`facts`, `synopsis`; page-spend.ts), each capped by `derive.max_usd_per_page` on its own,* apart from the embedding ledger (page_embedding_budget), so derivation spend never starves a page's embeddings.*/export const PAGE_SEGMENT_DERIVATIONS_SQL = `CREATE TABLE IF NOT EXISTS page_segment_derivations (@@ -280,7 +280,7 @@ export const PAGE_SEGMENT_DERIVATIONS_SQL = `CREATE TABLE IF NOT EXISTS page_segCREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');CREATE TABLE IF NOT EXISTS page_derivation_spend (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),+ family TEXT NOT NULL CHECK (family IN ('facts','synopsis')),spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),reserved_at TIMESTAMPTZ,diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex 10d2c64611..edc6792b22 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -187,7 +187,7 @@ export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,/*** Reserve `estimateUsd` of one paid step on `page` against its per-page cap (wave-b spec 8.3), before the provider call.* An embedding reserves on page_embedding_budget under `embed.max_usd_per_page` (a new embedding model starts a new- * ledger, as planPageEmbedding does); a derivation (facts, atoms, synopsis) on its own family's ledger (page-spend.ts).+ * ledger, as planPageEmbedding does); a derivation (facts, synopsis) on its own family's ledger (page-spend.ts).* Metered: segmented pages and pages over `pages.inline_max_bytes`; any other page is unmetered. A refusal reserves* nothing, so the caller skips the call. A derivation runs its call through meterPaidCall, which books the actual cost.*/diff --git a/src/core/page-spend.ts b/src/core/page-spend.tsindex b5265a89b9..03b047a26c 100644--- a/src/core/page-spend.ts+++ b/src/core/page-spend.ts@@ -2,7 +2,7 @@* PR 4 (Wave B incremental derivation, transcripts): the per-page spend ledgers of the paid derivations on a large page* (wave-b spec 8.3) and the reservation window both ledgers use.*- * Families: every paid derivation family (conversation facts and the facts backstop as `facts`, `atoms`, `synopsis`)+ * Families: every paid derivation family (conversation facts and the facts backstop as `facts`, `synopsis`)* has its own lifetime ledger per page in page_derivation_spend, each capped by `derive.max_usd_per_page` (default $2;* unlimited under `spend.posture tokenmax` when unset; `off` disables it). Embedding keeps its own ledger and cap* (page_embedding_budget, `embed.max_usd_per_page`), so derivation spend never starves a page's embeddings, and a new@@ -21,8 +21,8 @@ import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';export const PAGE_DERIVATION_CAP_KEY = 'derive.max_usd_per_page';export const DEFAULT_PAGE_DERIVATION_CAP_USD = 2;-/** What a paid step spends on a page: the kind and its model, `embedding:<signature>`, `facts:<model>`, `atoms:<model>`, `synopsis:<model>`. */-export type PageSpendKind = 'embedding' | 'facts' | 'atoms' | 'synopsis';+/** What a paid step spends on a page: the kind and its model, `embedding:<signature>`, `facts:<model>`, `synopsis:<model>`. */+export type PageSpendKind = 'embedding' | 'facts' | 'synopsis';export type PageSpendSignature = `${PageSpendKind}:${string}`;export type DerivationFamily = Exclude<PageSpendKind, 'embedding'>;diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex ee026b434b..d0e2ad7ba2 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -112,7 +112,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('page_body_staging_parts', 'operational', 'Raw parts of open upload sessions; without them a client resuming an upload starts over.'),carry('page_body_stagings', 'operational', 'Body stagings of segmented writes and upload sessions (idempotent begin and commit, expiry deadlines).'),carry('page_body_staging_texts', 'operational', 'The segment texts each live body staging needs, so a page purge keeps an unpublished write\'s texts.'),- carry('page_derivation_spend', 'operational', 'Large-page derivation spend ledger: per-page lifetime spend of fact, atom and synopsis extraction under derive.max_usd_per_page; without it a page could be paid for past its cap.'),+ carry('page_derivation_spend', 'operational', 'Large-page derivation spend ledger: per-page lifetime spend of fact and synopsis extraction under derive.max_usd_per_page; without it a page could be paid for past its cap.'),carry('page_embedding_budget', 'operational', 'Large-page embedding spend ledger: per-page spend, holds awaiting approval and caps; without it held pages would embed without consent.'),carry('page_extraction_state', 'operational', 'Extraction watermarks and partial-input receipts per page and pipeline; without them the next extraction of a large page reads its head again and records the receipt anew.'),carry('page_facts_reconcile', 'operational', 'Facts reconcile watermark: per-page revision extract_facts last reconciled; without it every page is due again.'),@@ -121,7 +121,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),carry('page_purges', 'user_data', 'Text-free page purge tombstones (#5575); dropping them would let purged pages re-import.'),carry('page_retrievals', 'operational', 'Retrieval telemetry: when a user-facing read last surfaced each page (stale-page bias, volunteer usage stats).'),- carry('page_segment_derivations', 'operational', 'Per-segment derivation watermarks (links, mentions, timeline, fences, conversation facts, atoms, backstop, synopsis) keyed by manifest occurrence; without them the next pass re-derives every segment, including paid conversation-facts windows.'),+ carry('page_segment_derivations', 'operational', 'Per-segment derivation watermarks (links, mentions, timeline, fences, conversation facts, backstop, synopsis) keyed by manifest occurrence; without them the next pass re-derives every segment, including paid conversation-facts windows.'),carry('page_segment_derivation_purge_pages', 'operational', 'Pages whose derivation rows entered a recorded purge sweep\'s scope while it ran (an occurrence retired, a page soft-deleted); without them a graduated brain finishes a sweep without checking those pages again.'),carry('page_segment_derivation_purges', 'operational', 'Recorded purge sweeps of segment derivation rows still in progress, with their cursor and claim; without them a graduated brain stops refusing claimed text and never finishes sweeping it out of copied derivation rows.'),carry('page_segment_texts', 'user_data', 'Segment texts of segmented page bodies, stored once per source; without them a large page has no body.'),diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 0de82ceb10..0ca773f286 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1391,7 +1391,7 @@ CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_tex-- Wave B per-segment derivation watermarks (migration v265; src/core/page-body/derivations.ts).CREATE TABLE IF NOT EXISTS page_segment_derivations (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','extract_atoms','facts_backstop','synopsis')),+ pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','facts_backstop','synopsis')),occurrence_id BIGINT NOT NULL,pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),@@ -1406,7 +1406,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivations (CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');CREATE TABLE IF NOT EXISTS page_derivation_spend (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),+ family TEXT NOT NULL CHECK (family IN ('facts','synopsis')),spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),reserved_at TIMESTAMPTZ,diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex dadc9cbc8b..f38e846219 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2135,7 +2135,7 @@ CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_tex-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL). Edit that file, then run: bun run build:schemaCREATE TABLE IF NOT EXISTS page_segment_derivations (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','extract_atoms','facts_backstop','synopsis')),+ pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','facts_backstop','synopsis')),occurrence_id BIGINT NOT NULL,pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),@@ -2150,7 +2150,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivations (CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');CREATE TABLE IF NOT EXISTS page_derivation_spend (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),+ family TEXT NOT NULL CHECK (family IN ('facts','synopsis')),spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),reserved_at TIMESTAMPTZ,diff --git a/src/schema.sql b/src/schema.sqlindex 6cf988fdd5..98a6a43e18 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2131,7 +2131,7 @@ CREATE INDEX IF NOT EXISTS page_body_staging_texts_text ON page_body_staging_tex-- BEGIN GENERATED from src/core/page-body/schema.ts (PAGE_SEGMENT_DERIVATIONS_SQL). Edit that file, then run: bun run build:schemaCREATE TABLE IF NOT EXISTS page_segment_derivations (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','extract_atoms','facts_backstop','synopsis')),+ pipeline TEXT NOT NULL CHECK (pipeline IN ('links','mentions','timeline','fences','conversation_facts','facts_backstop','synopsis')),occurrence_id BIGINT NOT NULL,pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 0),segment_sha256 BYTEA NOT NULL CHECK (octet_length(segment_sha256) = 32),@@ -2146,7 +2146,7 @@ CREATE TABLE IF NOT EXISTS page_segment_derivations (CREATE INDEX IF NOT EXISTS page_segment_derivations_unsettled ON page_segment_derivations (pipeline, page_id) WHERE state IN ('partial','failed');CREATE TABLE IF NOT EXISTS page_derivation_spend (page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,- family TEXT NOT NULL CHECK (family IN ('facts','atoms','synopsis')),+ family TEXT NOT NULL CHECK (family IN ('facts','synopsis')),spent_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (spent_usd >= 0),reserved_usd DOUBLE PRECISION NOT NULL DEFAULT 0 CHECK (reserved_usd >= 0),reserved_at TIMESTAMPTZ,diff --git a/test/e2e/conversation-facts-incremental-core-postgres.test.ts b/test/e2e/conversation-facts-incremental-core-postgres.test.tsindex 706d28c16f..0669a77d5c 100644--- a/test/e2e/conversation-facts-incremental-core-postgres.test.ts+++ b/test/e2e/conversation-facts-incremental-core-postgres.test.ts@@ -8,7 +8,7 @@*/import { afterAll, beforeAll, describe } from 'bun:test';import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';-import { defineConversationFactsIncrementalCases, defineSegmentReceiptDoctorCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';+import { defineConversationFactsIncrementalCases, defineSegmentReceiptDoctorCases, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';import { defineDerivationSpendCases } from '../helpers/derivation-spend-cases.ts';import { defineDerivationUnpricedCases } from '../helpers/derivation-unpriced-cases.ts';import { hasDatabase } from './helpers.ts';@@ -19,7 +19,6 @@ import { hasDatabase } from './helpers.ts';afterAll(async () => { await brain.close(); }, 120_000);defineConversationFactsIncrementalCases({ getBrain: () => brain });defineSegmentedBackstopCases({ getBrain: () => brain });- defineSegmentedAtomsCases({ getBrain: () => brain });defineSegmentReceiptDoctorCases({ getBrain: () => brain });defineDerivationSpendCases({ getBrain: () => brain });defineDerivationUnpricedCases({ getBrain: () => brain });diff --git a/test/e2e/extract-atoms-segmented-skip-postgres.test.ts b/test/e2e/extract-atoms-segmented-skip-postgres.test.tsnew file mode 100644index 0000000000..21b9b0b0e1--- /dev/null+++ b/test/e2e/extract-atoms-segmented-skip-postgres.test.ts@@ -0,0 +1,15 @@+/**+ * extract_atoms skips segmented pages, Postgres arm. Cases: test/helpers/extract-atoms-segmented-skip-cases.ts. PGLite+ * arm: test/large-pages/extract-atoms-segmented-skip.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';+import { defineExtractAtomsSegmentedSkipCases } from '../helpers/extract-atoms-segmented-skip-cases.ts';+import { hasDatabase } from './helpers.ts';++(hasDatabase() ? describe : describe.skip)('extract_atoms skips segmented pages [postgres]', () => {+ let brain: AppendBrain;+ beforeAll(async () => { brain = await openAppendBrain('postgres'); }, 120_000);+ afterAll(async () => { await brain.close(); }, 120_000);+ defineExtractAtomsSegmentedSkipCases({ getBrain: () => brain });+});diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 7d8b9d2be2..ac5c80b33e 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -234,7 +234,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -274,7 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex fedf21c0d3..4d1d9296eb 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -234,7 +234,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -274,7 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex 035e91497c..f2b4dd5981 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -234,7 +234,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -274,7 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 7816c1ac38..2115fc8a02 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -168,7 +168,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -201,7 +201,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex 9e342f1172..c9bcfa94df 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -168,7 +168,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -201,7 +201,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex bb1ce87ab7..5214be0c5d 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -168,7 +168,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -201,7 +201,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/postgres-db-initschema.json b/test/fixtures/goldens/catalog/postgres-db-initschema.jsonindex 4d883a444d..4fd2ea5dcc 100644--- a/test/fixtures/goldens/catalog/postgres-db-initschema.json+++ b/test/fixtures/goldens/catalog/postgres-db-initschema.json@@ -179,7 +179,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -212,7 +212,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 861d579d8a..0d2e54750f 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -238,7 +238,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -278,7 +278,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 4c499650fc..316dde4f52 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -238,7 +238,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -278,7 +278,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex 7664cfd1a3..7c0c43d7aa 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -238,7 +238,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -278,7 +278,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 80eb118c5e..f0a2211c75 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -4218,8 +4218,8 @@"idempotent": true,"name": "segment_derivations","sql": {- "length": 6551,- "sha256": "ef3a87c79cfcc26453bbd616c57a5285eeea7b7dd7f0a63cb1eb3bf72d15c69b"+ "length": 6527,+ "sha256": "6817b97b501c8fadfb66177fa317ecd4e1a05ef879cc0c411df134f99019e491"},"sqlFor": "absent","transaction": false,diff --git a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.jsonindex f5474eec61..64877f98f5 100644--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json@@ -234,7 +234,7 @@"page_body_stagings.page_body_stagings_principal_kind_principal_id_client_reque_key": "u UNIQUE (principal_kind, principal_id, client_request_id)","page_body_stagings.page_body_stagings_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE","page_body_stagings.page_body_stagings_state_check": "c CHECK ((state = ANY (ARRAY['open'::text, 'sealed'::text, 'prepared'::text, 'committed'::text, 'aborted'::text, 'expired'::text])))",- "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'atoms'::text, 'synopsis'::text])))",+ "page_derivation_spend.page_derivation_spend_family_check": "c CHECK ((family = ANY (ARRAY['facts'::text, 'synopsis'::text])))","page_derivation_spend.page_derivation_spend_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE","page_derivation_spend.page_derivation_spend_pkey": "p PRIMARY KEY (page_id, family)","page_derivation_spend.page_derivation_spend_reserved_usd_check": "c CHECK ((reserved_usd >= (0)::double precision))",@@ -274,7 +274,7 @@"page_segment_derivation_purges.page_segment_derivation_purges_stalled_reason_check": "c CHECK ((stalled_reason = ANY (ARRAY['statement_timeout'::text, 'paid_row_unreadable'::text])))","page_segment_derivations.page_segment_derivations_context_hash_check": "c CHECK ((octet_length(context_hash) = 32))","page_segment_derivations.page_segment_derivations_page_id_fkey": "f FOREIGN KEY (page_id) REFERENCES pages(id) ON DELETE CASCADE",- "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'extract_atoms'::text, 'facts_backstop'::text, 'synopsis'::text])))",+ "page_segment_derivations.page_segment_derivations_pipeline_check": "c CHECK ((pipeline = ANY (ARRAY['links'::text, 'mentions'::text, 'timeline'::text, 'fences'::text, 'conversation_facts'::text, 'facts_backstop'::text, 'synopsis'::text])))","page_segment_derivations.page_segment_derivations_pipeline_version_check": "c CHECK ((pipeline_version >= 0))","page_segment_derivations.page_segment_derivations_pkey": "p PRIMARY KEY (page_id, pipeline, occurrence_id)","page_segment_derivations.page_segment_derivations_segment_sha256_check": "c CHECK ((octet_length(segment_sha256) = 32))",diff --git a/test/helpers/conversation-facts-incremental-cases.ts b/test/helpers/conversation-facts-incremental-cases.tsindex 00ff02ff81..205ebc48b3 100644--- a/test/helpers/conversation-facts-incremental-cases.ts+++ b/test/helpers/conversation-facts-incremental-cases.ts@@ -27,8 +27,6 @@ import { lineWindows } from '../../src/core/facts/backstop-segments.ts';import { MAX_TURN_TEXT_CHARS } from '../../src/core/facts/extract.ts';import { truthLead } from '../../src/core/page-body/segment-blocks.ts';import { __setChatTransportForTests, chat as gatewayChat, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';-import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';-import { MAX_ATOM_WINDOWS_PER_PAGE_RUN } from '../../src/core/cycle/extract-atoms-segments.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';@@ -321,102 +319,6 @@ export function defineSegmentedBackstopCases(opts: { getBrain: () => AppendBrain}, 600_000);}-/**- * extract_atoms over a segmented page (wave-b spec 8.2 "extract_atoms"): an import extracts every input-cap window of- * every occurrence once (one atom per window from the fake model), across runs when a run's window budget stops it; an- * append by a remote writer extracts only windows whose text no run extracted before, and once the page settles the- * atoms of windows that left the page are retired and every other atom stays; a cap the newest window does not fit- * refuses before any call. Fake chat (the phase's _chat seam), counted by prompt.- */-export function defineSegmentedAtomsCases(opts: { getBrain: () => AppendBrain }): void {- const slug = `notes/atoms-segmented-${randomUUID().slice(0, 8)}`;- const cap = 50_000;- let prompts: string[] = [];- let calls = 0;- let before: string[] = [];- const chat = async (o: ChatOpts): Promise<ChatResult> => {- prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));- const title = `window atom ${++calls}`;- const text = JSON.stringify({ atoms: [{ title, atom_type: 'insight', body: `Body for ${title}.`, source_quote: null, lesson: null, concepts: null, virality_score: null, emotional_register: null }] });- return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test',- usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };- };- /** Runs the phase until a run makes no call; returns the calls made for page S (other pages in the brain are extracted too). */- const drain = async (engine: BrainEngine, s: string): Promise<number> => {- prompts = [];- for (let run = 0; run < 20; run++) {- const made = prompts.length;- await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [] });- if (prompts.length === made) break;- }- prompts = prompts.filter(p => p.includes('Source: ' + s + '\n'));- return prompts.length;- };- const windowsOf = async (brain: AppendBrain, s: string): Promise<string[]> => {- const [page] = await brain.engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]);- const truth = Buffer.from((await brain.body(s)).truth, 'utf8');- return (await brain.engine.readManifest(Number(page!.id)))- .flatMap(row => lineWindows(truth.subarray(row.byteStart, row.byteStart + row.byteLen).toString('utf8'), cap)).filter(w => w.trim());- };- const atoms = async (engine: BrainEngine, s: string) => engine.executeRaw<{ slug: string; live: boolean }>(- `SELECT slug, deleted_at IS NULL AS live FROM pages WHERE source_id='default' AND type='atom' AND frontmatter->>'source_slug'=$1`, [s]);- const rowsOf = async (engine: BrainEngine, s: string) => {- const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]);- return engine.readSegmentDerivations(Number(page!.id), { kind: 'extract_atoms' });- };- const digest = (text: string) => createHash('sha256').update(text).digest('hex');-- test('an import extracts every window of every occurrence once, one atom each; a settled page extracts nothing', async () => {- const brain = opts.getBrain();- await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');- await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');- await brain.engine.setConfig('cycle.extract_atoms.max_input_chars', String(cap));- await brain.seed(slug, chatPage('Atoms', chatDays(700, 100, 5)).replace('type: conversation', 'type: meeting'));- before = await windowsOf(brain, slug);- const made = await drain(brain.engine, slug);- const rows = await rowsOf(brain.engine, slug);- const stored = await atoms(brain.engine, slug);- expect(before.length).toBeGreaterThan(MAX_ATOM_WINDOWS_PER_PAGE_RUN);- expect({ calls: made, covered: before.filter(w => prompts.filter(p => p.includes(w)).length === 1).length, rows: [...new Set(rows.map(r => r.state))],- atoms: stored.filter(a => a.live).length })- .toEqual({ calls: before.length, covered: before.length, rows: ['done'], atoms: before.length });- expect(await drain(brain.engine, slug)).toBe(0);- }, 600_000);-- test('an append by a remote writer extracts only the new windows and retires only the atoms of windows that left the page', async () => {- const brain = opts.getBrain();- const appended = chatDays(800, 2, 5);- expect(await brain.call('append_page', { slug, text: appended, request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });- const after = await windowsOf(brain, slug);- const old = new Set(before.map(digest));- const live = new Set(after.map(digest));- const fresh = after.filter(w => !old.has(digest(w)));- const made = await drain(brain.engine, slug);- const stored = await atoms(brain.engine, slug);- const recorded = new Set((await rowsOf(brain.engine, slug)).flatMap(r => ((r.output as { windows: { atoms: string[] }[] }).windows).flatMap(w => w.atoms)));- expect(fresh.length).toBeLessThanOrEqual(Math.ceil(appended.length / cap) + 2);- expect({ calls: made, covered: fresh.every(w => prompts.some(p => p.includes(w))), live: stored.filter(a => a.live).length,- retired: stored.filter(a => !a.live).length, recorded: stored.filter(a => a.live).every(a => recorded.has(a.slug)) })- .toEqual({ calls: fresh.length, covered: true, live: live.size, retired: [...old].filter(h => !live.has(h)).length, recorded: true });- }, 600_000);-- test('a cap the newest window does not fit refuses before any call and records the unread windows', async () => {- const brain = opts.getBrain();- const capped = `notes/atoms-capped-${randomUUID().slice(0, 8)}`;- await brain.seed(capped, chatPage('Atoms capped', chatDays(900, 100, 6)).replace('type: conversation', 'type: meeting'));- await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');- try {- const made = await drain(brain.engine, capped);- const rows = await rowsOf(brain.engine, capped);- expect({ calls: made, receipts: [...new Set(rows.map(r => JSON.stringify({ state: r.state, reason: (r.receipt as { reason?: string } | null)?.reason ?? null })))] })- .toEqual({ calls: 0, receipts: [JSON.stringify({ state: 'partial', reason: 'cap_reached' })] });- expect(rows.length).toBeGreaterThan(0);- } finally {- await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');- }- }, 600_000);-}-/** Doctor's extraction_input_truncated reads page_segment_derivations receipts too (wave-b spec 8.1), not only page_extraction_state. */export function defineSegmentReceiptDoctorCases(opts: { getBrain: () => AppendBrain }): void {test('doctor lists a segmented page whose windows the cap left unread, with the per-page cap as the fix', async () => {@@ -425,13 +327,13 @@ export function defineSegmentReceiptDoctorCases(opts: { getBrain: () => AppendBrawait seed(s, chatPage('Doctor unread', chatDays(950, 100, 5)).replace('type: conversation', 'type: note'));const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [s]);const [first] = await engine.readManifest(Number(page!.id));- await engine.upsertSegmentDerivations([{ pageId: Number(page!.id), kind: 'extract_atoms', occurrenceId: first!.occurrenceId, version: 1,+ await engine.upsertSegmentDerivations([{ pageId: Number(page!.id), kind: 'facts_backstop', occurrenceId: first!.occurrenceId, version: 1,segmentSha256: first!.sha256, contextHash: new Uint8Array(32), state: 'partial', output: { windows: [] },- receipt: { kind: 'unread_windows', pipeline: 'extract_atoms', reason: 'cap_reached', windows_read: 0, windows_total: 3 } }]);+ receipt: { kind: 'unread_windows', pipeline: 'facts_backstop', reason: 'cap_reached', windows_read: 0, windows_total: 3 } }]);const check = (await extractionInputTruncatedEntry.run({ engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'extraction_input_truncated')!;const groups = (check.details as { groups: Array<{ pipeline: string; kind: string; samples: string[] }> }).groups;expect({ status: check.status, argv: (check as { fix?: { argv: string[] } }).fix?.argv,- listed: groups.some(g => g.pipeline === 'extract_atoms' && g.kind === 'unread_windows' && g.samples.includes(`default:${s}`)) })+ listed: groups.some(g => g.pipeline === 'facts_backstop' && g.kind === 'unread_windows' && g.samples.includes(`default:${s}`)) }).toEqual({ status: 'warn', argv: ['gbrain', 'config', 'set', PAGE_DERIVATION_CAP_KEY, '<USD>'], listed: true });}, 600_000);}diff --git a/test/helpers/derivation-purge-cases.ts b/test/helpers/derivation-purge-cases.tsindex 2123e8e18b..751bf89aac 100644--- a/test/helpers/derivation-purge-cases.ts+++ b/test/helpers/derivation-purge-cases.ts@@ -25,10 +25,7 @@ import { extractionInputTruncatedEntry } from '../../src/commands/doctor/checks/import { categorizeCheck } from '../../src/core/doctor-categories.ts';import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';import { forgetFactInFence } from '../../src/core/facts/forget.ts';-import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';-import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';-import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';import { deriveAll, KINDS, liveOccurrences, resetDeriveWork, storedPage } from './derivation-equivalence-cases.ts';import { conversationBody } from './conversation-page.ts';import { openAppendBrain, type AppendBrain } from './append-brain.ts';@@ -1005,9 +1002,8 @@ export function registerDerivationPurgeScopeCases(kind: 'pglite' | 'postgres'):}/**- * A row that alone outruns the budget stalls only its sweep; paid rows are never deleted unread and paid pipelines- * make no call on a covered page; a purge returns pending and --continue finishes it; the receipt probe and doctor- * report a pending, verified or residual sweep.+ * A row that alone outruns the budget stalls only its sweep; paid rows are never deleted unread; a purge returns+ * pending and --continue finishes it; the receipt probe and doctor report a pending, verified or residual sweep.*/export function registerDerivationPurgeStallsCases(kind: 'pglite' | 'postgres'): void {describe(`purge leaves no derivation row holding the claim (${kind}): stalls, paid work, receipts and doctor`, () => {@@ -1045,38 +1041,6 @@ export function registerDerivationPurgeStallsCases(kind: 'pglite' | 'postgres'):expect({ rows: await exactHolders(h.brain.engine, rowsA, claimA), recorded: await sweepsRecorded() }).toEqual({ rows: [], recorded: 0 });}, 600_000);- test('a paid pipeline makes no call on a page a pending purge sweep covers, so a second run repeats no paid window', async () => {- const slug = 'notes/sweep-atoms-purge', claim = 'Purge Example oven code is 3184';- await candidateRowsPage('notes/sweep-atoms-rows', claim, 300, 0);- await h.brain.seed(slug, purgePage(claim).replace('type: person', 'type: meeting'));- await runExtractFacts(h.brain.engine, { slugs: [slug] });- const [fact] = await h.brain.engine.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact=$3 AND expired_at IS NULL', [SOURCE, slug, claim]);- const params = await confirmed(Number(fact!.id));- await h.brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');- await h.brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');- let prompts: string[] = [];- const chat = async (o: ChatOpts): Promise<ChatResult> => {- prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));- const text = JSON.stringify({ atoms: [{ title: `${claim} ${prompts.length}`, atom_type: 'insight', body: `Body: ${claim}.`, source_quote: null, lesson: null, concepts: null,- virality_score: null, emotional_register: null }] });- return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test',- usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };- };- const run = async () => {- prompts = [];- await runPhaseExtractAtoms(h.brain.engine, { sourceId: SOURCE, _chat: chat, _transcripts: [] });- return prompts.filter(p => p.includes('Source: ' + slug + '\n')).length;- };- __setDerivationSweepLimitsForTests({ batchRows: 50, totalMs: 0 });- try {- expect((await h.brain.call('purge_fact', params)).body.derivation_sweep).toBe('pending');- expect({ first: await run(), second: await run() }).toEqual({ first: 0, second: 0 });- } finally { __setDerivationSweepLimitsForTests(null); }- const resumed = await h.brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true });- expect(resumed.body.derivation_sweep).toBeUndefined();- expect(await run()).toBeGreaterThan(0);- }, 600_000);-test('an unread delete keeps the row of a page restored after the sweep picked it (the scope is checked in the DELETE)', async () => {const fixture = await unreadFixture('unread-restore', 'links', true);installFaultHook(point => { if (point === 'purge:derivation_batch') throw timeout(); });@@ -1089,7 +1053,7 @@ export function registerDerivationPurgeStallsCases(kind: 'pglite' | 'postgres'):}, 600_000);test('a paid row that alone outruns the budget is never deleted unread: the sweep stalls with a named reason, and a retry that fits sweeps it', async () => {- const fixture = await unreadFixture('unread-paid', 'extract_atoms', false);+ const fixture = await unreadFixture('unread-paid', 'synopsis', false);installFaultHook(point => { if (point === 'purge:derivation_batch') throw timeout(); });try { await continueDerivationPurges(h.brain.engine, 'unread-paid', { first: fixture.requestId }); } finally { installFaultHook(undefined); }expect({ rows: await fixture.rows(), sweep: await derivationPurgeState(h.brain.engine, fixture.requestId) })@@ -1145,7 +1109,7 @@ export function registerDerivationPurgeStallsCases(kind: 'pglite' | 'postgres'):expect({ sweep: done.derivation_sweep, recorded: await sweepsRecorded() }).toEqual({ sweep: undefined, recorded: 0 });}, 600_000);- test('doctor names a pending sweep with its request id and the command that continues it, and atom receipts it blocked point there, not at the spend cap', async () => {+ test('doctor names a pending sweep with its request id and the command that continues it, and fact receipts it blocked point there, not at the spend cap', async () => {const claim = 'Purge Example loft code is 8461';await candidateRowsPage('notes/sweep-doctor-rows', claim, 300, 0);const params = await confirmed(await seed('notes/sweep-doctor-purge', claim));@@ -1158,12 +1122,12 @@ export function registerDerivationPurgeStallsCases(kind: 'pglite' | 'postgres'):expect(check!.details.records).toContainEqual(expect.objectContaining({ request_id: params.request_id, state: 'pending', command }));const page = await storedPage(h.brain.engine, 'notes/sweep-doctor-purge');await h.brain.engine.executeRaw(`INSERT INTO page_segment_derivations (page_id, pipeline, occurrence_id, pipeline_version, segment_sha256, context_hash, state, output, receipt)- VALUES ($1, 'extract_atoms', 999999, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'partial', '{"windows":[]}'::jsonb,- jsonb_build_object('kind', 'unread_windows', 'pipeline', 'extract_atoms', 'reason', 'purge_sweep_pending', 'windows_read', 0, 'windows_total', 2))`, [page.id]);+ VALUES ($1, 'conversation_facts', 999999, 1, decode(repeat('00', 32), 'hex'), decode(repeat('00', 32), 'hex'), 'partial', '{"windows":[]}'::jsonb,+ jsonb_build_object('kind', 'unread_windows', 'pipeline', 'conversation_facts', 'reason', 'purge_sweep_pending', 'windows_read', 0, 'windows_total', 2))`, [page.id]);const [truncated] = (await extractionInputTruncatedEntry.run({ engine: h.brain.engine } as never) as Array<Record<string, any>>).filter(c => c.name === 'extraction_input_truncated');- const group = (truncated!.details.groups as Array<Record<string, any>>).find(g => g.pipeline === 'extract_atoms' && g.kind === 'purge_sweep_pending');+ const group = (truncated!.details.groups as Array<Record<string, any>>).find(g => g.pipeline === 'conversation_facts' && g.kind === 'purge_sweep_pending');expect({ remedy: group?.remedy.includes('derivation_purge_sweeps'), cap: group?.remedy.includes(PAGE_DERIVATION_CAP_KEY) }).toEqual({ remedy: true, cap: false });- await h.brain.engine.executeRaw("DELETE FROM page_segment_derivations WHERE page_id=$1 AND pipeline='extract_atoms' AND occurrence_id=999999", [page.id]);+ await h.brain.engine.executeRaw("DELETE FROM page_segment_derivations WHERE page_id=$1 AND pipeline='conversation_facts' AND occurrence_id=999999", [page.id]);expect((await h.brain.call('purge_fact', { status: true, request_id: params.request_id, continue: true })).body.derivation_sweep).toBeUndefined();const [clear] = await derivationPurgeSweepsEntry.run({ engine: h.brain.engine } as never) as Array<Record<string, any>>;expect(clear!.status).toBe('ok');diff --git a/test/helpers/derivation-spend-cases.ts b/test/helpers/derivation-spend-cases.tsindex f51f62765f..498807d8ca 100644--- a/test/helpers/derivation-spend-cases.ts+++ b/test/helpers/derivation-spend-cases.ts@@ -7,12 +7,10 @@* facts and rows; an abort partway through a page keeps the finished windows; a facts call reserves every attempt* extract.ts may make and books what the provider reported for each attempt; a cap stop after a title change keeps* the facts of the windows it did not extract again; a --since run keeps the facts before it and never settles the- * page; windows run across segment cuts exactly as the whole-page pass cuts them; extract_atoms retires nothing when- * the page changed before it settled; a visibility change re-extracts; the facts backstop keeps its finished windows'- * rows when a window throws.+ * page; windows run across segment cuts exactly as the whole-page pass cuts them; a visibility change re-extracts;+ * the facts backstop keeps its finished windows' rows when a window throws.* 2. Fails when: a throw or an abort drops finished windows or their spend, a retry is paid past the cap, a partial or- * filtered run deletes facts it did not replace, windows stop at segment cuts, or atoms are retired by a settle whose- * revision check failed.+ * filtered run deletes facts it did not replace, or windows stop at segment cuts.*/import { expect, test } from 'bun:test';import { createHash, randomUUID } from 'node:crypto';@@ -28,7 +26,6 @@ import { outcomeSession, regularPageVersionToken } from '../../src/core/facts/coimport { TERMINAL_AUDIT_SOURCE } from '../../src/core/facts/audit-sources.ts';import { runFactsBackstop } from '../../src/core/facts/backstop.ts';import { truthLead } from '../../src/core/page-body/segment-blocks.ts';-import { runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';import { chatDays, chatPage, derivations, extract, factsOf, PAID_MODEL, paidTransport } from './conversation-facts-incremental-cases.ts';const pageIdOf = async (engine: BrainEngine, slug: string) =>@@ -219,64 +216,6 @@ export function defineDerivationSpendCases(opts: { getBrain: () => AppendBrain }expect(prompts.length).toBeGreaterThan(0);} finally { __setChatTransportForTests(null); }}, 600_000);-- test('extract_atoms retires no atom when the page changed between its last window and its settle', async () => {- const brain = opts.getBrain();- const slug = `notes/atoms-race-${randomUUID().slice(0, 8)}`;- await caps(brain.engine, 'off');- await brain.engine.setConfig('cycle.extract_atoms.max_input_chars', '50000');- await brain.seed(slug, chatPage('Atoms race', chatDays(2400, 100, 14)).replace('type: conversation', 'type: meeting'));- const pageId = await pageIdOf(brain.engine, slug);- const prompts: string[] = [];- let n = 0;- const chat = async (o: ChatOpts): Promise<ChatResult> => {- prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));- const title = `race atom ${++n}`;- const text = JSON.stringify({ atoms: [{ title, atom_type: 'insight', body: `Body for ${title}.`, source_quote: null, lesson: null, concepts: null, virality_score: null, emotional_register: null }] });- return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test', usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };- };- // The page is edited right after a window of this page settles on its derivation row: with one window offered, that- // is between the last window and the page's settle.- let armed = false;- let edited = false;- const engine = new Proxy(brain.engine, {- get(target, prop) {- if (prop === 'upsertSegmentDerivations') {- return async (rows: Parameters<BrainEngine['upsertSegmentDerivations']>[0]) => {- const out = await target.upsertSegmentDerivations(rows);- if (armed && rows.some(row => row.pageId === pageId && row.kind === 'extract_atoms' && row.state === 'done')) {- armed = false;- expect(await brain.call('append_page', { slug, text: chatDays(2600, 1, 14), request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });- edited = true;- }- return out;- };- }- const value = Reflect.get(target, prop, target);- return typeof value === 'function' ? value.bind(target) : value;- },- });- const drain = async () => { for (let run = 0; run < 20; run++) { const made = n; await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [] }); if (n === made) break; } };- const live = async () => (await brain.engine.executeRaw<{ slug: string }>(- "SELECT slug FROM pages WHERE source_id='default' AND type='atom' AND deleted_at IS NULL AND frontmatter->>'source_slug'=$1", [slug])).map(r => r.slug).sort();- await drain();- // An atom of an earlier whole-page extraction: the page's next settle retires it.- const earlier = `atoms/earlier-${randomUUID().slice(0, 8)}`;- await brain.engine.putPage(earlier, { type: 'atom', title: 'Earlier atom', compiled_truth: 'From a whole-page extraction.', frontmatter: { source_slug: slug, source_hash: 'earlier00000000' } });- const settled = await live();- expect(settled).toContain(earlier);- // One more turn grows the tail window only: one window is offered.- expect(await brain.call('append_page', { slug, text: 'Bob Example (11:59 PM): one more budget review.', request_id: randomUUID() }, { remote: true })).toMatchObject({ isError: false });- prompts.length = 0;- armed = true;- await runPhaseExtractAtoms(engine, { sourceId: 'default', _chat: chat, _transcripts: [] });- expect({ edited, offered: prompts.filter(p => p.includes('Source: ' + slug + '\n')).length }).toEqual({ edited: true, offered: 1 });- const after = await live();- expect(settled.filter(s => !after.includes(s))).toEqual([]);- // Once the page stops changing, its windows settle and the earlier atom is retired.- await drain();- expect(await live()).not.toContain(earlier);- }, 600_000);}/** A production-extractor run (no injected extractor): the gateway's fake transport answers. */diff --git a/test/helpers/derivation-unpriced-cases.ts b/test/helpers/derivation-unpriced-cases.tsindex 9421ad4863..0c1252db32 100644--- a/test/helpers/derivation-unpriced-cases.ts+++ b/test/helpers/derivation-unpriced-cases.ts@@ -4,7 +4,7 @@* (test/e2e/conversation-facts-incremental-core-postgres.test.ts). No default changes and no price is invented: an unpriced* model reserves its ceiling estimate, so the per-page cap stops it after about one window. Fake extractors only.*- * 1. Protects: when the facts, conversation facts, atoms or synopsis step stops (or books its reservation) because the+ * 1. Protects: when the facts, conversation facts or synopsis step stops (or books its reservation) because the* model has no price, its derivation receipt says reason `unpriced_model` with the model id, and doctor* derivation_unpriced_model warns with a fix naming pricing.overrides (gbrain pricing set <model> ...); once the price* is registered the warning clears.@@ -18,7 +18,6 @@ import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';import { PAGE_DERIVATION_CAP_KEY } from '../../src/core/page-spend.ts';import { derivationUnpricedModelEntry } from '../../src/commands/doctor/checks/derivation-pricing.ts';import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';-import { runPhaseExtractAtoms, EXTRACT_ATOMS_MODEL_KEY } from '../../src/core/cycle/extract-atoms.ts';import { __setChatTransportForTests, chat as gatewayChat, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';import type { DoctorContext } from '../../src/commands/doctor/context.ts';@@ -30,7 +29,7 @@ export const UNPRICED = 'anthropic:claude-unpriced-example';const doctor = async (engine: BrainEngine) => (await derivationUnpricedModelEntry.run({ engine } as unknown as DoctorContext) as Check[]).find(c => c.name === 'derivation_unpriced_model')!;-const receiptsOf = async (engine: BrainEngine, slug: string, kind: 'extract_atoms' | 'synopsis') => {+const receiptsOf = async (engine: BrainEngine, slug: string, kind: 'synopsis') => {const [page] = await engine.executeRaw<{ id: number }>("SELECT id FROM pages WHERE source_id='default' AND slug=$1", [slug]);return (await engine.readSegmentDerivations(Number(page!.id), { kind })).map(r => r.receipt as Record<string, unknown> | null).filter(Boolean);};@@ -69,33 +68,6 @@ export function defineDerivationUnpricedCases(opts: { getBrain: () => AppendBrai}}, 600_000);- test('atoms under an unpriced model: the cap stop says unpriced_model with the model', async () => {- const brain = opts.getBrain();- const slug = `notes/unpriced-atoms-${randomUUID().slice(0, 8)}`;- const prompts: string[] = [];- const chat = async (o: ChatOpts): Promise<ChatResult> => {- prompts.push(String(o.messages[0]?.content ?? ''));- const text = JSON.stringify({ atoms: [] });- return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: UNPRICED, providerId: 'groq', usage: { input_tokens: 10, output_tokens: 2, cache_read_tokens: 0, cache_creation_tokens: 0 } };- };- await brain.engine.setConfig(PAGE_EMBED_CAP_KEY, 'off');- await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, '0.000001');- await brain.engine.setConfig(EXTRACT_ATOMS_MODEL_KEY, UNPRICED);- try {- await brain.seed(slug, chatPage('Unpriced atoms', chatDays(4500, 100, 42)).replace('type: conversation', 'type: meeting'));- await runPhaseExtractAtoms(brain.engine, { sourceId: 'default', _chat: chat, _transcripts: [] });- const receipts = await receiptsOf(brain.engine, slug, 'extract_atoms');- expect({ receipts: [...new Set(receipts.map(r => JSON.stringify({ kind: r!.kind, reason: r!.reason, model: r!.model })))] })- .toEqual({ receipts: [JSON.stringify({ kind: 'unread_windows', reason: 'unpriced_model', model: UNPRICED })] });- const check = await doctor(brain.engine);- expect({ status: check.status, atoms: (check.details as { models: Array<{ model: string; pipelines: string[] }> }).models.some(m => m.model === UNPRICED && m.pipelines.includes('extract_atoms')) })- .toEqual({ status: 'warn', atoms: true });- } finally {- await brain.engine.setConfig(EXTRACT_ATOMS_MODEL_KEY, '');- await brain.engine.setConfig(PAGE_DERIVATION_CAP_KEY, 'off');- }- }, 600_000);-test('synopsis under an unpriced model: the refused reservation says unpriced_model with the model', async () => {const brain = opts.getBrain();const slug = `notes/unpriced-synopsis-${randomUUID().slice(0, 8)}`;diff --git a/test/helpers/extract-atoms-segmented-skip-cases.ts b/test/helpers/extract-atoms-segmented-skip-cases.tsnew file mode 100644index 0000000000..00670237b5--- /dev/null+++ b/test/helpers/extract-atoms-segmented-skip-cases.ts@@ -0,0 +1,54 @@+/**+ * extract_atoms never reads a segmented page (git is the parent: on an unmanaged brain extract_atoms writes atom pages+ * to the database through importFromContent before git has them, so it is not extended to a new input). Shared by the+ * PGLite arm (test/large-pages/extract-atoms-segmented-skip.test.ts) and the Postgres arm+ * (test/e2e/extract-atoms-segmented-skip-postgres.test.ts). Fake chat (the phase's _chat seam), counted by prompt.+ *+ * 1. Protects: discovery does not offer a segmented page; the phase makes no model call for it and creates no atom page+ * from it, while an inline page of the same type in the same run is extracted (the phase did run).+ * 2. Fails when: a segmented page is discovered, prompted or yields an atom page.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { AppendBrain } from './append-brain.ts';+import { discoverExtractablePages, runPhaseExtractAtoms } from '../../src/core/cycle/extract-atoms.ts';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import { chatDays, chatPage } from './conversation-facts-incremental-cases.ts';++export function defineExtractAtomsSegmentedSkipCases(opts: { getBrain: () => AppendBrain }): void {+ test('a segmented page is not offered to extract_atoms and yields no atom page; an inline page in the same run is extracted', async () => {+ const brain = opts.getBrain();+ const segmented = `notes/atoms-segmented-skip-${randomUUID().slice(0, 8)}`;+ const inline = `notes/atoms-inline-control-${randomUUID().slice(0, 8)}`;+ await brain.seed(segmented, chatPage('Segmented meeting', chatDays(5000, 100, 51)).replace('type: conversation', 'type: meeting'));+ await brain.seed(inline, chatPage('Inline meeting', chatDays(5200, 1, 52)).replace('type: conversation', 'type: meeting'));+ expect({ segmented: (await brain.body(segmented)).storage, inline: (await brain.body(inline)).storage }).toEqual({ segmented: 'segmented', inline: 'inline' });++ const offered = (await discoverExtractablePages(brain.engine, 'default')).map(p => p.slug);+ expect({ segmented: offered.includes(segmented), inline: offered.includes(inline) }).toEqual({ segmented: false, inline: true });++ const prompts: string[] = [];+ let n = 0;+ const chat = async (o: ChatOpts): Promise<ChatResult> => {+ prompts.push(o.messages.map(m => typeof m.content === 'string' ? m.content : JSON.stringify(m.content)).join('\n'));+ const title = `probe atom ${++n}`;+ const text = JSON.stringify({ atoms: [{ title, atom_type: 'insight', body: `Body for ${title}.`, source_quote: null, lesson: null, concepts: null, virality_score: null, emotional_register: null }] });+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: 'test:stub', providerId: 'test',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };+ };+ for (let run = 0; run < 5; run++) {+ const made = prompts.length;+ await runPhaseExtractAtoms(brain.engine, { sourceId: 'default', _chat: chat, _transcripts: [] });+ if (prompts.length === made) break;+ }+ const atomsOf = async (engine: BrainEngine, slug: string) => (await engine.executeRaw<{ slug: string }>(+ "SELECT slug FROM pages WHERE source_id='default' AND type='atom' AND frontmatter->>'source_slug'=$1", [slug])).length;+ expect({+ segmentedPrompts: prompts.filter(p => p.includes('Source: ' + segmented + '\n')).length,+ segmentedAtoms: await atomsOf(brain.engine, segmented),+ inlinePrompted: prompts.some(p => p.includes('Source: ' + inline + '\n')),+ inlineAtoms: (await atomsOf(brain.engine, inline)) > 0,+ }).toEqual({ segmentedPrompts: 0, segmentedAtoms: 0, inlinePrompted: true, inlineAtoms: true });+ }, 600_000);+}diff --git a/test/large-pages/conversation-facts-incremental-core.test.ts b/test/large-pages/conversation-facts-incremental-core.test.tsindex 0a591dd5ee..231fb5fc17 100644--- a/test/large-pages/conversation-facts-incremental-core.test.ts+++ b/test/large-pages/conversation-facts-incremental-core.test.ts@@ -7,7 +7,7 @@*/import { afterAll, beforeAll, describe } from 'bun:test';import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';-import { defineConversationFactsIncrementalCases, defineSegmentReceiptDoctorCases, defineSegmentedAtomsCases, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';+import { defineConversationFactsIncrementalCases, defineSegmentReceiptDoctorCases, defineSegmentedBackstopCases } from '../helpers/conversation-facts-incremental-cases.ts';import { defineDerivationSpendCases } from '../helpers/derivation-spend-cases.ts';import { defineDerivationUnpricedCases } from '../helpers/derivation-unpriced-cases.ts';@@ -19,7 +19,6 @@ afterAll(async () => { await brain.close(); }, 120_000);describe('conversation facts incremental, core [pglite]', () => {defineConversationFactsIncrementalCases({ getBrain: () => brain });defineSegmentedBackstopCases({ getBrain: () => brain });- defineSegmentedAtomsCases({ getBrain: () => brain });defineSegmentReceiptDoctorCases({ getBrain: () => brain });defineDerivationSpendCases({ getBrain: () => brain });defineDerivationUnpricedCases({ getBrain: () => brain });diff --git a/test/large-pages/extract-atoms-segmented-skip.test.ts b/test/large-pages/extract-atoms-segmented-skip.test.tsnew file mode 100644index 0000000000..9e24ccf12c--- /dev/null+++ b/test/large-pages/extract-atoms-segmented-skip.test.ts@@ -0,0 +1,16 @@+/**+ * extract_atoms skips segmented pages, PGLite arm. Cases: test/helpers/extract-atoms-segmented-skip-cases.ts. Postgres+ * arm: test/e2e/extract-atoms-segmented-skip-postgres.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';+import { defineExtractAtomsSegmentedSkipCases } from '../helpers/extract-atoms-segmented-skip-cases.ts';++let brain: AppendBrain;++beforeAll(async () => { brain = await openAppendBrain('pglite'); }, 120_000);+afterAll(async () => { await brain.close(); }, 120_000);++describe('extract_atoms skips segmented pages [pglite]', () => {+ defineExtractAtomsSegmentedSkipCases({ getBrain: () => brain });+});diff --git a/test/page-spend-reservation.test.ts b/test/page-spend-reservation.test.tsindex d988a33d60..ddc7d2839c 100644--- a/test/page-spend-reservation.test.ts+++ b/test/page-spend-reservation.test.ts@@ -1,6 +1,6 @@/*** Per-page spend ledgers (wave-b spec 8.3, PR 4 lane 4b): embeddings reserve on page_embedding_budget under- * `embed.max_usd_per_page`; each paid derivation family (facts, atoms, synopsis) reserves on its own page_derivation_spend+ * `embed.max_usd_per_page`; each paid derivation family (facts, synopsis) reserves on its own page_derivation_spend* row under `derive.max_usd_per_page`; meterPaidCall books what the provider reported.** 1. Protects: each family has its own cap and the embedding cap counts embeddings only; a reservation over what a cap@@ -96,16 +96,15 @@ describe('per-page spend ledgers', () => {const page = await segmentedPage(engine);const calls = { n: 0 };expect((await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.6, calls)).kind, name).toBe('grant');- expect((await paidStep(engine, page, 'atoms:anthropic:claude-haiku-5-5', 0.5, calls)).kind, name).toBe('grant');const refused = await paidStep(engine, page, 'facts:anthropic:claude-haiku-5-5', 0.5, calls);expect(refused, name).toEqual({ kind: 'refused', reason: 'cap_reached', capUsd: 1, spentUsd: 0.6, reservedUsd: 0, estimateUsd: 0.5 });- expect(calls.n, name).toBe(2);+ expect(calls.n, name).toBe(1);expect((await paidStep(engine, page, 'embedding:openai:text-embedding-3-large:1536', 1, calls)).kind, name).toBe('grant');expect((await paidStep(engine, page, 'synopsis:anthropic:claude-haiku-5-5', 0.9, calls)).kind, name).toBe('grant');- expect(calls.n, name).toBe(4);- expect({ facts: await familyLedger(engine, page.id, 'facts'), atoms: await familyLedger(engine, page.id, 'atoms'),+ expect(calls.n, name).toBe(3);+ expect({ facts: await familyLedger(engine, page.id, 'facts'),synopsis: await familyLedger(engine, page.id, 'synopsis'), embedding: await embedLedger(engine, page.id) }, name).toEqual({- facts: { spent: 0.6, reserved: 0 }, atoms: { spent: 0.5, reserved: 0 }, synopsis: { spent: 0.9, reserved: 0 },+ facts: { spent: 0.6, reserved: 0 }, synopsis: { spent: 0.9, reserved: 0 },embedding: { spent: 1, reserved: 0, signature: 'openai:text-embedding-3-large:1536' } });}});@@ -243,8 +242,8 @@ describe('per-page spend ledgers', () => {await expect(meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, async () => { throw new Error('failed before any call'); }), name).rejects.toThrow('before any call');expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: expect.closeTo(after, 12), reserved: 0 });__setChatTransportForTests(async () => ({ ...answer(10, 10), model: 'test:unpriced-model' }));- await meterPaidCall(engine, page, 'atoms:test:unpriced-model', 0.05, () => chat({ model: 'test:unpriced-model', messages: [{ role: 'user', content: 'w' }], maxTokens: 50 }));- expect(await familyLedger(engine, page.id, 'atoms'), name).toEqual({ spent: 0.05, reserved: 0 });+ await meterPaidCall(engine, page, 'synopsis:test:unpriced-model', 0.05, () => chat({ model: 'test:unpriced-model', messages: [{ role: 'user', content: 'w' }], maxTokens: 50 }));+ expect(await familyLedger(engine, page.id, 'synopsis'), name).toEqual({ spent: 0.05, reserved: 0 });__setChatTransportForTests(null);}});@@ -262,8 +261,8 @@ describe('per-page spend ledgers', () => {expect({ out, ledger: await familyLedger(engine, page.id, 'synopsis') }, name).toEqual({ out: { value: 'done' }, ledger: { spent: expect.closeTo(reservationCostUsd(HAIKU, 'chat', 1000, 200)!, 12), reserved: 0 } });__setChatTransportForTests(async () => { throw Object.assign(new Error('fixture rate limit'), { status: 429 }); });- await meterPaidCall(engine, page, `atoms:${HAIKU}`, 0.2, () => ask().catch(() => null));- expect(await familyLedger(engine, page.id, 'atoms'), name).toEqual({ spent: 0, reserved: 0 });+ await meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, () => ask().catch(() => null));+ expect(await familyLedger(engine, page.id, 'facts'), name).toEqual({ spent: 0, reserved: 0 });__setChatTransportForTests(null);}});@@ -411,7 +410,7 @@ describe('per-page spend ledgers', () => {try {const first = withBudgetTracker(parent, () => meterPaidCall(engine, page, `facts:${HAIKU}`, 0.2, big));await inFlight;- const second = await withBudgetTracker(parent, () => meterPaidCall(engine, page, `atoms:${HAIKU}`, 0.2, big))+ const second = await withBudgetTracker(parent, () => meterPaidCall(engine, page, `synopsis:${HAIKU}`, 0.2, big)).then(() => 'ran', (error: unknown) => (error instanceof BudgetExhausted ? 'refused by --max-usd' : String(error)));release();expect({ second, first: await first }, name).toEqual({ second: 'refused by --max-usd', first: { value: answer(1000, 200) } });