Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
PR 2 fix lane J: segmented pages in the extraction stale list; held budget rows stop applying once a page shrinks
garrytanba830fe6a355
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 59e833d28f..aaae34de04 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -20,7 +20,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `src/core/page-body/limits.ts` — Wave B size classes, ceilings, retention numbers and config keys in one place. `readPageBodyPolicy` is the single question every write asks: `segmented` is the effective `pages.segmented_storage` (unset means `SEGMENTED_STORAGE_DEFAULT`, `off` in this release; `off` or an unrecognized value is off; held off while `segmentedWriterBlockers` finds a recent writer that blocks, and an unreadable gate counts as blocked), `maxBytes` the engine ceiling (256 MiB Postgres, 128 MiB PGLite, lowered by `pages.max_bytes`) while on and `PAGE_MAX_BYTES` while off. Config is read per call; only the writer gate is cached (`SEGMENTED_WRITER_GATE_TTL_MS`, `_resetSegmentedWriterGateForTests`). `chooseBodyStorage` applies the 1 MiB / 512 KiB hysteresis. The writer gate (`segmentedGateWriters` in `persistence/writer-versions.ts`) reads seven days of admitted requests in any state, committed publications, `ingest_log` rows and, on Postgres, `persistence_consumers` heartbeats; a row blocks when its version is below `SEGMENTED_WRITER_FLOOR` or unparsable, or when it lacks the segment-reader mark (migration v251: `admitter_segment_reader`, `consumer_segment_reader`, `persistence_consumers.segment_reader`, `ingest_log.writer_segment_reader`), because releases 0.60.252.0-0.60.262.0 have no segment readers and a version string cannot tell them apart. Not seen: an older binary's unmanaged single-page write, a run that dies before it logs, and read-only or export use. Tests: `test/large-pages/segmented-switch.test.ts`.- `src/core/page-body/read-range.ts` + `segment-projection.ts` + `segment-ledger.ts` — Wave B PR 2 (spec 7.1, 7.3): the segment reader. `openSegmentedBody` reads a page's live manifest rows and its withdrawal ledger (`readBodyLedger`); `readBodyRange(engine, { pageId, space, start, end, audience, region?, body? })` streams pieces one segment text at a time, never the whole body. Remote reads and every projected-space read serve the read projection: `projectSegment` projects whole segments from their stored protected regions (takes, truncated tail and markers out, keys as the projection token, facts regions rendered world-only and credential-projected), after the withdrawal overlay (`overlaySegmentText`; a fence split by a forced cut is omitted for reads and refuses a trusted read) and the fence overlay (held and purged rows out, rows below the page tier in the low-tier block after the truth). A transform or stale metadata recomputes the regions from the segment's entry state; with none usable the read refuses `page_projection_stale`, never raw text. Trusted stored-space reads give the overlaid stored stream. `projectedLayout` (cached on the handle), `projectedUnits` (rows and fixed text in projected order, for `page-window/segmented.ts`), `projectedTotals`, `projectedLineStart` and `projectedOutline` (outline from stored metadata, no segment text) locate projected bytes; the concatenation equals `projectPageText` of the joined body byte for byte except where a facts fence is longer than a segment (shows less). The chunker (`segment-chunks.ts`) chunks the same projection, so sealed segmented pages carry `MARKDOWN_CHUNKER_VERSION`; `sealSegmentedPage` indexes the overlaid, sanitized timeline lead. Pinned by `test/large-pages/projection-parity.test.ts`, `remote-window-privacy.test.ts` and `sealed-segmented-search.test.ts` (fixture `test/helpers/segmented-privacy-fixture.ts`).- `src/core/page-body/segment-rewrite.ts` — fence rewrites of a segmented body without holding it as one string (forget strikes, purge drops). Only stored `facts`/`takes` protected regions are decoded and passed, in body order with their region, to a `FenceTransform` (a region crossing forced cuts is joined with its neighbours, refused above `PAGE_MAX_BYTES`). `rewriteLiveSegmentedFences` re-stages the live body through `prepareSegmentedBody` from the segment stream with the changed units replaced and flips it in the caller's transaction (trust tier and soft delete kept; null when nothing changed); `rewriteSegmentedGeneration` rebuilds one retained generation under its own number and updates its versions' hash and size; `rewrittenContentHash` streams the hash of a rewritten generation; `segmentedBodyContains` searches a body segment by segment with the previous segment's tail carried over. Tests: `test/large-pages/purge-segments.test.ts`, `forget-scope.test.ts`, `page-purge-segments.test.ts`.-- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.+- `src/core/page-body/segment-blocks.ts` + `segment-links.ts` + `segment-takes.ts` — Wave B PR 2 (spec 8, full-pass mode): the derived passes over a segmented body, O(page) work and O(segment) memory, not yet incremental. `bodyBlocks(engine, page, { regions?, separator?, want? })` yields the trusted, withdrawal-overlaid joined body one block at a time (a segment, or a run joined across forced cuts, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`; `want` skips a run unread), so each block starts where the parsers start fresh; `truthLead` reads a bounded lead; `readGarbageCollector` forces a collection every 4 MiB read; `detachedValue` copies a result kept past its block so it pins no segment text; `segmentedPassWork` counts the passes' work for the linearity test. `extractSegmentedPageLinks` runs `extractBodyLinks` over each block in a window (`bodyWindows`: the whole blocks before it, 4096 chars after, the headings still open), with the role phrases a first pass found (`segmentedRoleText`), and merges candidates in `extractPageLinks` order, plus the temporal inputs (`TemporalBody`). `parseTakesFenceBlocks` gives `parseTakesFence` of the joined body. Consumers: link preparation and the links effect, stale-links maintenance, source reconciliation, the sweep, `extract links|timeline|takes --source db`, `extract --stale` (the stale list includes segmented pages since PR 2 fix lane J1; test `test/large-pages/segmented-extraction-stale.test.ts`), the mention pass (`pageMentions`), the canonical prior view (`segmentedPriorView`), `segmentedTimelineText`, the chronicle judge and the facts planner (`planSegmentedExtraction`). Tests: `test/large-pages/segmented-derived-parity.test.ts`, `segmented-derived-passes.test.ts`, `segmented-derived-linear.test.ts`, `segmented-derived-memory.slow.test.ts`, `segmented-derived-work.test.ts`. `segment-lines.ts` serves the line-local maintenance scans: `bodyLines` yields the joined text's complete lines a block at a time (a line cut by a block boundary is carried, counted in `segmentedPassWork.carry`), consumed by `gbrain integrity` and `reconcile-links`; `segmentedRegionContains` searches one region for literal markers across block boundaries (repair `connector-fences`). Test: `test/large-pages/segmented-maintenance-commands.test.ts`.- `src/core/persistence/large-file.ts` — Wave B PR 2 fix lane D: canonical files over 24 MiB (`LARGE_FILE_MIN_BYTES`) on the publication path, never one string or Buffer. `hashFile`/`hashDescriptor` (the persistence file hash, read in one-segment pieces), `FileBytes` (a file read on demand through one descriptor, the `ByteSource` the drift check's `fileBodyDigests` takes; `close` refuses `source_changed` when the file changed while read), `StreamedFileContent` (restore_page's file: export's serializer over the segments, measured once in preparation, produced again by `stageStreamedContent` into the reserved publication stage after the recovery record is durable and before the publication transaction; a mismatch removes the stage and refuses `revision_conflict`), and `stageBeforeCopy` (the prior file copied by the kernel into its `before` stage, hashed and fsynced; the recovery record names it by path and SHA-256 instead of embedding base64, and reserves the file once). `largeFileWork` (@internal) counts bytes read, written and copied and the largest piece. Coordinator: `pageRecoveryRecord` → `largeRecoveryRecord`, `stageLargeFiles`, `publishStagedContent`; a group publication never takes such a member (`groupable`). Tests: `test/large-pages/segmented-delete-restore-file.slow.test.ts` (27 and 90 MiB round trips byte for byte, both engines), `test/large-pages/segmented-delete-crash.slow.test.ts` (SIGKILL between file removal and commit, and after the restoration rename).- `src/core/page-body/body-digests.ts` — Wave B PR 2: the digests the drift check of a segmented page over the single-string ceiling compares (`page-prepare.ts` `segmentedFileMatches`). `fileBodyDigests(bytes, reading, filePath, opts)` runs the streamed importer's pass 1 (`BodyScanner`) over one reading of the file's bytes (an inferred-frontmatter prefix, then the bytes past a BOM), then SHA-256 over each region's byte ranges, and reports a facts fence marker; `storedBodyDigests(engine, pageId, ledger)` hashes each region of the trusted stored body (`readBodyRange`, one segment per read, `readGarbageCollector`). `bodyDigestWork` counts file and stored bytes and the largest piece handed to a scan or hash (at most a segment). In `page-prepare.ts`, `prepareFileTarget` compares a page whose body was not read back through `segmentedFileMatches` (the raw reading, then the inferred one from `streamed-import.ts` `inferredHeadPrefix`; the same normalizations as `fileMatchesSnapshot` via `importedFileType`); a file body with a facts fence under a withdrawal ledger that applies refuses `page_body_segmented` instead of reading as drift. `restore_page` of such a page (`prepareUnreadRestore`) versions it, clears `deleted_at` and reseals (or leaves the projection queued when chunks are missing) without re-importing, and publishes `serializePageToMarkdown`'s bytes streamed from the segments by `segmentedExportMarkdown` into one buffer (under the 25 MiB pre-push scan cap); a core page and an external_untrusted writer refuse `page_body_segmented`, and an agent-tier writer's advisory write-gate scan is not re-run over the unchanged body. Tests: `test/large-pages/segmented-file-drift.test.ts`.- `src/core/page-body/segment-facts.ts` + `segment-conversation.ts` — Wave B PR 2 lane 2e2 (spec 8, full-pass mode): the facts fence reconcile and conversation facts over a segmented body. `segmentedFactsFenceView` is `factsFenceView` (facts-fence.ts: each section's parsed fence, which sections hold one, and the #3625 timeline marker) read from the segments: one SQL query selects the live manifest rows that carry facts slots, a forced cut, or a begin/end marker (bytea `position`, nothing transferred), and `bodyBlocks`' `want` option reads only the runs holding them; the segmenter never cuts inside a fence, so a fence lies in one block (a longer one is a forced run, refused above `BLOCK_MAX_BYTES` with `page_body_segmented`), and joining one across blocks is a bounded fallback. `segmentedBodyMatchesFile` is `canonicalCacheState`'s stale-cache check for a segmented page: the canonical file streamed through `BodyScanner` against the stored regions, by length and SHA-256. `readSegmentedConversationInput` gives `readConversationInput` (conversation-parser/body.ts) the summary body through ranged reads: whole within `CONVERSATION_WINDOW_BYTES` (`PAGE_MAX_BYTES`), else the newest whole segments that fit (never starting inside a forced run) with the window's `fallbackDate` from its first segment's entry state; extract-conversation-facts parses that window, passes the date to the parse and the extractor, and writes a `tail_window` receipt (`window_rule: no_prior_facts`), but only on a page with no conversation facts: one that has any keeps them and is skipped (`skipped_too_large`, `window_rule: prior_facts_kept`), since the run clears every prior fact. Each loop counts its reads in `segmentedPassWork`. Consumers: `runExtractFacts` (`planFenceReconcile`, the stale-cache guard, the managed fence-facts request), the sweep's fence candidates (segmented pages with facts slots), `extract-conversation-facts`. Tests: `test/large-pages/segmented-facts-reconcile.test.ts`, `segmented-conversation-facts.test.ts`, `segmented-derived-linear.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-1.md b/docs/architecture/key-files/core-utilities-1.mdindex e87578f04c..18650d8cc7 100644--- a/docs/architecture/key-files/core-utilities-1.md+++ b/docs/architecture/key-files/core-utilities-1.md@@ -36,8 +36,8 @@ The `src/core/cycle.ts` entry is on its own page: [Core Cycle primitive](core-cy- `src/core/enrichment-service.ts` — Global enrichment service: entity slug generation, tier auto-escalation, batch throttling. `slugifyEntity` keeps letters of every script (accents folded, NFC); before minting a page, `enrichEntity` reuses one at `legacyAsciiEntitySlug` (the old ASCII-only slug) only within the same source and only when that page's title names the entity, since the legacy slug is lossy. Write path is trust-gated: `enrichEntity` / `enrichEntities` / `extractAndEnrich` take `EnrichmentTrustOptions { trusted?, sourceId? }`; only an explicit `trusted: true` writes authoritative `people/` / `companies/` stubs. Anything else (undefined/false — fail-closed, mirroring `OperationContext.remote`) creates the stub with the extraction quarantine markers from `src/core/extraction-review.ts` and reports `quarantined: true` in `EnrichmentResult`. The ONLY sanctioned op surface is `extract_entities` (operations.ts), which grants `trusted` solely for `ctx.remote === false` callers passing `--trusted-extraction`. On a managed brain (`EnrichmentTrustOptions.ctx` set, #6262) every write goes through the coordinator under the caller's authority: the stub is a create-only `put_page` (`content_origin: tool_output` when the source page is `external_untrusted`), then `lowerDerivedPageIn`, the timeline row and the backlink each run in `coordinatedDatabaseWrite` as operation `extract_entities` at the source page's derived tier. There is no direct-write fallback; a refusal or `write_pending` stops the batch and its `why` names the entities already written. A grant without `put_page` cannot create stubs there. Pinned by `test/extract-entities-managed.test.ts`.-- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.-- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation). `listBudgetLimitedPages` feeds doctor `partial_embedding` and `gbrain embed --held`. #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.+- `src/core/page-size-policy.ts` — large pages Wave A: the one page ceiling every raisable ingress bound derives from. `PAGE_MAX_BYTES` (24 MiB: import, sync and the managed sync read, CLI stdin, `content_sanity.bytes_block` default), `PUSH_SCAN_MAX_FILE_BYTES` (25 MiB; no canonical file write may exceed it), `CODE_FILE_MAX_BYTES` (5 MB, code keeps its own bound) and `PAGE_INLINE_MAX_BYTES` (1 MiB) with `isLargePageBytes`: a large page commits with NULL vectors, embeds through the sweep under the per-page cap, uses the title context tier and keeps `LARGE_PAGE_VERSIONS_KEPT` large snapshots. `largePageBodyFilter(alias)` is its SQL twin (`body_bytes` of a segmented page, else the body columns' `octet_length`) and `pageBudgetLimitedFilter(alias)` the held-or-capped budget predicate built on it, so a budget row on a page edited down to 1 MiB or under stops applying (PR 2 fix lane J2; test `test/large-pages/held-budget-shrink.test.ts`). The per-entry-point table is in `docs/guides/memory-boundaries.md#large-page-limits`.+- `src/core/page-embedding-budget.ts` — large pages: the per-page embedding spend cap `embed.max_usd_per_page` (default $2; unlimited under `spend.posture tokenmax` when unset) and its ledger `page_embedding_budget` (migration v246; states `open` / `held` / `capped`, spent and reserved USD per embedding signature). `planPageEmbedding(engine, page, stale, { signature, approvedCapUsd })` is called by every paid embedding entry point (embed-stale sweep, `gbrain embed` slug/`--all`/`--stale` paths, the managed embedding effect): small pages are `unmetered`; a held page returns `held` unless the user's approval is passed; otherwise it reserves the newest stale chunks that fit the remaining budget under a row lock and returns a grant to `settle`. A reservation older than an hour counts as spent. The sampled junk check (`assessSampledJunk`) holds a boilerplate large page. Held and capped pages leave the stale queue (`staleChunkWhere`, `listStaleChunks`, embedding-invalidation) while they are large (`pageBudgetLimitedFilter`); a page edited down to 1 MiB or under is unmetered and its row is ignored there, in `listBudgetLimitedPages` and in `pageSizeState`, and applies again if the page grows back. `listBudgetLimitedPages` feeds doctor `partial_embedding` and `gbrain embed --held`. #6722 receipts: `pageSizeState` / `readPageSizeStates` / `sizeStateField` give the one `size_state` shape (`deferred` / `partial` / `held` / `skipped`, with reason and bytes) that `put_page` (page-prepare), managed sync (sync-prepare) and `remember` (memory-prepare) receipts carry for a large or embed_skip page; `addSizeState` / `sizeStateLines` build the sync tally `size_states` (managed cursor counts, legacy incremental and full sync) and its output lines. Tests: `test/oversized-backfill.serial.test.ts`, `test/persistence-embedding-effects.test.ts`, `test/size-state-receipts-6722.test.ts`.- `src/core/oversized-backfill.ts` — large pages upgrade: `runOversizedBackfill` (`gbrain reindex --oversized`, and a two-minute pass in `gbrain post-upgrade` via `printOversizedBackfillUpgradeNotice`) rewrites pages an older gbrain stored chunkless for size (gate-written `embed_skip.reason = oversized`) through the normal write path (canonical owner on a managed brain, as `quarantine clear` does) with `forceRechunk` and no embedding: under the effective `bytes_block` the marker and `content_flag: oversized` are removed; over it (and under the ceiling) a chunkless page keeps both and is only re-chunked for keyword search (`rechunked_over_block`, #6722). A segmented page is sized by `body_bytes` and re-indexed from its materialized snapshot (`materializedSnapshot`, Wave B PR 2; `test/large-pages/oversized-backfill-segmented.test.ts`). CPU-only, keyless-safe, idempotent, resumable. Pages over 1 MiB are held (`upgrade_backfill`) for embedding approval first. The receipt names pages re-indexed, chunks pending, estimated cost and the finish/preview/approve commands.- `src/core/extraction-watermark.ts` — large pages A7: no silent head-only page extraction. `planExtraction(body, stored, { cap, pipeline, emptyTail })` decides what one extraction reads: the whole body when it fits `cap` (`full`); the text past a stored watermark when the body still starts with exactly the watermarked prefix (`tail`; UTF-8 byte offset + sha256 of the prefix + `EXTRACTION_PIPELINE_VERSION`), its newest `cap` characters when the tail is longer (receipt `tail_window`, never starting inside a surrogate pair, snapped to a line start in the first tenth); otherwise the head (`truncateUtf8`) with receipt `head` and reason `no_watermark` / `prefix_changed` / `version_changed` / `no_new_text`. An empty tail is a skip (`facts_backstop`) or a head re-read (`extract_atoms`, after a cap rise). `readPageWatermark` (by source + slug, fail-soft), `commitExtractionPlan` (after a successful extraction: the watermark moves to the end of the planned body; a full read clears `input_truncated`, a truncated read replaces it, a complete tail read keeps the gap an earlier read left) and `setExtractionReceipt` (the conversation-facts size skip, no watermark) write `page_extraction_state` (migration v247; hashes, offsets and counts only, rows cascade with the page). Doctor `extraction_input_truncated` reads the receipts. Tests: `test/extraction-watermark.test.ts`, `test/extraction-watermark-facts.test.ts`, `test/extraction-watermark-atoms.test.ts`.diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex 3b2951c8bd..4441a04f29 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -65,6 +65,7 @@ const VETTED_BUILDERS: Record<string, string> = {quoteIdentifier: 'src/core/search/embedding-column.ts: double-quoted identifier (embedded quotes doubled); callers pass registry-resolved or COLUMN_NAME_REGEX-checked embedding column names',vectorCastSuffix: 'src/core/search/embedding-column.ts: constant ::vector / ::halfvec cast suffix from the resolved column type',safeChunksFilter: 'src/core/search/safe-chunks.ts: constant safe-chunk predicate over a caller alias',+ pageBudgetLimitedFilter: 'src/core/page-size-policy.ts: constant held-or-capped budget predicate over a caller page alias; no values',movableChunkSql: 'src/core/search/safe-chunks.ts: constant vector-matches-its-text predicate over a caller-quoted embedding column; no values',bodyWriteChunkVersion: 'src/core/search/safe-chunks.ts: constant chunker-version CASE over caller column expressions (or master\'s literal $1/$2 bind reuse); no values',privateLinkOriginFilterFragment: 'src/core/search/private-visibility.ts: constant link-origin visibility predicate over a caller alias',diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 6b29a8fc7c..d7d70a1418 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -8,7 +8,7 @@ src/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilosrc/commands/doctor.ts 686 ratchet +19 #6696 doctor tiers: Check.elapsed_ms and DoctorReport tier/complete/unknown_sections/elapsed_ms/budget_ms fields, buildChecks/runDoctor deadline params (logic in doctor/budget.ts); +1 agent operator gate fixes: --probe consent gate (logic in doctor/probe-consent.ts); refactor wave 1 split target (W4 doctor); ceiling rationale: docs/architecture/key-files/commands-2.md entry for src/commands/doctor.tssrc/commands/embed.ts 2304 ratchet +2 agent operator wave D2: --json failure envelope via writeCliError; lowered v0.46.26.0: embedBatchWithBackoff + retry cluster peeled to core/embed-retry.ts (core/commands layering fix); grown wave-g (#4530): per-model input-limit wiring; wave-k #3622 reimpl: --stale zero-progress failure quarantine; +29 #4668 (#4530): oversize-heal call sites in both --stale drains — kept low by peeling the healed-row remap to core/embed-oversize-heal.ts (shared with embed-stale.ts); +35 #4647 (refs #4599): per-tick timeout+abort on the single-flight lock heartbeat refresh (interval deliberately NOT unref'd); +122 refs #4599: stall-watchdog race around the drain + shared idempotent flushAndRelease + CLI stall exit mapping (watchdog machinery itself lives in core/embed-stall.ts); +12: adversarial-review hardening (healed_splits progress key + heal-tick comment); #5105: guarded derived projection preparation and read seals; #5105: conditional embedding installer wiring; archived eligibility: active-only dispatch with honest stranded-work reporting; explicit archived admission: live-source snapshots and honest refused-installation failures; +2 fw3: embed --stale --images dispatch (sweep lives in core/embed-stale-images.ts); +5 #5289: dry run reports restamp-only chunks apart from chunks to embed (count lives in core/embedding-invalidation.ts); +6 #4616: keep a partially refused batch in embedPageTexts and name the recovery command in failure samples (guard lives in core/ai/embedding-guard.ts); +5 #5226: embed summary counts distinct pages; +3 #5804: null projection snapshot counted as a failure with one batch summary in embed --stale; +18 wave 8 lane D1: #5527 mixed-space warning subtracts current-model chunks (+4), #5885 takes option/result fields and the stale-drain takes call (pass lives in core/embed-takes.ts); +9 Foundations 1 F4d: time-budget stop result fields, stdout verdict and stop recording in embed --stale (logic in core/embed-budget-stop.ts); +8 green-master lane A: chunkless install re-reads through retryProjectionConflict instead of recording an unavailable page (retry lives in core/page-state/projections.ts, failure line in core/agent-output.ts); +8 fix wave 13 P1.18: runEmbed consent parameter, cost-cap stop wiring and result fields, --slugs parsing to the next flag (cap, verdict and resume logic live in core/embed-cost-cap.ts); +28 large pages A9/T3/T16: --held listing and per-page cap metering on every embed path (logic in core/page-embedding-budget.ts meterPageBatch/spendGrant/heldEmbedArgv), approvedPageCapUsd from --max-usd on --slugs; +1 #6722: an explicit slug embed skips an embed_skip page (it keeps keyword chunks, never vectors); merge v0.60.240.0: large pages and master growth compose at 2265; +39 large pages Wave B lane 1e: segmented pages route to the keyset sweep on the slug, --all and --stale paths, with a dry-run count and provenance stamp (logic in core/page-body/segmented-embedding.ts)src/commands/extract-conversation-facts.ts 2103 ratchet grown v0.46.x per-provider gateway-unavailable copy; grown wave-g (#4482): expected budget/deadline caps classified apart from error halts; wave-k: save-time resolution caller (#4052/#3729 — supersedes wave-g's per-row resolveEntitySlug mapper); +1: key-aware llm-fallback default (#3813); +1: pricingOverrides wiring into the owned BudgetTracker (#4633 adoption); +3: #4869 snapshot-mismatch counts as pages_failed; merged reliability/shared-skills source integration; +19: additive skip reasons and model-free dry-run (#5364); +21 #5757: managed extraction buffers a page's rows and replaces the prior batch in one coordinator transaction (replacement helper lives in core/persistence/derived-facts.ts); +18 #5823: result diagnostics, strict explicit-cap parsing and CLI recovery/help; default-cap decision lives in facts/conversation-budget.ts; +18 fix wave 7 (#5704, #5448): --json envelope on stdout (parser flag, help line, summary block gated behind the human-output branch); +2 fix wave 10 (#6037, issue #6033): explicit-slug page failures are contained per page through one bounded failure logger (recordPageFailure) shared with the pooled path; +4 fix wave 10 (#5120): facts.default_visibility resolved once per run (resolveDefaultVisibility) and applied to extracted rows only; 2 P2 segmentObservationDate + segmentValidFrom helpers (date-grounding observation time per segment; extractor event date wins over segment start); +4: ExtractConversationFactsResult.failed_pages (interface field) and the help text exit-status paragraph; partial-success logic lives in core/facts/conversation-run-status.ts; re-summed at the master 6ccf30c3e merge (2179 master lines + 20 integration lines over base); re-summed at the #6020 merge on actual lines (as rehearsed on capy/mpw-integration-p2); re-summed at the wave 10 merge on actual lines (+1 recordPageFailure fills failed_pages); lowered at the wave-9 follow-ups merge: the three zero-result literals became emptyExtractConversationFactsResult(); lowered to 2075 at wave 15 P2.5 (#6267): segment tunables, splitIntoSegments and renderSegmentForExtraction moved to core/facts/conversation-windows.ts, the message/segment types to core/facts/conversation-types.ts (re-exported here); +12 large pages T2: the oversized-sidecar snapshot and the durable size-skip receipt (skippedForSize; the cap and the bounded sidecar read live in core/conversation-parser/body.ts, the receipt in core/extraction-watermark.ts); merge v0.60.240.0: large pages and master growth compose at 2087; +7 large pages PR 2 lane 2e2: a segmented conversation over the window cap (snapshot.window, the tail_window receipt, the window fallback date; the window read lives in core/page-body/segment-conversation.ts); +9 lane 2e2 follow-up: the lossless window rule (a page over the window with conversation facts keeps them and is skipped, the receipt names the rule; the count lives in core/facts/conversation-publication.ts)-src/commands/extract.ts 2637 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline+src/commands/extract.ts 2640 ratchet grown v0.46.26.0 megawave: FS-walk stamp snapshot + legacy timeline repair wiring (#3957 D4) + PR#4486 rebase onto current master; grown wave-g (#4542): --from-meetings zero-match warning + default-pass note; +29: #3478 federated-only gate on the cross-source 'default' link fallback; +44: #3908 cross_source opt-in — counted drops + deterministic cross-source pick; +36: #4611 configured-sources.default fallback (resolveLinkFallbackDefault); +14: #4890 extractStaleFromDB quiet opt + extractForSlugs jsonMode batch_error stderr fallback; +5: #4855 stroke-letter fold in link extraction; +5: #4793 by-mention scan honours link_resolution.cross_source; +18: wave review — ExtractOpts.quiet threaded through the fs-walk extractors (stdout silence decoupled from jsonMode); +77: shared buildSlugPathIndex — every per-slug extractor resolves the real on-disk path, and the sync hooks report which slugs they actually read; +10 #4999: includeFrontmatter default-resolved inside extractLinksForSlugs + extractStaleFromDB (resolveIncludeFrontmatter), --stale flag absent -> configured knob; +20: pre-landing review of #4967 — resolveSlugRelPath: index miss falls back to the legacy slug+'.md' path so admitted _-prefixed / include_hidden pages keep their edges; T2: source-qualified inference and atomic origin-scoped derived links; standard DB extraction fences captured endpoint revisions; shared authoritative attendance/source reconciliation moved to the core module; +7 A2 preview-bound attendance repair import, help and authority dispatch; bounded incomplete-attendance diagnostics and consistent basename resolution; fail closed before graph mutation when active ontology is unavailable; +16 source-selected ontology cache, type-scoped preflight and non-starving failed stale drain; +7 write-path wave: per-slug extractors replace page links + retract removed timeline rows + rename-alias resolution; +5 fw3 derived-sync: timeline --prune-orphans CLI (#4649) and full-walk page link replacement; +13 fw3 A16/A15: sync link hook reads scoped page metadata and reports per-page extraction errors; +1 fw3 managed-lifecycle: extract --stale dispatches managed brains to the coordinator-safe path; +4 fw3 integration: managed brains refuse the direct timeline orphan prune; +26 #5609: managed extract --stale publishes links, canonical timeline and watermark per page in one coordinated transaction; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +4 at the merge; +6 fix wave 3 lane B: a managed brain routes the extract phase file walk through extractManagedStaleLinks instead of the refused raw timeline batch, keeping the extract.links_fs progress phase; +6 #5761: the unmanaged extract --stale sweep marks unresolved-attendance skips attendance-blocked; +2 eval-wave N9-3/N12-7: a page-type-bound pack attended rule defers to canonical attendance on the filesystem path (ownsAttendanceInference); lowered to 2528 #5904: the DB timeline walk moved to commands/extract-timeline-db.ts (coordinated publication on managed brains, honest refusal + non-zero exit); +13 entity mention index: extract --stale runs the mention pass after link work (half the budget reserved while mention-due pages exist), dry-run and JSON report mention counts, and the help documents the pass and `extract mentions --explain` (logic in core/mentions/); cat40 entity wave merge with v0.60.61.0 (2541 measured); +6 fix wave 10 lane L1 #5556: quarantined pages skipped by the file walks, slug lists and DB walks (slug lookup in quarantine.ts quarantinedSlugs); +3 #5556: the abort check stays its own statement in each quarantine-aware scan loop (cycle-abort coverage pin); 2 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +5 P5 line grammar: stated relation types on the filesystem link scan; +3 PGLite stale link drains refresh planner statistics before and during the drain (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 12 W2.1 S4 (#6228): extract --stale flushes and stamps the pages a batch finished before an aborting page; +12 P5 wanted pages: both DB extract paths record unresolved authored refs with each page's links; +9 Q2 parser gaps: both DB extract paths read the line-grammar settings once, publish through replaceDerivedLinksUnlessSettingsChanged and report pages a mid-run settings change left stale; +25 GBRA-69: extract --source db reads snapshots and publishes derived links BATCH_SIZE pages at a time (readPageSnapshotsBatch in core/page-snapshot-batch.ts, replay in derived-links.ts replaceDerivedLinksBatchOrReplay); +2 GBRA-75 w7: the --source db links walk refreshes planner statistics (logic in planner-stats.ts plannerStatsForLinkDrain); +10 fix wave 13 P2.16 (#6272): both unmanaged DB link drains defer and count a page a concurrent writer moved (skipped_concurrent_write) instead of aborting the run (classifier and skip line in core/derived-links.ts); +3 fix wave 13 P2.18 (S4): extract all --source db stamps the pages both phases completed at one revision, in a finally (stampCompletedIntersection), instead of every links-phase page; +1 fix wave 13 P2.15 (#6273): --from-meetings exits non-zero while managed entity pages are still pending; +7 fix wave 13 PR2: extractFromDB split out of runExtract so runExtract stays under its function-size baseline; +3 PR 2 fix lane J1: extract --stale reads a segmented page block by block (extractSegmentedPageLinks, segmentedTimelineText) now that the stale list includes itsrc/commands/jobs.ts 666 ratchet refactor wave 1 split target (W4 jobs, cut line); ceiling rationale: docs/architecture/key-files/commands-4.md entry for src/commands/jobs.ts; help lines: authorize-legacy --select (#5157 T3) and jobs cancel --select (DX-T2); submit --queue-only + PGLite work drain note (agent-first operator wave E5); +2 spend authorization: jobs submit --yes/--max-usd and jobs list --group help lines; +4 fix wave 9: supervisor stop help documents the 45 s wait, --queue and the verified-drain exit codessrc/commands/serve-http.ts 932 ratchet refactor wave 1 W4 split into serve-http-<area>.ts modules; ceiling rationale: docs/architecture/key-files/commands-5.md entry for src/commands/serve-http.ts; +2 agent operator wave A6: ServeHttpContext.noticeLedger (import + field; logic in core/notice-ledger.ts); +2 agent contract F1/F2: ServeHttpContext.readinessCache (probed readiness for initialize tails + gbrain://capabilities); +5 Lane D facts drain: serve --http starts the drain scheduler and stops it before the engine disconnect (logic in core/facts/drain-scheduler.ts); +2 agent-operator follow-up Item 3: ServeHttpOptions.adoptServer (status-only recovery hands its bound listener to listenOrRefuse; logic in serve-http-status.ts); +5 #6317: managed-sync movement watch start/stop (watch in persistence/sync-movement.ts); +1 #6589: imports loadServeConfigs (operations see the DB-plane config read once at startup; logic in mcp/serve-config.ts)src/core/ai/gateway.ts 4523 ratchet +17 #6607: lazy OpenAI model discovery (discoverBeforeOpenAICall, once per reconfigure, at the chat/expand/embed entry points; it re-resolves through the gateway-internal resolveGatewayModels, so it cannot move); +18 W11 item 3: embedQuery query-embedding cache lookup/store + clear at every model-cache clear site and the test transport seam (cache lives in ai/query-embed-cache.ts); +7 fix wave 5 (#5137): provider-key redactor on every upstream error path and the first embedding 401/403 report (logic in ai/key-redact.ts, ai/key-warnings.ts); +20 System One v1: decide() delegating export + transport seam, RerankInput.onMeta/RerankMeta, TypeSafe reranker delegation to ai/decide/rerank-adapter.ts; +3 #5585: reconfigureGatewayWithEngine records expansion/chat model provenance (ai/gateway-model-sources.ts) + clears it with gateway state; lowered #5585: tracker record sites collapsed onto ai/budget-record.ts (recordOnTracker + failedCallUsage) while adding ledger fields (requested model, purpose, failed, estimated, countsAsCall); +20: schema-rejection fallback in chat() (retry once schemaless on a json_schema 4xx, remember the recipe for the process — mirrors expand()); re-summed after merging master v0.50.0.0 with the wave (structured-output + pricing hunks); +48: #4863 ChatOpts.responseSchema → tolerant json_schema Output on the chat() generateText call for openai-compatible recipes that declare structured outputs (facts extraction on Ollama); +74: #3657 post-sunset rerank short-circuit (effective-model check, once-per-process audit row + stderr, injected-clock seam); grown v0.46.26.0 megawave: config-plane probes + halt telemetry (#3387 #4312); +21 lines (OpenAI Responses API reasoning-item echo: ChatBlock 'reasoning' variant, chat()/toModelMessages() round-trip); wave-k absorbs: OCR routing seam (#4107 class), config-snapshot reader block (#3980); +21: #4107 OCR-model routing (getImageOcrModel); +10: keyless OPENAI_BASE_URL embedding override (#4385); wave-k #3622 reimpl: GBRAIN_EMBED_MAX_BATCH_TOKENS env cap for no_batch_cap recipes; +9: DeepSeek judge thinking pin plumbed through chat opts (#4069); +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); ranker wave v0.48.4.0: ChatOpts.temperature threaded to the transport (+15); +24: #4172 recipe-declared thinking headroom on the chat()/toolLoop() default — shared isThinkingModel predicate (Claude-5 regex || recipe thinking_by_default, fail-closed), also consumed by the subagent handler; +20: #4861 claude-cli expansion routed to the schemaless viaText path (the CLI adapter ignores responseFormat, so the native generateObject branch had no fallback); retired provider integration removed; safety wave: migration reranker input ceilings; lowered by fix wave 3 #5680 (embed request planning peeled to ai/embed-batch-plan.ts); +5 #4616: empty inputs skip the provider and every text/multimodal result is screened for zero-norm/NaN/Inf vectors (logic lives in ai/embedding-guard.ts); fix wave 3 integration: #4616 empty-input filtering feeds the shared #5680 batch planner; +3 #5691: embedQuery takes a per-request queryPrefix (no gateway state); +26 fix wave 7 (#5642): embed spend records bank provider-reported usage.tokens (all sub-batches reported → measured; chars-per-token estimate stays the fallback and the failure charge); +2 #5892: import + load-time call of installAiSdkWarningWriter (writer lives in ai/sdk-warnings.ts); +12 #5490: chat() delegation to ai/chat-fallback.ts when chat_fallback_chain is set (attempt loop lives there), ChatOpts.allowFallback + ToolLoopOpts.allowFallback fields and the toolLoop forward; +2 #5490 review: ChatResult.fallbackFrom (the call model a chat_fallback_chain answer replaced); +1 fix wave lane B3: configureGateway keeps chat_fallback_on_refusal (the refusal switch lives in ai/chat-fallback.ts); +18 fix wave 9 lane B: ChatOpts.thinking (#5331, per-route mapping lives in ai/thinking-off.ts), ChatOpts.timeoutMs + ToolLoopOpts.turnTimeoutMs and the turn forward (#4921); interface fields and their docs cannot move; +2 P8: GBRAIN_AI_CALL_LOG observer install in configureGateway (logic in ai/call-log.ts); +2 W9F item 5: thinkingOffOutputCap export shared by chat() and the judge preflight estimates (capability table lives in ai/thinking-off.ts); +3 A1 (wave 0): ChatResult.usage.reasoning_tokens (interface field + doc) and the chat() reasoning-subset read beside the cache counts; the ai-sdk importer allowlist is shrink-only, so the seam stays here); +9 GOOGLE_GENERATIVE_AI_BASE_URL: resolveNativeBaseUrl('google') + the three native-google construction sites (eval metering proxy); re-summed at the master 6ccf30c3e merge (4417 integration + 4423 master - 4408 base); lowered -5: the expand() prompt template peeled to ai/expansion-prompt.ts (buildExpansionPrompt) so the longmemeval call planner measures the same textdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex 3a9c136918..e8bb676f71 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -324,6 +324,7 @@ src/core/page-body/segment-ledger.ts overlaySegmentText field NONE not the pagesrc/core/page-body/streamed-import.ts importScanned field LEAD bounded heads of the streamed file's regions for the sanity and type checks; the body itself streams to the segmentersrc/core/page-embedding-budget.ts planPageEmbedding field META lane 1e file: body_bytes for segmented pagessrc/core/page-embedding-budget.ts readPageSizeStates sql META lane 1e file: body_bytes for segmented pages+src/core/page-size-policy.ts largePageBodyFilter sql META fix lane J2: octet_length of the inline body columns, body_bytes for segmented pages (the size twin of pageBodyBytes)src/core/page-snapshot-batch.ts readPageSnapshotsBatch field STREAM same as readPageSnapshot: overlay skipped for a segmented pagesrc/core/page-snapshot-batch.ts readPageSnapshotsBatch sql STREAM p.* feeds rowToPage; the byte budget counts a segmented row as 0 (no body shipped); fingerprint over a NULL body is emptysrc/core/page-state/credential-reseal.ts PENDING sql STREAM regex over NULL is false: segmented pages postdate the v189 unseal and are chunked by the credential-safe segment chunker; pem regions in PR 2diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex e54ff730ab..675a54fee5 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -70,7 +70,7 @@ import { resolveIncludeFrontmatter } from '../core/extract-frontmatter.ts';import { inferLinkTypeFromPack, ownsAttendanceInference } from '../core/schema-pack/link-inference.ts';import { PageRegexBudget } from '../core/schema-pack/redos-guard.ts';export { extractTimelineFromContent, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';-import { extractTimelineFromContent, pruneTimelineOrphans, retractRemovedTimelineEntries, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';+import { extractTimelineFromContent, pruneTimelineOrphans, retractRemovedTimelineEntries, segmentedTimelineText, type ExtractedTimelineEntry } from '../core/timeline-extract.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { addProjectedTimelineBatch, addProjectedTimelineEntry } from '../core/trust/timeline-projection.ts';import { createProgress } from '../core/progress.ts';@@ -2227,18 +2227,19 @@ export async function extractStaleFromDB(}const snapshot = await engine.readPageSnapshot(page.slug, { sourceId: page.source_id });if (!snapshot) { skippedConcurrentWrite++; continue; } // deleted since the stale scan: nothing to stamp- const fullContent = snapshot.page.compiled_truth + '\n' + snapshot.page.timeline;+ // A segmented body is read block by block (page-body/segment-links.ts, segmentedTimelineText), never as one string.+ const fullContent = isSegmentedPage(snapshot.page) ? null : snapshot.page.compiled_truth + '\n' + snapshot.page.timeline;const linkRows: LinkBatchInput[] = [];if (!resolvers.has(page.source_id)) resolvers.set(page.source_id, makeResolver(engine, { mode: 'batch', sourceId: page.source_id }));const resolver = resolvers.get(page.source_id)!;- const extracted = await extractPageLinks(- page.slug, fullContent, snapshot.page.frontmatter, snapshot.page.type, resolver,- { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {- const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, page.slug,- page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId });- return !resolved.ok ? undefined : targetSlug === page.slug && resolved.toSourceId === page.source_id ? snapshot.page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;- } },- );+ const pageLinkOpts = { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug: string, targetSourceId?: string) => {+ const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, page.slug,+ page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId });+ return !resolved.ok ? undefined : targetSlug === page.slug && resolved.toSourceId === page.source_id ? snapshot.page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;+ } };+ const extracted: Awaited<ReturnType<typeof extractSegmentedPageLinks>> = fullContent === null+ ? await extractSegmentedPageLinks(engine, { ...withoutBody(snapshot.page), id: Number(snapshot.page.id), slug: page.slug, source_id: page.source_id }, resolver, { ...pageLinkOpts, temporal: true })+ : await extractPageLinks(page.slug, fullContent, snapshot.page.frontmatter, snapshot.page.type, resolver, pageLinkOpts);if (!extracted.attendanceComplete) {skippedAttendanceIncomplete++;attendanceBlocked.push({ slug: page.slug, source_id: page.source_id, revision: snapshot.revision });@@ -2263,15 +2264,17 @@ export async function extractStaleFromDB(crossSourceAllowed: federatedSourceIds.has(page.source_id) || crossSource, resolve: c => resolveCandidateSources(c, page.slug,page.source_id, allSlugs, slugToSources, federatedSourceIds.has(page.source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];const linkOpts = { includeFrontmatter, lineGrammar: grammar, expectedEndpoints: capturedLinkEndpoints(linkRows, targetMetadata, origin),- wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted } };+ wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] as const : ['body'] as const, rows: wanted },+ ...(extracted.temporalBody ? { temporalBody: extracted.temporalBody } : {}) };const stampIso = page.updated_at.getTime() >= Date.parse(versionTs) ? page.updated_at_iso : versionTs;const written = await replaceDerivedLinksDeferringConflicts(engine, origin, linkRows, linkOpts);// Settings moved, or a concurrent writer moved the page or an endpoint (#6272): not stamped, re-extracts next run.if (written === 'settings_changed') { skippedChanged++; continue; }if (written === 'concurrent_write') { skippedConcurrentWrite++; continue; }linksCreated += written.created;- await retractRemovedTimelineEntries(engine, page.slug, page.source_id, fullContent);- for (const entry of parseTimelineEntries(fullContent)) {+ const timelineText = fullContent ?? await segmentedTimelineText(engine, snapshot.page);+ await retractRemovedTimelineEntries(engine, page.slug, page.source_id, timelineText);+ for (const entry of typeof timelineText === 'string' ? parseTimelineEntries(timelineText) : timelineText.entries) {// #3957: carry the parsed source label — omitting it wrote source=''// while the FS path wrote the split label, so the same bullet// extracted via both paths duplicated under the (page_id, date,diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 0f7315e653..5ee23220d7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -729,6 +729,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: '`gbrain get` against a remote brain of a page too large for one response holds one window in memory instead of the whole page: the windows wait in a temp file readable only by you in the system temp directory (`TMPDIR`), as large as the page and removed when the command ends, until their size and sha256 verify. Nothing prints before they do, as before. `--json` still refuses a page over 24 MiB.' },{ since: 'TBD', text: 'A streamed `gbrain import` or `gbrain sync` of a Markdown file over 24 MiB (`pages.segmented_storage` on) checks every block it stores against the sha256 its first read of the file recorded. A file rewritten during the import that keeps its size and modification time is now held as `file_too_large` ("the file changed while it was imported (import it again)") instead of being stored as the first version\'s frontmatter over the second version\'s body.' },{ since: 'TBD', text: 'Reads of a page stored in segments that follow an authorization (MCP `get_page` windows, outlines, sizes and its whole-body refusal, `fetch`, evidence windows and the `entity` card excerpt) now read the revision they authorized: a page edited, made private or dropped below the caller\'s `min_trust` mid-read refuses with `revision_changed` (or `page_not_found`) instead of returning the newer body, and evidence falls back to the hit chunk. A segmented page whose segment rows the reader cannot see, or that has a gap or a missing tail, refuses with the new `page_body_rows_unreadable` in every reader that produces its body (MCP reads, export, backup and restore file writes, body digests, fence rewrites) instead of reading as empty or short; an export with such a page fails. `purge_fact` now aborts a write in flight that staged a text holding the purged claim (its publish refuses `body_staging_expired`), segment maintenance keeps every text a live write staged, a page purge of an inline page no longer reports other pages\' segments as incomplete, and MCP `get_versions` reports a segmented version\'s readable size as `total_bytes` instead of its stored `body_bytes`.' },+ { since: 'TBD', text: '`gbrain extract --stale`, the cycle\'s stale-extraction drain and the managed stale-links pass now extract a page stored in segments whose links or timeline are stale, reading its body block by block, and stamp it. Before, doctor `links_extraction_lag` and the sync report counted such a page as needing extraction while no extractor picked it up, so the count never reached 0.' },+ { since: 'TBD', text: 'A large page held for embedding approval or stopped by `embed.max_usd_per_page` that is edited down to 1 MiB or under (inline, or still stored in segments) now embeds through the stale sweep and `gbrain embed --stale` like any page of its size, and no longer appears as held or capped in `gbrain embed --held`, doctor `partial_embedding` or write and sync receipts. Its budget row is kept: if the page grows past 1 MiB again, the hold or cap it had applies again.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/embedding-invalidation.ts b/src/core/embedding-invalidation.tsindex 0655d50ead..0fd1978e71 100644--- a/src/core/embedding-invalidation.ts+++ b/src/core/embedding-invalidation.ts@@ -31,6 +31,7 @@ import {resolveActiveEmbeddingColumnFromEngine,quoteIdentifier,} from './search/embedding-column.ts';+import { pageBudgetLimitedFilter } from './page-size-policy.ts';export function splitEmbeddingSignature(signature: string): { model: string; dims: number | null } {const separator = signature.lastIndexOf(':');@@ -90,7 +91,7 @@ export function falseStampPageWhere(colId: string, signatureParam = 1, modelParap.embedding_signature = $${signatureParam}AND p.deleted_at IS NULLAND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')- AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT ${pageBudgetLimitedFilter('p')}AND EXISTS (SELECT 1 FROM content_chunks cWHERE c.page_id = p.id AND c.${colId} IS NOT NULL@@ -174,7 +175,7 @@ export async function countRestampOnlyChunks(`SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_idWHERE p.deleted_at IS NULL AND ${sigClause}AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')- AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT ${pageBudgetLimitedFilter('p')}AND ($4::text IS NULL OR p.source_id = $4)AND ${currentSpaceChunkPredicate(colId, 2, 3)}`,[opts.signature, model, dims, opts.sourceId ?? null],@@ -208,7 +209,7 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(AND cc.${colId} IS NOT NULLAND NOT ${currentChunk}AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')- AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT ${pageBudgetLimitedFilter('p')}AND p.deleted_at IS NULLAND p.text_projection_revision = p.knowledge_revisionAND ${sigClause}${srcClause}@@ -222,7 +223,7 @@ export async function invalidateStaleSignatureEmbeddingsGuarded(AND p.deleted_at IS NULLAND p.text_projection_revision = p.knowledge_revisionAND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')- AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT ${pageBudgetLimitedFilter('p')}AND EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id)AND NOT EXISTS (SELECT 1 FROM content_chunks ccdiff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 8d33b45fb4..555b15fde2 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -38,6 +38,7 @@ import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { splitEmbeddingSignature, lockEmbeddingSources } from '../embedding-invalidation.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from '../embed-skip.ts';import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';+import { pageBudgetLimitedFilter } from '../page-size-policy.ts';import { SAFE_FENCE_CHUNKER_VERSION } from '../search/safe-chunks.ts';import { mapChunkWindowRows, type ChunkWindowOpts, type ChunkWindowPage, type ChunkWindowRequest } from '../search/chunk-windows.ts';import type { SqlExecutor } from './executor.ts';@@ -63,6 +64,9 @@ export type ChunkTransactionRunner = <T>(fn: (tx: Pick<BrainEngine, 'executeRaw'type StaleChunkOpts = { sourceId?: string; signature?: string; includeNullSignature?: boolean };+/** Held or capped large pages (page-embedding-budget.ts) leave the embedding queue while the hold applies. */+const budgetLimited = trustedSql(pageBudgetLimitedFilter('p'));+export async function upsertChunksOnce(exec: SqlExecutor,guards: ChunkPageGuards,@@ -512,8 +516,8 @@ function staleChunkWhere(column: string, opts?: StaleChunkOpts): SqlFragment {conds.push(sqlFragment`${staleColRef} IS NULL`);}conds.push(sqlFragment`NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip')`);- // Large pages held for approval or at their spend cap (page-embedding-budget.ts) leave the queue until it changes.- conds.push(sqlFragment`NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')`);+ // Large pages held for approval or at their spend cap (page-embedding-budget.ts) leave the queue until it changes or the page is no longer large.+ conds.push(sqlFragment`NOT ${budgetLimited}`);if (opts?.sourceId !== undefined) conds.push(sqlFragment`p.source_id = ${opts.sourceId}`);return joinFragments(conds, ' AND ');}@@ -619,7 +623,7 @@ export async function invalidateContentDriftEmbeddings(AND cc.${colId} IS NOT NULLAND cc.embedded_text_hash IS NOT NULLAND cc.embedded_text_hash <> md5(cc.chunk_text)- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')${srcClause}+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}${srcClause}RETURNING cc.page_id`);return (await tx.executeRaw(text, params)).length;});@@ -657,7 +661,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}AND ${generation}ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASCLIMIT ${limit}@@ -668,7 +672,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}AND ${generation}AND (p.updated_at < ${afterUpdated}::timestamptz@@ -687,7 +691,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {JOIN pages p ON p.id = cc.page_idWHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULLAND p.source_id = ${opts.sourceId}- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}AND ${generation}ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASCLIMIT ${limit}@@ -699,7 +703,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {JOIN pages p ON p.id = cc.page_idWHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULLAND p.source_id = ${opts.sourceId}- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}AND ${generation}AND (p.updated_at < ${afterUpdated}::timestamptz@@ -718,7 +722,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULL- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}AND ${generation}AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})ORDER BY cc.page_id, cc.chunk_index@@ -732,7 +736,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {JOIN pages p ON p.id = cc.page_idWHERE cc.${staleColId} IS NULL AND p.deleted_at IS NULLAND p.source_id = ${opts.sourceId}- AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')+ AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT ${budgetLimited}AND ${generation}AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})ORDER BY cc.page_id, cc.chunk_indexdiff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex dcf24abc67..f5d9717599 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -756,13 +756,13 @@ export async function listStalePagesForExtraction(exec: ScopedRead, opts: {// #1768: project a deterministic full-µs UTC string alongside updated_at.// to_char (not ::text — DateStyle-fragile) so extractStaleFromDB can stamp// links_extracted_at = the exact updated_at and the staleness predicate clears.- // A segmented page is not listed (its body columns are NULL: extracting ''- // would delete its derived links) but stays counted as stale until the- // per-segment extraction reads it.+ // A segmented page is listed like an inline one (count and list share+ // stalePagesWhere): its body columns are NULL, so every extractor reads+ // its snapshot and, for a segmented page, the body block by block.const { text, params } = renderFragment(sqlFragment`SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at,to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS updated_at_isoFROM pages- WHERE ${stalePagesWhere(opts)} AND body_storage = 'inline'${afterClause}+ WHERE ${stalePagesWhere(opts)}${afterClause}ORDER BY idLIMIT ${opts.batchSize}`);const { rows } = await exec.unsafe(text, params);diff --git a/src/core/engine.ts b/src/core/engine.tsindex d2ef9731f3..d97e413eff 100644--- a/src/core/engine.ts+++ b/src/core/engine.ts@@ -1392,9 +1392,9 @@ export interface BrainEngine {/*** List a keyset page (ordered by `id`, `id > afterPageId`) of stale pages* WITH their content so the caller extracts without an N+1 `getPage`. Same- * stale predicate as countStalePagesForExtraction. Caller passes a SMALL- * batchSize (page bodies are unbounded — 25MB transcript pages exist) and- * applies its own per-batch byte budget.+ * stale predicate as countStalePagesForExtraction (segmented rows carry no body:+ * read it block by block). The caller passes a SMALL batchSize (25MB transcript+ * pages exist) and applies its own per-batch byte budget.*/listStalePagesForExtraction(opts: {batchSize: number;diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex 294d73a511..455fdcda2b 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -36,7 +36,7 @@ import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './conteimport type { BodyStorage, ManifestRow } from './page-body/types.ts';import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';import { estimateCostFromChars, lookupEmbeddingPrice } from './embedding-pricing.ts';-import { PAGE_INLINE_MAX_BYTES, isLargePageBytes } from './page-size-policy.ts';+import { PAGE_INLINE_MAX_BYTES, largePageBodyFilter, isLargePageBytes } from './page-size-policy.ts';import { isEmbedSkipped } from './embed-skip.ts';import { parseUsdLimit, resolveSpendPosture } from './spend-posture.ts';import { chunkGenerationFilter } from './search/safe-chunks.ts';@@ -194,7 +194,7 @@ export function estimatePageEmbedUsd(chars: number, signature: string | null | u/** Held and capped pages with their stale chunk counts (doctor `partial_embedding`, `gbrain embed --held`). */export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRaw'>, opts: { state?: 'held' | 'capped'; sourceId?: string; limit?: number } = {}): Promise<PageBudgetReport[]> {const params: unknown[] = [opts.limit ?? 1000];- const filters = [`b.state <> 'open'`, 'p.deleted_at IS NULL'];+ const filters = [`b.state <> 'open'`, largePageBodyFilter('p'), 'p.deleted_at IS NULL'];if (opts.state) filters.push(`b.state = $${params.push(opts.state)}`);if (opts.sourceId) filters.push(`p.source_id = $${params.push(opts.sourceId)}`);const pending = `(CASE WHEN p.body_storage = 'segmented' THEN cc.${quoteIdentifier((await embeddingWriteTarget(engine)).column.name)} IS NULL ELSE cc.embedded_at IS NULL END)`;@@ -283,9 +283,10 @@ export function pageSizeState(bytes: number, frontmatter: Record<string, unknownif (isEmbedSkipped(frontmatter)) {return { embedding: 'skipped', reason: (frontmatter!.embed_skip as { reason?: unknown } | null)?.reason === 'oversized' ? 'oversized' : 'operator_marker', bytes };}- if (budget?.state === 'held') return { embedding: 'held', reason: budget.reason ?? 'awaiting_approval', bytes };- if (budget?.state === 'capped') return { embedding: 'partial', reason: 'spend_cap', bytes };- return isLargePageBytes(bytes) || segmented ? { embedding: 'deferred', reason: 'large_page', bytes } : null;+ const large = isLargePageBytes(bytes);+ if (large && budget?.state === 'held') return { embedding: 'held', reason: budget.reason ?? 'awaiting_approval', bytes };+ if (large && budget?.state === 'capped') return { embedding: 'partial', reason: 'spend_cap', bytes };+ return large || segmented ? { embedding: 'deferred', reason: 'large_page', bytes } : null;}/**diff --git a/src/core/page-size-policy.ts b/src/core/page-size-policy.tsindex cd3672d0bb..eb16384c65 100644--- a/src/core/page-size-policy.ts+++ b/src/core/page-size-policy.ts@@ -38,3 +38,18 @@ export const PAGE_INLINE_MAX_BYTES = 1024 ** 2;export function isLargePageBytes(bytes: number): boolean {return bytes > PAGE_INLINE_MAX_BYTES;}++/** SQL twin of isLargePageBytes(pageBodyBytes(page)) over a `pages` row aliased `alias`: `body_bytes` of a segmented page, else its body columns' bytes. */+export function largePageBodyFilter(alias: string): string {+ return `(CASE WHEN ${alias}.body_storage = 'segmented' THEN ${alias}.body_bytes ELSE octet_length(${alias}.compiled_truth) + octet_length(COALESCE(${alias}.timeline, '')) END) > ${PAGE_INLINE_MAX_BYTES}`;+}++/**+ * SQL over a `pages` row aliased `alias`: the page has a held or capped+ * `page_embedding_budget` row (page-embedding-budget.ts) that still applies.+ * The budget meters large pages only, so a row left on a page edited down to+ * the inline threshold or under no longer keeps it out of the embedding queue.+ */+export function pageBudgetLimitedFilter(alias: string): string {+ return `EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = ${alias}.id AND peb.state <> 'open' AND ${largePageBodyFilter(alias)})`;+}diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex fdd3bf1bf5..40ff8718d0 100644--- a/test/fixtures/goldens/sql-text/chunks.json+++ b/test/fixtures/goldens/sql-text/chunks.json@@ -33,8 +33,8 @@{"lane": "pool","params": [],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')",- "textSha256": "364d46feaba0272a76622f1b3a06ce9d06af491748c4983689e0b3dc15f4fa8f"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576)",+ "textSha256": "e83227b9f8a2a11848819a683ff9a14d87c35b36b55c2581cf4fab097b8f5cdf"}],"signature+includeNullSignature": [@@ -49,8 +49,8 @@"params": ["string"],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')",- "textSha256": "f981130d0cfc273d84f0765edd8dac854ca41f771e2a79a750ced186b410ef1e"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR p.embedding_signature IS NULL OR p.embedding_signature <> $1) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576)",+ "textSha256": "0601a60050db58018495d7d45f55002a4e6b591c17305f7f3de4b1450b5c4c2b"}],"signature+sourceId": [@@ -66,8 +66,8 @@"string","string"],- "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND p.source_id = $2",- "textSha256": "2223d700a8bf30585b9a816f717220c6b66fa0a78c87c28fe3f5d4ba1313a682"+ "sql": "SELECT count(*)::int AS count FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND p.source_id = $2",+ "textSha256": "5c75ef9176fa2316ed9a82fa49c8edb8ab2006794e95e6f39153c621fb41004e"}]},@@ -414,8 +414,8 @@"params": ["array<>"],- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') RETURNING cc.page_id",- "textSha256": "fb381f53bfef8651bd109cb1182781bd25f65cf2a1b0b94ffbfc3d97186acc08"+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) RETURNING cc.page_id",+ "textSha256": "0fb0f0109e484923bce97a50af889d1656cea824024ea92f6c40fee587797d11"},{"event": "commit",@@ -448,8 +448,8 @@"array<>","string"],- "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND p.source_id = $2 RETURNING cc.page_id",- "textSha256": "ab5f41f2171c1b82bfd50dba397be0dbd0f23849bb1ffe55b2a1bc389ba13a5b"+ "sql": "UPDATE content_chunks cc SET \"embedding\" = NULL, embedded_at = NULL, embedded_text_hash = NULL, embedding_pending_since = now() FROM pages p WHERE cc.page_id = p.id AND p.source_id=ANY($1::text[]) AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived) AND p.deleted_at IS NULL AND cc.\"embedding\" IS NOT NULL AND cc.embedded_text_hash IS NOT NULL AND cc.embedded_text_hash <> md5(cc.chunk_text) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND p.source_id = $2 RETURNING cc.page_id",+ "textSha256": "69ae8c768a3a7efcd985c7980cb3166fe36b15ecc3da10672b1d0953a11a797f"},{"event": "commit",@@ -571,8 +571,8 @@"array<string>","number"],- "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",- "textSha256": "19a968efbb91cff8f1f0fab46d7e0e15a0ce1b533e8f1ea39a1ed524a0c89e94"+ "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) ) r WHERE r.state = ANY($2::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $3",+ "textSha256": "ab23be333adf4fdb219fea5b7bcbf91be54b2bd15186b5a5b0902cb100584b3e"}],"sourceIds": [@@ -591,8 +591,8 @@"array<string>","number"],- "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",- "textSha256": "1e8153643b4495c6800096c412f4c53fca3f3d645d8c435407c93a4ed1925645"+ "sql": "SELECT r.slug, r.source_id, r.state, r.chunks, r.bytes, r.embed_skip_reason, r.marker_bytes, r.quarantine_reason, r.deleted_at, r.overdue FROM ( SELECT p.slug, p.source_id, CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) THEN 'pending' ELSE 'keyword_only' END AS state, count(*)::bigint AS chunks, COALESCE(sum(octet_length(cc.chunk_text)), 0)::bigint AS bytes, p.frontmatter -> 'embed_skip' ->> 'reason' AS embed_skip_reason, CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END AS marker_bytes, p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at, COALESCE(p.deleted_at < now() - make_interval(hours => $1::int), false) AS overdue FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[]) GROUP BY p.id, 3 UNION ALL SELECT p.slug, p.source_id, CASE WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') THEN 'keyword_only' WHEN p.deleted_at IS NULL AND (p.compiled_truth <> '' OR p.timeline <> '' OR (p.body_storage = 'segmented' AND p.body_bytes > 0)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) THEN 'chunkless_healable' ELSE 'empty' END, 0::bigint, (octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))::bigint, p.frontmatter -> 'embed_skip' ->> 'reason', CASE WHEN jsonb_typeof(p.frontmatter -> 'embed_skip' -> 'bytes') = 'number' THEN (p.frontmatter -> 'embed_skip' ->> 'bytes')::numeric::bigint END, p.frontmatter -> 'quarantine' ->> 'reason', p.deleted_at, false FROM pages p WHERE p.deleted_at IS NULL AND NOT EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = p.id) AND p.source_id = ANY($3::text[]) ) r WHERE r.state = ANY($4::text[]) ORDER BY r.state, r.source_id, r.slug LIMIT $5",+ "textSha256": "ab6cca173b1db8f5e1459ead208e1b27ed245f5a3ac0f814628db618dc16e66b"}]},@@ -611,8 +611,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",- "textSha256": "a41e226d810b74525060ad936914de93d6804badc46e0644770a8bd18991ecc3"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",+ "textSha256": "43e1e9a1f41696ea88ef821dd7d8bb2739e86d2f2246212bed3c7e10be339752"}],"sourceId": [@@ -630,8 +630,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",- "textSha256": "dee70bea35251fcb642d0f4b369ed207bd025becd2131a24bbaa3fa202a35c50"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",+ "textSha256": "feb2f91ac34cce170f5a25e79a6fba43959dbd07a502a946a56bf80fd156e164"}],"updated_desc": [@@ -646,8 +646,8 @@"params": ["number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",- "textSha256": "2060e059f461a956597a2035b6c7c08f7401e16d069c012e5bf1f7346c6b3f6c"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",+ "textSha256": "0b9d9d00a2d02ba20abd83cd85b7dc6b2ba8607ea17d69be6b8c8a1b3bcd6034"}],"updated_desc+cursor": [@@ -668,8 +668,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.id > $3) OR (p.updated_at = $4::timestamptz AND p.id = $5 AND cc.chunk_index > $6) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $7",- "textSha256": "bcbb4c6e7c3227d0f3e34bee28e5f2004233194685cabb7376dfa53d020a396c"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $1::timestamptz OR (p.updated_at = $2::timestamptz AND p.id > $3) OR (p.updated_at = $4::timestamptz AND p.id = $5 AND cc.chunk_index > $6) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $7",+ "textSha256": "14e05e5362b3f96c021dee659ad6c04a656915c6d81aa862fd08312e9b12a8bc"}],"updated_desc+sourceId": [@@ -685,8 +685,8 @@"string","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",- "textSha256": "d9dc727d9dfb4c3f4d209704f69b08eba3a03ba85b046f6e8ae3cfe3ddd5595e"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",+ "textSha256": "1f308ec9b71a2d430dffa6c0746917dcbead9aed5daed00914a7fac0cc2d43cf"}],"updated_desc+sourceId+cursor": [@@ -708,8 +708,8 @@"number","number"],- "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $2::timestamptz OR (p.updated_at = $3::timestamptz AND p.id > $4) OR (p.updated_at = $5::timestamptz AND p.id = $6 AND cc.chunk_index > $7) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $8",- "textSha256": "b603cf513a4145b8638be743a1ce107692fa9c6bf995524aa30c63d650f119e1"+ "sql": "SELECT p.slug, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, p.source_id, cc.page_id, p.updated_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE cc.\"embedding\" IS NULL AND p.deleted_at IS NULL AND p.source_id = $1 AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND ( p.updated_at < $2::timestamptz OR (p.updated_at = $3::timestamptz AND p.id > $4) OR (p.updated_at = $5::timestamptz AND p.id = $6 AND cc.chunk_index > $7) ) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $8",+ "textSha256": "30a408c8494070d912f5b0e1bafec94a93e64a52633de47abbf9e4b9b8996f95"}]},@@ -726,8 +726,8 @@"params": ["number"],- "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation))))) s GROUP BY s.state",- "textSha256": "5d9d1c9bedc77e5af44f0ab330a0e3c15a670341bfd55f6c7269ea5f44997b80"+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation))))) s GROUP BY s.state",+ "textSha256": "b1fc6d17a408d2b5d43f85a7317983d19470bbe6145a6d63c64864127a7bcc9c"},{"lane": "pool",@@ -755,8 +755,8 @@"number","array<string>"],- "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open') THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[])) s GROUP BY s.state",- "textSha256": "567c13023ca4f921061804c280d572a55dac61142d915c6bb48c0acbdc727713"+ "sql": "SELECT s.state, count(*)::bigint AS n, count(*) FILTER (WHERE s.eligible)::bigint AS eligible, count(*) FILTER (WHERE s.overdue)::bigint AS overdue, count(*) FILTER (WHERE s.unstamped)::bigint AS unstamped, min(s.created_at) FILTER (WHERE s.unstamped) AS unstamped_min FROM (SELECT CASE WHEN p.deleted_at IS NOT NULL THEN 'deleted_page_chunks' WHEN NOT NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') THEN 'quarantined' WHEN cc.\"embedding\" IS NOT NULL THEN 'embedded' WHEN p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576) THEN 'pending' ELSE 'keyword_only' END AS state, NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AS eligible, COALESCE((p.deleted_at < now() - make_interval(hours => $1::int)), false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_at FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND p.source_id = ANY($2::text[])) s GROUP BY s.state",+ "textSha256": "089182bfd064f4f1c211169a74c9fffc8c942fbd1fe2e0e8f072aca02959c74c"},{"lane": "pool",@@ -817,8 +817,8 @@{"lane": "pool","params": [],- "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')",- "textSha256": "6b90c75b7ee5221cf0bbdab5ecaf31504172286e69501d9fe1547d2e58a3ad9d"+ "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND cc.\"embedding\" IS NULL AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576)",+ "textSha256": "66337386af837f35a811885fff1e7431a5d74cf73f2ee472d6078b81d7248870"}],"signature": [@@ -833,8 +833,8 @@"params": ["string"],- "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open')",- "textSha256": "a6db634edced27d38165b7232a396fd91c49e8f71b24c596d36c26ece1810d66"+ "sql": "SELECT COALESCE(SUM(LENGTH(cc.chunk_text)), 0)::bigint AS chars FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.deleted_at IS NULL AND ((cc.body_generation IS NULL AND p.body_storage <> 'segmented') OR (cc.body_generation <= p.body_generation AND EXISTS (SELECT 1 FROM page_body_manifest lm WHERE lm.page_id = cc.page_id AND lm.occurrence_id = cc.occurrence_id AND lm.staging_id IS NULL AND lm.gen_from <= p.body_generation AND (lm.gen_to IS NULL OR lm.gen_to > p.body_generation)))) AND (cc.\"embedding\" IS NULL OR (p.embedding_signature IS NOT NULL AND p.embedding_signature <> $1)) AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'embed_skip') AND NOT EXISTS (SELECT 1 FROM page_embedding_budget peb WHERE peb.page_id = p.id AND peb.state <> 'open' AND (CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END) > 1048576)",+ "textSha256": "02de5a5856cf3bccf48f839f37a46f9e050dcb3ae7261e8252a0cb74337fc120"}]},diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.jsonindex 29909bd4dd..5c43541aea 100644--- a/test/fixtures/goldens/sql-text/pages.json+++ b/test/fixtures/goldens/sql-text/pages.json@@ -680,8 +680,8 @@"number","number"],- "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND body_storage = 'inline' AND id > $3 ORDER BY id LIMIT $4",- "textSha256": "1ab30a03a7515fc473086bf91c7f83adca485b27801bf9a2527674ee40238be4"+ "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR links_extracted_at < $1::timestamptz OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND source_id = $2 AND id > $3 ORDER BY id LIMIT $4",+ "textSha256": "22fb498ad7872c970f05a3905d04bebef7df2790c417bea32d6a214eb0ae4505"}],"default": [@@ -690,8 +690,8 @@"params": ["number"],- "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) AND body_storage = 'inline' ORDER BY id LIMIT $1",- "textSha256": "183a892cb76864e3da999c28c4eed5ceb6495ef22656b92c89ec1ff087fe2fd3"+ "sql": "SELECT id, slug, source_id, type, title, compiled_truth, timeline, frontmatter, updated_at, to_char(updated_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"') AS updated_at_iso FROM pages WHERE deleted_at IS NULL AND NOT (COALESCE(pages.frontmatter, '{}'::jsonb) ? 'quarantine') AND (links_extracted_at IS NULL OR updated_at > links_extracted_at OR id IN (SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND t.slug = w.target_ref AND t.deleted_at IS NULL WHERE t.updated_at > w.checked_at UNION SELECT w.origin_page_id FROM wanted_links w JOIN pages t ON t.source_id = w.target_source_id AND regexp_replace(t.slug, '^.*/', '') = w.target_ref AND t.deleted_at IS NULL WHERE w.ref_kind = 'name' AND t.updated_at > w.checked_at)) ORDER BY id LIMIT $1",+ "textSha256": "27cc368fcbecffffad33b5d8542adbc3d0fcd24e6700ce7b5d351ec5e2103a57"}]},diff --git a/test/large-pages/held-budget-shrink.test.ts b/test/large-pages/held-budget-shrink.test.tsnew file mode 100644index 0000000000..3a7c0115f5--- /dev/null+++ b/test/large-pages/held-budget-shrink.test.ts@@ -0,0 +1,109 @@+/**+ * PR 2 fix lane J2: a large page held (or capped) by the per-page embedding+ * budget that is edited down to the inline threshold or under embeds again.+ *+ * 1. Protects: the budget meters large pages only (planPageEmbedding treats a+ * page at or under 1 MiB as unmetered), so a held row left on a page that+ * shrank no longer applies: the stale-chunk queue (staleChunkWhere and the+ * stale lists), the held lists (`gbrain embed --held`, doctor+ * `partial_embedding`) and the write receipts' size state ignore it, and+ * the stale sweep embeds the page's chunks. Covers an inline page shrinking+ * inline, a segmented page shrinking within the demotion hysteresis (it+ * stays segmented under 1 MiB) and one demoted to inline.+ * 2. Fails when: a stale held row keeps a page that is no longer large out of+ * the embedding queue (it stays keyword-only forever) or reported as held.+ * 3. Why existing coverage misses it: the budget tests hold pages that stay+ * large.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { embedStaleForSource } from '../../src/core/embed-stale.ts';+import { holdPageEmbedding, listBudgetLimitedPages, readPageSizeStates } from '../../src/core/page-embedding-budget.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { visibleChunks } from '../helpers/segmented-page-checks.ts';+import { withEnv } from '../helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-held-budget-shrink-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++const note = (bytes: number, seed: number) => `---\ntype: note\ntitle: Held note\n---\n\n${conversationBody(bytes, { seed })}\n`;++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++/** Run the stale sweep for the source with a stand-in provider; returns how many texts it sent. */+async function sweep(engine: BrainEngine, sourceId: string): Promise<number> {+ const [column] = await engine.executeRaw<{ dims: number }>(`SELECT atttypmod AS dims FROM pg_attribute WHERE attrelid='content_chunks'::regclass AND attname='embedding'`);+ let sent = 0;+ await embedStaleForSource(engine, sourceId, { embedFn: async (batch: string[]) => {+ sent += batch.length;+ return batch.map(() => new Float32Array(Number(column!.dims)).fill(0.1));+ } });+ return sent;+}++async function pageRow(engine: BrainEngine, sourceId: string, slug: string) {+ const [row] = await engine.executeRaw<{ id: number; body_storage: string; bytes: string }>(+ `SELECT id, body_storage, (CASE WHEN body_storage='segmented' THEN body_bytes ELSE octet_length(compiled_truth)+octet_length(COALESCE(timeline,'')) END)::text AS bytes+ FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, slug]);+ return { id: Number(row!.id), body_storage: row!.body_storage, bytes: Number(row!.bytes) };+}++const cases = [+ { name: 'an inline page shrinking inline', switch: 'off', large: 1_200_000, small: 200_000, before: 'inline', after: 'inline' },+ { name: 'a segmented page shrinking under 1 MiB (it stays segmented)', switch: 'on', large: 1_200_000, small: 800_000, before: 'segmented', after: 'segmented' },+ { name: 'a segmented page demoted to inline', switch: 'on', large: 1_200_000, small: 200_000, before: 'segmented', after: 'inline' },+] as const;++describe('a held large page that shrinks under 1 MiB', () => {+ for (const c of cases) {+ test(`${c.name}: its held row no longer applies and the stale sweep embeds it`, async () => withEnv(env, async () => {+ for (const engine of engines) {+ const sourceId = `held-${randomUUID().slice(0, 8)}`;+ const slug = 'notes/held';+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES($1,$1,'{}')", [sourceId]);+ await engine.setConfig('pages.segmented_storage', c.switch);+ expect(await importFromContent(engine, slug, note(c.large, 91), { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ const large = await pageRow(engine, sourceId, slug);+ expect(large.body_storage).toBe(c.before);+ expect(large.bytes).toBeGreaterThan(1024 ** 2);+ await holdPageEmbedding(engine, large.id, 'awaiting_approval');+ expect(await sweep(engine, sourceId)).toBe(0);+ expect((await listBudgetLimitedPages(engine, { sourceId })).map(p => p.slug)).toEqual([slug]);++ expect(await importFromContent(engine, slug, note(c.small, 92), { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ const small = await pageRow(engine, sourceId, slug);+ expect(small).toMatchObject({ id: large.id, body_storage: c.after });+ expect(small.bytes).toBeLessThanOrEqual(1024 ** 2);+ expect(await engine.countStaleChunks({ sourceId })).toBeGreaterThan(0);+ expect(await sweep(engine, sourceId)).toBeGreaterThan(0);+ const chunks = await visibleChunks(engine, small.id);+ expect(chunks.length).toBeGreaterThan(0);+ expect(chunks.every(chunk => chunk.embedded)).toBe(true);+ expect(await engine.countStaleChunks({ sourceId })).toBe(0);+ expect(await listBudgetLimitedPages(engine, { sourceId })).toEqual([]);+ expect((await readPageSizeStates(engine, sourceId, [slug])).filter(s => s.embedding === 'held')).toEqual([]);+ }+ }), 600_000);+ }+});diff --git a/test/large-pages/segmented-extraction-stale.test.ts b/test/large-pages/segmented-extraction-stale.test.tsnew file mode 100644index 0000000000..bd4f6b5e50--- /dev/null+++ b/test/large-pages/segmented-extraction-stale.test.ts@@ -0,0 +1,148 @@+/**+ * PR 2 fix lane J1: link/timeline extraction lists, extracts and stamps a+ * segmented page.+ *+ * 1. Protects: listStalePagesForExtraction lists exactly the pages+ * countStalePagesForExtraction counts, inline and segmented alike, so the+ * stale count doctor and sync status report is work an extractor does;+ * `extract --stale` (unmanaged) reads a segmented page's links and dated+ * lines block by block, writes its edge and timeline row and stamps it;+ * the managed stale-links pass (no slugs given) finds and stamps one too.+ * After either pass the count is 0.+ * 2. Fails when: the list filters segmented pages out while the count keeps+ * them (the count stays 1 forever), or the unmanaged sweep reads a+ * segmented page's body as one string (page_body_segmented) or as empty.+ * 3. Why existing coverage misses it: the segmented extraction tests pass the+ * page's slug explicitly (`extract --slugs`, the managed pass's `slugs`),+ * which never consults the stale list.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { extractStaleFromDB } from '../../src/commands/extract.ts';+import { effectiveLinkExtractorWatermark } from '../../src/core/link-extraction-watermark.ts';+import { extractManagedStaleLinks } from '../../src/core/persistence/links-maintenance.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-extract-stale-'));+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++/** About 1.2 MiB: a link to the target early and a dated bullet at the end. */+const segmentedNote = (seed: number) => `---\ntype: note\ntitle: Segmented note\n---\n\nSee [[people/alice-example]].\n\n`+ + `${conversationBody(1_200_000, { seed })}\n\n## Timeline\n\n- **2026-03-04** | Kickoff with Alice\n`;++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++async function staleState(engine: BrainEngine, sourceId: string): Promise<{ count: number; listed: string[] }> {+ const versionTs = await effectiveLinkExtractorWatermark(engine);+ const count = await engine.countStalePagesForExtraction({ sourceId, versionTs });+ const listed: string[] = [];+ for (let afterPageId = 0; ;) {+ const rows = await engine.listStalePagesForExtraction({ batchSize: 1, afterPageId, sourceId, versionTs });+ if (!rows.length) break;+ listed.push(...rows.map(row => row.slug));+ afterPageId = rows[rows.length - 1]!.id;+ }+ return { count, listed: listed.sort() };+}++async function extractedState(engine: BrainEngine, sourceId: string, slug: string) {+ const [page] = await engine.executeRaw<{ id: number; body_storage: string; stamped: boolean }>(+ 'SELECT id, body_storage, links_extracted_at IS NOT NULL AS stamped FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]);+ const links = await engine.executeRaw<{ slug: string }>('SELECT t.slug FROM links l JOIN pages t ON t.id=l.to_page_id WHERE l.from_page_id=$1 ORDER BY t.slug', [page!.id]);+ const timeline = await engine.executeRaw<{ date: string; summary: string }>(+ "SELECT to_char(date,'YYYY-MM-DD') AS date, summary FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL ORDER BY date", [page!.id]);+ return { body_storage: page!.body_storage, stamped: page!.stamped, links: links.map(row => row.slug), timeline };+}++/** Drop the derived rows of a source's pages and their extraction stamps, so every page needs extraction again. */+async function unextract(engine: BrainEngine, sourceId: string): Promise<void> {+ await engine.executeRaw('DELETE FROM links WHERE from_page_id IN (SELECT id FROM pages WHERE source_id=$1)', [sourceId]);+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id IN (SELECT id FROM pages WHERE source_id=$1)', [sourceId]);+ await engine.executeRaw('UPDATE pages SET links_extracted_at=NULL WHERE source_id=$1', [sourceId]);+}++describe('segmented pages in the extraction stale list', () => {+ test('unmanaged: the list matches the count over inline and segmented pages, and extract --stale drains both', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const sourceId = `xstale-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw("INSERT INTO sources(id,name,config) VALUES($1,$1,'{}')", [sourceId]);+ await engine.setConfig('pages.segmented_storage', 'off');+ await importFromContent(engine, 'people/alice-example', '---\ntype: person\ntitle: Alice Example\n---\n\nAlice fixture.\n', { sourceId, noEmbed: true });+ await importFromContent(engine, 'notes/inline', '---\ntype: note\ntitle: Inline\n---\n\nSee [[people/alice-example]].\n', { sourceId, noEmbed: true });+ await engine.setConfig('pages.segmented_storage', 'on');+ expect(await importFromContent(engine, 'notes/segmented', segmentedNote(81), { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ await unextract(engine, sourceId);++ expect((await extractedState(engine, sourceId, 'notes/segmented')).body_storage).toBe('segmented');+ const before = await staleState(engine, sourceId);+ expect(before.listed).toEqual(['notes/inline', 'notes/segmented', 'people/alice-example']);+ expect(before.count).toBe(before.listed.length);++ const result = await extractStaleFromDB(engine, { sourceIdFilter: sourceId, quiet: true, dryRun: false, jsonMode: false, catchUp: true });+ expect(result.pagesProcessed).toBe(3);+ expect(await staleState(engine, sourceId)).toEqual({ count: 0, listed: [] });+ expect(await extractedState(engine, sourceId, 'notes/segmented')).toEqual({ body_storage: 'segmented', stamped: true,+ links: ['people/alice-example'], timeline: [{ date: '2026-03-04', summary: 'Kickoff with Alice' }] });+ expect((await extractedState(engine, sourceId, 'notes/inline')).links).toEqual(['people/alice-example']);+ }+ }), 600_000);++ test('managed: the stale-links pass without slugs lists, links and stamps a segmented page', async () => withEnv(env, async () => {+ for (const engine of engines) {+ const sourceId = `xstale-m-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await engine.putPage('people/alice-example', { type: 'person', title: 'Alice', compiled_truth: 'Alice fixture.', timeline: '', frontmatter: {} }, { sourceId });+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ writeFileSync(join(root, 'notes/segmented.md'), segmentedNote(82));+ expect(await importManagedFile(engine, join(root, 'notes/segmented.md'), 'notes/segmented.md', { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ // The writer guard refuses direct derived-row writes while the brain is managed; the reset runs with it off.+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await unextract(engine, sourceId);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const before = await staleState(engine, sourceId);+ expect(before.listed).toEqual(['notes/segmented', 'people/alice-example']);+ expect(before.count).toBe(before.listed.length);++ const result = await extractManagedStaleLinks(engine, { sourceId, mentions: false });+ expect(result).toMatchObject({ pages: 2, skipped: 0, remaining: 0, timeline: 1 });+ expect(await staleState(engine, sourceId)).toEqual({ count: 0, listed: [] });+ expect(await extractedState(engine, sourceId, 'notes/segmented')).toEqual({ body_storage: 'segmented', stamped: true,+ links: ['people/alice-example'], timeline: [{ date: '2026-03-04', summary: 'Kickoff with Alice' }] });+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ }+ }), 600_000);+});diff --git a/test/oversized-backfill.serial.test.ts b/test/oversized-backfill.serial.test.tsindex 835b06b830..a4800adf89 100644--- a/test/oversized-backfill.serial.test.ts+++ b/test/oversized-backfill.serial.test.ts@@ -173,14 +173,15 @@ describe('per-page embedding budget (embed.max_usd_per_page)', () => {const stale = (n: number) => Array.from({ length: n }, (_, i) => ({ chunk_index: i, chunk_text: 'x'.repeat(4000) }));const page = (id: number) => ({ id, compiled_truth: 'y'.repeat(1_100_000), timeline: '' });- async function pageId(slug: string): Promise<number> {- await engine.putPage(slug, { type: 'note', title: slug, compiled_truth: 'short' });+ /** The stored page matches the size planPageEmbedding is given: a budget row applies only while the page is large. */+ async function pageId(slug: string, compiled_truth = 'short'): Promise<number> {+ await engine.putPage(slug, { type: 'note', title: slug, compiled_truth });return (await engine.getPage(slug))!.id;}test('grants the newest chunks that fit the cap, marks the page capped, and never re-grants spent budget', async () => {await withHome(null, async () => {- const id = await pageId('notes/capped');+ const id = await pageId('notes/capped', page(0).compiled_truth);await engine.setConfig('embed.max_usd_per_page', '0.0003');const first = await planPageEmbedding(engine, page(id), stale(10), { signature: `${MODEL}:${DIMS}` });if (first.kind !== 'grant') throw new Error(`expected a grant, got ${first.kind}`);@@ -212,8 +213,9 @@ describe('per-page embedding budget (embed.max_usd_per_page)', () => {test('a large page whose head, middle and tail windows are all boilerplate is held instead of embedded', async () => {await withHome(null, async () => {- const id = await pageId('notes/boilerplate');- const decision = await planPageEmbedding(engine, { id, compiled_truth: navRow.repeat(Math.ceil(1_100_000 / navRow.length)) }, stale(3));+ const body = navRow.repeat(Math.ceil(1_100_000 / navRow.length));+ const id = await pageId('notes/boilerplate', body);+ const decision = await planPageEmbedding(engine, { id, compiled_truth: body }, stale(3));expect(decision).toEqual({ kind: 'held', reason: 'sampled_markup_heavy' });expect(await listBudgetLimitedPages(engine)).toEqual([expect.objectContaining({ slug: 'notes/boilerplate', state: 'held' })]);});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex c09c089134..7cc729e8c5 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -71,6 +71,7 @@ test/large-pages/contextual-reembed-segmented.test.tstest/large-pages/credential-reseal-segments.test.tstest/large-pages/forget-reason-segmented.test.tstest/large-pages/forget-scope.test.ts+test/large-pages/held-budget-shrink.test.tstest/large-pages/managed-import-outside-root.test.tstest/large-pages/managed-streamed-import.test.tstest/large-pages/managed-sync-segmented-rename.test.ts@@ -107,6 +108,7 @@ test/large-pages/segmented-embedding-paths.test.tstest/large-pages/segmented-embedding.test.tstest/large-pages/segmented-evidence-read-cost.test.tstest/large-pages/segmented-evidence.test.ts+test/large-pages/segmented-extraction-stale.test.tstest/large-pages/segmented-facts-forced-lines.test.tstest/large-pages/segmented-facts-reconcile.test.tstest/large-pages/segmented-file-drift-ledger.test.ts