Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 1 lane 1e: chunk visibility, segmented embedding scope, versions as manifests
garrytana2b1e33b1c8e
diff --git a/docs/architecture/key-files/core-search-2.md b/docs/architecture/key-files/core-search-2.mdindex 5afe834722..613a8fc3fb 100644--- a/docs/architecture/key-files/core-search-2.md+++ b/docs/architecture/key-files/core-search-2.md@@ -26,7 +26,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/return-policy.ts` (default OFF) — intent-aware adaptive return-sizing. Pure, dependency-light module that trims the final ranked candidate set to an intent-driven cap instead of returning the full top-K. `entity` intent gets a tight cap; `temporal`/`event`/`general` get a recall-preserving cap (`concept` is coerced to `general` by `hybrid.ts` before the call — concept queries want breadth). A `minKeep` failsafe (≥1) guarantees a human never gets a silent blank when candidates exist. WHY a cap, not a score-cliff detector: PrecisionMemBench instrumentation (gbrain-evals) measured the rank1→rank2 RRF gap is ~identical whether rank-1 is correct (0.602) or wrong (0.569) — mechanical decay, not a separatrix; rank-1 is right in 94% of single-answer cases, so "return a tight set" is the whole win and cliff-cutting just adds noise. Exports `AdaptiveReturnConfig`, `DEFAULT_ADAPTIVE_RETURN` (frozen: `enabled=false`, `entityMax=2`, `otherMax=6`, `minKeep=1`), `AdaptiveReturnDecision` (`{applied, intent, cap, kept, total}`), `AdaptiveReturnInput` (`boolean | Partial<AdaptiveReturnConfig> | undefined`), `adaptiveReturnFromConfig(cfg)`, `resolveAdaptiveReturn(perCall, fromConfig)` (defaults → config → per-call merge), `adaptiveReturnEnabled(...)` (cache-skip gate check), `applyAdaptiveReturn(results, intent, cfg)` (the trim). Config knobs (DB or file plane): `search.adaptive_return` (master switch), `search.adaptive_return_entity_max`, `search.adaptive_return_other_max`, `search.adaptive_return_min_keep` (each clamped ≥1). Wired into `hybridSearch` AFTER `applyReranker`, BEFORE the `limit` slice, and ONLY on the first page (`offset===0`) — paginating a confidence-gated set is incoherent, so paginated calls fall through to the fixed limit. Stamps the decision onto `HybridSearchMeta.adaptive_return` for `gbrain search --explain`. `hybridSearchCached` SKIPS the cache when the gate is on (a trimmed set must not be served to a gate-off lookup and vice versa). `SearchOpts.adaptiveReturn` + `HybridSearchMeta.adaptive_return` declared in `src/core/types.ts`. Agent-facing: the `query` op (`src/core/operations.ts`) exposes an `adaptive_return` boolean param whose description instructs the agent WHEN to set it (single-answer → on; breadth/exploration → off; pass `limit:1` for a hard single-answer cap), threaded into `hybridSearchCached` — end users never touch the config knob; their agent decides per query (same pattern as `salience`/`recency`). Pinned by `test/search/return-policy.test.ts` (mechanism) + `test/search/query-op-adaptive-return.test.ts` (agent surface: param exists + description teaches both directions + the never-empty contract).-- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. `chunkWriteInvalidations(pageId, chunks)` yields one guarded `chunker_version = -1` invalidation per row batch of a chunk replacement (`batch-rows.ts` `jsonRowBatches`); the caller stops at the first that returns a row.+- `src/core/search/safe-chunks.ts` — shared current-revision and remote safe-chunk predicates. `currentTextProjectionFilter` emits `(text_projection_revision = knowledge_revision) IS TRUE`, preserving NULL exclusion while allowing expression statistics to guide the planner. Visibility and revision predicates stay inside candidate selection. Body/chunk changes invalidate the safe index until a guarded rebuild. `belowSafeChunkFence` is the page-level predicate shared by the importers' unchanged-content re-seal and the drain. `chunkWriteInvalidations(pageId, chunks)` yields one guarded `chunker_version = -1` invalidation per row batch of a chunk replacement (`batch-rows.ts` `jsonRowBatches`); the caller stops at the first that returns a row. Wave B: `chunkVisibleFilter(p, c)` (current projection plus `chunkGenerationFilter`: a row of the page's live body generation; every inline row passes) is the search-facing chunk predicate, `chunkGenerationProbe(c)` the same without a joined page, and `chunkManifestJoin` / `chunkDocumentOrder` give segmented rows document order (manifest byte_start, local_ordinal); `scripts/check-chunk-visibility.ts` requires one of them or a reason on every `content_chunks` reader (rules in its header).- `src/core/search/source-boost.ts` — Source-type boost map keyed by slug prefix. `DEFAULT_SOURCE_BOOSTS` (originals/ 1.5, concepts/ 1.3, writing/ 1.4, people/companies/deals/ 1.2, daily/ 0.8, media/x/ 0.7, <fork>/chat/ 0.5, archive/ 0.5, extracts/ 0.3) and `DEFAULT_HARD_EXCLUDES` (test/, attachments/, .raw/). `archive/` is DEMOTED (findable, ranked below curated), not hard-excluded — archive holds high-signal history users expect to retrieve; the demote is a prior at the SQL/fusion layer and the cross-encoder reranker can still promote a strongly-matching archive page. `parseSourceBoostEnv`/`parseHardExcludesEnv` parse comma-separated `prefix:factor` pairs from `GBRAIN_SOURCE_BOOST`/`GBRAIN_SEARCH_EXCLUDE`. `resolveBoostMap(env, config)` layers defaults (dropped by a `none` entry), the brain's `search.source_boosts` config and the env override; hybridSearch resolves it once from the mode config snapshot and passes it to the engines as `SearchOpts.source_boosts` (engines fall back to defaults + env when absent; the keyword-only `search` op branch reads the key itself). `resolveHardExcludes` merges defaults + env + caller `SearchOpts.exclude_slug_prefixes`/`include_slug_prefixes`. The surviving exclude policy is auditable via the `hidden_by_search_policy` doctor check (`src/commands/doctor/checks/calibration.ts`, local + remote paths) which counts chunked pages withheld per active exclude prefix, reusing `resolveHardExcludes` + `buildVisibilityClause` + the exported `escapeLikePattern`.- `src/core/search/provenance-demotion.ts` — `applyGeneratedDemotion(engine, list, query, scope)`, called first in `applyIdentityBoosts` (hybrid/request.ts) on the fused path and both keyword-only paths, so it runs before reranking and before the pool is cut. Rows whose page carries a gbrain-owned marker (frontmatter `dream_generated: true`, type `extract_receipt`) get `provenance: 'generated'`; such a row is multiplied by `GENERATED_FACTOR` (0.5, stamped `generated_demotion`) only when the query names an entity (`resolveQueryEntity`), the page links to it, and a non-generated row in the pool is the entity page or links to it. `recordsCorrection` (frontmatter `supersedes`/`corrects`, a facts-fence row with `valid_until`) exempts corrections. `search.demote_generated=false` keeps scores. Tests: `test/search-provenance-demotion.test.ts`.diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 8227e8bf3f..834e3ce8e0 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -11,7 +11,7 @@ The page-state concurrency foundation under `src/core/page-state/` and the shareEmbedding-only publication also requires a live, unarchived source and nondeleted page under the same source/page row locks. A prepared vector cannot bypass a later archive, model change or withdrawal. `test/e2e/migration-wave-prepared-withdrawal.test.ts` exercises both publication orders and exact unchanged-vector refusal on both engines.-- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction.+- `src/core/page-state/version-types.ts` — complete canonical version contract with nullable legacy fields, re-exported by `types.ts` for existing callers. `page-state/versions.ts` records deletion, timeline, tags and originating revision in the page publication transaction. Wave B: a segmented page's version references its body generation (`body_storage: 'segmented'`, `body_generation`, `body_bytes`, `content_hash`, NULL bodies; O(1)); `pruneSegmentedVersions` keeps the newest `versions.segmented_max_per_page` and prunes oldest-first while bytes pinned beyond the live generation exceed max(`versions.segmented_max_pinned_bytes`, body_bytes), then `sweepSegments`; `get_versions` returns their size and, with `include_body`, a `body_ref`; `revert_version` refuses them with `page_body_segmented` until PR 3. `LARGE_PAGE_VERSIONS_KEPT` lives in `page-body/limits.ts`.- `src/core/progressive-batch/` — shared ramp-up + cost-cap + verification primitive (trial 10 → ramp 100 → ramp 500 → full, with verification at each stage), with verifier+policy injection (callers describe HOW TO MEASURE SUCCESS, not WHEN TO WAIT FOR CTRL-C). Modules: `types.ts` (Stage, StageVerdict, AbortReason, discriminated `Verifier` union `OutputCountVerifier | IdempotentMutationVerifier | NoopVerifier`, Policy, StageReport), `orchestrator.ts` (`runProgressiveBatch(items, verifier, policy, runner)` — reads `getCurrentBudgetTracker()` ahead of `Policy.maxCostUsd` fail-closed; null both ways triggers `abort_cost_cap reason='no_budget_safety_net'`), `audit.ts` (ISO-week JSONL at `~/.gbrain/audit/progressive-batch-YYYY-Www.jsonl` via the shared `audit-writer` primitive), `stage-report.ts` (ASCII formatter for the default `Policy.onStageReport`). Env knobs: `GBRAIN_PROGRESSIVE_BATCH_DISABLED=1`, `GBRAIN_PROGRESSIVE_BATCH_AUTO=1` (skip Ctrl-C grace), `GBRAIN_PROGRESSIVE_BATCH_STAGES=10,100,500`. Sites that "jump straight to full" stay that way by default; ramp is opt-in per-site via `Policy.interactiveAbortMs > 0`. Pinned by `test/progressive-batch/orchestrator.test.ts` (35 cases, every verdict path).diff --git a/docs/architecture/key-files/files-and-sync-2.md b/docs/architecture/key-files/files-and-sync-2.mdindex 49679ac62f..1e730bf55a 100644--- a/docs/architecture/key-files/files-and-sync-2.md+++ b/docs/architecture/key-files/files-and-sync-2.md@@ -3,7 +3,7 @@[Subsystem index](../KEY_FILES.md). Read only the entries relevant to your change.Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.-- `src/core/import-chunk-reuse.ts` — `reuseStoredChunkVectors`: A13 vector reuse for one markdown page import, shared by the inline import (before its transaction, to decide which chunks reach the provider) and every import's transaction (under the page lock, `importFromContent` in `import-file.ts`). It copies each stored vector the reuse gate admits onto its matching new chunk and maps the chunk to the stored row id when that row already holds exactly what the chunk would insert, so the import keeps it in place and deletes and writes only the rest; with `keepUnembedded` (the in-transaction pass) an identical never-embedded row stays under a new chunk that carries no vector either. Inline, `--no-embed` and prepared imports all keep rows; a prepared import reuses nothing from a page stored under per-chunk synopsis. Pinned by `test/import-inline-chunk-keep.test.ts` (both engines) and `test/persistence-edit-embedding-reuse.test.ts`.+- `src/core/import-chunk-reuse.ts` — `reuseStoredChunkVectors`: A13 vector reuse for one markdown page import, shared by the inline import (before its transaction, to decide which chunks reach the provider) and every import's transaction (under the page lock, `importFromContent` in `import-file.ts`). It copies each stored vector the reuse gate admits onto its matching new chunk and maps the chunk to the stored row id when that row already holds exactly what the chunk would insert, so the import keeps it in place and deletes and writes only the rest; with `keepUnembedded` (the in-transaction pass) an identical never-embedded row stays under a new chunk that carries no vector either. Inline, `--no-embed` and prepared imports all keep rows; a prepared import reuses nothing from a page stored under per-chunk synopsis. Pinned by `test/import-inline-chunk-keep.test.ts` (both engines) and `test/persistence-edit-embedding-reuse.test.ts`. `reuseSegmentChunkVectors` (Wave B) reads only the rows of the retired occurrences with their vectors and applies the same gate and `chunk_source\0chunk_text` plan, so an unchanged chunk inside a rewritten tail keeps its vector.- `src/core/sync-policy.ts` — `isSyncDisabledConfig(config)`: the one predicate for `config.syncEnabled === false` ("excluded from AUTOMATIC/bulk sync"), unwrapping PGLite's JSON-string config scalar via `parseSourceConfig`. Read by the `sync --all` fan-out filter (`src/commands/sync.ts`), autopilot's per-source freshness dispatcher (`src/commands/autopilot.ts`, skip before `queue.add('sync')`) and the full-cycle fan-out (`src/commands/autopilot-fanout.ts`, which drops the `sync` phase + pull from a disabled source's `autopilot-cycle` payload but keeps lint/backlinks/extract and the freshness stamp) and the `sync_enabled` column of `buildSyncStatusReport` (`src/core/sync-status-report.ts`, whose callers pass RAW `SELECT config` rows — a JSON string on PGLite — so a raw cast there contradicted the fan-out filter). Doctor's `checkSyncFreshness` also applies this predicate, including the legacy query fallback: disabled sources contribute neither warnings nor freshness counts; only boolean `false` disables, not the string `'false'`. `checkCycleFreshness` still monitors their maintenance cycles. Pinned by `test/doctor-sync-policy.test.ts` and `test/doctor-cycle-freshness.test.ts`. Deliberately does NOT gate `performSync()`: an explicit `gbrain sync --source <id>` still runs; `sync-cost-gate.ts` keeps its own inline check because it also feeds the explicit single-source cost preview. Pinned by `test/sync-policy.test.ts`, the `#4399` cases in `test/autopilot-fanout-wiring.test.ts` (source-text) and `test/autopilot-fanout.test.ts` (stubbed dispatch).- `src/core/sync-applicability.ts` — agent-first operator wave E4. `syncContentDirectory(engine, {sourceId, repoPath})` resolves the sync root exactly as `performSync` does and returns it when it is a gbrain-owned content directory (under `<GBRAIN_HOME>/.gbrain/content/`, or an owned `--content-root` recorded in the shared-skills setup receipt) with no `.git` at the root; null otherwise (fail-open). `performSync` calls `assertSyncApplicable` first, so such a source refuses with `sync_not_applicable` (reason `content_directory`, fix `gbrain import <dir> [--no-embed] --source <id>`, `git init` named only as an ask-the-user option) before the managed path or the legacy #2964 anchor self-heal could `git init` it. `sync --all` skips these sources with one line; the dream cycle's sync phase reports them `skipped` (`details.reason: sync_not_applicable`). The CLI `sync` record renders fix-carrying OperationErrors through `renderCliError` (`src/cli/commands/sync.ts`). Pinned by `test/sync-applicability.test.ts`.- `src/core/sync-upstream.ts` — upstream observation for remote-tracking sources (#5255/#5176). `observeUpstream(root, syncedCommit)` reads the checkout's `@{upstream}` commit, the newer of the `FETCH_HEAD` and upstream-ref reflog mtimes (the last fetch, pull or push by any process) and `rev-list --count` of upstream commits the synced commit lacks; `recordUpstreamObservation` (called by `performSync` in `src/commands/sync/perform.ts` after every non-dry-run legacy or managed sync, best-effort) writes them to `sources.upstream_checked_at` / `upstream_commit` / `upstream_behind`, which `managed_writer_guard` does not protect. `upstreamFreshness` is doctor `sync_freshness`'s separate "upstream checked" verdict (a `remote_url` source with no observation or one at least 24 h old is upstream unknown; any observed upstream lead is behind), DB-only so remote doctor runs it. `managedPullWarning` / `UpstreamRefresh` back the cycle sync phase (`runPhaseSync` in `src/core/cycle.ts`), which runs a managed `pull: true` as no-pull and reports `details.upstream_refresh` (`pulled|failed|skipped_managed|not_requested`) plus a `managed_pull_skipped` warning when the checkout tracks an upstream. A managed brain's fix (the warning and doctor's behind/unknown verdict) is `gbrain sources refresh <source>`; an unmanaged one's is `gbrain sync --source <source>`. Tests: `test/managed-cycle-pull-upstream.test.ts`, the pull row of `test/managed-phase-matrix.test.ts`.diff --git a/docs/architecture/key-files/providers.md b/docs/architecture/key-files/providers.mdindex fa7364e06e..5791a54b63 100644--- a/docs/architecture/key-files/providers.md+++ b/docs/architecture/key-files/providers.md@@ -25,7 +25,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/embed-skip.ts` — 5-site shared predicate for the soft-block embed-skip filter. Exports `shouldSkipEmbedding(frontmatter): boolean` (JS predicate for callers holding the page in memory), `EMBED_SKIP_SQL_FRAGMENT` (parameterized SQL clause shared by Postgres + PGLite via `executeRaw`), and `buildEmbedSkipMarker(reason: string)` (writes `frontmatter.embed_skip = {at: ISO_TIMESTAMP, reason}` so the JSONB shape stays uniform). The 5 sites: `embed.ts --stale`, `embed.ts --all`, the `embed-stale` Minion helper, plus both engines' `listStaleChunks` + `countStaleChunks`. Single source of truth so the filter cannot drift. Pinned by `test/embed-skip.test.ts` (cross-site invariant + JSONB shape).- `src/core/embedding-state.ts` — #6696 B3 derived embedding state: every chunk, and every live page with no chunk row, in one of `embedded | pending | keyword_only | quarantined | empty | deleted_page_chunks | chunkless_healable` against the ACTIVE embedding column (no stored status). The classifier SQL lives once in `engine-sql/chunks.ts` (`chunkEmbeddingState` reuses `staleChunkWhere`, `chunklessPageState` reuses `chunklessPagesWhere`) behind `BrainEngine.readEmbeddingStateCounts` / `listEmbeddingStateRows`. `readEmbeddingState(engine, { mode, sourceIds })`: `full` is exact; `ops` reads only index-backed counts (the partial index `WHERE <active column> IS NULL`, the frontmatter GIN, the purge index; `embedded` is a planner estimate) and is `status: 'unknown', reason: 'no_covering_index'` without that index, never a scan. `unsearchable` sums pending, quarantined, empty and chunkless_healable (pending drops out on a brain keyless by choice). `embeddingStateFix` builds each state's protocol fix from existing commands. Consumers: doctor `embedding_state`, `gbrain pages unsearchable`, lane B's `get_brain_health`. Tests: `test/embedding-state.test.ts`.-- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`.+- `src/core/embed-stale.ts` — source-wide stale embedding and explicit-page completion keep vector installation, complete-provenance signature checks and title-tier demotion in one page-guarded transaction. The three `src/commands/embed.ts` paths use the same transaction boundary; providers run before it. Standalone/background projection recovery preserves NULL-signature grandfathering and existing stale eligibility; the job's deadline, abort signal and source lease fence recovery, invalidation and publication. Oversized-chunk healing checks ownership and stop conditions before and after its transaction, rolling back prepared changes on loss. The restamp always uses the captured page metadata, so a later same-revision contextual rebuild cannot retain its vectors while an older completion overwrites its mode or corpus generation. `persistence/effects.ts` also retains this atomic completion boundary. `test/embedding-completion-atomic.serial.test.ts` exercises all five completion paths; `test/e2e/migration-wave-healing-fence.test.ts` pins healing rollback on both engines. #5902: without an explicit `concurrency`, `embedStaleForSource` (the unpaced `embed-backfill` job and the remediation embed step) runs `resolveStaleEmbedConcurrency` workers from `src/core/embed-concurrency.ts`: `min(20, max(1, floor(poolMax/2)))` of the engine's real pool (`getPoolDiagnostics().poolMax`, a worker's instance pool included), 20 without a pool; an explicit `GBRAIN_EMBED_CONCURRENCY` keeps the full-pool clamp. Pinned by `test/embed-stale-pool-default.test.ts` + `test/e2e/embed-stale-pool-default-postgres.test.ts`. Wave B: a segmented page is embedded by `page-body/segmented-embedding.ts` (vector-less live rows by chunk_index keyset with the title and plain tier, metered per page, installed by chunk_index and exact text onto rows still in the live generation; never the body or every chunk), from here, `gbrain embed` and the post-commit embedding effect (`data.occurrence_ids` limits an append's effect to the new occurrences).- `src/core/embed-stale-images.ts` — `gbrain embed --stale --images [--source <id>] [--dry-run] [--json]` (requires `GBRAIN_EMBEDDING_MULTIMODAL=true`): selects live image pages whose index `importImageFile`'s hash-skip would call incomplete (unsealed or stale projection, no `embedding_image` chunk, or no OCR text/`ocr_status: done` while `GBRAIN_EMBEDDING_IMAGE_OCR=true`), resolves each file from the source's `local_path` (the `default` source falls back to `sync.repo_path`; a subpath-scoped `source_path` resolves against the checkout's git root; a page with no recorded `source_path` is located by its slug, which is the lower-cased repo-relative path, and counted in `missingSourcePath`) and hands it back to the importer, so OCR budget, protected-OCR refusal and the rebuild stay there. #6529: on a managed brain the import goes through `importManagedFile` (the coordinated importer; the legacy writer refuses a managed brain), only for a file inside the source root, and the import records `source_path`. Reports candidates, rebuilt, unchanged, missing source files (`missing_samples`: up to 5 `source:slug: no file at <path tried>` lines, the first printed) and failures; the explicit `--images` CLI (`runEmbedStaleImagesCli`) counts an all-missing, nothing-rebuilt sweep as failures (`sweepFoundNoFiles`), so it never exits 0 as a quiet success. `runStaleImageSweepFirst` is the sweep a plain `gbrain embed --stale` (no `--slugs`) runs before its text drain when multimodal embedding is on, and `foldImageSweep` folds it into the `EmbedResult` as `images`: import failures count toward the run's failures, fileless pages are reported once on stderr (`missingFile`, first sample) and leave the exit code to the text run; a text-only install skips it and keeps the `--images` hint. Pinned by `test/embed-stale-images.test.ts` and `test/embed-stale-images-managed-6529.test.ts` (both engines). Under a cost cap (fix wave 13 P1.18) each import is metered and the sweep stops before the next image once the cap refused; a refused image is not a failure.- `src/core/embed-budget-stop.ts` — the loud time-budget stop for `gbrain embed --stale`. `noteEmbedBudgetStop(engine, result, {sourceId, signature, includeNullSignature, skip})` counts the stale chunks left (same predicate as the catch-up remaining count) and, when any remain, sets `reason: 'time_budget'`, `remaining_stale` and `resume_command` (`gbrain embed --stale --catch-up [--source X] [--include-null-signature]`) on the result; `skip` covers dry runs, `--catch-up` and caller aborts. `embedBudgetStopVerdict(result)` is the stdout verdict `runEmbed` prints; `src/cli/commands/embed.ts` maps the reason to `BUDGET_STOP_EXIT_CODE` (failures still win with 1). Called from every budget exit in `embedAllStale` (readiness-phase deadline returns and the main drain). Pinned by `test/embed.serial.test.ts` ("time-budget stop is loud").diff --git a/package.json b/package.jsonindex 1baa3b87ef..ec666955de 100644--- a/package.json+++ b/package.json@@ -158,6 +158,7 @@"check:durable-flush": "bun scripts/check-durable-flush.ts","check:windows-hide": "bun scripts/check-windows-hide.ts","check:engine-sql-ratchet": "bun scripts/check-engine-sql-ratchet.ts",+ "check:chunk-visibility": "bun scripts/check-chunk-visibility.ts","check:engine-sql-dynamic": "bun scripts/check-engine-sql-dynamic.ts","check:engine-sql-brands": "bun scripts/check-engine-sql-brands.ts","check:sync-run-state": "bun scripts/check-sync-run-state.ts",diff --git a/scripts/check-chunk-visibility.ts b/scripts/check-chunk-visibility.tsnew file mode 100644index 0000000000..748becfbe0--- /dev/null+++ b/scripts/check-chunk-visibility.ts@@ -0,0 +1,255 @@+#!/usr/bin/env bun+/**+ * Chunk-visibility ratchet (Wave B large pages, spec 4.2). This header is its+ * documentation (docs/TESTING.md is at its byte cap); `bun run check:chunk-visibility`, in `bun run verify`.+ *+ * A segmented page stages chunk rows under a body generation above the page's+ * (invisible until the generation flip) and retires rows by generation, so a+ * `content_chunks` reader that skips the generation predicate can serve staged+ * rows of an unpublished write or retired rows of an old body. This guard+ * parses every `src/**\/*.ts` file (TypeScript compiler API) and finds each+ * string or template literal whose own literal text reads `FROM content_chunks`+ * or `JOIN content_chunks` (`DELETE FROM` is a write and never counts). Such a+ * statement is covered when:+ *+ * - its source text (substitutions included) calls `chunkVisibleFilter(`,+ * `chunkGenerationFilter(` or `chunkGenerationProbe(`+ * (`src/core/search/safe-chunks.ts`), or `buildVisibilityClause(...)` with+ * a chunk alias, or names a function or variable declared in the same file+ * whose declaration does (transitively), or+ * - it carries a marker with a non-empty reason: `-- chunk-visibility-ok: <reason>`+ * inside the SQL, or `// chunk-visibility-ok: <reason>` on the literal's first+ * line or the line directly above it.+ *+ * Every uncovered statement counts against its file's row in+ * scripts/chunk-visibility-baseline.tsv (`<path><TAB><count>`). Rows only shrink:+ *+ * 1. a file with more uncovered statements than its row (or no row) -> FAIL (new)+ * 2. a file with fewer uncovered statements than its row -> FAIL (stale; lower the row)+ * 3. a duplicate or malformed row, or a marker with an empty reason -> FAIL+ *+ * `--prune` rewrites the baseline with the current (lower) counts; nothing ever+ * raises a row. Seam: GBRAIN_GUARD_ROOT (fixture tree root; baseline read from+ * <root>/scripts/chunk-visibility-baseline.tsv).+ */+import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';+import { join, relative } from 'node:path';+import ts from 'typescript';++/** `ts.getTokenAtPosition` is exported at runtime but absent from typescript's public declarations. */+const tsInternal = ts as typeof ts & { getTokenAtPosition(sourceFile: ts.SourceFile, position: number): ts.Node };++const ROOT = process.env.GBRAIN_GUARD_ROOT ?? join(import.meta.dir, '..');+const BASELINE_REL = 'scripts/chunk-visibility-baseline.tsv';+const ANCHOR = 'scripts/check-chunk-visibility.ts (header)';+const MARKER = 'chunk-visibility-ok';+const READ = /(?<!\bdelete\s{1,40})\b(?:from|join)\s+content_chunks\b/i;+const COVERED = /\bchunk(?:VisibleFilter|GenerationFilter|GenerationProbe)\(|\bbuildVisibilityClause\(\s*'\w+'\s*,\s*'\w+'\s*,(?:[^()]|\([^()]*\))*?,\s*'\w+'\s*\)/;+const SQL_MARKER = new RegExp(String.raw`--\s*${MARKER}:([^\n]*)`);++export interface Statement {+ path: string;+ line: number;+ covered: boolean;+ /** Line of a marker whose reason is empty. */+ emptyMarker: number | null;+}++function tsFiles(dir: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const entry of readdirSync(dir).sort()) {+ const full = join(dir, entry);+ if (statSync(full).isDirectory()) out.push(...tsFiles(full));+ else if (entry.endsWith('.ts') && !entry.endsWith('.d.ts')) out.push(full);+ }+ return out;+}++function ownLiteralText(node: ts.Node): string | null {+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;+ if (ts.isTemplateExpression(node)) return [node.head.text, ...node.templateSpans.map(span => span.literal.text)].join(' _sub_ ');+ return null;+}++function lineComments(sf: ts.SourceFile): Map<number, string> {+ const text = sf.getFullText();+ const out = new Map<number, string>();+ const re = new RegExp(String.raw`//\s*${MARKER}\b(:?)([^\n]*)`, 'g');+ for (let m = re.exec(text); m; m = re.exec(text)) {+ const token = tsInternal.getTokenAtPosition(sf, m.index);+ if (token.getStart(sf) <= m.index && m.index < token.end) continue;+ out.set(sf.getLineAndCharacterOfPosition(m.index).line + 1, m[1] ? m[2].trim() : '');+ }+ return out;+}++/** Identifiers referenced inside a node (substitutions and call arguments; never literal text). */+function identifiers(node: ts.Node): Set<string> {+ const out = new Set<string>();+ const visit = (n: ts.Node): void => {+ if (ts.isIdentifier(n)) out.add(n.text);+ ts.forEachChild(n, visit);+ };+ visit(node);+ return out;+}++interface Decl { name: string; covered: boolean; refs: Set<string> }++function enclosingScope(node: ts.Node): ts.Node {+ for (let n = node.parent; n; n = n.parent) if (ts.isFunctionLike(n) || ts.isSourceFile(n)) return n;+ return node.getSourceFile();+}++/** Functions and variables declared directly in each scope (function body or file). */+function scopeDecls(sf: ts.SourceFile): Map<ts.Node, Decl[]> {+ const out = new Map<ts.Node, Decl[]>();+ const visit = (node: ts.Node): void => {+ if ((ts.isFunctionDeclaration(node) || ts.isVariableDeclaration(node)) && node.name && ts.isIdentifier(node.name)) {+ const body = ts.isFunctionDeclaration(node) ? node.body : node.initializer;+ if (body) {+ const scope = enclosingScope(node);+ out.set(scope, [...(out.get(scope) ?? []), { name: node.name.text, covered: COVERED.test(body.getText(sf)), refs: identifiers(body) }]);+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(sf);+ return out;+}++/** Names visible from `node` (its scope chain) whose declarations apply the predicate, transitively. */+export function coveringNames(node: ts.Node, decls: Map<ts.Node, Decl[]>): Set<string> {+ const visible: Decl[] = [];+ for (let scope: ts.Node | undefined = enclosingScope(node); scope; scope = ts.isSourceFile(scope) ? undefined : enclosingScope(scope)) {+ visible.push(...(decls.get(scope) ?? []));+ }+ const names = new Set<string>();+ for (let grew = true; grew;) {+ grew = false;+ for (const d of visible) {+ if (names.has(d.name) || !(d.covered || [...d.refs].some(r => names.has(r)))) continue;+ names.add(d.name);+ grew = true;+ }+ }+ return names;+}++function covers(node: ts.Node, decls: Map<ts.Node, Decl[]>): boolean {+ const names = coveringNames(node, decls);+ return [...identifiers(node)].some(id => names.has(id));+}++export function scanFile(abs: string, rel: string): Statement[] {+ const sf = ts.createSourceFile(abs, readFileSync(abs, 'utf8'), ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ const comments = lineComments(sf);+ const decls = scopeDecls(sf);+ const out: Statement[] = [];+ const visit = (node: ts.Node): void => {+ const literal = ownLiteralText(node);+ if (literal !== null && READ.test(literal)) {+ const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;+ const sqlMarker = SQL_MARKER.exec(literal);+ const commentLine = comments.has(line) ? line : comments.has(line - 1) ? line - 1 : null;+ const reason = sqlMarker ? sqlMarker[1].trim() : commentLine !== null ? comments.get(commentLine)! : null;+ out.push({+ path: rel,+ line,+ covered: COVERED.test(node.getText(sf)) || covers(node, decls) || !!reason,+ emptyMarker: reason === '' ? (commentLine ?? line) : null,+ });+ }+ ts.forEachChild(node, visit);+ };+ visit(sf);+ return out;+}++export function scanTree(root: string): Statement[] {+ return tsFiles(join(root, 'src')).flatMap(abs => scanFile(abs, relative(root, abs).replace(/\\/g, '/')));+}++interface Row { lineNo: number; raw: string; path: string; count: number; malformed: boolean }++function parseBaseline(text: string): Row[] {+ const rows: Row[] = [];+ text.split('\n').forEach((raw, i) => {+ if (raw.trim() === '' || raw.startsWith('#')) return;+ const cols = raw.split('\t');+ const count = Number(cols[1]);+ const malformed = cols.length !== 2 || !cols[0] || !Number.isInteger(count) || count < 1;+ rows.push({ lineNo: i + 1, raw, path: cols[0] ?? '', count, malformed });+ });+ return rows;+}++if (import.meta.main) {+ const prune = process.argv.includes('--prune');+ const baselinePath = join(ROOT, BASELINE_REL);+ if (!existsSync(baselinePath)) {+ console.error(`FAIL: ${BASELINE_REL}:1 baseline file missing`);+ console.error(`Fix: git checkout ${BASELINE_REL}`);+ console.error(`See: ${ANCHOR}`);+ process.exit(1);+ }+ const baselineText = readFileSync(baselinePath, 'utf8');+ const rows = parseBaseline(baselineText);+ const statements = scanTree(ROOT);+ const uncovered = new Map<string, Statement[]>();+ for (const s of statements) {+ if (s.covered) continue;+ uncovered.set(s.path, [...(uncovered.get(s.path) ?? []), s]);+ }+ const violations: string[] = [];+ const allowed = new Map<string, number>();+ const pruned = new Map<number, string | null>();++ for (const s of statements) {+ if (s.emptyMarker !== null) violations.push(`FAIL: ${s.path}:${s.emptyMarker} ${MARKER} marker has no reason\n Fix: write '${MARKER}: <why this reader may see staged or retired chunk rows>'`);+ }+ for (const row of rows) {+ const where = `${BASELINE_REL}:${row.lineNo}`;+ if (row.malformed) {+ violations.push(`FAIL: ${where} malformed row '${row.raw}'\n Fix: use '<path><TAB><positive count>'`);+ continue;+ }+ if (allowed.has(row.path)) {+ pruned.set(row.lineNo, null);+ violations.push(`FAIL: ${where} duplicate row for ${row.path}\n Fix: delete this line (or: bun scripts/check-chunk-visibility.ts --prune)`);+ continue;+ }+ allowed.set(row.path, row.count);+ const found = uncovered.get(row.path)?.length ?? 0;+ if (found < row.count) {+ pruned.set(row.lineNo, found === 0 ? null : `${row.path}\t${found}`);+ violations.push(`FAIL: ${where} stale row: ${row.path} has ${found} uncovered content_chunks reader(s), the row allows ${row.count}\n Fix: lower the row to ${found}${found === 0 ? ' (delete it)' : ''}; rows only shrink (or: bun scripts/check-chunk-visibility.ts --prune)`);+ }+ }+ for (const [path, list] of uncovered) {+ const limit = allowed.get(path) ?? 0;+ if (list.length <= limit) continue;+ const lines = list.map(s => s.line).join(', ');+ violations.push(`FAIL: ${path}:${list[0].line} ${list.length} content_chunks reader(s) without the chunk-visibility predicate (lines ${lines}), the baseline allows ${limit}\n Fix: add \${chunkVisibleFilter('p', 'cc')} (search-facing) or \${chunkGenerationFilter('p', 'cc')} (maintenance), or mark the statement '-- ${MARKER}: <reason>'`);+ }++ if (prune) {+ const kept = baselineText.split('\n').flatMap((line, i) => {+ const next = pruned.get(i + 1);+ return next === undefined ? [line] : next === null ? [] : [next];+ });+ writeFileSync(baselinePath, kept.join('\n'));+ console.log(`check-chunk-visibility: pruned ${pruned.size} row(s) in ${BASELINE_REL}`);+ process.exit(0);+ }+ if (violations.length) {+ for (const v of violations) console.error(v);+ console.error('Why: staged chunk rows (body_generation above the page) and retired rows must never reach search, chunk reads or embedding.');+ console.error(`See: ${ANCHOR}`);+ console.error(`check-chunk-visibility: ${violations.length} violation(s)`);+ process.exit(1);+ }+ const covered = statements.filter(s => s.covered).length;+ console.log(`check-chunk-visibility: ok (${covered} covered, ${statements.length - covered} baselined content_chunks readers)`);+}diff --git a/scripts/check-engine-sql-dynamic.ts b/scripts/check-engine-sql-dynamic.tsindex e76d369cf1..2e8002e87a 100644--- a/scripts/check-engine-sql-dynamic.ts+++ b/scripts/check-engine-sql-dynamic.ts@@ -58,6 +58,10 @@ const VETTED_BUILDERS: Record<string, string> = {currentCodeEdgeFilter: 'src/core/code-intel/read-scope.ts: constant current-edge predicate over a caller alias',buildCJKKeywordSql: 'src/core/search/cjk-keyword-sql.ts: binds the query as params; shared by both engines',currentTextProjectionFilter: 'src/core/search/safe-chunks.ts: constant projection predicate over a caller alias',+ chunkVisibleFilter: 'src/core/search/safe-chunks.ts: constant projection + live body generation predicate over caller page/chunk aliases (Wave B)',+ chunkGenerationFilter: 'src/core/search/safe-chunks.ts: constant live body generation predicate over caller page/chunk aliases (Wave B)',+ chunkManifestJoin: 'src/core/search/safe-chunks.ts: constant LEFT JOIN onto the live page_body_manifest row over caller aliases (Wave B)',+ chunkDocumentOrder: 'src/core/search/safe-chunks.ts: constant ORDER BY column list over caller chunk/manifest aliases (Wave B)',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',diff --git a/scripts/chunk-visibility-baseline.tsv b/scripts/chunk-visibility-baseline.tsvnew file mode 100644index 0000000000..5db9233562--- /dev/null+++ b/scripts/chunk-visibility-baseline.tsv@@ -0,0 +1,50 @@+# path<TAB>uncovered content_chunks readers (rows only shrink)+src/commands/code-def.ts 2+src/commands/code-refs.ts 1+src/commands/config.ts 1+src/commands/doctor/checks/calibration.ts 1+src/commands/doctor/checks/data-integrity.ts 2+src/commands/doctor/checks/embedding-health.ts 2+src/commands/doctor/checks/extraction-sync.ts 1+src/commands/doctor/checks/graph-embedding.ts 1+src/commands/doctor/checks/image-embedding-coverage.ts 1+src/commands/doctor/checks/schema-health.ts 1+src/commands/doctor/checks/vector-plan.ts 2+src/commands/reindex-multimodal.ts 4+src/commands/reindex-search-vector.ts 1+src/core/code-graph-readiness.ts 2+src/core/code-intel/read-scope.ts 1+src/core/code-intel/recursive-walk.ts 4+src/core/destructive-guard.ts 2+src/core/embed-consent.ts 2+src/core/embed-stale-images.ts 1+src/core/embedding-invalidation.ts 4+src/core/embedding-migration-retention.ts 1+src/core/embedding-migration-worst-case.ts 2+src/core/embedding-migration.ts 8+src/core/embedding-readiness.ts 3+src/core/engine-sql/chunks.ts 5+src/core/engine-sql/code-edges.ts 1+src/core/engine-sql/health.ts 1+src/core/engine-sql/pages.ts 2+src/core/entities/resolve.ts 2+src/core/facts/purge-verify.ts 2+src/core/facts/withdrawal-discovery.ts 1+src/core/import-chunk-reuse.ts 1+src/core/import-file.ts 1+src/core/onboard/mcp-onboarding.ts 1+src/core/oversized-backfill.ts 2+src/core/page-state/contextual-proof.ts 1+src/core/page-state/projections.ts 2+src/core/persistence/embedding-noop-settle.ts 1+src/core/persistence/page-purge.ts 1+src/core/pglite-engine.ts 1+src/core/postgres-engine.ts 1+src/core/repair/contextual-mode.ts 1+src/core/schema-migrations/v116-code-edges-source-backfill-and-callee-index.ts 1+src/core/search-vector-backfill.ts 1+src/core/source-health.ts 1+src/core/sync-status-report.ts 1+src/eval/brainbench/metrics/deletion.ts 1+src/eval/brainbench/metrics/trust-reads.ts 1+src/eval/longmemeval/retrieval-arms.ts 1diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 2b98089d9a..b677fd849d 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -13,7 +13,7 @@ src/commands/doctor/bootstrap-checks.ts bootstrapDoctorChecks 476 seed: W5 baselsrc/commands/doctor/checks/extraction-sync.ts checkSyncFreshness 333 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/doctor/report-remote.ts doctorReportRemote 416 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/dream-retriage.ts runDreamRetriage 524 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/embed.ts embedAllStale 569 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary; +4 wave 8 lane D1 #5527: subtract current-model chunks from the mixed-space warning; +2 Foundations 1 F4d: a time-budget stop with stale chunks left records reason, remaining count and resume command (src/core/embed-budget-stop.ts); +3 TODO: large-pages A9/T3: per-page spend cap meters each page (logic in core/page-embedding-budget.ts meterStaleBatch/spendGrant)+src/commands/embed.ts embedAllStale 570 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +9 #5804: a null projection snapshot is a counted failure (archived sources left to reportArchived) with one end-of-run batch summary; +4 wave 8 lane D1 #5527: subtract current-model chunks from the mixed-space warning; +2 Foundations 1 F4d: a time-budget stop with stale chunks left records reason, remaining count and resume command (src/core/embed-budget-stop.ts); +3 TODO: large-pages A9/T3: per-page spend cap meters each page (logic in core/page-embedding-budget.ts meterStaleBatch/spendGrant); +1 TODO: large-pages Wave B PR 1 lane 1e: a segmented page's stale rows route to the keyset sweep (logic in core/page-body/segmented-embedding.ts)src/commands/embed.ts runEmbedCore 381 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +5 wave 8 lane D1 #5885: stale-drain takes pass call and its watchdog progress countersrc/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/extract-conversation-facts.ts processPage 320 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes); +12 fix wave 9 lane P (#5025, D-N2): not-extractable skip call (decision in facts/conversation-skip.ts) and the email-thread segment gapdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 902ef453cc..850b5234b6 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -6,7 +6,7 @@src/cli/main.ts 3009 ratchet +1 Cat 41 run 4: recall's SELF_HELP_WITHOUT_ENGINE table entry (a dispatch table row cannot move); moved from src/cli.ts at 3214 (cold start: src/cli.ts is now the 66-line entry with the --version/help fast path; the top-level help text moved to cli/top-help.ts and the exit seam became runCli/exitOnFatalCliError); +2 #6340: the sync status / sync unblock preflight skip (logic in commands/sync/operator.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +2 retrieval feedback: answer id line on stderr and additive answer_id on --json search/query rows (logic in feedback/record.ts); +1 feedback help line and its D3 table-dispatch entry (logic in commands/feedback.ts); 6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x engine graduation composition: both deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); P3 x foundations-2 composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); P3 x P1 (v0.60.57.0) composition: deltas re-summed at the merge; 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); 1 Foundations 2 Lane F: sources refresh pre-connect delegation to a resident PGLite owner (logic in commands/sources-refresh-delegate.ts); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +3 agent operator gate fixes: repair-failed connect wrapper (logic in cli/cli-error.ts exitOnRepairFailed), transcripts recent through a live serve (logic in commands/transcripts.ts), pre-connect status reason (logic in commands/serve-status.ts); +23 merged from the collector (Lanes B/E/F: thin-client token reason, status-only serve hand-off, jobs/sync readiness wiring); +9 agent operator wave D3/D4: curated --help short-circuit (renderer in cli/help/render.ts), curated flag-value validation call (cli/help/validate.ts), table-dispatched SELF_HELP_WITHOUT_ENGINE entries for the selfHelp flips; +5 agent operator wave C10 (merged from the collector): serve --fail-fast in the connect-failure path; +31 #5950 (D6): connectEngine thin-client backstop, engine-free MCP-twin dispatch, recall/advisor/export refusal hints, refusal fix subcommand (lowered to 3131 by D1's renderCliError seam first); +2 agent operator wave A4: observational startup (probe-only connect for startup:observational commands; completeEngineStartup split out of connectEngine, exposed as ctx.completeStartup); +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5232: write-wait import, reporter-owned verdict in the op catch, thin-client writeWaitMs, ctx.writeWaitMs (logic in persistence/write-wait.ts); +1 #4768: serve --access help line; +4 #5433: list_pages TSV cell escaping in formatResult; +2 #lane-h pricing: help line + thin-client refusal hint for `gbrain pricing`; +2 fix wave 5 (#5401): projections drain help line and thin-client hint; +2 (#5137) key-shadow warning seam, logic in ai/key-warnings.ts; +2 System One v1: decide help line + thin-client refusal hint; refactor wave 1 split target (W4 cli); ceiling rationale: docs/architecture/key-files/entrypoints-and-docs.md entry for src/cli.ts; evidence delivery: thin-client return_unit version-skew warning (+3; logic in search/evidence-delivery.ts); put stdin recovery (#5700): stdin hint in the --content requires-a-value error and stdin usage/required text in printOpHelp (+7); logic in persistence/deactivation.ts); +36 #5827: link-command help examples, local --source vs --source-id/--all-sources conflict check, ambient-binding return from applyThinClientSourceScope (logic in cli/source-scope.ts); +4 #5433: list_pages TSV cell escaping in formatResult; +1 #5984: a strict run deadline when no progress window is set; v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (3199 measured); +6 engine graduation (GBRA-50 G3): migrate pre-connect route (logic in commands/migrate-graduation.ts), serve start refusal and degraded-reconnect identity gate (logic in persistence/graduation-serve-guard.ts), usage line; +3 engine graduation (GBRA-50 G2a): connect-path graduation check on every engine (logic in persistence/graduation-custody.ts assertGraduationConnectAllowed); GBRA-49: edge-proposals answers --help without a brain (SELF_HELP_WITHOUT_ENGINE row); -25 agent-operator follow-up Item 3: the host connect moved to core/engine-connect.ts (throw-only connectEngineForServe, wrapped by connectEngine; the graduation connect gate moved with it); +2 entity recall: the human `gbrain entity` card prints referenced_by groups and a non-complete mention coverage; cat40 entity wave merge with v0.60.61.0 (3179 measured); +3 #4772 (W14 PR3): get_health text output says the entity ratios are n/a because the schema pack did not load (entity_types_status); +1 C4: gbrain questions CLI-only dispatch row (its help line is in cli/top-help.ts); +1 #6696 (A4): a local write captures the capacity notices (one call; logic in cli/op-notices.ts captureCapacityNotices); +1 large pages A6: the stdin cap reads PAGE_MAX_BYTES from core/page-size-policy.tssrc/commands/autopilot.ts 1642 ratchet refactor wave 1 split target (W4 autopilot, cut line); ceiling rationale: docs/architecture/key-files/commands-1.md entry for src/commands/autopilot.ts; +2 fix wave 5: nosemgrep justifications on the per-brain job launchctl/systemctl calls (#5195); +2 #5813: boot reconcile names attempted and running versions in log + audit; +2 #5855: Bun floor gate before the swap and the swap-refusal hold (logic in core/bun-floor.ts); +3 agent operator wave E9: --dry-run and the persistent_install consent gate before anything is written (logic in autopilot/install-consent.ts)src/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.ts-src/commands/embed.ts 2265 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+src/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 2087 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 2087src/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 baselinesrc/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 codesdiff --git a/scripts/run-verify-parallel.sh b/scripts/run-verify-parallel.shindex fff9ce6e21..cf553c96b0 100755--- a/scripts/run-verify-parallel.sh+++ b/scripts/run-verify-parallel.sh@@ -177,6 +177,9 @@ CHECKS=(# Goal (a) (refactor wave 1): engine SQL only shrinks; baseline# scripts/engine-sql-baseline.tsv."check:engine-sql-ratchet"+ # Wave B large pages: every content_chunks reader applies the chunk-visibility+ # predicate or carries a reason; baseline scripts/chunk-visibility-baseline.tsv only shrinks.+ "check:chunk-visibility"# CQ3 / EO17 (refactor wave 1): engine-sql splices only constant text, no# composed $n, no expanded IN lists."check:engine-sql-dynamic"diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex f79dd5ffca..9811088b4b 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -51,6 +51,7 @@ export { resolveEmbedConcurrency, _resetEmbedConcurrencyClampWarningForTest } frimport { isEmbeddingZeroNormError } from '../core/ai/embedding-guard.ts';import { wrapChunkTextsForStoredMode } from '../core/embedding-context.ts';import { heldEmbedArgv, meterPageBatch, spendGrant } from '../core/page-embedding-budget.ts';+import { countSegmentedEmbedRows, embedSegmentedPage, readSegmentedEmbedPage, type SegmentedEmbedPage } from '../core/page-body/segmented-embedding.ts';import {restampIfDemotedToTitleTier,embedBatchWithBackoff,@@ -1064,6 +1065,34 @@ export async function runEmbed(engine: BrainEngine, args: string[], selectedConf}}+/**+ * Wave B: embed a segmented page's vector-less live rows by keyset+ * (`embedSegmentedPage`), never through its body or a whole-page chunk read.+ * A dry run only counts those rows.+ */+async function embedSegmented(engine: BrainEngine, page: SegmentedEmbedPage, result: EmbedResult,+ opts: { dryRun: boolean; signal?: AbortSignal; signature?: string; approvedCapUsd?: number }): Promise<void> {+ if (opts.dryRun) {+ const counts = await countSegmentedEmbedRows(engine, page.id);+ result.total_chunks += counts.total;+ result.would_embed += counts.stale;+ result.pages_processed++;+ return;+ }+ try {+ const done = await embedSegmentedPage(engine, page, { embedFn: (texts, o) => embedBatchWithBackoff(texts, o),+ signal: opts.signal, signature: opts.signature, approvedCapUsd: opts.approvedCapUsd });+ result.embedded += done.embedded;+ const stamp = done.complete ? await resolveProvenanceStamp(engine, opts.signature) : undefined;+ if (stamp) await stampIfPageProvenanceComplete(engine, page.slug, page.source_id, stamp);+ if (done.stopped === 'page_moved') recordFailure(result, 1, page.slug, EMBED_UNAVAILABLE_MESSAGE);+ } catch (e: unknown) {+ if (isAborted(opts.signal)) throw e;+ recordFailure(result, 1, page.slug, e);+ }+ result.pages_processed++;+}+async function embedPage(engine: BrainEngine,slug: string,@@ -1079,6 +1108,12 @@ async function embedPage(if (!initial) {throw new Error(`Page not found: ${slug}`);}+ const segmented = await readSegmentedEmbedPage(engine, { sourceId: initial.page.source_id, slug });+ if (segmented) {+ if (isEmbedSkipped(initial.page.frontmatter)) { if (!quiet) serr(` ${slug}: skipped (frontmatter.embed_skip set); its chunks stay keyword-searchable`); return; }+ await embedSegmented(engine, segmented, result, { dryRun, signal, signature: currentEmbeddingSignature() ?? undefined, approvedCapUsd: approvedPageCapUsd });+ return;+ }const origin = await readProjectionSnapshot(engine, slug, initial.page.source_id, { allowUnsealed: true, requireLiveSource: !dryRun });if (!origin || origin.snapshot.revision !== initial.revision || origin.snapshot.page.id !== initial.page.id|| origin.snapshot.sourceIncarnation !== initial.sourceIncarnation) {@@ -1336,6 +1371,8 @@ async function embedAll(// target the correct (source_id, slug) row, not the 'default' source.const pageSourceId = page.source_id;const pageOpts = pageSourceId ? { sourceId: pageSourceId } : undefined;+ const segmented = await observed(pacer, () => readSegmentedEmbedPage(engine, { id: page.id }));+ if (segmented) { await embedSegmented(engine, segmented, result, { dryRun, signal, signature }); return; }const prepared = await observed(pacer, () => readProjectionSnapshot(engine, page.slug, pageSourceId, { requireLiveSource: !dryRun }));if (!prepared) {if (!dryRun) recordFailure(result, 1, page.slug, EMBED_UNAVAILABLE_MESSAGE);@@ -2041,6 +2078,8 @@ async function embedAllStale(const keySourceId = stale[0]?.source_id ?? 'default';const slug = stale[0].slug;try {+ const segmented = await observed(pacer, () => readSegmentedEmbedPage(engine, { sourceId: keySourceId, slug }));+ if (segmented) { await embedSegmented(engine, segmented, result, { dryRun: false, signal: effectiveSignal, signature }); processedPageKeys.add(key); return; }// SUP-3874: split legacy oversized chunk_text BEFORE the embed call.// `--stale` reuses stored rows; without this, one pre-cap chunk// (e.g. a long pre-cap notes page on a 512-token model) failsdiff --git a/src/core/chunkers/symbol-resolver.ts b/src/core/chunkers/symbol-resolver.tsindex e9431e86c9..b5965bde44 100644--- a/src/core/chunkers/symbol-resolver.ts+++ b/src/core/chunkers/symbol-resolver.ts@@ -55,7 +55,7 @@*/import type { BrainEngine } from '../engine.ts';-import { currentTextProjectionFilter } from '../search/safe-chunks.ts';+import { chunkVisibleFilter } from '../search/safe-chunks.ts';/*** Bump this ISO timestamp whenever the extractor or resolver shape@@ -141,7 +141,7 @@ export async function resolveSymbolEdgesIncremental(JOIN pages p ON p.id = cc.page_idJOIN sources s ON s.id = p.source_idWHERE p.source_id = $1 AND p.deleted_at IS NULL AND NOT s.archived- AND ${currentTextProjectionFilter('p')}+ AND ${chunkVisibleFilter('p', 'cc')}AND (cc.edges_backfilled_at IS NULLOR cc.edges_backfilled_at < $2::timestamptz)ORDER BY cc.id@@ -155,7 +155,7 @@ export async function resolveSymbolEdgesIncremental(`SELECT cc.id, cc.page_id, p.slug FROM content_chunks ccJOIN pages p ON p.id=cc.page_id JOIN sources s ON s.id=p.source_idWHERE cc.id=ANY($1::int[]) AND p.source_id=$2 AND p.deleted_at IS NULL AND NOT s.archived- AND ${currentTextProjectionFilter('p')}+ AND ${chunkVisibleFilter('p', 'cc')}AND (cc.edges_backfilled_at IS NULL OR cc.edges_backfilled_at < $3::timestamptz)ORDER BY cc.id`, [chunks.map(chunk => chunk.id), opts.sourceId, EDGE_EXTRACTOR_VERSION_TS],);@@ -219,6 +219,7 @@ async function processChunkBatch(const candidatesByKey = new Map<string, ChunkCandidate[]>();if (pagesToProbe.length > 0) {const rows = await engine.executeRaw<{ id: number; page_id: number; symbol_name_qualified: string }>(+ // chunk-visibility-ok: code symbol candidates: code pages are never segmented (chooseBodyStorage)`SELECT id, page_id, symbol_name_qualifiedFROM content_chunksWHERE page_id = ANY($1::int[])diff --git a/src/core/content-sanity.ts b/src/core/content-sanity.tsindex d5f5420a05..26b53a1424 100644--- a/src/core/content-sanity.ts+++ b/src/core/content-sanity.ts@@ -361,7 +361,12 @@ export interface SampledJunkAssessment {*/export function assessSampledJunk(body: string, opts: { max_markup_ratio?: number;extra_literals?: ReadonlyArray<OperatorLiteral>; disabled_patterns?: ReadonlyArray<string> }): SampledJunkAssessment {- const windows = sampleWindows(body);+ return assessJunkWindows(sampleWindows(body), opts);+}++/** `assessSampledJunk` over windows the caller already sampled (a segmented page reads them from its segments). */+export function assessJunkWindows(windows: string[], opts: { max_markup_ratio?: number;+ extra_literals?: ReadonlyArray<OperatorLiteral>; disabled_patterns?: ReadonlyArray<string> }): SampledJunkAssessment {const markup_ratios = windows.map(window => assessProse(window).markup_ratio);const max = opts.max_markup_ratio ?? DEFAULT_MAX_MARKUP_RATIO;const hits = windows.filter(window => {diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.tsindex fe0e5af46e..1e4835f1ba 100644--- a/src/core/embed-stale.ts+++ b/src/core/embed-stale.ts@@ -21,7 +21,7 @@ import { readContentChunksEmbeddingDim } from './embedding-dim-check.ts';*/import type { BrainEngine } from './engine.ts';-import type { Chunk, ChunkInput } from './types.ts';+import type { Chunk, ChunkInput, StaleChunkRow } from './types.ts';import { embedBatchWithBackoff, restampIfDemotedToTitleTier } from './embed-retry.ts';import { wrapChunkTextsForStoredMode } from './embedding-context.ts';import { healOversizedPageChunks, healedChunksToStaleRows } from './embed-oversize-heal.ts';@@ -35,6 +35,8 @@ import { type DbPacer, createNoopPacer, observed } from './db-pacer.ts';import { resolveStaleEmbedConcurrency } from './embed-concurrency.ts';import { AbortError } from './abort-check.ts';import { meterPageBatch, spendGrant } from './page-embedding-budget.ts';+import { chunkGenerationFilter, chunkVisibleFilter } from './search/safe-chunks.ts';+import { embedSegmentedPage, embedSegmentedRows, readSegmentedEmbedPage, type SegmentedEmbedOpts } from './page-body/segmented-embedding.ts';/*** W0 fix-wave (Tier-1 #3, CONFIRMED): the ONE carry-through field list for@@ -195,7 +197,7 @@ export async function stampIfPageProvenanceComplete(`SELECT count(*) > 0AND bool_and(${currentSpaceChunkPredicate(colId, 1, 4)}) AS completeFROM content_chunks cc JOIN pages p ON p.id = cc.page_id- WHERE p.slug = $2 AND p.source_id = $3 AND p.text_projection_revision=p.knowledge_revision+ WHERE p.slug = $2 AND p.source_id = $3 AND ${chunkVisibleFilter('p', 'cc')}AND EXISTS (SELECT 1 FROM sources s WHERE s.id=p.source_id AND NOT s.archived)`,[model, slug, sourceId, dims],);@@ -266,6 +268,23 @@ export async function probeEmbedder(* worker: stored-CR-mode wrapping, metadata carry, full-restale signature* stamp, title-tier restamp.*/+/**+ * Wave B: when the batch's page is segmented, embed these rows by keyset+ * (`embedSegmentedRows`, never through its body or every chunk), stamp the+ * page's provenance when it is complete, and return true; false for an inline page.+ */+async function embedSegmentedStaleRows(engine: BrainEngine, stale: readonly StaleChunkRow[], result: { embedded: number; pagesProcessed: number },+ opts: Omit<SegmentedEmbedOpts, 'beforeInstall'> & { stamp?: ProvenanceStamp; pacer: DbPacer; assertOwned?: (tx?: BrainEngine) => Promise<void>; stopped: () => boolean }): Promise<boolean> {+ const page = await observed(opts.pacer, () => readSegmentedEmbedPage(engine, { id: stale[0]!.page_id }));+ if (!page) return false;+ const installed = await embedSegmentedRows(engine, page, stale, { ...opts,+ beforeInstall: async tx => { await opts.assertOwned?.(tx); if (opts.stopped()) throw new AbortError(); } });+ if (opts.stamp && installed) await stampIfPageProvenanceComplete(engine, page.slug, page.source_id, opts.stamp);+ result.embedded += installed ?? 0;+ if (installed) result.pagesProcessed += 1;+ return true;+}+export async function embedStalePages(engine: BrainEngine,slugs: string[],@@ -293,6 +312,15 @@ export async function embedStalePages(return result;}try {+ const segmented = await readSegmentedEmbedPage(engine, { sourceId, slug });+ if (segmented) {+ const page = await embedSegmentedPage(engine, segmented, { embedFn, signal: opts.signal, signature: opts.embeddingSignature });+ const stamp = page.complete ? await resolveProvenanceStamp(engine, opts.embeddingSignature) : undefined;+ if (stamp) await stampIfPageProvenanceComplete(engine, slug, sourceId, stamp);+ result.embedded += page.embedded;+ if (page.embedded) result.pagesProcessed += 1;+ continue;+ }// SUP-3874: split legacy oversized rows before embedding so a single// pre-cap chunk cannot permanently fail the page.await healOversizedPageChunks(engine, slug, { sourceId });@@ -303,7 +331,7 @@ export async function embedStalePages((await engine.executeRaw<{ chunk_index: number }>(`SELECT cc.chunk_indexFROM content_chunks cc JOIN pages p ON p.id = cc.page_id- WHERE p.slug = $1 AND p.source_id = $2 AND cc.${staleColId} IS NULL+ WHERE p.slug = $1 AND p.source_id = $2 AND cc.${staleColId} IS NULL AND ${chunkGenerationFilter('p', 'cc')}ORDER BY cc.chunk_index`,[slug, sourceId],)).map(r => r.chunk_index),@@ -528,7 +556,7 @@ export async function embedStaleForSource(const slug = stale[0].slug;try {await opts.assertOwned?.();- if (stopped()) return;+ if (stopped() || await embedSegmentedStaleRows(engine, stale, result, { embedFn, signal, signature, stamp, pacer, assertOwned: opts.assertOwned, stopped })) return;// SUP-3874: split legacy oversized chunk_text before embedding.const healed = await observed(pacer, () => engine.transaction(async tx => {await opts.assertOwned?.(tx);diff --git a/src/core/embedding-readiness.ts b/src/core/embedding-readiness.tsindex dd853a0d6a..594b7d0f46 100644--- a/src/core/embedding-readiness.ts+++ b/src/core/embedding-readiness.ts@@ -3,6 +3,7 @@ import { readProjectionSnapshot, queuePageProjection, preparePageProjection, insimport { quoteIdentifier, resolveActiveEmbeddingColumnFromEngine } from './search/embedding-column.ts';import { QUARANTINE_FILTER_FRAGMENT } from './quarantine.ts';import { isMultimodalEnabled } from './sync.ts';+import { buildSegmentedProjection } from './page-body/projection.ts';export async function countArchivedEmbeddingWork(engine: BrainEngine, opts: { sourceId?: string; signature?: string; includeNullSignature?: boolean; includeUnsealed?: boolean } = {}, activeColumn?: string | null): Promise<number> {const column = activeColumn === undefined ? (await resolveActiveEmbeddingColumnFromEngine(engine)).name : activeColumn;@@ -102,6 +103,11 @@ export async function prepareEmbeddingProjections(engine: BrainEngine, opts: { sawait opts.assertOwned?.();try {if (await readProjectionSnapshot(engine, row.slug, row.source_id)) continue;+ const [segmented] = await engine.executeRaw(`SELECT 1 FROM pages WHERE id=$1 AND body_storage='segmented'`, [row.id]);+ if (segmented) {+ if ((await buildSegmentedProjection(engine, { sourceId: row.source_id, slug: row.slug })).sealed) rebuilt++;+ continue;+ }const queued = await engine.transaction(async tx => {await opts.assertOwned?.(tx);await tx.lockPageKeys([{ sourceId: row.source_id, slug: row.slug }]);diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex f3d3d966eb..662339a283 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -33,7 +33,7 @@ import {COLUMN_NAME_REGEX,EmbeddingColumnNotRegisteredError,} from '../search/embedding-column.ts';-import { chunkWriteInvalidations, currentTextProjectionFilter, movableChunkSql, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';+import { chunkDocumentOrder, chunkGenerationFilter, chunkManifestJoin, chunkVisibleFilter, chunkWriteInvalidations, currentTextProjectionFilter, movableChunkSql, requiresSafeChunks, safeChunksFilter } from '../search/safe-chunks.ts';import { privatePagesFilterFragment } from '../search/private-visibility.ts';import { splitEmbeddingSignature, lockEmbeddingSources } from '../embedding-invalidation.ts';import { EMBED_SKIP_FILTER_FRAGMENT } from '../embed-skip.ts';@@ -354,6 +354,7 @@ export async function upsertChunksOnce(*/async function moveDisplacedChunksAndPrune(exec: SqlExecutor, pageId: number, chunks: ChunkInput[], writeColId: string): Promise<void> {const newIndices = chunks.map(c => c.chunk_index);+ // chunk-visibility-ok: inline projection write path (upsertChunks); segmented pages stage rows through stageSegmentChunksconst { rows } = await exec.run<{ id: number; chunk_index: number; chunk_source: string | null; text_md5: string; movable: boolean }>(sqlFragment`SELECT id, chunk_index, chunk_source, md5(chunk_text) AS text_md5, ${trustedSql(movableChunkSql(writeColId))} AS movableFROM content_chunks WHERE page_id = ${pageId} ORDER BY chunk_index`);@@ -386,7 +387,7 @@ async function moveDisplacedChunksAndPrune(exec: SqlExecutor, pageId: number, chawait exec.run(sqlFragment`UPDATE content_chunks SET chunk_index = -1 - chunk_index WHERE page_id = ${pageId} AND chunk_index < 0`);}-/** The by-slug chunk read predicate shared by getChunks and getChunkPage: scope, privacy, sealed text, safe chunks. */+/** The by-slug chunk read predicate shared by getChunks and getChunkPage: scope, privacy, sealed text and live body generation, safe chunks. */function chunkReadWhere(slug: string,scope: { sourceIds?: string[]; sourceId: string },@@ -397,7 +398,7 @@ function chunkReadWhere(: sqlFragment`p.source_id = ${scope.sourceId}`;return sqlFragment`p.slug = ${slug} AND ${scopeSql}${opts?.excludePrivate ? trustedSql(`AND ${privatePagesFilterFragment('p')}`) : sqlFragment``}- ${opts?.includeUnsealed ? sqlFragment`` : trustedSql(`AND ${currentTextProjectionFilter('p')}`)}+ AND ${trustedSql(opts?.includeUnsealed ? chunkGenerationFilter('p', 'cc') : chunkVisibleFilter('p', 'cc'))}${requiresSafeChunks(opts) ? trustedSql(`AND ${safeChunksFilter('p')}`) : sqlFragment``}`;}@@ -406,7 +407,7 @@ export async function getChunks(column: string,slug: string,scope: { sourceIds?: string[]; sourceId: string },- opts?: { includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; indexRange?: { from: number; to: number } },+ opts?: { includeEmbedding?: boolean; excludePrivate?: boolean; requireSafeChunks?: boolean; includeUnsealed?: boolean; indexRange?: { from: number; to: number; ordinal?: boolean } },): Promise<Chunk[]> {const colId = trustedSql(quoteIdentifier(column));const includeEmbedding = opts?.includeEmbedding === true;@@ -420,21 +421,37 @@ export async function getChunks(// rebuild NULLs vectors without touching embedded_at). S2: it reports// the registry-ACTIVE column's truth — `embed <page>` filters on it.const embedCol = includeEmbedding ? sqlFragment`, cc.${colId} AS embedding` : sqlFragment``;- const range = opts?.indexRange- ? sqlFragment`AND cc.chunk_index >= ${opts.indexRange.from} AND cc.chunk_index < ${opts.indexRange.to}` : sqlFragment``;- const { rows } = await exec.run(sqlFragment`- SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,+ const columns = sqlFragment`cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,cc.model, cc.token_count, cc.embedded_at, cc.language,cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality,cc.projected_byte_start, cc.projected_byte_end,(cc.${colId} IS NULL) AS embedding_is_null- ${embedCol}- FROM content_chunks cc+ ${embedCol}`;+ const from = sqlFragment`FROM content_chunks ccJOIN pages p ON p.id = cc.page_id- WHERE ${chunkReadWhere(slug, scope, opts)}- ${range}- ORDER BY cc.chunk_index+ ${trustedSql(chunkManifestJoin('p', 'cc', 'm'))}+ WHERE ${chunkReadWhere(slug, scope, opts)}`;+ const order = trustedSql(chunkDocumentOrder('cc', 'm'));+ const range = opts?.indexRange;+ if (range?.ordinal) {+ const { rows } = await exec.run(sqlFragment`+ SELECT * FROM (+ SELECT ${columns},+ (row_number() OVER (PARTITION BY cc.page_id ORDER BY ${order}) - 1)::int AS page_position,+ row_number() OVER (ORDER BY ${order}) AS document_position+ ${from}+ ) r+ WHERE r.page_position >= ${range.from} AND r.page_position < ${range.to}+ ORDER BY r.document_position+ `);+ return rows.map((r) => rowToChunk(r, includeEmbedding));+ }+ const { rows } = await exec.run(sqlFragment`+ SELECT ${columns}+ ${from}+ ${range ? sqlFragment`AND cc.chunk_index >= ${range.from} AND cc.chunk_index < ${range.to}` : sqlFragment``}+ ORDER BY ${order}`);return rows.map((r) => rowToChunk(r, includeEmbedding));}@@ -445,7 +462,9 @@ export async function getChunks(* applies, plus the count of every chunk that predicate admits and the* highest chunk_index, so the caller knows whether more remain. A range,* not a row LIMIT, so a slug that matches one page in each of two federated- * sources never splits a chunk_index between two calls.+ * sources never splits a chunk_index between two calls. A segmented page's+ * chunk_index is an insertion sequence, so its range is over positions in+ * document order instead (`fromIndex` and `max_chunk_index` are positions).*/export async function getChunkPage(exec: ScopedRead,@@ -454,14 +473,20 @@ export async function getChunkPage(scope: { sourceIds?: string[]; sourceId: string },opts: { fromIndex: number; limit: number; excludePrivate?: boolean; requireSafeChunks?: boolean },): Promise<{ chunks: Chunk[]; total_chunks: number; max_chunk_index: number | null }> {- const { rows } = await exec.run<{ total: number | string; max_index: number | null }>(sqlFragment`- SELECT count(*) AS total, max(cc.chunk_index) AS max_index- FROM content_chunks cc- JOIN pages p ON p.id = cc.page_id- WHERE ${chunkReadWhere(slug, scope, opts)}+ const { rows } = await exec.run<{ total: number | string; max_index: number | null; segmented: boolean | null; max_page_chunks: number | string | null }>(sqlFragment`+ SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks+ FROM (+ SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented+ FROM content_chunks cc+ JOIN pages p ON p.id = cc.page_id+ WHERE ${chunkReadWhere(slug, scope, opts)}+ GROUP BY cc.page_id+ ) t`);- const chunks = await getChunks(exec, column, slug, scope, { ...opts, indexRange: { from: opts.fromIndex, to: opts.fromIndex + opts.limit } });- return { chunks, total_chunks: Number(rows[0]?.total ?? 0), max_chunk_index: rows[0]?.max_index == null ? null : Number(rows[0].max_index) };+ const segmented = rows[0]?.segmented === true;+ const chunks = await getChunks(exec, column, slug, scope, { ...opts, indexRange: { from: opts.fromIndex, to: opts.fromIndex + opts.limit, ordinal: segmented } });+ const maxIndex = segmented ? Number(rows[0]?.max_page_chunks) - 1 : rows[0]?.max_index == null ? null : Number(rows[0].max_index);+ return { chunks, total_chunks: Number(rows[0]?.total ?? 0), max_chunk_index: maxIndex };}/**@@ -476,7 +501,7 @@ export async function getChunkPage(*/function staleChunkWhere(column: string, opts?: StaleChunkOpts): SqlFragment {const staleColRef = trustedSql(`cc.${quoteIdentifier(column)}`);- const conds: SqlFragment[] = [sqlFragment`p.deleted_at IS NULL`];+ const conds: SqlFragment[] = [sqlFragment`p.deleted_at IS NULL`, sqlFragment`${trustedSql(chunkGenerationFilter('p', 'cc'))}`];if (opts?.signature !== undefined) {conds.push(opts.includeNullSignature@@ -616,6 +641,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {// BEFORE the scoped transaction, falling back to legacy on a broken registry).const staleColId = trustedSql(quoteIdentifier(column));const read = async (fragment: SqlFragment) => (await exec.run(fragment)).rows as unknown as StaleChunkRow[];+ const generation = trustedSql(chunkGenerationFilter('p', 'cc'));// v0.41.18.0 (A13, codex #9): --priority recent path. Composite cursor// (updated_at DESC NULLS LAST, page_id ASC, chunk_index ASC). Backed by@@ -632,6 +658,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 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 ${generation}ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASCLIMIT ${limit}`) : read(sqlFragment`@@ -642,6 +669,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 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 ${generation}AND (p.updated_at < ${afterUpdated}::timestamptzOR (p.updated_at = ${afterUpdated}::timestamptz AND p.id > ${afterPid})@@ -660,6 +688,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {WHERE 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 ${generation}ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASCLIMIT ${limit}`) : read(sqlFragment`@@ -671,6 +700,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {WHERE 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 ${generation}AND (p.updated_at < ${afterUpdated}::timestamptzOR (p.updated_at = ${afterUpdated}::timestamptz AND p.id > ${afterPid})@@ -689,6 +719,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 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 ${generation}AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})ORDER BY cc.page_id, cc.chunk_indexLIMIT ${limit}@@ -702,6 +733,7 @@ export async function listStaleChunks(exec: ScopedRead, column: string, opts?: {WHERE 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 ${generation}AND (cc.page_id, cc.chunk_index) > (${afterPid}, ${afterIdx})ORDER BY cc.page_id, cc.chunk_indexLIMIT ${limit}@@ -842,7 +874,7 @@ export async function readEmbeddingStateCounts(exec: ScopedRead, column: string,FROM (SELECT ${chunkEmbeddingState(column)} AS state, ${trustedSql(EMBED_SKIP_FILTER_FRAGMENT)} AS eligible,COALESCE(${overdue}, false) AS overdue, cc.embedding_pending_since IS NULL AS unstamped, cc.created_atFROM content_chunks cc JOIN pages p ON p.id = cc.page_id- WHERE ${where}${scope}) s+ WHERE ${where} AND ${trustedSql(chunkGenerationFilter('p', 'cc'))}${scope}) sGROUP BY s.state`);const chunkRows = (await aggregate(opts.mode === 'ops' ? sqlFragment`${colRef} IS NULL` : sqlFragment`TRUE`)).rows.map(row => normalizeStateCount(row));let pendingUnstamped = 0;@@ -920,7 +952,7 @@ export async function listEmbeddingStateRows(exec: ScopedRead, column: string,p.frontmatter -> 'quarantine' ->> 'reason' AS quarantine_reason, p.deleted_at,COALESCE(p.deleted_at < now() - make_interval(hours => ${opts.purgeWindowHours}::int), false) AS overdueFROM content_chunks cc JOIN pages p ON p.id = cc.page_id- WHERE TRUE${scope}+ WHERE ${trustedSql(chunkGenerationFilter('p', 'cc'))}${scope}GROUP BY p.id, 3UNION ALLSELECT p.slug, p.source_id, ${chunklessPageState()}, 0::bigint,@@ -980,7 +1012,7 @@ export async function getEmbeddingsByChunkIds(exec: LegacyUnscopedRead, ids: numconst quotedCol = trustedSql(quoteIdentifier(column));const { text, params } = renderFragment(sqlFragment`SELECT cc.id, vector_send(cc.${quotedCol}::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id- WHERE cc.id = ANY(${ids}::int[]) AND cc.${quotedCol} IS NOT NULL AND ${trustedSql(currentTextProjectionFilter('p'))}+ WHERE cc.id = ANY(${ids}::int[]) AND cc.${quotedCol} IS NOT NULL AND ${trustedSql(chunkVisibleFilter('p', 'cc'))}`);const { rows } = await exec.unsafe(text, params);const result = new Map<number, Float32Array>();@@ -1015,7 +1047,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqSELECT * FROM unnest(${requests.map(r => r.page_id)}::int[], ${requests.map(r => r.from_index)}::int[],${requests.map(r => r.to_index)}::int[], ${requests.map(r => r.priority)}::int[]) AS r(page_id, lo, hi, prio)), auth AS (- SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline,+ SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation,(COALESCE(p.chunker_version, 0) >= ${SAFE_FENCE_CHUNKER_VERSION}) AS sealed,(SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prioFROM pages p@@ -1027,7 +1059,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqSELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prioFROM auth aJOIN content_chunks cc ON cc.page_id = a.id- WHERE a.sealed+ WHERE a.sealed AND ${trustedSql(chunkGenerationFilter('a', 'cc'))}AND cc.chunk_source = ANY(${opts.chunkSources}::text[])AND COALESCE(cc.modality, 'text') = 'text'AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi)@@ -1035,7 +1067,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqLIMIT ${maxRows + 1})SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio,- (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index,+ (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND ${trustedSql(chunkGenerationFilter('a', 'c2'))}) AS max_chunk_index,a.compiled_truth, a.timeline,NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source,NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end@@ -1050,7 +1082,7 @@ export async function getChunkWindows(exec: ScopedRead, requests: ChunkWindowReqexport async function getChunksWithEmbeddings(exec: LegacyUnscopedRead, slug: string, opts?: { sourceId?: string; includeUnsealed?: boolean }): Promise<Chunk[]> {const sourceId = opts?.sourceId;- const projection = trustedSql(opts?.includeUnsealed ? 'TRUE' : currentTextProjectionFilter('p'));+ const projection = trustedSql(opts?.includeUnsealed ? chunkGenerationFilter('p', 'cc') : chunkVisibleFilter('p', 'cc'));const { rows } = sourceId? await exec.run(sqlFragment`SELECT cc.* FROM content_chunks ccdiff --git a/src/core/engine-sql/pages.ts b/src/core/engine-sql/pages.tsindex 512ba96e46..0225aa8959 100644--- a/src/core/engine-sql/pages.ts+++ b/src/core/engine-sql/pages.ts@@ -19,6 +19,7 @@ import type { GetVersionsOpts, PageVersionRows } from '../page-state/version-typimport { PAGE_SORT_SQL } from '../types.ts';import type { PageWriteOptions } from '../page-state/types.ts';import { moveSlugBindings, recordRenameAlias } from '../page-state/rename-alias.ts';+import { segmentedRevertRefusal } from '../page-state/versions.ts';import { sanitizeText } from '../batch-rows.ts';import { SAFE_FENCE_CHUNKER_VERSION, bodyWriteChunkVersion } from '../search/safe-chunks.ts';import { privatePagesFilterFragment, privateSnapshotFilterFragment } from '../search/private-visibility.ts';@@ -896,6 +897,8 @@ const PAGE_VERSION_COLUMNS = trustedSql('pv.id, pv.page_id, pv.compiled_truth, p+ 'pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path');const PAGE_VERSION_METADATA_COLUMNS = trustedSql('pv.id, pv.page_id, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, '+ 'pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path');+/** Wave B: the reference columns of a segmented version, kept only on segmented rows so inline rows stay as they were. */+const PAGE_VERSION_SEGMENTED_COLUMNS = trustedSql('pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash');/*** Newest first (`pv.id` breaks snapshot_at ties). Scope and privacy@@ -915,14 +918,19 @@ export async function getVersions<B extends boolean = true>(const columns = opts?.includeBody === false ? PAGE_VERSION_METADATA_COLUMNS : PAGE_VERSION_COLUMNS;const limit = opts?.limit !== undefined ? sqlFragment`LIMIT ${opts.limit}` : sqlFragment``;const { rows } = await exec.run(sqlFragment`- SELECT ${columns} FROM page_versions pv+ SELECT ${columns}, ${PAGE_VERSION_SEGMENTED_COLUMNS} FROM page_versions pvJOIN pages p ON p.id = pv.page_idWHERE p.slug = ${slug} ${scope}${privacy}ORDER BY pv.snapshot_at DESC, pv.id DESC${limit}`);- return rows as PageVersionRows<B>;+ return rows.map(row => {+ const { body_storage, body_generation, body_bytes, content_hash, ...version } = row as Record<string, unknown>;+ return body_storage === 'segmented'+ ? { ...version, body_storage, body_generation: Number(body_generation), body_bytes: Number(body_bytes), content_hash }+ : version;+ }) as PageVersionRows<B>;}export async function revertToVersion(@@ -931,6 +939,14 @@ export async function revertToVersion(versionId: number,opts?: { sourceId?: string },): Promise<void> {+ // Wave B: a segmented page or version is refused before anything is written (segment writer: PR 3).+ const scope = opts?.sourceId ? sqlFragment`AND p.source_id = ${opts.sourceId}` : sqlFragment``;+ const { rows: segmented } = await exec.run(sqlFragment`+ SELECT 1 FROM pages p JOIN page_versions pv ON pv.page_id = p.id+ WHERE p.slug = ${slug} ${scope} AND pv.id = ${versionId}+ AND (p.body_storage = 'segmented' OR pv.body_storage = 'segmented')+ `);+ if (segmented.length > 0) throw segmentedRevertRefusal(slug, versionId);// v0.31.8 (D12): two-branch. With opts.sourceId, scope BOTH the page lookup// AND the version reference. Without it, multi-source brains can revert// the wrong same-slug page.diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.tsindex b72167a895..4e87688b79 100644--- a/src/core/import-chunk-reuse.ts+++ b/src/core/import-chunk-reuse.ts@@ -9,6 +9,9 @@ import { canReuseMarkdownVector, planEmbeddingReuse } from './embed-reuse.ts';import { modeRequiresSynopsis } from './embedding-context.ts';import type { Chunk, ChunkInput, CRMode } from './types.ts';import type { SegmentChunkInput } from './page-body/types.ts';+import { quoteIdentifier } from './search/embedding-column.ts';+import { chunkGenerationFilter } from './search/safe-chunks.ts';+import { parseEmbedding } from './utils.ts';/*** A13 reuse for one page import: copies each stored vector the reuse gate@@ -73,12 +76,40 @@ export async function reuseStoredChunkVectors(}/**- * Wave B (lane 1e): vector reuse for a segmented write, scoped to the chunk- * rows of the occurrences the write retires (never the whole page). Copies- * each admitted stored vector onto the new chunk with the same source and- * text; returns how many chunks got one.+ * Wave B: vector reuse for a segmented write, scoped to the live chunk rows of+ * the occurrences the write retires (never the whole page): one statement+ * reads those rows with their vectors, the same gate as+ * `reuseStoredChunkVectors` admits each (recorded input hash for the write's+ * tier, nothing from a page stored under per-chunk synopsis), and each admitted+ * vector is copied, with its recorded input, onto the new chunk with the same+ * source and text (`chunk_source\0chunk_text`, FIFO for duplicates). So an+ * unchanged chunk inside a rewritten tail keeps its vector and only new text+ * reaches the provider. Returns how many chunks got one.*/-export async function reuseSegmentChunkVectors(_exec: BrainEngine, _input: { pageId: number; retiredOccurrences: readonly number[];- chunks: SegmentChunkInput[]; title: string; corpusGeneration: string | null; tier: 'title' | 'none' }): Promise<number> {- throw new Error('reuseSegmentChunkVectors: implemented by Wave B lane 1e');+export async function reuseSegmentChunkVectors(exec: BrainEngine, { pageId, retiredOccurrences, chunks, title, corpusGeneration, tier }: {+ pageId: number; retiredOccurrences: readonly number[]; chunks: SegmentChunkInput[]; title: string; corpusGeneration: string | null; tier: 'title' | 'none' }): Promise<number> {+ if (retiredOccurrences.length === 0 || chunks.length === 0) return 0;+ const target = await embeddingWriteTarget(exec);+ const provenance = embeddingInputContext(target, title, corpusGeneration, []);+ const col = quoteIdentifier(target.column.name);+ const rows = await exec.executeRaw<{ chunk_text: string; chunk_source: string; embedding: unknown; token_count: number | null; model: string | null;+ embedding_input_hash: string | null; contextual_retrieval_mode: string | null }>(+ `SELECT c.chunk_text, c.chunk_source, c.${col} AS embedding, c.token_count, c.model, c.embedding_input_hash, p.contextual_retrieval_mode+ FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE c.page_id = $1 AND c.occurrence_id = ANY($2::bigint[]) AND c.${col} IS NOT NULL AND ${chunkGenerationFilter('p', 'c')}+ ORDER BY c.chunk_index`, [pageId, [...retiredOccurrences]]);+ const mode = rows[0]?.contextual_retrieval_mode ?? null;+ if (rows.length === 0 || (mode && modeRequiresSynopsis(mode as CRMode))) return 0;+ const stored = rows.map(row => ({ chunk_text: row.chunk_text, chunk_source: row.chunk_source, embedding: parseEmbedding(row.embedding),+ token_count: row.token_count, model: row.model, embedding_input_hash: row.embedding_input_hash }))+ .filter(chunk => canReuseMarkdownVector(chunk.embedding_input_hash, mode, tier, provenance, chunk));+ const { reuse } = planEmbeddingReuse(stored, chunks, c => `${c.chunk_source}\0${c.chunk_text}`);+ for (const [i, matched] of reuse) {+ const row = matched as typeof stored[number];+ chunks[i]!.embedding = row.embedding as Float32Array;+ chunks[i]!.token_count = row.token_count ?? undefined;+ if (row.model) chunks[i]!.model = row.model;+ if (row.embedding_input_hash) chunks[i]!.embedding_input_hash = row.embedding_input_hash;+ }+ return reuse.size;}diff --git a/src/core/ops/admin.ts b/src/core/ops/admin.tsindex 362e8b2c2a..da9d92b102 100644--- a/src/core/ops/admin.ts+++ b/src/core/ops/admin.ts@@ -223,9 +223,17 @@ const get_versions: Operation = {}const plain = page(await ctx.engine.getVersions(p.slug as string, opts));const versions = canReadWriteAttribution(ctx) ? await attributeVersions(ctx.engine, plain) : plain;- if (ctx.remote === false) return versions;- return versions.map(v => ({ ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth),- ...(typeof v.timeline === 'string' ? { timeline: sanitizeRemoteBody(v.timeline) } : {}) }));+ // Wave B: a segmented version's body is never returned whole; body_ref names its size and the windowed read.+ return versions.map(v => {+ if (v.body_storage === 'segmented') {+ const { compiled_truth: _b, timeline: _t, ...rest } = v;+ return { ...rest, body_ref: { version_id: v.id, total_bytes: v.body_bytes,+ read: { tool: 'get_page', arguments: { slug: p.slug, version_id: v.id, body: 'window' } } } };+ }+ if (ctx.remote === false) return v;+ return { ...v, compiled_truth: sanitizeRemoteBody(v.compiled_truth),+ ...(typeof v.timeline === 'string' ? { timeline: sanitizeRemoteBody(v.timeline) } : {}) };+ });},scope: 'read',cliHints: { name: 'history', positional: ['slug'] },diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex 8893fdcd19..38b6884610 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -43,6 +43,7 @@ import {} from '../page-window/window.ts';import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';import type { QuarantinedView } from './get-page-projection.ts';+import { chunkGenerationProbe } from '../search/safe-chunks.ts';export const BODY_MODES = ['auto', 'full', 'none', 'outline', 'window'] as const;export type BodyMode = typeof BODY_MODES[number];@@ -235,7 +236,7 @@ async function aroundChunk(ctx: OperationContext, page: Page, doc: PageDocument,Promise<{ window: WindowSlice | null; chunkText: string; anchor: 'stored_span' | 'located' | 'chunk_only'; span?: { byte_start: number; byte_end: number } }> {const rows = await ctx.engine.executeRaw<{ chunk_text: string; chunk_source: string; projected_byte_start: unknown; projected_byte_end: unknown }>(`SELECT chunk_text, chunk_source, projected_byte_start, projected_byte_end FROM content_chunks- WHERE id = $1 AND page_id = $2 AND COALESCE(modality, 'text') = 'text'`, [chunkId, page.id]);+ WHERE id = $1 AND page_id = $2 AND COALESCE(modality, 'text') = 'text' AND ${chunkGenerationProbe('content_chunks')}`, [chunkId, page.id]);const row = rows[0];if (!row) {throw opError('revision_changed', `Chunk ${chunkId} is not part of page ${page.slug} at its current revision.`,@@ -296,7 +297,8 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIif (mode === 'none') {const [counts] = await ctx.engine.executeRaw<{ total: unknown; embedded: unknown }>(- `SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunks WHERE page_id = $1`, [page.id]);+ `SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunks+ WHERE page_id = $1 AND ${chunkGenerationProbe('content_chunks')}`, [page.id]);const fm = (page.frontmatter ?? {}) as Record<string, unknown>;return { ...out, chunks: { total: Number(counts?.total ?? 0), embedded: Number(counts?.embedded ?? 0) },...(fm.embed_skip ? { embed_skip: true } : {}), truncated: doc.bytes.length > 0 };diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.tsindex 204b216808..6990f0466e 100644--- a/src/core/page-body/limits.ts+++ b/src/core/page-body/limits.ts@@ -54,6 +54,14 @@ export const STAGE_BATCH_BYTES: Readonly<Record<'postgres' | 'pglite', number>>/** Chunk rows the generation flip retires inside the publication transaction; above it the page publishes unsealed and a projection job retires the rest. */export const DEFAULT_FLIP_RETIRE_MAX_ROWS = 20_000;+/**+ * Snapshots of an inline page over the inline cap kept per page (Wave A). Each+ * one is a full copy of the body, so an append-heavy 24 MiB page would otherwise+ * grow history by 24 MiB per write. Snapshots at or under the inline cap, and+ * every snapshot of a small page, are never pruned.+ */+export const LARGE_PAGE_VERSIONS_KEPT = 5;+/** Segmented version retention: newest N kept, then oldest-first pruning while pinned bytes exceed max(floor, body_bytes). */export const DEFAULT_SEGMENTED_VERSIONS_MAX_PER_PAGE = 50;export const DEFAULT_SEGMENTED_VERSIONS_MAX_PINNED_BYTES = 64 * 1024 ** 2;diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.tsnew file mode 100644index 0000000000..8549218d2d--- /dev/null+++ b/src/core/page-body/segmented-embedding.ts@@ -0,0 +1,150 @@+/**+ * Embedding for segmented pages (Wave B, spec 4.4). The inline path+ * (`readProjectionSnapshot` / `installPageEmbeddings`) reads the page body, its+ * fence overlay and every chunk of the page; a segmented page is embedded from+ * its stale chunk rows alone: keyset pages of live, vector-less rows with their+ * text, the page title and the plain tier (the synopsis tier stays off for+ * segmented pages, so no input depends on the rest of the body), metered by the+ * per-page budget and installed by chunk_index and exact text onto rows still+ * in the page's live body generation. It never reads a segment.+ */+import type { BrainEngine } from '../engine.ts';+import type { CRMode } from '../types.ts';+import { jsonRowBatches } from '../batch-rows.ts';+import { wrapChunkTextsForStoredMode } from '../embedding-context.ts';+import { embeddingInputHash, plainEmbeddingTier } from '../embedding-input-hash.ts';+import { meterPageBatch, spendGrant } from '../page-embedding-budget.ts';+import { embeddingInputContext, embeddingWriteTarget } from '../page-state/projections.ts';+import { quoteIdentifier, vectorCastSuffix } from '../search/embedding-column.ts';+import { chunkGenerationFilter, chunkVisibleFilter, currentTextProjectionFilter } from '../search/safe-chunks.ts';++/** Stale rows read and embedded per provider round trip. */+export const SEGMENTED_EMBED_BATCH_ROWS = 500;++/** The page fields a segmented embed reads: metadata only, never the body. */+export interface SegmentedEmbedPage {+ id: number;+ slug: string;+ source_id: string;+ title: string;+ contextual_retrieval_mode: CRMode | null;+ body_storage: 'segmented';+ body_bytes: number;+}++export interface SegmentedStaleRow { chunk_index: number; chunk_text: string; chunk_source: string }++export type SegmentedEmbedFn = (texts: string[], opts: { abortSignal?: AbortSignal }) => Promise<Float32Array[]>;++export interface SegmentedEmbedOpts {+ embedFn: SegmentedEmbedFn;+ signal?: AbortSignal;+ signature?: string | null;+ approvedCapUsd?: number;+ /** Runs inside the install transaction after the page guard (ownership, effect claim); throwing installs nothing. */+ beforeInstall?: (tx: BrainEngine) => Promise<void>;+}++/** A segmented page that is live, sealed and in a live source, by id or by source and slug; null otherwise (inline pages included). */+export async function readSegmentedEmbedPage(engine: Pick<BrainEngine, 'executeRaw'>,+ ref: { id: number } | { sourceId: string; slug: string }): Promise<SegmentedEmbedPage | null> {+ const [where, params] = 'id' in ref ? ['p.id = $1', [ref.id]] : ['p.source_id = $1 AND p.slug = $2', [ref.sourceId, ref.slug]];+ const [row] = await engine.executeRaw<{ id: number; slug: string; source_id: string; title: string; contextual_retrieval_mode: CRMode | null; body_bytes: number | string }>(+ `SELECT p.id, p.slug, p.source_id, p.title, p.contextual_retrieval_mode, p.body_bytes+ FROM pages p JOIN sources s ON s.id = p.source_id+ WHERE ${where} AND p.body_storage = 'segmented' AND p.deleted_at IS NULL AND NOT s.archived AND ${currentTextProjectionFilter('p')}`, params);+ return row ? { ...row, id: Number(row.id), body_storage: 'segmented', body_bytes: Number(row.body_bytes) } : null;+}++/** A dry run's counts: the page's live rows and those not yet embedded. */+export async function countSegmentedEmbedRows(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<{ total: number; stale: number }> {+ const [row] = await engine.executeRaw<{ total: number; stale: number }>(+ `SELECT count(*)::int AS total, count(*) FILTER (WHERE cc.embedded_at IS NULL)::int AS stale+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.page_id = $1 AND ${chunkVisibleFilter('p', 'cc')}`, [pageId]);+ return { total: Number(row?.total ?? 0), stale: Number(row?.stale ?? 0) };+}++/** Vector-less live rows of a segmented page after `afterChunkIndex`, in chunk_index order; `occurrenceIds` limits them to the occurrences a write added. */+export async function listSegmentedStaleRows(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, column: string,+ opts: { afterChunkIndex: number; limit: number; occurrenceIds?: readonly number[] }): Promise<SegmentedStaleRow[]> {+ const col = quoteIdentifier(column);+ return engine.executeRaw<SegmentedStaleRow>(+ `SELECT cc.chunk_index, cc.chunk_text, cc.chunk_source+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.page_id = $1 AND cc.${col} IS NULL AND cc.chunk_index > $2+ AND ($4::bigint[] IS NULL OR cc.occurrence_id = ANY($4::bigint[])) AND ${chunkVisibleFilter('p', 'cc')}+ ORDER BY cc.chunk_index LIMIT $3`,+ [pageId, opts.afterChunkIndex, opts.limit, opts.occurrenceIds ? [...opts.occurrenceIds] : null]);+}++/**+ * Embed `rows` of one segmented page: meter them under the per-page budget,+ * call the provider once for the granted rows, and install each vector with+ * its recorded input on the row with the same chunk_index and text while that+ * row is in the live generation and the page's title, mode and write target+ * are unchanged. Returns the rows that took a vector; null when the budget+ * holds the page or the cap left nothing to embed.+ */+export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmbedPage, rows: readonly SegmentedStaleRow[],+ opts: SegmentedEmbedOpts): Promise<number | null> {+ if (rows.length === 0) return 0;+ const metered = await meterPageBatch(engine, page, rows, { signature: opts.signature ?? null, approvedCapUsd: opts.approvedCapUsd });+ if (!metered) return null;+ const chunks = metered.chunks;+ const target = await embeddingWriteTarget(engine);+ const vectors = await spendGrant(metered.grant, () => opts.embedFn(wrapChunkTextsForStoredMode(page, chunks), { abortSignal: opts.signal }));+ if (vectors.length !== chunks.length || vectors.some(v => !v?.length || !v.every(Number.isFinite))) {+ throw new Error('Embedding provider returned an incomplete or invalid batch');+ }+ const tier = plainEmbeddingTier(page.contextual_retrieval_mode);+ const provenance = embeddingInputContext(target, page.title, null, []);+ const updates = chunks.map((chunk, i) => ({ chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text,+ embedding: `[${Array.from(vectors[i]!).join(',')}]`, hash: embeddingInputHash(provenance, tier, chunk) }));+ const col = quoteIdentifier(target.column.name);+ return engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);+ await opts.beforeInstall?.(tx);+ const current = await readSegmentedEmbedPage(tx, { id: page.id });+ const now = await embeddingWriteTarget(tx);+ if (!current || current.slug !== page.slug || current.title !== page.title+ || current.contextual_retrieval_mode !== page.contextual_retrieval_mode+ || now.column.name !== target.column.name || now.provenanceModel !== target.provenanceModel) return 0;+ let installed = 0;+ for (const batch of jsonRowBatches(updates, update => update)) {+ installed += (await tx.executeRaw(`UPDATE content_chunks cc SET ${col} = v.embedding${vectorCastSuffix(target.column)},+ embedding_input_hash = v.hash, embedded_at = now(), embedded_text_hash = md5(cc.chunk_text), model = COALESCE($3, cc.model),+ embedding_pending_since = NULL+ FROM jsonb_to_recordset($2::text::jsonb) AS v(chunk_index int, chunk_text text, embedding text, hash text), pages p+ WHERE cc.page_id = $1 AND p.id = cc.page_id AND cc.chunk_index = v.chunk_index AND cc.chunk_text = v.chunk_text+ AND ${chunkGenerationFilter('p', 'cc')}+ RETURNING cc.id`, [page.id, batch, target.model])).length;+ }+ return installed;+ });+}++/**+ * Embed every vector-less live row of a segmented page (or only the rows of+ * `occurrenceIds`, the occurrences an append added), one keyset batch at a+ * time, until the rows run out (`complete`), the budget holds the page or+ * leaves no room (`stopped: 'budget'`), or the page moved under an install+ * (`stopped: 'page_moved'`).+ */+export async function embedSegmentedPage(engine: BrainEngine, page: SegmentedEmbedPage,+ opts: SegmentedEmbedOpts & { occurrenceIds?: readonly number[]; batchRows?: number }): Promise<{ embedded: number; complete: boolean; stopped?: 'budget' | 'page_moved' }> {+ const column = (await embeddingWriteTarget(engine)).column.name;+ const limit = opts.batchRows ?? SEGMENTED_EMBED_BATCH_ROWS;+ let embedded = 0;+ for (let after = -1; ;) {+ opts.signal?.throwIfAborted();+ const rows = await listSegmentedStaleRows(engine, page.id, column, { afterChunkIndex: after, limit, occurrenceIds: opts.occurrenceIds });+ if (rows.length === 0) return { embedded, complete: true };+ const installed = await embedSegmentedRows(engine, page, rows, opts);+ if (installed === null) return { embedded, complete: false, stopped: 'budget' };+ embedded += installed;+ if (installed === 0) return { embedded, complete: false, stopped: 'page_moved' };+ if (installed < rows.length) return { embedded, complete: false, stopped: 'budget' };+ after = rows[rows.length - 1]!.chunk_index;+ }+}diff --git a/src/core/page-embedding-budget.ts b/src/core/page-embedding-budget.tsindex 5e9b6cb892..3c003f963a 100644--- a/src/core/page-embedding-budget.ts+++ b/src/core/page-embedding-budget.ts@@ -32,11 +32,13 @@* budget it may already have used.*/import type { BrainEngine } from './engine.ts';-import { assessSampledJunk } from './content-sanity.ts';+import { JUNK_SAMPLE_CHARS, assessJunkWindows, assessSampledJunk } from './content-sanity.ts';+import type { ManifestRow } from './page-body/types.ts';import { estimateCostFromChars, lookupEmbeddingPrice } from './embedding-pricing.ts';import { PAGE_INLINE_MAX_BYTES, 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';export const PAGE_EMBED_CAP_KEY = 'embed.max_usd_per_page';export const DEFAULT_PAGE_EMBED_CAP_USD = 2;@@ -72,10 +74,42 @@ export type PageEmbedDecision =interface BudgetRow { state: PageBudgetState; reason: string | null; embedding_signature: string | null; spent_usd: number; reserved_usd: number; stale_reservation: boolean; cap_usd: number | null }-type BudgetPage = { id: number; compiled_truth: string; timeline?: string | null };+/** A segmented page (Wave B) carries `body_bytes` and no body strings; an inline page carries its body. */+type BudgetPage = { id: number; body_storage?: string | null; body_bytes?: number | string | null; compiled_truth?: string; timeline?: string | null };++function isSegmentedBudgetPage(page: BudgetPage): boolean {+ return page.body_storage === 'segmented';+}function pageBytes(page: BudgetPage): number {- return Buffer.byteLength(page.compiled_truth, 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8');+ if (isSegmentedBudgetPage(page)) return Number(page.body_bytes);+ return Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8');+}++/**+ * The head, middle and tail sample windows of a segmented page, read one+ * segment at a time from the live manifest (never the whole body): the head+ * window from the first segments, the middle window from the segment at the+ * middle byte on, the tail window from the last segments back.+ */+async function segmentedSampleWindows(engine: BrainEngine, pageId: number): Promise<string[]> {+ const manifest = await engine.readManifest(pageId);+ if (manifest.length === 0) return [''];+ const decoder = new TextDecoder();+ const read = async (row: ManifestRow) => {+ const texts = await engine.readSegmentTexts(row.sourceId, [row.sha256]);+ return decoder.decode(texts.get(Buffer.from(row.sha256).toString('hex')) ?? new Uint8Array());+ };+ const forward = async (from: number) => {+ let text = '';+ for (let i = from; i < manifest.length && text.length < JUNK_SAMPLE_CHARS; i++) text += await read(manifest[i]!);+ return text.slice(0, JUNK_SAMPLE_CHARS);+ };+ let tail = '';+ for (let i = manifest.length - 1; i >= 0 && tail.length < JUNK_SAMPLE_CHARS; i--) tail = await read(manifest[i]!) + tail;+ const totalBytes = manifest.reduce((n, row) => n + row.byteLen, 0);+ const middle = manifest.findIndex(row => row.byteStart + row.byteLen > totalBytes / 2);+ return [await forward(0), await forward(Math.max(0, middle)), tail.slice(-JUNK_SAMPLE_CHARS)];}function currentPricePerMTok(signature: string | null | undefined): { rate: number; priced: boolean } {@@ -111,7 +145,9 @@ export async function planPageEmbedding(engine: BrainEngine, page: BudgetPage,if (!row) return { kind: 'unmetered' } as const;if (row.state === 'held' && !approved) return { kind: 'held', reason: row.reason ?? 'awaiting_approval' } as const;if (!approved && row.state === 'open') {- const junk = assessSampledJunk(`${page.compiled_truth}\n${page.timeline ?? ''}`, { max_markup_ratio: opts.maxMarkupRatio });+ const junk = isSegmentedBudgetPage(page)+ ? assessJunkWindows(await segmentedSampleWindows(tx, page.id), { max_markup_ratio: opts.maxMarkupRatio })+ : assessSampledJunk(`${page.compiled_truth}\n${page.timeline ?? ''}`, { max_markup_ratio: opts.maxMarkupRatio });if (junk.junk) {const reason = junk.reasons.join(',');await tx.executeRaw(`UPDATE page_embedding_budget SET state = 'held', reason = $2, updated_at = now() WHERE page_id = $1`, [page.id, reason]);@@ -168,8 +204,8 @@ export async function listBudgetLimitedPages(engine: Pick<BrainEngine, 'executeRif (opts.state) filters.push(`b.state = $${params.push(opts.state)}`);if (opts.sourceId) filters.push(`p.source_id = $${params.push(opts.sourceId)}`);const rows = await engine.executeRaw<PageBudgetReport>(`SELECT p.slug, p.source_id, b.state, b.reason, b.spent_usd, b.cap_usd,- (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL) AS pending_chunks,- (SELECT COALESCE(sum(length(cc.chunk_text)), 0)::bigint FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL) AS pending_chars+ (SELECT count(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL AND ${chunkGenerationFilter('p', 'cc')}) AS pending_chunks,+ (SELECT COALESCE(sum(length(cc.chunk_text)), 0)::bigint FROM content_chunks cc WHERE cc.page_id = p.id AND cc.embedded_at IS NULL AND ${chunkGenerationFilter('p', 'cc')}) AS pending_charsFROM page_embedding_budget b JOIN pages p ON p.id = b.page_idWHERE ${filters.join(' AND ')} ORDER BY b.updated_at DESC, p.id LIMIT $1`, params);return rows.map(row => ({ ...row, spent_usd: Number(row.spent_usd), cap_usd: row.cap_usd === null ? null : Number(row.cap_usd), pending_chunks: Number(row.pending_chunks), pending_chars: Number(row.pending_chars) }));@@ -263,7 +299,7 @@ export function pageSizeState(bytes: number, frontmatter: Record<string, unknown*/export async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slugs: readonly string[] | null): Promise<Array<{ slug: string } & PageSizeState>> {if (slugs?.length === 0) return [];- const bytes = `(octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')))`;+ const bytes = `(CASE WHEN p.body_storage = 'segmented' THEN p.body_bytes ELSE octet_length(p.compiled_truth) + octet_length(COALESCE(p.timeline, '')) END)`;const rows = await engine.executeRaw<{ slug: string; bytes: number; frontmatter: Record<string, unknown> | null; state: PageBudgetState | null; reason: string | null }>(`SELECT p.slug, ${bytes}::bigint AS bytes, p.frontmatter, b.state, b.reasonFROM pages p LEFT JOIN page_embedding_budget b ON b.page_id = p.id@@ -278,9 +314,10 @@ export async function readPageSizeStates(engine: Pick<BrainEngine, 'executeRaw'>/** The receipt field for one written page: `{ size_state }` for a large or embed_skip page, else nothing (no query). */export async function sizeStateField(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string,- page: { compiled_truth?: string | null; timeline?: string | null; frontmatter?: Record<string, unknown> | null } | null | undefined): Promise<{ size_state?: PageSizeState }> {+ page: { body_storage?: string | null; body_bytes?: number | string | null; compiled_truth?: string | null; timeline?: string | null; frontmatter?: Record<string, unknown> | null } | null | undefined): Promise<{ size_state?: PageSizeState }> {if (!page) return {};- const bytes = Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8');+ const bytes = page.body_storage === 'segmented' ? Number(page.body_bytes)+ : Buffer.byteLength(page.compiled_truth ?? '', 'utf-8') + Buffer.byteLength(page.timeline ?? '', 'utf-8');if (!isLargePageBytes(bytes) && !isEmbedSkipped(page.frontmatter)) return {};const [state] = await readPageSizeStates(engine, sourceId, [slug]);return state ? { size_state: { embedding: state.embedding, reason: state.reason, bytes: state.bytes } } : {};diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex c7b82d6508..f7c3a049cc 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -16,6 +16,7 @@ import { getEmbeddingModel } from '../ai/gateway.ts';import { jsonRowBatches } from '../batch-rows.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { belowSafeChunkFence, movableChunkSql } from '../search/safe-chunks.ts';+import { buildSegmentedProjection } from '../page-body/projection.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';@@ -140,7 +141,16 @@ async function indexingContext(engine: BrainEngine, snapshot: PageSnapshot, maxCcorpusGeneration: projection?.corpus_generation ?? null };}-/** A short guarded read binds the exact chunk set and title/body revision. */+/** Wave B: a segmented page's snapshot carries no body strings (lane 1c's `isSegmentedPage` shape). */+function segmentedSnapshot(snapshot: PageSnapshot): boolean {+ return (snapshot.page as { body_storage?: unknown }).body_storage === 'segmented';+}++/**+ * A short guarded read binds the exact chunk set and title/body revision.+ * Null for a segmented page: its projection is `buildSegmentedProjection` and+ * its embedding `page-body/segmented-embedding.ts`, never this body read.+ */export async function readProjectionSnapshot(engine: BrainEngine, slug: string, sourceId: string,opts: { allowUnsealed?: boolean; maxChunkTokens?: number; requireLiveSource?: boolean } = {}): Promise<ProjectionSnapshot | null> {return engine.transaction(async tx => {@@ -153,7 +163,7 @@ export async function readProjectionSnapshot(engine: BrainEngine, slug: string,async function readGuardedProjectionSnapshot(tx: BrainEngine, slug: string, sourceId: string,opts: { allowUnsealed?: boolean; maxChunkTokens?: number; requireLiveSource?: boolean }): Promise<ProjectionSnapshot | null> {const snapshot = await tx.readPageSnapshot(slug, { sourceId, ...(opts.requireLiveSource && { requireLiveSource: true }) });- if (!snapshot || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;+ if (!snapshot || segmentedSnapshot(snapshot) || (!opts.allowUnsealed && snapshot.page.text_projection_revision !== snapshot.revision)) return null;const context = await indexingContext(tx, snapshot, opts.maxChunkTokens);const fenceOverlay = context.pageKind === 'markdown' ? await loadFenceChunkOverlay(tx, { sourceId, slug, compiled_truth: snapshot.page.compiled_truth, timeline: snapshot.page.timeline }) : undefined;return { snapshot, chunks: await tx.getChunks(slug, { sourceId, includeUnsealed: true }), indexingContext: context.key,@@ -282,7 +292,7 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Projeawait tx.lockPageKeys([{ sourceId, slug }]);const current = await tx.readPageSnapshot(slug, { sourceId });if (!current || current.page.deleted_at || current.sourceIncarnation !== snapshot.sourceIncarnation || current.page.id !== snapshot.page.id- || current.page.text_projection_revision !== current.revision) return refused;+ || current.page.text_projection_revision !== current.revision || segmentedSnapshot(current)) return refused;const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);if (!source || source.archived) return refused;const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);@@ -497,7 +507,11 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, observed);if (!pending.length) return null;const read = await readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });- if (!read) return null;+ if (!read) {+ const [segmented] = await tx.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND body_storage='segmented' AND deleted_at IS NULL`,+ [job.source_id, job.slug]);+ return segmented ? 'segmented' : null;+ }const { snapshot } = read;if (snapshot.sourceIncarnation === job.source_incarnation && snapshot.revision === job.revision) return read;if (snapshot.sourceIncarnation !== job.source_incarnation || snapshot.page.text_projection_revision === snapshot.revision) {@@ -510,6 +524,15 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =});if (!prepared) { superseded++; continue; }if (prepared === 'removed') { superseded++; opts.onHeal?.({ kind: 'removed', source_id: job.source_id, slug: job.slug }); continue; }+ if (prepared === 'segmented') {+ const built = await buildSegmentedProjection(engine, { sourceId: job.source_id, slug: job.slug });+ await engine.executeRaw(built.sealed+ ? 'DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid'+ : 'UPDATE page_projection_jobs SET updated_at=now() WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', observed);+ if (built.sealed) rebuilt++;+ else superseded++;+ continue;+ }const projection = await preparePageProjection(prepared);await installPageProjection(engine, prepared, projection.chunks, { seal: true, preserveEmbeddings: true, code: projection.code });rebuilt++;diff --git a/src/core/page-state/version-types.ts b/src/core/page-state/version-types.tsindex ac6dcdcf0c..3e2177acc6 100644--- a/src/core/page-state/version-types.ts+++ b/src/core/page-state/version-types.ts@@ -11,6 +11,13 @@ export interface PageVersion {tags?: string[] | null;/** The page's recorded canonical file when the version was taken; NULL on file-less pages and legacy versions. */source_path?: string | null;+ /** Wave B: present only on a segmented version, whose compiled_truth and timeline are NULL (the body lives in segments). */+ body_storage?: 'segmented';+ /** Segmented versions: the body generation the version references. */+ body_generation?: number;+ /** Segmented versions: the referenced body's UTF-8 bytes. */+ body_bytes?: number;+ content_hash?: string | null;id: number;page_id: number;compiled_truth: string;diff --git a/src/core/page-state/versions.ts b/src/core/page-state/versions.tsindex dd9abc5715..0f0c0c047e 100644--- a/src/core/page-state/versions.ts+++ b/src/core/page-state/versions.ts@@ -2,14 +2,11 @@ import type { BrainEngine } from '../engine.ts';import type { PageVersion } from '../types.ts';import type { PageSnapshot } from './types.ts';import { PAGE_INLINE_MAX_BYTES, isLargePageBytes } from '../page-size-policy.ts';+import { LARGE_PAGE_VERSIONS_KEPT, readPageBodyPolicy } from '../page-body/limits.ts';+import { opError, type OperationError } from '../ops/contract.ts';+import type { RegistryCode } from '../error-registry.ts';-/**- * Snapshots of a large page (over the inline cap) kept per page. Each one is a- * full copy of the body, so an append-heavy 24 MiB page would otherwise grow- * history by 24 MiB per write. Snapshots at or under the inline cap, and every- * snapshot of a small page, are never pruned.- */-export const LARGE_PAGE_VERSIONS_KEPT = 5;+export { LARGE_PAGE_VERSIONS_KEPT };/*** Version the same canonical view an API reader receives, including withdrawals.@@ -19,6 +16,7 @@ export const LARGE_PAGE_VERSIONS_KEPT = 5;export async function createPageVersion(engine: BrainEngine, slug: string, sourceId: string, preimage?: PageSnapshot): Promise<PageVersion> {const insert = async (tx: BrainEngine, snapshot: PageSnapshot) => {const { page, tags, revision } = snapshot;+ if ((page as { body_storage?: unknown }).body_storage === 'segmented') return insertSegmentedVersion(tx, snapshot);const rows = await tx.executeRaw<PageVersion>(`INSERT INTO page_versions(page_id,compiled_truth,frontmatter,knowledge_revision,timeline,title,type,tags,is_deleted,source_path)VALUES ($1,$2,$3::text::jsonb,$4::uuid,$5,$6,$7,$8::text::jsonb,$9,$10) RETURNING *`,@@ -38,3 +36,65 @@ export async function createPageVersion(engine: BrainEngine, slug: string, sourcreturn insert(tx, snapshot);});}++/**+ * Wave B (spec 5): a segmented page's version is a reference, not a copy: the+ * page's live body generation (its manifest rows stay alive as a GC root),+ * body_bytes and content_hash with NULL body columns, O(1) at any page size.+ * It references the generation live when it is inserted, so a caller versions+ * before its generation flip, as every caller versions before its page write.+ * Then the page's segmented history is pruned by `pruneSegmentedVersions`.+ */+async function insertSegmentedVersion(tx: BrainEngine, snapshot: PageSnapshot): Promise<PageVersion> {+ const { page, tags, revision } = snapshot;+ const [row] = await tx.executeRaw<PageVersion>(`INSERT INTO page_versions+ (page_id,compiled_truth,timeline,body_storage,body_generation,body_bytes,content_hash,frontmatter,knowledge_revision,title,type,tags,is_deleted,source_path)+ SELECT p.id,NULL,NULL,'segmented',p.body_generation,p.body_bytes,p.content_hash,$2::text::jsonb,$3::uuid,$4,$5,$6::text::jsonb,$7,$8+ FROM pages p WHERE p.id = $1 AND p.body_storage = 'segmented' RETURNING *`,+ [page.id, JSON.stringify(page.frontmatter), revision, page.title, page.type, JSON.stringify(tags), page.deleted_at != null, page.source_path ?? null]);+ if (!row) throw new Error(`createVersion failed: page id ${page.id} is no longer segmented`);+ if ((await pruneSegmentedVersions(tx, page.id)) > 0) await tx.sweepSegments({ pageId: page.id });+ return { ...row, snapshot_at: new Date(row.snapshot_at) };+}++/**+ * Segmented retention (spec 5): keep the newest `versions.segmented_max_per_page`+ * segmented versions of the page, and prune oldest-first while the bytes they+ * pin beyond the live generation (manifest rows a kept version's generation+ * references that are closed, each counted once) exceed+ * max(`versions.segmented_max_pinned_bytes`, the page's body_bytes). A row's+ * bytes count from the newest version that references it, so the pinned bytes+ * of the newest k versions are a running sum and the kept set is a prefix.+ * Inline snapshots of the page are never touched here. Returns the versions deleted.+ */+export async function pruneSegmentedVersions(tx: BrainEngine, pageId: number): Promise<number> {+ const policy = await readPageBodyPolicy(tx);+ const deleted = await tx.executeRaw(`WITH v AS (+ SELECT id, body_generation AS g, row_number() OVER (ORDER BY id DESC) AS rk+ FROM page_versions WHERE page_id = $1 AND body_storage = 'segmented'),+ pinned AS (+ SELECT min(v.rk) AS rk, m.byte_len+ FROM page_body_manifest m JOIN v ON m.gen_from <= v.g AND v.g < m.gen_to+ WHERE m.page_id = $1 AND m.gen_to IS NOT NULL AND m.staging_id IS NULL+ GROUP BY m.occurrence_id, m.gen_from, m.byte_len),+ per_rank AS (SELECT rk, sum(byte_len) AS bytes FROM pinned GROUP BY rk),+ kept AS (+ SELECT v.id, v.rk, sum(COALESCE(per_rank.bytes, 0)) OVER (ORDER BY v.rk) AS bytes+ FROM v LEFT JOIN per_rank ON per_rank.rk = v.rk),+ cap AS (SELECT GREATEST($3::bigint, COALESCE(body_bytes, 0)) AS bytes FROM pages WHERE id = $1)+ DELETE FROM page_versions WHERE id IN (SELECT kept.id FROM kept, cap WHERE kept.rk > $2 OR kept.bytes > cap.bytes)+ RETURNING id`, [pageId, policy.versionsMaxPerPage, policy.versionsMaxPinnedBytes]);+ return deleted.length;+}++/**+ * `revert_version` of a segmented page or version is not available until the+ * segment writer (Wave B PR 3): the version's body lives in segments, and the+ * revert path rebuilds the page from an inline body. Refused before anything is written.+ */+export function segmentedRevertRefusal(slug: string, versionId: unknown): OperationError {+ return opError('page_body_segmented' as RegistryCode,+ `Page ${slug} or its version ${String(versionId)} is stored in segments, so revert_version cannot restore it yet; nothing was changed.`,+ `Read the version with get_versions (body_bytes, content_hash), then write the content you want with put_page or edit_page.`,+ { reason: 'segmented_revert' });+}diff --git a/src/core/persistence/effect-model.ts b/src/core/persistence/effect-model.tsindex e771ce6fc8..2bc1150e96 100644--- a/src/core/persistence/effect-model.ts+++ b/src/core/persistence/effect-model.ts@@ -57,6 +57,8 @@ export interface PersistenceEffect {source_incarnation: string;worktree_id: string | null;data: { version?: 2; targets?: WithdrawalTarget[]; slug?: string; page_id?: number; relative_path?: string; expected_hash?: string | null; after_slug?: string; source_id?: string; source_scan?: boolean; visibility?: 'private' | 'world'; embedding_attempt_base?: number; embedding_retry_base?: number;+ /** Wave B: the occurrences a segmented write added; its embedding effect embeds only their chunk rows. */+ occurrence_ids?: number[];/** A single-file Git target's GitCommitNote, when its preparer gave one. */commit_subject?: string;commit_line?: string;diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.tsindex a0ffced3c7..6f1e7b44ae 100644--- a/src/core/persistence/effects.ts+++ b/src/core/persistence/effects.ts@@ -16,6 +16,8 @@ import { serializePageToMarkdown } from '../markdown.ts';import { isWriteTargetContained } from '../path-confine.ts';import { materializePageSnapshot } from '../page-state/materialize.ts';import { installPageEmbeddings, readProjectionSnapshot } from '../page-state/projections.ts';+import { embedSegmentedPage, readSegmentedEmbedPage, type SegmentedEmbedPage } from '../page-body/segmented-embedding.ts';+import { resolveProvenanceStamp, stampIfPageProvenanceComplete } from '../embed-stale.ts';import { currentEmbeddingSignature, embedBatch } from '../embedding.ts';import { assertEmbeddingEnabled, EmbeddingDisabledError } from '../embedding-dim-check.ts';import { validateEmbeddingCreds, EmbeddingCredentialError } from '../embed-preflight.ts';@@ -46,6 +48,7 @@ import { nativeFileTarget } from './native-file-target.ts';import { sourceMirrorReadOnly } from './mirror-read-only.ts';import { isLockOpenFailure } from './native-lock.ts';import { planPageEmbedding } from '../page-embedding-budget.ts';+import { chunkGenerationFilter } from '../search/safe-chunks.ts';const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(`Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,@@ -291,7 +294,7 @@ export async function readEmbeddingEffectProjection(engine: BrainEngine, effect:const completion = await tx.executeRaw<{ id: number; complete: boolean }>(`SELECT cc.id,p.embedding_signature=$2 AND cc.${quoteIdentifier(column.name)} IS NOT NULL AND cc.embedded_at IS NOT NULLAND cc.embedded_text_hash=md5(cc.chunk_text) AND cc.model IS NOT DISTINCT FROM $3 AS complete- FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.id=$1`,+ FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE p.id=$1 AND ${chunkGenerationFilter('p', 'cc')}`,[snapshot.page.id, signature, embeddingCompletionModel(column, signature, model)]);const complete = new Set(completion.filter(chunk => chunk.complete === true).map(chunk => chunk.id));const pending = prepared.chunks.filter(chunk => !complete.has(chunk.id));@@ -310,6 +313,8 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers`Page ${snapshot.page.slug} in source ${effect.source_id} was saved but cannot be embedded: this brain has no embedding provider. Pages and keyword search keep working; check embedding readiness and ask the user before configuring a paid provider.`,{ fix: embeddingsFix() });if (isEmbedSkipped(snapshot.page.frontmatter)) { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'embed_skip' }); return; }+ const segmented = await readSegmentedEmbedPage(engine, { id: snapshot.page.id });+ if (segmented) { await embedSegmentedEffect(engine, config, effect, snapshot, segmented, signature, opts); return; }const projection = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);const { prepared } = projection;let pending = projection.pending;@@ -411,6 +416,43 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Persawait finishPage(engine, effect, snapshot);}+/**+ * Wave B: a segmented page's embedding effect embeds only the rows of the+ * occurrences its write added (`data.occurrence_ids`; every stale live row+ * without them), by keyset and without reading the body. Each provider call+ * renews the claim first, and each install re-checks the claim, the source and+ * the embedding switch under the page guard.+ */+async function embedSegmentedEffect(engine: BrainEngine, config: GBrainConfig, effect: PersistenceEffect, snapshot: PageSnapshot,+ page: SegmentedEmbedPage, signature: string, opts: EffectWorkerOptions): Promise<void> {+ await assertEmbeddingEffectEnabled(engine, config);+ if (effect.attempts - (effect.data.embedding_retry_base ?? effect.data.embedding_attempt_base ?? 0) > MAX_RATE_LIMIT_RETRIES) {+ await failEffect(engine, effect, 'embedding_attempts_exhausted'); return;+ }+ if (!opts.embedding) validateEmbeddingCreds();+ const claimLost = () => opError('write_claim_lost', 'The embedding claim changed.',+ `Another worker took over the embedding of ${page.slug} in source ${effect.source_id}; this attempt stops without installing vectors and the owning claim finishes it.`,+ { fix: effectStatusFix(effect) });+ const embed = opts.embedding?.embed ?? embedBatch;+ const result = await embedSegmentedPage(engine, page, { signature, signal: opts.signal, occurrenceIds: effect.data.occurrence_ids,+ embedFn: (texts, o) => withAIInvocationPreflight(async () => {+ opts.signal?.throwIfAborted();+ if (!await renewPersistenceEffectClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, effect)) throw claimLost();+ await assertEmbeddingEffectEnabled(engine, config);+ }, async () => (await embed(texts, { abortSignal: o.abortSignal, maxRetries: 0 })) as Float32Array[]),+ beforeInstall: async tx => {+ await guardEffectSource(tx, effect, opts.hostId);+ const [claim] = await tx.executeRaw<PersistenceEffect>('SELECT state,execution_token FROM persistence_effects WHERE id=$1 FOR UPDATE', [effect.id]);+ if (claim?.state !== 'running' || claim.execution_token !== effect.execution_token) throw claimLost();+ await assertEmbeddingEffectEnabled(tx, config);+ } });+ if (result.stopped === 'budget') { await completeEffect(engine, effect, { embedding: 'skipped', reason: 'budget_capped' }); return; }+ if (result.stopped === 'page_moved') { await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return; }+ const stamp = await resolveProvenanceStamp(engine, signature);+ if (stamp) await stampIfPageProvenanceComplete(engine, page.slug, page.source_id, stamp);+ await finishPage(engine, effect, snapshot);+}+export async function assertEmbeddingEffectEnabled(engine: BrainEngine, config: GBrainConfig | null): Promise<void> {assertEmbeddingEnabled(config);const disabled = await engine.getConfig('embedding_disabled').catch(error => { throw embeddingStorageFailure(error); });diff --git a/src/core/persistence/noop-kernel.ts b/src/core/persistence/noop-kernel.tsindex 1ff346a70f..a23019ab9f 100644--- a/src/core/persistence/noop-kernel.ts+++ b/src/core/persistence/noop-kernel.ts@@ -32,7 +32,7 @@ import type { PreparedMutation } from './coordinator.ts';import { persistenceFileHash } from './coordinator.ts';import type { WriteRequest } from './model.ts';import type { PageSnapshot } from '../page-state/types.ts';-import { belowSafeChunkFence } from '../search/safe-chunks.ts';+import { belowSafeChunkFence, chunkGenerationFilter } from '../search/safe-chunks.ts';import { sha256 } from './digest.ts';export interface NoopKernelResult {@@ -73,8 +73,8 @@ export async function inspectUnchanged(engine: Pick<BrainEngine, 'executeRaw'>,if (observedRevision !== snapshot.revision) return result('revision_moved');const [page] = await engine.executeRaw<{ chunker_version: number | null; text_projection_revision: string | null; knowledge_revision: string;mode_pending: boolean; unembedded: boolean; source_path: string | null }>(`SELECT p.chunker_version,p.text_projection_revision::text,p.knowledge_revision::text,p.source_path,- (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL)) AS mode_pending,- EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL) AS unembedded+ (p.contextual_retrieval_mode IS NULL AND EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NOT NULL AND ${chunkGenerationFilter('p', 'c')})) AS mode_pending,+ EXISTS (SELECT 1 FROM content_chunks c WHERE c.page_id=p.id AND c.embedding IS NULL AND ${chunkGenerationFilter('p', 'c')}) AS unembeddedFROM pages p WHERE p.id=$1 AND p.deleted_at IS NULL`, [snapshot.page.id]);if (!page) return result('page_missing');// The page's current revision, read after the preparer ran: a write that landed since the snapshot was read is admitted.diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 717e365be7..ecc240dd57 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -41,6 +41,7 @@ import { isUnboundSourcePage } from './unbound-source.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';import { pipelined } from '../page-state/transactions.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';+import { segmentedRevertRefusal } from '../page-state/versions.ts';import { materializeTimeline, prepareCanonicalProjections, type TimelineRowsRemoved } from './canonical-projections.ts';import { assertTimelineNotOmitted, timelineWritePolicy } from './timeline-omission.ts';import { preserveProtectedTakes } from './protected-takes.ts';@@ -440,6 +441,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ'SELECT * FROM page_versions WHERE id=$1 AND page_id=$2', [p.version_id, page.id]);if (!version) throw pageRefusal('not_found', 'Version not found for this page.', row,`Version ${String(p.version_id)} is not in the history of page ${row.slug}, so nothing was reverted. List the page's versions (get_versions; CLI: gbrain history) and revert to one of them.`);+ if (version.body_storage === 'segmented' || (page as { body_storage?: unknown }).body_storage === 'segmented') throw segmentedRevertRefusal(row.slug, p.version_id);targetDeleted = version.is_deleted ?? (snapshot.page.deleted_at != null);page = { ...page, compiled_truth: version.compiled_truth, frontmatter: version.frontmatter,...(version.timeline !== null && version.timeline !== undefined ? { timeline: version.timeline } : {}),diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 98349b4bc0..6d0150e73b 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -1411,7 +1411,7 @@ export class PGLiteEngine implements BrainEngine {const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);// v0.26.5: visibility filter (soft-deleted + archived-source).- const visibilityClause = buildVisibilityClause('p', 's', opts);+ const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');// v0.32.7: CJK query branch. PGLite uses websearch_to_tsquery('english')// which can't tokenize CJK; queries return empty. Switch to ILIKE on@@ -1622,7 +1622,7 @@ export class PGLiteEngine implements BrainEngine {const sourceFactorCase = buildSourceFactorCase('p.slug', boostMap, opts?.detail);const hardExcludePrefixes = resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes);const hardExcludeClause = buildHardExcludeClause('p.slug', hardExcludePrefixes);- const visibilityClause = buildVisibilityClause('p', 's', opts);+ const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');// v0.32.7: CJK branch (same as searchKeyword but without page-dedup).if (hasCJK(query)) {diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 129239a575..b5f3caf487 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -1005,7 +1005,7 @@ export class PostgresEngine implements BrainEngine {if (hasCJK(query)) {return this._searchKeywordCJK(query, {limit, offset, innerLimit, sourceFactorCase, hardExcludeClause,- visibilityClause: buildVisibilityClause('p', 's', opts),+ visibilityClause: buildVisibilityClause('p', 's', opts, 'cc'),detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',opts, dedup: true,});@@ -1077,7 +1077,7 @@ export class PostgresEngine implements BrainEngine {// archived sources. Joined `sources s` lets the predicate compile to a// column lookup. NOT bypassed by detail=high — soft-delete is a contract,// not a temporal preference.- const visibilityClause = buildVisibilityClause('p', 's', opts);+ const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();@@ -1228,7 +1228,7 @@ export class PostgresEngine implements BrainEngine {limit, offset,innerLimit: 0, // unused on chunk-grain (no inner CTE)sourceFactorCase, hardExcludeClause,- visibilityClause: buildVisibilityClause('p', 's', opts),+ visibilityClause: buildVisibilityClause('p', 's', opts, 'cc'),detailFilter: detailLow ? `AND cc.chunk_source = 'compiled_truth'` : '',opts, dedup: false,});@@ -1290,7 +1290,7 @@ export class PostgresEngine implements BrainEngine {const offsetParam = `$${params.length}`;// v0.26.5: visibility filter for searchKeywordChunks (anchor primitive).- const visibilityClause = buildVisibilityClause('p', 's', opts);+ const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');// FTS config name (e.g. 'english', 'pt_br'). Validated by getFtsLanguage()// — safe to interpolate into raw SQL.const ftsLang = getFtsLanguage();diff --git a/src/core/search/cjk-keyword-sql.ts b/src/core/search/cjk-keyword-sql.tsindex 05a4e58e68..2b05d6cb6b 100644--- a/src/core/search/cjk-keyword-sql.ts+++ b/src/core/search/cjk-keyword-sql.ts@@ -110,6 +110,7 @@ export function buildCJKKeywordSql(query: string, ctx: CjkKeywordCtx, variant: Clet fromClause = 'content_chunks cc';if (variant.candidateIds) {params.push(variant.candidateIds);+ // chunk-visibility-ok: ctx.visibilityClause is buildVisibilityClause(..., 'cc') (engine searchKeywordCJK)fromClause = `unnest($${params.length}::bigint[]) AS cand(id) JOIN content_chunks cc ON cc.id = cand.id`;}const { whereLikeClause, matchedExpr } = likeClauses(terms, likeParamIndices, any);@@ -165,6 +166,7 @@ export function buildCJKCandidateSql(const capIndex = params.length;const { whereLikeClause } = likeClauses(terms, likeParamIndices, stage.match === 'any' && terms.length > 1);return {+ // chunk-visibility-ok: ctx.visibilityClause is buildVisibilityClause(..., 'cc') (engine searchKeywordCJK)sql: `SELECT cc.id AS chunk_idFROM content_chunks ccJOIN pages p ON p.id = cc.page_iddiff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex 96c42deef8..708725ec65 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -27,7 +27,7 @@ import { estimateTokens as heuristicTokens } from './token-budget.ts';import { redactRetrievalOutput } from './output-redaction.ts';import { buildSnippetMarker } from './snippet-cap.ts';import { pageReadFilter } from './read-policy-sql.ts';-import { currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } from './safe-chunks.ts';+import { chunkGenerationFilter, currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } from './safe-chunks.ts';import { resolveExcludePrivatePages } from './private-visibility.ts';import { safeSplitIndex } from '../text-safe.ts';import { loadFenceChunkOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';@@ -1435,7 +1435,7 @@ export async function resolveFrozenHits(cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM unnest($1::text[], $2::text[], $3::int[], $4::int[]) AS h(source_id, slug, chunk_id, ord)JOIN pages p ON p.source_id = h.source_id AND p.slug = h.slug- LEFT JOIN content_chunks cc ON cc.page_id = p.id+ LEFT JOIN content_chunks cc ON cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')}AND CASE WHEN h.chunk_id > 0 THEN cc.id = h.chunk_id ELSE cc.chunk_index = 0 ENDWHERE ${filter} AND ${currentTextProjectionFilter('p')} ${safe}`,params,diff --git a/src/core/search/explain-target.ts b/src/core/search/explain-target.tsindex 3a99f656c7..fa66d178e1 100644--- a/src/core/search/explain-target.ts+++ b/src/core/search/explain-target.ts@@ -24,7 +24,7 @@import type { SearchResult, PageReadPolicy } from '../types.ts';import type { Action } from '../agent-output.ts';import { pageReadFilter } from './read-policy-sql.ts';-import { belowSafeChunkFence } from './safe-chunks.ts';+import { belowSafeChunkFence, chunkGenerationFilter } from './safe-chunks.ts';export interface ExplainTargetRef {slug: string;@@ -180,7 +180,7 @@ export async function probeTarget(query: ReadQuery, slug: string, policy: PageReconst filter = pageReadFilter('p', policy, params, true);const rows = await query<{ source_id: string; chunks: number; current: boolean; chunker_version: number | null }>(`SELECT p.source_id,- (SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id) AS chunks,+ (SELECT COUNT(*)::int FROM content_chunks cc WHERE cc.page_id = p.id AND ${chunkGenerationFilter('p', 'cc')}) AS chunks,((p.text_projection_revision = p.knowledge_revision) IS TRUE) AS current,p.chunker_versionFROM pages p WHERE p.slug = $1 AND ${filter} ORDER BY p.source_id`, params);diff --git a/src/core/search/image-vector-presence.ts b/src/core/search/image-vector-presence.tsindex 95bdc38f3d..c0919164cb 100644--- a/src/core/search/image-vector-presence.ts+++ b/src/core/search/image-vector-presence.ts@@ -16,6 +16,7 @@ export async function brainHasImageVectors(engine: Pick<BrainEngine, 'executeRawif (hit && now - hit.at < TTL_MS) return hit.value;let value = true;try {+ // chunk-visibility-ok: image vectors live on image pages, which are never segmented (chooseBodyStorage)const [row] = await engine.executeRaw<{ present: boolean }>('SELECT EXISTS (SELECT 1 FROM content_chunks WHERE embedding_image IS NOT NULL) AS present');value = row?.present === true || (row?.present as unknown) === 't';} catch {diff --git a/src/core/search/keyword-chunk-match.ts b/src/core/search/keyword-chunk-match.tsindex 2c1a42dae2..48ea171a8f 100644--- a/src/core/search/keyword-chunk-match.ts+++ b/src/core/search/keyword-chunk-match.ts@@ -20,8 +20,9 @@ export function buildKeywordChunkMatch(ftsLang: string, excludePrivate: booleanconst tsq = `websearch_to_tsquery('${ftsLang}', $1)`;if (!excludePrivate) return { from: 'content_chunks cc', match: `cc.search_vector @@ ${tsq}`, modality: `AND cc.modality = 'text'` };return {+ // chunk-visibility-ok: the outer search statement applies buildVisibilityClause(..., 'cc') to the generation columns this subquery projectsfrom: `(- SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type+ SELECT id, page_id, chunk_index, chunk_text, chunk_source, search_vector, language, symbol_type, body_generation, retired_generationFROM content_chunksWHERE search_vector @@ ${tsq} AND modality = 'text'OFFSET 0diff --git a/src/core/search/keyword-statement.ts b/src/core/search/keyword-statement.tsindex 8d690900a5..0f47ed15f2 100644--- a/src/core/search/keyword-statement.ts+++ b/src/core/search/keyword-statement.ts@@ -78,7 +78,7 @@ export function buildKeywordMatch(query: string, opts: SearchOpts | undefined):const hardExclude = buildHardExcludeClause('p.slug', resolveHardExcludes(opts?.exclude_slug_prefixes, opts?.include_slug_prefixes));const factor = buildSourceFactorCase('p.slug', opts?.source_boosts ?? resolveBoostMap(), opts?.detail);return {- where: `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', opts)} AND cc.modality = 'text'`,+ where: `${predicate}${filters} ${hardExclude} ${buildVisibilityClause('p', 's', opts, 'cc')} AND cc.modality = 'text'`,score: `((${rank}) * ${factor})::float8`,params,};diff --git a/src/core/search/read-enrichment.ts b/src/core/search/read-enrichment.tsindex a2537dac63..d5c49cc283 100644--- a/src/core/search/read-enrichment.ts+++ b/src/core/search/read-enrichment.ts@@ -1,6 +1,6 @@import type { PageReadScope, PageReadPolicy, AdjacencyRow, RelationalFanoutOpts, RelationalFanoutRow, ChainHopOpts, ChainHopEdge } from '../types.ts';import { unverifiedExtractionFragment } from '../extraction-review.ts';-import { currentTextProjectionFilter, protectedBodyFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';+import { chunkGenerationProbe, currentTextProjectionFilter, protectedBodyFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';import { hasReadPolicy, pageReadFilter } from './read-policy-sql.ts';import { relationshipFilterSql } from '../link-validity.ts';@@ -70,7 +70,7 @@ export async function readRelationalFanout(query: ReadQuery, seeds: string[], oparray_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS path_str,(array_agg(array_to_string(n.edges, chr(9)) ORDER BY n.depth ASC,array_length(n.path, 1) ASC, array_to_string(n.path, chr(9)) ASC))[1] AS edges_str,- (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = n.id+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = n.id AND ${chunkGenerationProbe('cc')}${requiresSafeChunks(opts) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = n.id AND ${safeChunksFilter('cp')})` : ''}ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_idFROM walk n WHERE n.depth > 0 GROUP BY n.source_id, n.slug, n.id@@ -212,7 +212,7 @@ export async function readChainHop(query: ReadQuery, frontier: number[], opts: Cr.link_ids, sf.slug AS stored_from_slug, st.slug AS stored_to_slug,CASE WHEN ev.id IS NOT NULL ${textGate} THEN el.context END AS context,el.origin_page_id, op.slug AS origin_slug, deg.degree AS from_degree, (r.per_frontier > $5) AS cap_hit,- (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = r.next_id+ (SELECT cc.id FROM content_chunks cc WHERE cc.page_id = r.next_id AND ${chunkGenerationProbe('cc')}${requiresSafeChunks(policy) ? `AND EXISTS (SELECT 1 FROM pages cp WHERE cp.id = r.next_id AND ${safeChunksFilter('cp')})` : ''}ORDER BY cc.chunk_index ASC LIMIT 1) AS canonical_chunk_idFROM ranked rdiff --git a/src/core/search/safe-chunks.ts b/src/core/search/safe-chunks.tsindex 22bba5bc49..997720fb5d 100644--- a/src/core/search/safe-chunks.ts+++ b/src/core/search/safe-chunks.ts@@ -38,6 +38,44 @@ export function currentTextProjectionFilter(alias: string): string {return `(${alias}.text_projection_revision = ${alias}.knowledge_revision) IS TRUE`;}+/**+ * Wave B: the chunk row belongs to its page's live body generation. Staged rows+ * (`body_generation` above the page's) and retired rows are invisible; every+ * inline-page row (`body_generation IS NULL`) passes. Row predicate, no join.+ */+export function chunkGenerationFilter(page: string, chunk: string): string {+ return `(${chunk}.body_generation IS NULL+ OR (${chunk}.body_generation <= ${page}.body_generation+ AND (${chunk}.retired_generation IS NULL OR ${chunk}.retired_generation > ${page}.body_generation)))`;+}++/** `chunkGenerationFilter` for a statement that has no page row joined: inline rows pass without the page lookup. */+export function chunkGenerationProbe(chunk: string): string {+ return `(${chunk}.body_generation IS NULL+ OR EXISTS (SELECT 1 FROM pages gp WHERE gp.id = ${chunk}.page_id AND ${chunkGenerationFilter('gp', chunk)}))`;+}++/** Search-facing chunk visibility: the current text projection and the live body generation. */+export function chunkVisibleFilter(page: string, chunk: string): string {+ return `(${currentTextProjectionFilter(page)} AND ${chunkGenerationFilter(page, chunk)})`;+}++/**+ * The live manifest row of a segmented chunk (no row for an inline chunk), for+ * `chunkDocumentOrder`. LEFT JOIN text; `page` must expose `body_generation`.+ */+export function chunkManifestJoin(page: string, chunk: string, manifest: string): string {+ return `LEFT JOIN page_body_manifest ${manifest} ON ${chunk}.occurrence_id IS NOT NULL+ AND ${manifest}.page_id = ${chunk}.page_id AND ${manifest}.occurrence_id = ${chunk}.occurrence_id+ AND ${manifest}.gen_from <= ${page}.body_generation+ AND (${manifest}.gen_to IS NULL OR ${manifest}.gen_to > ${page}.body_generation)`;+}++/** Document order: (manifest byte_start, local_ordinal) for segmented rows; inline rows keep chunk_index order. */+export function chunkDocumentOrder(chunk: string, manifest: string): string {+ return `${manifest}.byte_start, ${chunk}.local_ordinal, ${chunk}.chunk_index`;+}+/** A page of any kind chunked before the fence; remote reads withhold it until it is re-sealed. */export function belowSafeChunkFence(chunkerVersion: number | null | undefined): boolean {return (chunkerVersion ?? 0) < SAFE_FENCE_CHUNKER_VERSION;@@ -62,6 +100,7 @@ export function safeChunksFilter(alias: string): string {*/export function* chunkWriteInvalidations(pageId: number, chunks: ChunkInput[]): Generator<{ sql: string; params: unknown[] }> {const metadata = ['language', 'symbol_name', 'symbol_type', 'start_line', 'end_line', 'parent_symbol_path', 'doc_comment', 'symbol_name_qualified'] as const;+ // chunk-visibility-ok: inline chunk write invalidation; segmented pages stage rows through stageSegmentChunksconst sql = `UPDATE pages SET chunker_version = -1 WHERE id = $1 AND (NOT (${safeChunksFilter('pages')})OR EXISTS (SELECT 1 FROM content_chunks cc WHERE cc.page_id = $1 AND cc.chunk_index <> ALL($3::int[]))diff --git a/src/core/search/sql-ranking.ts b/src/core/search/sql-ranking.tsindex 6fc1fa0874..9a93957f97 100644--- a/src/core/search/sql-ranking.ts+++ b/src/core/search/sql-ranking.ts@@ -20,7 +20,7 @@import { quarantineFilterFragment } from '../quarantine.ts';import { unverifiedExtractionFragment } from '../extraction-review.ts';import { privatePagesFilterFragment } from './private-visibility.ts';-import { currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';+import { chunkVisibleFilter, currentTextProjectionFilter, requiresSafeChunks, safeChunksFilter } from './safe-chunks.ts';import { pageEligibleSql } from '../eligibility/sql.ts';import type { TrustTier } from '../trust/tier.ts';@@ -169,6 +169,9 @@ export function buildHardExcludeClause(slugColumn: string, prefixes: string[]):* @param pageAlias — page table alias (e.g. `'p'`)* @param sourceAlias — source table alias (e.g. `'s'`); the caller is* responsible for joining `sources` so this alias resolves.+ * @param chunkAlias — chunk table alias when the statement reads `content_chunks`+ * rows joined to the page: adds the live body generation+ * predicate (`chunkVisibleFilter`, Wave B).** @returns raw SQL fragment, e.g.* `AND p.deleted_at IS NULL AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine')`@@ -192,6 +195,7 @@ export function buildVisibilityClause(minTrust?: TrustTier;suppressFlagged?: boolean;},+ chunkAlias?: string,): string {// Single source of truth for the quarantine SQL lives in quarantine.ts so// the marker key + filter can't drift from the search filter (#1699).@@ -207,7 +211,8 @@ export function buildVisibilityClause(const pinnedQuestion = ` AND NOT (COALESCE(${pageAlias}.frontmatter, '{}'::jsonb) ? 'pinned_question')`;const trustClause = opts?.minTrust || opts?.suppressFlagged? ` AND ${pageEligibleSql(pageAlias, { floor: opts.minTrust, suppressFlagged: opts.suppressFlagged })}` : '';- return `AND ${pageAlias}.deleted_at IS NULL AND ${currentTextProjectionFilter(pageAlias)} AND NOT ${sourceAlias}.archived AND ${quarantine}${pinnedQuestion}${privateClause}${chunksClause}${trustClause}`;+ const projection = chunkAlias ? chunkVisibleFilter(pageAlias, chunkAlias) : currentTextProjectionFilter(pageAlias);+ return `AND ${pageAlias}.deleted_at IS NULL AND ${projection} AND NOT ${sourceAlias}.archived AND ${quarantine}${pinnedQuestion}${privateClause}${chunksClause}${trustClause}`;}// ============================================================diff --git a/src/core/search/title-statement.ts b/src/core/search/title-statement.tsindex ace3be0b08..e57993fdc7 100644--- a/src/core/search/title-statement.ts+++ b/src/core/search/title-statement.ts@@ -9,7 +9,7 @@ import type { SearchOpts } from '../types.ts';import { clampSearchLimit } from '../engine.ts';import { searchLimitCap } from './eval-pool-depth.ts';import { getFtsLanguage } from '../fts-language.ts';-import { requiresSafeChunks } from './safe-chunks.ts';+import { chunkGenerationFilter, requiresSafeChunks } from './safe-chunks.ts';import { normalizeAlias } from './alias-normalize.ts';import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';import {@@ -107,7 +107,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undconst sql = `WITH top_pages AS (SELECT p.slug, p.id AS page_id, p.title, p.type, p.source_id,- p.effective_date, p.effective_date_source, p.updated_at,+ p.effective_date, p.effective_date_source, p.updated_at, p.body_generation,(lower(btrim(p.title, ' "''' || chr(160))) = $2) AS exact_title,${rankSql} * ${sourceFactorCase} AS scoreFROM pages p@@ -131,7 +131,7 @@ export function buildSearchTitlesStatement(query: string, opts: SearchOpts | undLEFT JOIN LATERAL (SELECT cc.id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks cc- WHERE cc.page_id = tp.page_id+ WHERE cc.page_id = tp.page_id AND ${chunkGenerationFilter('tp', 'cc')}AND cc.modality = 'text'${detailLow ? `AND cc.chunk_source = 'compiled_truth'` : ''}ORDER BY (cc.chunk_source = 'compiled_truth') DESC, cc.chunk_index ASCdiff --git a/src/core/search/two-pass.ts b/src/core/search/two-pass.tsindex b0382e64a4..4b28ea4a9d 100644--- a/src/core/search/two-pass.ts+++ b/src/core/search/two-pass.ts@@ -23,7 +23,7 @@import type { BrainEngine } from '../engine.ts';import type { SearchResult } from '../types.ts';-import { currentTextProjectionFilter } from './safe-chunks.ts';+import { chunkVisibleFilter } from './safe-chunks.ts';import { readEdgeResolution } from '../chunkers/symbol-resolver.ts';const MAX_WALK_DEPTH = 2;@@ -87,6 +87,7 @@ export async function expandAnchors(try {const rows = opts.sourceId? await engine.executeRaw<{ id: number }>(+ // chunk-visibility-ok: code symbol anchors: code pages are never segmented (chooseBodyStorage)`SELECT cc.id FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE cc.symbol_name_qualified = $1 AND p.source_id = $2@@ -94,6 +95,7 @@ export async function expandAnchors([opts.nearSymbol, opts.sourceId],): await engine.executeRaw<{ id: number }>(+ // chunk-visibility-ok: code symbol anchors: code pages are never segmented (chooseBodyStorage)`SELECT id FROM content_chunks WHERE symbol_name_qualified = $1 LIMIT 50`,[opts.nearSymbol],);@@ -161,6 +163,7 @@ export async function expandAnchors(try {const resolved = opts.sourceId? await engine.executeRaw<{ id: number }>(+ // chunk-visibility-ok: code symbol targets: code pages are never segmented (chooseBodyStorage)`SELECT cc.id FROM content_chunks ccJOIN pages p ON p.id = cc.page_idWHERE cc.symbol_name_qualified = ANY($1::text[])@@ -169,6 +172,7 @@ export async function expandAnchors([unresolvedTargets, opts.sourceId],): await engine.executeRaw<{ id: number }>(+ // chunk-visibility-ok: code symbol targets: code pages are never segmented (chooseBodyStorage)`SELECT id FROM content_chunks WHERE symbol_name_qualified = ANY($1::text[]) LIMIT ${NEIGHBOR_CAP_PER_HOP}`,[unresolvedTargets],);@@ -211,7 +215,7 @@ export async function hydrateChunks(cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_sourceFROM content_chunks ccJOIN pages p ON p.id = cc.page_id- WHERE cc.id = ANY($1::int[]) AND ${currentTextProjectionFilter('p')}`,+ WHERE cc.id = ANY($1::int[]) AND ${chunkVisibleFilter('p', 'cc')}`,[chunkIds],);return rows.map((r) => ({diff --git a/src/core/search/vector-statement.ts b/src/core/search/vector-statement.tsindex b2dc86a09d..8b8ffe08ba 100644--- a/src/core/search/vector-statement.ts+++ b/src/core/search/vector-statement.ts@@ -63,6 +63,7 @@ import { unverifiedExtractionFragment } from '../extraction-review.ts';import { buildVectorCastFragment, normalizeEngineColumn } from './embedding-column.ts';import { resolveBoostMap, resolveHardExcludes } from './source-boost.ts';import { buildBestPerPagePoolCte, buildHardExcludeClause, buildSourceFactorCase, buildVisibilityClause } from './sql-ranking.ts';+import { chunkGenerationProbe } from './safe-chunks.ts';export const VECTOR_EXTENSION_VERSION_SQL = `SELECT extversion FROM pg_extension WHERE extname = 'vector'`;export const SET_STATEMENT_TIMEOUT_SQL = `SELECT set_config('statement_timeout', $1, true)`;@@ -172,6 +173,7 @@ export const SCOPE_CHUNK_SAMPLE_PAGES = 400;* deterministic (`hashint4`, so interleaved page ids do not alias a stride)* and costs one pass over the scope's page ids plus ~400 index probes.*/+// chunk-visibility-ok: planner size estimate; staged rows only nudge the sample countexport const SCOPE_CHUNKS_SQL = `WITH scope_pages AS MATERIALIZED (SELECT id FROM pages WHERE source_id = ANY($1::text[]) AND deleted_at IS NULL),total AS (SELECT count(*)::int AS pages FROM scope_pages),@@ -322,7 +324,8 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): Vconst modalityFilter = resolvedCol.name === 'embedding_image' ? `AND cc.modality = 'image'`: resolvedCol.name === 'embedding_multimodal' ? '' : `AND cc.modality = 'text'`;// v0.26.5: visibility in the inner CTE so hidden rows never take candidate slots.- const visibilityClause = buildVisibilityClause('p', 's', opts);+ const visibilityClause = buildVisibilityClause('p', 's', opts, 'cc');+ const pageVisibilityClause = buildVisibilityClause('p', 's', opts);const candidateFrom = (generation: string) => `FROM content_chunks ccJOIN pages p ON p.id = cc.page_idJOIN sources s ON s.id = p.source_id@@ -394,8 +397,9 @@ export function buildVectorSearchStatement(input: VectorSearchStatementInput): VWHERE true${pageFilters.join('\n ')}${hardExcludeClause}- ${visibilityClause}+ ${pageVisibilityClause}))+ AND ${chunkGenerationProbe('cc')}AND cc.${col} IS NOT NULL ${modalityFilter}${chunkFilters.join('\n ')}${relaxedGeneration}diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.jsonindex 766f64f3fd..11875497c2 100644--- a/test/fixtures/goldens/sql-text/_driver.json+++ b/test/fixtures/goldens/sql-text/_driver.json@@ -3827,6 +3827,15 @@},"revertToVersion": {"default": [+ {+ "paramCount": 2,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },{"paramCount": 2,"unsafeOptions": {@@ -3838,6 +3847,15 @@}],"sourceId": [+ {+ "paramCount": 3,+ "unsafeOptions": {+ "cancelFence": false,+ "prepare": true,+ "simple": false+ },+ "via": "unsafe"+ },{"paramCount": 3,"unsafeOptions": {diff --git a/test/fixtures/goldens/sql-text/chunks.json b/test/fixtures/goldens/sql-text/chunks.jsonindex e9e19824c1..4fe6c764d6 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.\"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": "97bfdf50343c2c13a69749e54ca43f8a8831070a4bda17853d6c06f667697009"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "72fc9180f5f7ce6a316c0022dfa993e39cdd7c6e6be65815f5fd69ce74d46682"}],"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.\"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": "da53d97719d3277cfbdfda19c015c9b2b05f80723dccfad34cbb7594e70b30df"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "bea74a86af17ff193a99597f7b54c89d6963f82d2ab451e438008894a221ea01"}],"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.\"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": "112deb1371695b66247475c2092862ab7bda82f38933168df00b8bb399671571"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "ed7eb47065da6a0065ed0a1879f5dd34b5844ccac708c7f18eefa0bb4f4bca2c"}]},@@ -98,8 +98,8 @@"string","string"],- "sql": "SELECT count(*) AS total, max(cc.chunk_index) AS max_index FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (p.text_projection_revision = p.knowledge_revision) IS TRUE",- "textSha256": "0abf9cfaa682610078e55dc3a67bf5533ec9e20da56d67637036fb58d08af0b5"+ "sql": "SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks FROM ( SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) GROUP BY cc.page_id ) t",+ "textSha256": "c27d5c843e714448bfc731469bde76e859efae4d143d9f03d17b38dd80573d71"},{"lane": "pool",@@ -109,8 +109,8 @@"number","number"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY cc.chunk_index",- "textSha256": "dcffdc693c90921c50f25acf3f875e4b9878429f7aa74318cdd369fb45719d55"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "38769a9c306cced7425165bc7ba71a9c9a0962de22c878fe76140ef08abe1f61"}],"sourceIds+excludePrivate": [@@ -126,8 +126,8 @@"string","array<string>"],- "sql": "SELECT count(*) AS total, max(cc.chunk_index) AS max_index FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND COALESCE(p.chunker_version, 0) >= 4",- "textSha256": "b5f4ce280ee064463e69c2f3b23f5b741de56a527aa89e167fb5b04cceefdd88"+ "sql": "SELECT COALESCE(sum(t.n), 0) AS total, max(t.max_index) AS max_index, bool_or(t.segmented) AS segmented, max(t.n) AS max_page_chunks FROM ( SELECT count(*) AS n, max(cc.chunk_index) AS max_index, bool_or(cc.body_generation IS NOT NULL) AS segmented FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND COALESCE(p.chunker_version, 0) >= 4 GROUP BY cc.page_id ) t",+ "textSha256": "1f24bdee58429ccc83caf61006e4a506b655df02ea0ca9e15902cb002c8d9fce"},{"lane": "pool",@@ -137,8 +137,8 @@"number","number"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND COALESCE(p.chunker_version, 0) >= 4 AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY cc.chunk_index",- "textSha256": "14cdb468082cbb9831a37defa61e7f7a81c6d49543ebdfb5e1c7381b80533fae"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND COALESCE(p.chunker_version, 0) >= 4 AND cc.chunk_index >= $3 AND cc.chunk_index < $4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "9aec5dc06d5b51f5888261cf237f05be3e3ca548344dbc14a08226b414505d51"}]},@@ -156,8 +156,8 @@"array<string>","number"],- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",- "textSha256": "d14fada1e869ff1662f3477a3cc0c779b55302fbda555e4222ed51e75d52afec"+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($7::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $8 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",+ "textSha256": "64aa9e142a90edbb495f64db0e2075740779bf7568da6bd32ecc15fb1cb7dd31"}],"scopedPrivateSafe": [@@ -174,8 +174,8 @@"array<string>","number"],- "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND COALESCE(p.chunker_version, 0) >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",- "textSha256": "9a88e0301a8db1150dce7e36e31ad294909b0d3c3f18f5c1975559770343059a"+ "sql": "WITH req AS ( SELECT * FROM unnest($1::int[], $2::int[], $3::int[], $4::int[]) AS r(page_id, lo, hi, prio) ), auth AS ( SELECT p.id, p.slug, p.source_id, p.type, p.knowledge_revision::text AS revision, p.compiled_truth, p.timeline, p.body_generation, (COALESCE(p.chunker_version, 0) >= $5) AS sealed, (SELECT MIN(req.prio) FROM req WHERE req.page_id = p.id) AS prio FROM pages p JOIN sources s ON s.id = p.source_id WHERE p.id = ANY($6::int[]) AND p.source_id = ANY($7::text[]) AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND COALESCE(p.chunker_version, 0) >= 4 ), chunk_rows AS ( SELECT cc.page_id, cc.id AS chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.projected_byte_start, cc.projected_byte_end, a.prio FROM auth a JOIN content_chunks cc ON cc.page_id = a.id WHERE a.sealed AND (cc.body_generation IS NULL OR (cc.body_generation <= a.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > a.body_generation))) AND cc.chunk_source = ANY($8::text[]) AND COALESCE(cc.modality, 'text') = 'text' AND EXISTS (SELECT 1 FROM req r WHERE r.page_id = cc.page_id AND cc.chunk_index BETWEEN r.lo AND r.hi) ORDER BY a.prio, cc.page_id, cc.chunk_index LIMIT $9 ) SELECT 'page' AS kind, a.id AS page_id, a.slug, a.source_id, a.type, a.revision, a.sealed, a.prio, (SELECT MAX(c2.chunk_index) FROM content_chunks c2 WHERE c2.page_id = a.id AND (c2.body_generation IS NULL OR (c2.body_generation <= a.body_generation AND (c2.retired_generation IS NULL OR c2.retired_generation > a.body_generation)))) AS max_chunk_index, a.compiled_truth, a.timeline, NULL::int AS chunk_id, NULL::int AS chunk_index, NULL::text AS chunk_text, NULL::text AS chunk_source, NULL::bigint AS projected_byte_start, NULL::bigint AS projected_byte_end FROM auth a UNION ALL SELECT 'chunk' AS kind, c.page_id, NULL, NULL, NULL, NULL, NULL, c.prio, NULL, NULL, NULL, c.chunk_id, c.chunk_index, c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end FROM chunk_rows c",+ "textSha256": "13fcac91c3f34640d067939313563c2628676ef25b1cd5b0ac04954284719612"}]},@@ -193,8 +193,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ORDER BY cc.chunk_index",- "textSha256": "94709f3a02195549c0106c82675ae0af6be2833d93e9712a7add3fe56b74bff5"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "7ee766d0a44b471068637dc5b605c0ee8a4d15a366fca49c47e410ad5a613194"}],"excludePrivate": [@@ -210,8 +210,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND COALESCE(p.chunker_version, 0) >= 4 ORDER BY cc.chunk_index",- "textSha256": "7098154f67dffe3614bf435c07d49e78e100acc3151affa5ac0c3a51a9d8f1c0"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND COALESCE(p.chunker_version, 0) >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "00ef510a41e536e2d7cd69253e815b638615601daa70d9a879374367e07c2a01"}],"includeEmbedding": [@@ -227,8 +227,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null , cc.\"embedding\" AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ORDER BY cc.chunk_index",- "textSha256": "c8ea75144bb3990310c694412db9a9b97ce79f3e7c4240d1c64b983aa0f72558"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null , cc.\"embedding\" AS embedding FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "7c084cfb23abe09539805e23ef8af34efd7e95b4f1ecd68226577e2f3f3542a3"}],"includeUnsealed": [@@ -244,8 +244,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY cc.chunk_index",- "textSha256": "3b244b8bbfe87547ec4cfb5ddf6ac88555a7ce110bdf2c097fccf88db3636f99"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "7d026b8c0a9f850b2fd6ff5b1c6e76d23c8af62cd64ab8d7d7d567f277e340bc"}],"requireSafeChunks": [@@ -261,8 +261,8 @@"string","string"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = $2 AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND COALESCE(p.chunker_version, 0) >= 4 ORDER BY cc.chunk_index",- "textSha256": "58cfabcc2bc8d59f7729c9637a807ea6bbefee0c0f5f1eca3f971dfeceb10032"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = $2 AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND COALESCE(p.chunker_version, 0) >= 4 ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "27b8030c7c2280b590e49265b61d7467d04bf6b6cdeb5f29d65aa218fcc90238"}],"sourceIds": [@@ -278,8 +278,8 @@"string","array<string>"],- "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND (p.text_projection_revision = p.knowledge_revision) IS TRUE ORDER BY cc.chunk_index",- "textSha256": "4e947132a232db58b8ca30892b573a982bb677e0cfa26552d6e286df8bdf3639"+ "sql": "SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.model, cc.token_count, cc.embedded_at, cc.language, cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line, cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.projected_byte_start, cc.projected_byte_end, (cc.\"embedding\" IS NULL) AS embedding_is_null FROM content_chunks cc JOIN pages p ON p.id = cc.page_id LEFT JOIN page_body_manifest m ON cc.occurrence_id IS NOT NULL AND m.page_id = cc.page_id AND m.occurrence_id = cc.occurrence_id AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation) WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) ORDER BY m.byte_start, cc.local_ordinal, cc.chunk_index",+ "textSha256": "b10dc9a665e8b6958c74ff273ca247285d758756e0ef3917fd2d3caa3f7668b1"}]},@@ -290,8 +290,8 @@"params": ["string"],- "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE (p.text_projection_revision = p.knowledge_revision) IS TRUE AND p.slug = $1 ORDER BY cc.chunk_index",- "textSha256": "e62b85ee2d471e487cc48b9f66b6f93b5044ce4b9e88b6eefbd0a616c757ae86"+ "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND p.slug = $1 ORDER BY cc.chunk_index",+ "textSha256": "897164893af24138f37b51ef61ca0600647ff6b13b4f0101ce110e178fb01f09"}],"sourceId+includeUnsealed": [@@ -301,8 +301,8 @@"string","string"],- "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE TRUE AND p.slug = $1 AND p.source_id = $2 ORDER BY cc.chunk_index",- "textSha256": "a7c39709a1b403f91f01517541031dd8b4a5ed0cc4dce05617a732fe764c5dc9"+ "sql": "SELECT cc.* FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND p.slug = $1 AND p.source_id = $2 ORDER BY cc.chunk_index",+ "textSha256": "ab3935a8dead2d558acf4767af5e6a8bee1f3ec71dfedfb1b1cf82a3d4317c3e"}]},@@ -313,8 +313,8 @@"params": ["array<number>"],- "sql": "SELECT cc.id, vector_send(cc.\"embedding_voyage\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding_voyage\" IS NOT NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE",- "textSha256": "62f4d3f7d81e398383af2b4529b462393291c395ae0d7f8c640ae3edc75de8f0"+ "sql": "SELECT cc.id, vector_send(cc.\"embedding_voyage\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding_voyage\" IS NOT NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))))",+ "textSha256": "a23ecb0b4221ed9ee3ae4c9a5a4e58e8fe5df5f454d015ac4e715cc796b3889d"}],"default": [@@ -323,8 +323,8 @@"params": ["array<number>"],- "sql": "SELECT cc.id, vector_send(cc.\"embedding\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding\" IS NOT NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE",- "textSha256": "c489f80e76fee469d26c10cf90e5251306d04b3c7fbdd97b33c7d1f658d2cc11"+ "sql": "SELECT cc.id, vector_send(cc.\"embedding\"::vector) AS embedding FROM content_chunks cc JOIN pages p ON p.id=cc.page_id WHERE cc.id = ANY($1::int[]) AND cc.\"embedding\" IS NOT NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))))",+ "textSha256": "899d57095ec8c255e6e5175bfdd546fcfbbffac3b235f40116e5e845ec8c928b"}]},@@ -511,8 +511,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.\"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 TRUE 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 <> '') 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": "3d71cdf159ebad019eea22f58553af9f889457384ee3106aee4ae010b3767cbe"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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 <> '') 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": "1e7d563076ef0bb20f4327efff466a44cb5c98696c620f3f20d00bf55b1d4782"}],"sourceIds": [@@ -531,8 +531,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.\"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 TRUE 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 <> '') 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": "61f9b4ebfd354ec3aae76e6e1e31f239801c7e3ee203a4524004948dc5d248ca"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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 <> '') 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": "69218d0c6798a19f396c66a58539e1276fcab3c6c38757f8622795da5ff8e9f8"}]},@@ -551,8 +551,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.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",- "textSha256": "30e3022cbdd786647cd5d83b3e6e290d685612da6f4ff4d0e60ae2d32a62da47"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND (cc.page_id, cc.chunk_index) > ($1, $2) ORDER BY cc.page_id, cc.chunk_index LIMIT $3",+ "textSha256": "3098f5d265a6f1cf3e6f9dc91a68c3c19c1e00b4b0ff84bcec4f5efc08ac0919"}],"sourceId": [@@ -570,8 +570,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.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",- "textSha256": "2bcb4b1c3ef490a7c0dd05a40de054a9a723e102f1c6d7ef5ea9ba4d2907c752"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND (cc.page_id, cc.chunk_index) > ($2, $3) ORDER BY cc.page_id, cc.chunk_index LIMIT $4",+ "textSha256": "62b87452bcd52effbcc44cd2167ce4c7ff9729c204c0fc9c585789650f79d0fb"}],"updated_desc": [@@ -586,8 +586,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') ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",- "textSha256": "ae7a9e008a2ee2e9a06c81076831d0aab18e2a7687caf4ddebe242f4af32c5d3"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $1",+ "textSha256": "da46de54a47d6bbdc155f72c47b812e48d1d9b78f1baf4db267ffd2d7eca2ff4"}],"updated_desc+cursor": [@@ -608,8 +608,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 ( 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": "a6705a1ff3131f3f832055d173b08efaf220385b9ea9bede8b02dc3c009590bc"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "6801846f3611cd0d015651a3c60151b2a03a7bc33097ad3b4c1db1774454abcc"}],"updated_desc+sourceId": [@@ -625,8 +625,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') ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",- "textSha256": "d2a8d36b4683a0ae5b0983b0d06fb22e1cc0e6360b6e0a8593c46014adefe2f1"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) ORDER BY p.updated_at DESC NULLS LAST, p.id ASC, cc.chunk_index ASC LIMIT $2",+ "textSha256": "4b3e7be6b2d68a6adb7daef9cf3a9f0f636157dc6d8f441f60412ec864c3ed80"}],"updated_desc+sourceId+cursor": [@@ -648,8 +648,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 ( 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": "e7d5d93ccb96ab546168596ee9ea4b15d2441d62bb0d05d4505f4dc1d10a8c98"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "5efa6b07f9d7ed7a59552bc5698e4e4d8faff347762015dd1491517474673649"}]},@@ -666,8 +666,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.\"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) s GROUP BY s.state",- "textSha256": "9cb1aa305b5fd7f774c63a8f46e1a86a85ce2ba35bacf3deee2ba82295d5ad77"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) s GROUP BY s.state",+ "textSha256": "d747198df5c4ed086cc774f7ac81461f5d576c8adf37e37d97e72491daa328d8"},{"lane": "pool",@@ -695,8 +695,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.\"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 p.source_id = ANY($2::text[])) s GROUP BY s.state",- "textSha256": "bcdf40657218e62e8eee518dc0cf9e86443be3e87f59a1b9f8570c1918b09218"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation))) AND p.source_id = ANY($2::text[])) s GROUP BY s.state",+ "textSha256": "bc6f020b1cd852a8feca47e968b2520ce8040382b08874200543936c2a98c607"},{"lane": "pool",@@ -757,8 +757,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.\"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": "67b4ffd6b3b6383b7b7d4a9737bd2e6fa6a4be6c63106a284daa636e37a55168"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "7def567d09677a18a09f063043c393c9c8f7aa66bc5981866e65174914a81138"}],"signature": [@@ -773,8 +773,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.\"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": "9c034aef0db1eb12ebc2f41441bdb1bb9a71f59663efbfa7ca19099e7e8aaa97"+ "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 OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > 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": "a590a7f68a81dd3d520770d26707790ce2a365a529bbb8b8aa2d8225e84f9efd"}]},diff --git a/test/fixtures/goldens/sql-text/cjk-search.json b/test/fixtures/goldens/sql-text/cjk-search.jsonindex f46914707f..e5feaf7fca 100644--- a/test/fixtures/goldens/sql-text/cjk-search.json+++ b/test/fixtures/goldens/sql-text/cjk-search.json@@ -59,8 +59,8 @@"number","number"],- "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",- "textSha256": "ecda758ab14f9584f956752fb37e85963bc8c565e4d8b80119ce045fba5a2ae6"+ "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",+ "textSha256": "3d0622c80f2290ca631148a81df192c733fb226465b163c91b34b9a0816b4899"},{"event": "commit",@@ -125,8 +125,8 @@"number","number"],- "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND cc.chunk_source = 'compiled_truth' AND p.type = $10 AND p.source_id = ANY($11::text[]) AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $12 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $13 OFFSET $14",- "textSha256": "cd7d8e564e18c13ccf096e0c6db89f2f144d490c316229a46f9fe77593299250"+ "sql": "WITH ranked AS ( SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND cc.chunk_source = 'compiled_truth' AND p.type = $10 AND p.source_id = ANY($11::text[]) AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') AND cc.modality = 'text' ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $12 ), best_per_page AS ( SELECT DISTINCT ON (COALESCE(source_id, 'default'), slug) * FROM ranked ORDER BY COALESCE(source_id, 'default'), slug, score DESC, page_id ASC, chunk_id ASC ) SELECT * FROM best_per_page ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $13 OFFSET $14",+ "textSha256": "7d86a89584c4be40109f304d309195d4f7d9aa45df079fe391ba05555f089b5d"},{"event": "commit",@@ -175,8 +175,8 @@"number","number"],- "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 OFFSET $11",- "textSha256": "57713d787b34b97fb3b342fb611e5c3a988fae32480ab756e715390badb1a600"+ "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $10 OFFSET $11",+ "textSha256": "381368cdd0079fd647f6603f9bdbd7a1a18378d19774c82d1ddd5ce43ff49446"},{"event": "commit",@@ -224,8 +224,8 @@"number","number"],- "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND p.source_id = $10 AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND (p.text_projection_revision = p.knowledge_revision) IS TRUE AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",- "textSha256": "08597c71a787e99a280bd636cdd82da2c999221166f3762030b6473e7a762697"+ "sql": "SELECT p.slug, p.id as page_id, p.title, p.type, p.source_id, p.effective_date, p.effective_date_source, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN p.frontmatter->>'message_id' END AS message_id, p.frontmatter->>'thread_id' AS thread_id, CASE WHEN NULLIF(regexp_replace(p.frontmatter->>'message_id', '^[[:space:]]+|[[:space:]]+$', '', 'g'), '') IS NOT NULL THEN NULLIF(p.frontmatter->>'subject', '') END AS source_subject, cc.id as chunk_id, cc.chunk_index, cc.chunk_text, cc.chunk_source, ((((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $1, ''))) / NULLIF(LENGTH($2), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $3, ''))) / NULLIF(LENGTH($4), 0)::real) + ((LENGTH(cc.chunk_text) - LENGTH(REPLACE(cc.chunk_text, $5, ''))) / NULLIF(LENGTH($6), 0)::real) + COALESCE(1.0 / NULLIF(POSITION($7 IN cc.chunk_text), 0)::real, 0.0)) * (CASE WHEN (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'provenance') = 'auto-extracted' AND (COALESCE(p.frontmatter, '{}'::jsonb) ->> 'status') = 'unverified' THEN 1.0 WHEN p.slug LIKE 'media/articles/%' THEN 1.1 WHEN p.slug LIKE 'openclaw/chat/%' THEN 0.5 WHEN p.slug LIKE 'media/repos/%' THEN 1.1 WHEN p.slug LIKE 'originals/%' THEN 1.5 WHEN p.slug LIKE 'companies/%' THEN 1.2 WHEN p.slug LIKE 'concepts/%' THEN 1.3 WHEN p.slug LIKE 'meetings/%' THEN 1.1 WHEN p.slug LIKE 'extracts/%' THEN 0.3 WHEN p.slug LIKE 'writing/%' THEN 1.4 WHEN p.slug LIKE 'media/x/%' THEN 0.7 WHEN p.slug LIKE 'archive/%' THEN 0.5 WHEN p.slug LIKE 'people/%' THEN 1.2 WHEN p.slug LIKE 'deals/%' THEN 1.2 WHEN p.slug LIKE 'civic/%' THEN 1 WHEN p.slug LIKE 'daily/%' THEN 0.8 WHEN p.slug LIKE 'yc/%' THEN 1 ELSE 1.0 END)) AS score, CASE WHEN p.updated_at < ( SELECT MAX(te.created_at) FROM timeline_entries te WHERE te.page_id = p.id ) THEN true ELSE false END AS stale FROM content_chunks cc JOIN pages p ON p.id = cc.page_id JOIN sources s ON s.id = p.source_id WHERE cc.chunk_text LIKE $8 ESCAPE '\\' AND cc.chunk_text LIKE $9 ESCAPE '\\' AND p.source_id = $10 AND NOT (p.slug LIKE 'test/%' OR p.slug LIKE 'attachments/%' OR p.slug LIKE '.raw/%') AND p.deleted_at IS NULL AND ((p.text_projection_revision = p.knowledge_revision) IS TRUE AND (cc.body_generation IS NULL OR (cc.body_generation <= p.body_generation AND (cc.retired_generation IS NULL OR cc.retired_generation > p.body_generation)))) AND NOT s.archived AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'quarantine') AND NOT (COALESCE(p.frontmatter, '{}'::jsonb) ? 'pinned_question') ORDER BY score DESC, page_id ASC, chunk_id ASC LIMIT $11 OFFSET $12",+ "textSha256": "cff744e2ef5eb761a32372bd31a9839ee0838549781224a2c1f6d5cff32f14cf"},{"event": "commit",diff --git a/test/fixtures/goldens/sql-text/pages.json b/test/fixtures/goldens/sql-text/pages.jsonindex c51486bbb7..8df6eb03a9 100644--- a/test/fixtures/goldens/sql-text/pages.json+++ b/test/fixtures/goldens/sql-text/pages.json@@ -324,8 +324,8 @@"params": ["string"],- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 ORDER BY pv.snapshot_at DESC, pv.id DESC",- "textSha256": "32879564166486f18b4931ad6f8c763b6869c5d116a8286665d44cb37271049c"+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path, pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 ORDER BY pv.snapshot_at DESC, pv.id DESC",+ "textSha256": "f8969d4b4aeffa4dc360a1ad3eeeb5cc549705e2adae4bdb660a422256dbdbf2"}],"excludePrivate": [@@ -334,8 +334,8 @@"params": ["string"],- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND (COALESCE(pv.frontmatter->>'visibility', CASE WHEN (pv.type IN ('atom', 'question') OR (pv.type = 'concept' AND pv.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pv.frontmatter ? 'pinned_question', false)) ORDER BY pv.snapshot_at DESC, pv.id DESC",- "textSha256": "a8bbcecc91ed44a995db7550f23714fff7cdf4baff863993c24e80e94d25b93f"+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path, pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND ((COALESCE(p.frontmatter->>'visibility', CASE WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(p.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN p.type = 'atom' THEN EXISTS (SELECT 1 FROM pages derived_origin WHERE derived_origin.source_id = p.source_id AND derived_origin.slug = p.frontmatter->>'source_slug' AND derived_origin.frontmatter->>'visibility' = 'private') WHEN (p.type IN ('atom', 'question') OR (p.type = 'concept' AND p.frontmatter->>'synthesized_by' IS NOT NULL)) THEN EXISTS (SELECT 1 FROM links derived_input_link JOIN pages derived_input ON derived_input.id = derived_input_link.to_page_id WHERE derived_input_link.from_page_id = p.id AND derived_input_link.link_source = 'concept-provenance' AND derived_input_link.link_type = 'synthesized_from' AND (COALESCE(derived_input.frontmatter->>'visibility', CASE WHEN derived_input.type = 'atom' THEN 'private' ELSE 'world' END) = 'private' OR EXISTS (SELECT 1 FROM pages derived_input_origin WHERE derived_input_origin.source_id = derived_input.source_id AND derived_input_origin.slug = derived_input.frontmatter->>'source_slug' AND derived_input_origin.frontmatter->>'visibility' = 'private'))) WHEN p.type = 'event' AND p.frontmatter->>'captured_via' LIKE 'life-chronicle:%' THEN NOT EXISTS (SELECT 1 FROM pages chronicle_origin WHERE chronicle_origin.source_id = p.source_id AND chronicle_origin.slug = p.frontmatter->'event'->>'depth' AND (COALESCE(chronicle_origin.frontmatter->>'visibility', CASE WHEN (chronicle_origin.type IN ('atom', 'question') OR (chronicle_origin.type = 'concept' AND chronicle_origin.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(chronicle_origin.frontmatter ? 'pinned_question', false)) AND NOT (CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = chronicle_origin.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(chronicle_origin.frontmatter->'derived_from') = 'array' THEN chronicle_origin.frontmatter->'derived_from' ELSE jsonb_build_array(chronicle_origin.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) ELSE false END) AND NOT (CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') IN ('array', 'string') THEN EXISTS ( SELECT 1 FROM pages declared_origin WHERE declared_origin.source_id = p.source_id AND declared_origin.frontmatter->>'visibility' = 'private' AND declared_origin.slug = ANY(ARRAY( SELECT regexp_replace(declared.slug, '\\.md$', '') FROM jsonb_array_elements_text( CASE WHEN jsonb_typeof(p.frontmatter->'derived_from') = 'array' THEN p.frontmatter->'derived_from' ELSE jsonb_build_array(p.frontmatter->'derived_from') END) AS declared(slug)))) ELSE false END)) AND (COALESCE(pv.frontmatter->>'visibility', CASE WHEN (pv.type IN ('atom', 'question') OR (pv.type = 'concept' AND pv.frontmatter->>'synthesized_by' IS NOT NULL)) THEN 'private' ELSE 'world' END) <> 'private' AND NOT COALESCE(pv.frontmatter ? 'pinned_question', false)) ORDER BY pv.snapshot_at DESC, pv.id DESC",+ "textSha256": "950dab0c6e396f3cf326361158f5174eddb58116ee1222e9ffd38ef2c20c4cca"}],"limit": [@@ -346,8 +346,8 @@"string","number"],- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC, pv.id DESC LIMIT $3",- "textSha256": "9839ece55c3a9571965051d0380fd26c9ac4b11e70b44b9a5c44731f4d9e7087"+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path, pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC, pv.id DESC LIMIT $3",+ "textSha256": "7c0864acfb5ea8e165d239eb10bbc15743f0a48b82f23030e27a3be65864c108"}],"metadataOnly": [@@ -357,8 +357,8 @@"string","array<string>"],- "sql": "SELECT pv.id, pv.page_id, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC, pv.id DESC",- "textSha256": "58fb695b83a4ff6bf64add66f0caf4d76515e10bc88e43e9148c070ec41d9ce0"+ "sql": "SELECT pv.id, pv.page_id, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path, pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC, pv.id DESC",+ "textSha256": "e8730b64d22f6764af2dd8d3da0ec42b596ca9f7419adc596e98103a35d422ea"}],"sourceId": [@@ -368,8 +368,8 @@"string","string"],- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC, pv.id DESC",- "textSha256": "b42549daaa1a104ab1da4c06e09b4f47a80d14f75a3ea85a198d76b4e47f3847"+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path, pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = $2 ORDER BY pv.snapshot_at DESC, pv.id DESC",+ "textSha256": "1ee3103a09341aa7fa18432ef4fe259fd155417ce7ba6c7ee440613b24ba62d7"}],"sourceIds": [@@ -379,8 +379,8 @@"string","array<string>"],- "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC, pv.id DESC",- "textSha256": "45b816d8e527a6e0e92fee18a95d7c02fa86fcb30e5295d2d9e47aa56d2bedfb"+ "sql": "SELECT pv.id, pv.page_id, pv.compiled_truth, pv.frontmatter, pv.snapshot_at, pv.knowledge_revision, pv.timeline, pv.title, pv.type, pv.tags, pv.is_deleted, pv.source_path, pv.body_storage, pv.body_generation, pv.body_bytes, pv.content_hash FROM page_versions pv JOIN pages p ON p.id = pv.page_id WHERE p.slug = $1 AND p.source_id = ANY($2::text[]) ORDER BY pv.snapshot_at DESC, pv.id DESC",+ "textSha256": "85aad668b6876569f29975a13b8c80bfb609afc0ff1014e8c26e002646e81463"}]},@@ -1260,6 +1260,15 @@},"revertToVersion": {"default": [+ {+ "lane": "pool",+ "params": [+ "string",+ "number"+ ],+ "sql": "SELECT 1 FROM pages p JOIN page_versions pv ON pv.page_id = p.id WHERE p.slug = $1 AND pv.id = $2 AND (p.body_storage = 'segmented' OR pv.body_storage = 'segmented')",+ "textSha256": "fcfdc6d3e88ec26342f6bf9661e763d09d2bd7d8647194036be0bf3e5126729a"+ },{"lane": "pool","params": [@@ -1271,6 +1280,16 @@}],"sourceId": [+ {+ "lane": "pool",+ "params": [+ "string",+ "string",+ "number"+ ],+ "sql": "SELECT 1 FROM pages p JOIN page_versions pv ON pv.page_id = p.id WHERE p.slug = $1 AND p.source_id = $2 AND pv.id = $3 AND (p.body_storage = 'segmented' OR pv.body_storage = 'segmented')",+ "textSha256": "f76c712b0870d1849d6e6f540d73fd130ab2c39f5a399eae60a5fe0f42406023"+ },{"lane": "pool","params": [diff --git a/test/helpers/segmented-chunks-fixture.ts b/test/helpers/segmented-chunks-fixture.tsnew file mode 100644index 0000000000..a25fc1e914--- /dev/null+++ b/test/helpers/segmented-chunks-fixture.ts@@ -0,0 +1,90 @@+/**+ * Wave B fixture: turn a page into a segmented page with hand-placed manifest+ * and chunk rows (raw SQL, no segmenter or flip), so chunk-visibility,+ * vector-reuse and version tests can put rows in exactly the generation+ * states they probe: live, staged (body_generation above the page's) and+ * retired. The page is sealed as an inline page first, then its body columns+ * are cleared the way a segmented row stores them (NULL bodies, body_bytes).+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';+import { installFixtureChunks } from './page-projection.ts';++export interface FixtureChunk {+ text: string;+ /** Insertion sequence (segmented chunk_index); defaults to the order rows are listed across occurrences. */+ chunkIndex?: number;+ /** First generation the row is part of; defaults to the occurrence's genFrom. */+ generation?: number;+ retiredGeneration?: number | null;+ /** A unit vector seed: the row gets a vector with 1 at this dimension. */+ vector?: number;+}++export interface FixtureOccurrence {+ id: number;+ byteStart: number;+ genFrom: number;+ genTo?: number | null;+ /** Bytes the manifest row pins (defaults to the chunk texts' length). */+ byteLen?: number;+ chunks: FixtureChunk[];+}++export interface SegmentedFixture { pageId: number; chunkIds: Map<string, number> }++export const sha256 = (text: string) => createHash('sha256').update(text).digest();++/** A unit vector of the active column's dimensions with 1 at `seed`. */+export async function unitVector(engine: BrainEngine, seed: number): Promise<number[]> {+ const col = await resolveActiveEmbeddingColumnFromEngine(engine);+ return Array.from({ length: col.dimensions }, (_, i) => (i === seed ? 1 : 0));+}++export async function segmentPage(engine: BrainEngine, slug: string, opts: {+ generation: number;+ occurrences: FixtureOccurrence[];+ title?: string;+ bodyBytes?: number;+ sourceId?: string;+}): Promise<SegmentedFixture> {+ const sourceId = opts.sourceId ?? 'default';+ await engine.putPage(slug, { type: 'note', title: opts.title ?? slug, compiled_truth: 'Segmented fixture.', timeline: '', frontmatter: {} }, { sourceId });+ await installFixtureChunks(engine, slug, [{ chunk_index: 0, chunk_text: 'Segmented fixture.', chunk_source: 'compiled_truth' }], { sourceId });+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1 AND source_id = $2', [slug, sourceId]);+ const pageId = Number(page!.id);+ const live = opts.occurrences.filter(o => o.genFrom <= opts.generation && (o.genTo == null || o.genTo > opts.generation));+ const bodyBytes = opts.bodyBytes ?? live.reduce((n, o) => n + (o.byteLen ?? o.chunks.map(c => c.text).join('\n\n').length), 0);+ await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [pageId]);+ await engine.executeRaw(`UPDATE pages SET body_storage = 'segmented', compiled_truth = NULL, timeline = NULL,+ body_bytes = $2, body_generation = $3, content_hash = $4 WHERE id = $1`,+ [pageId, bodyBytes, opts.generation, sha256(`${slug}@${opts.generation}`).toString('hex')]);+ const col = await resolveActiveEmbeddingColumnFromEngine(engine);+ const chunkIds = new Map<string, number>();+ let nextIndex = 0;+ for (const [seq, occ] of opts.occurrences.entries()) {+ const text = occ.chunks.map(c => c.text).join('\n\n');+ await engine.executeRaw(`INSERT INTO page_segment_texts (source_id, sha256, byte_len, line_count, body)+ VALUES ($1, $2, $3, 1, $4) ON CONFLICT DO NOTHING`, [sourceId, sha256(text), Buffer.byteLength(text), Buffer.from(text)]);+ await engine.executeRaw(`INSERT INTO page_body_manifest (page_id, occurrence_id, gen_from, gen_to, seq, region, source_id, sha256,+ byte_start, byte_len, line_start, line_count, cut_kind, entry_state, static_proj_bytes, static_proj_lines, hash_state)+ VALUES ($1, $2, $3, $4, $5, 'truth', $6, $7, $8, $9, 0, 1, 'heading', '{}'::jsonb, $10, 1, '\\x00'::bytea)`,+ [pageId, occ.id, occ.genFrom, occ.genTo ?? null, seq, sourceId, sha256(text), occ.byteStart, occ.byteLen ?? Buffer.byteLength(text), occ.byteLen ?? Buffer.byteLength(text)]);+ for (const [ordinal, chunk] of occ.chunks.entries()) {+ const chunkIndex = chunk.chunkIndex ?? nextIndex;+ nextIndex = Math.max(nextIndex, chunkIndex) + 1;+ const vector = chunk.vector === undefined ? null : `[${(await unitVector(engine, chunk.vector)).join(',')}]`;+ const [row] = await engine.executeRaw<{ id: number }>(`INSERT INTO content_chunks (page_id, chunk_index, chunk_text, chunk_source, token_count,+ occurrence_id, local_ordinal, body_generation, retired_generation, ${col.name}, model, embedded_at, embedded_text_hash)+ VALUES ($1, $2, $3, 'compiled_truth', $4, $5, $6, $7, $8, $9::vector, $10, $11, $12) RETURNING id`,+ [pageId, chunkIndex, chunk.text, Math.ceil(chunk.text.length / 4), occ.id, ordinal, chunk.generation ?? occ.genFrom,+ chunk.retiredGeneration ?? null, vector, col.embeddingModel, vector ? new Date() : null,+ vector ? createHash('md5').update(chunk.text).digest('hex') : null]);+ chunkIds.set(chunk.text, Number(row!.id));+ }+ }+ // Clearing the body and replacing the rows unseals the projection; the fixture's rows are the projection.+ await engine.executeRaw('UPDATE pages SET text_projection_revision = knowledge_revision WHERE id = $1', [pageId]);+ return { pageId, chunkIds };+}diff --git a/test/large-pages/chunk-visibility.test.ts b/test/large-pages/chunk-visibility.test.tsnew file mode 100644index 0000000000..67c2a8a5d7--- /dev/null+++ b/test/large-pages/chunk-visibility.test.ts@@ -0,0 +1,109 @@+/**+ * Wave B chunk visibility (spec 4.2).+ *+ * 1. Protects: a segmented page's staged rows (body_generation above the+ * page's, an unpublished write) and retired rows (an old body) never reach+ * keyword search, vector search, get_chunks, chunk windows or the embed+ * sweep's stale selection; inline pages' rows are unaffected; get_chunks+ * returns a segmented page in document order (manifest byte_start,+ * local_ordinal), paging by position.+ * 2. Fails when: a reader drops `chunkVisibleFilter` / `chunkGenerationFilter`+ * or a segmented page is ordered by its insertion-sequence chunk_index.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';+import { installFixtureChunks } from '../helpers/page-projection.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentPage, unitVector, type SegmentedFixture } from '../helpers/segmented-chunks-fixture.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SLUG = 'notes/segmented-log';+const LIVE = ['zebrafish opening of the log', 'second live passage', 'later appended passage about herons'];++for (const kind of testBackends()) {+ describe(`segmented chunk visibility (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let fixture: SegmentedFixture;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.putPage('notes/inline', { type: 'note', title: 'Inline', compiled_truth: 'Inline page about zebrafish care.', timeline: '', frontmatter: {} });+ await installFixtureChunks(engine, 'notes/inline', await prepareMarkdownChunks({ compiled_truth: 'Inline page about zebrafish care.', timeline: '' }));+ // Generation 2 is live. Occurrence 20 (byte 4096) was inserted first, so its+ // rows have lower chunk_index than occurrence 10 (byte 0): insertion order+ // differs from document order.+ fixture = await segmentPage(engine, SLUG, {+ generation: 2,+ occurrences: [+ { id: 20, byteStart: 4096, genFrom: 1, chunks: [{ text: LIVE[2]!, vector: 7, chunkIndex: 0 }] },+ { id: 10, byteStart: 0, genFrom: 1, chunks: [{ text: LIVE[0]!, vector: 7, chunkIndex: 1 }, { text: LIVE[1]!, vector: 7, chunkIndex: 2 }] },+ { id: 30, byteStart: 8192, genFrom: 1, genTo: 2, chunks: [{ text: 'retired quokka passage', vector: 9, retiredGeneration: 2 }] },+ { id: 40, byteStart: 8192, genFrom: 3, chunks: [{ text: 'staged wombat passage', vector: 9 }, { text: 'staged stale wombat tail' }] },+ { id: 50, byteStart: 12288, genFrom: 1, genTo: 2, chunks: [{ text: 'retired stale quokka tail', retiredGeneration: 2 }] },+ { id: 60, byteStart: 12288, genFrom: 2, chunks: [{ text: 'live stale heron tail' }] },+ ],+ });+ }, 120_000);+ afterAll(async () => { await close?.(); });++ const liveIds = () => [...LIVE, 'live stale heron tail'].map(t => fixture.chunkIds.get(t)!);+ const hiddenIds = () => ['retired quokka passage', 'staged wombat passage', 'staged stale wombat tail', 'retired stale quokka tail']+ .map(t => fixture.chunkIds.get(t)!);++ test('keyword search sees live rows only', async () => {+ expect((await engine.searchKeyword('zebrafish')).map(r => r.slug).sort()).toEqual(['notes/inline', SLUG]);+ expect(await engine.searchKeyword('quokka')).toEqual([]);+ expect(await engine.searchKeyword('wombat')).toEqual([]);+ });++ test('vector search sees live rows only', async () => {+ const live = await engine.searchVector(Float32Array.from(await unitVector(engine, 7)), { limit: 20 });+ expect(live.filter(r => r.slug === SLUG).map(r => Number(r.chunk_id)).every(id => liveIds().includes(id))).toBe(true);+ expect(live.some(r => r.slug === SLUG)).toBe(true);+ // Only the staged and retired rows carry this vector exactly.+ const hidden = await engine.searchVector(Float32Array.from(await unitVector(engine, 9)), { limit: 20 });+ for (const id of hidden.map(r => Number(r.chunk_id))) expect(hiddenIds()).not.toContain(id);+ });++ test('get_chunks returns live rows in document order and pages by position', async () => {+ const chunks = await engine.getChunks(SLUG);+ expect(chunks.map(c => c.chunk_text)).toEqual([LIVE[0], LIVE[1], LIVE[2], 'live stale heron tail']);+ const first = await engine.getChunkPage(SLUG, { fromIndex: 0, limit: 2 });+ expect(first.chunks.map(c => c.chunk_text)).toEqual([LIVE[0], LIVE[1]]);+ expect(first.total_chunks).toBe(4);+ expect(first.max_chunk_index).toBe(3);+ const second = await engine.getChunkPage(SLUG, { fromIndex: 2, limit: 2 });+ expect(second.chunks.map(c => c.chunk_text)).toEqual([LIVE[2], 'live stale heron tail']);+ });++ test('inline pages keep chunk_index order and every row', async () => {+ const chunks = await engine.getChunks('notes/inline');+ expect(chunks.map(c => c.chunk_index)).toEqual(chunks.map((_, i) => i));+ expect(chunks.length).toBeGreaterThan(0);+ });++ test('chunk windows read live rows only', async () => {+ const [page] = await engine.getChunkWindows([{ page_id: fixture.pageId, from_index: 0, to_index: 1000, priority: 0 }],+ { chunkSources: ['compiled_truth'], maxRows: 100 });+ const ids = page!.chunks.map(c => c.id);+ expect(ids.sort()).toEqual(liveIds().sort());+ expect(page!.max_chunk_index).toBe(Math.max(...(await engine.getChunks(SLUG)).map(c => c.chunk_index)));+ });++ test("the embed sweep's stale selection skips staged and retired rows", async () => {+ const stale = await engine.listStaleChunks({ batchSize: 100 });+ const texts = stale.filter(r => r.slug === SLUG).map(r => r.chunk_text);+ expect(texts).toEqual(['live stale heron tail']);+ });+ });+}diff --git a/test/large-pages/segment-vector-reuse.test.ts b/test/large-pages/segment-vector-reuse.test.tsnew file mode 100644index 0000000000..cb3d6bf9a2--- /dev/null+++ b/test/large-pages/segment-vector-reuse.test.ts@@ -0,0 +1,90 @@+/**+ * Wave B segment vector reuse (spec 4.4).+ *+ * 1. Protects: `reuseSegmentChunkVectors` reads only the live rows of the+ * occurrences a write retires (one statement, never the whole page or+ * `getChunks`), copies an admitted vector onto the new chunk with the same+ * source and text, so an unchanged chunk inside a rewritten tail keeps its+ * vector, and gives new text, text found only outside the retired+ * occurrences, staged rows' text and vectors recorded for another tier none.+ * 2. Fails when: reuse widens to every chunk of the page, ignores the+ * generation, or skips the input-hash gate.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { reuseSegmentChunkVectors } from '../../src/core/import-chunk-reuse.ts';+import { embeddingInputHash } from '../../src/core/embedding-input-hash.ts';+import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';+import type { SegmentChunkInput } from '../../src/core/page-body/types.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentPage, unitVector } from '../helpers/segmented-chunks-fixture.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SLUG = 'notes/segmented-reuse';+const TITLE = 'Segmented reuse';++const chunk = (text: string, ordinal: number): SegmentChunkInput => ({ chunk_text: text, chunk_source: 'compiled_truth', occurrence_id: 99,+ local_ordinal: ordinal, raw_byte_start: 0, raw_byte_end: text.length });++for (const kind of testBackends()) {+ describe(`segment vector reuse (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let pageId: number;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ ({ pageId } = await segmentPage(engine, SLUG, {+ generation: 2,+ title: TITLE,+ occurrences: [+ { id: 10, byteStart: 0, genFrom: 1, chunks: [{ text: 'only in a live occurrence', vector: 1 }] },+ { id: 20, byteStart: 4096, genFrom: 1, chunks: [{ text: 'unchanged tail chunk', vector: 2 }, { text: 'edited tail chunk', vector: 3 },+ { text: 'other tier chunk', vector: 4 }, { text: 'staged chunk text', vector: 5, generation: 3 }] },+ ],+ }));+ const provenance = embeddingInputContext(await embeddingWriteTarget(engine), TITLE, null, []);+ for (const text of ['only in a live occurrence', 'unchanged tail chunk', 'edited tail chunk', 'staged chunk text']) {+ await engine.executeRaw('UPDATE content_chunks SET embedding_input_hash = $3 WHERE page_id = $1 AND chunk_text = $2',+ [pageId, text, embeddingInputHash(provenance, 'title', { chunk_text: text, chunk_source: 'compiled_truth' })]);+ }+ await engine.executeRaw('UPDATE content_chunks SET embedding_input_hash = $3 WHERE page_id = $1 AND chunk_text = $2',+ [pageId, 'other tier chunk', embeddingInputHash(provenance, 'none', { chunk_text: 'other tier chunk', chunk_source: 'compiled_truth' })]);+ }, 120_000);+ afterAll(async () => { await close?.(); });++ test('only the retired occurrences rows are read, and only matching text keeps its vector', async () => {+ const chunks = ['unchanged tail chunk', 'brand new chunk', 'only in a live occurrence', 'staged chunk text', 'other tier chunk'].map(chunk);+ const exec = spyOn(engine, 'executeRaw');+ const getChunks = spyOn(engine, 'getChunks');+ let reused: number;+ try {+ reused = await reuseSegmentChunkVectors(engine, { pageId, retiredOccurrences: [20], chunks, title: TITLE, corpusGeneration: null, tier: 'title' });+ const reads = exec.mock.calls.map(([sql]) => String(sql)).filter(sql => /content_chunks/.test(sql));+ expect(reads).toHaveLength(1);+ expect(reads[0]).toContain('occurrence_id = ANY');+ expect(getChunks).not.toHaveBeenCalled();+ } finally { exec.mockRestore(); getChunks.mockRestore(); }+ expect(reused).toBe(1);+ expect(Array.from(chunks[0]!.embedding!)).toEqual(await unitVector(engine, 2));+ expect(chunks[0]!.embedding_input_hash).toEqual(expect.any(String));+ for (const i of [1, 2, 3, 4]) expect(chunks[i]!.embedding).toBeUndefined();+ });++ test('no retired occurrences reads nothing', async () => {+ const exec = spyOn(engine, 'executeRaw');+ try {+ expect(await reuseSegmentChunkVectors(engine, { pageId, retiredOccurrences: [], chunks: [chunk('unchanged tail chunk', 0)], title: TITLE, corpusGeneration: null, tier: 'title' })).toBe(0);+ expect(exec).not.toHaveBeenCalled();+ } finally { exec.mockRestore(); }+ });+ });+}diff --git a/test/large-pages/segmented-embedding.test.ts b/test/large-pages/segmented-embedding.test.tsnew file mode 100644index 0000000000..cda7449c4f--- /dev/null+++ b/test/large-pages/segmented-embedding.test.ts@@ -0,0 +1,97 @@+/**+ * Wave B segmented embedding (spec 4.4).+ *+ * 1. Protects: a segmented page is embedded from its vector-less live rows+ * alone (chunk text, title, plain tier): never a segment or body read,+ * never a staged or retired row; an append's effect (`occurrenceIds`)+ * embeds only the new occurrences' rows; `embedStalePages` routes a+ * segmented page here; each installed vector records its input hash.+ * 2. Fails when: the sweep reads the body or every chunk of a segmented page,+ * embeds rows outside the live generation, or widens an append's effect.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { embedStalePages } from '../../src/core/embed-stale.ts';+import { embeddingInputHash, plainEmbeddingTier } from '../../src/core/embedding-input-hash.ts';+import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';+import { embedSegmentedPage, readSegmentedEmbedPage } from '../../src/core/page-body/segmented-embedding.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentPage, unitVector } from '../helpers/segmented-chunks-fixture.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SLUG = 'notes/segmented-embed';+const TITLE = 'Segmented embed';++for (const kind of testBackends()) {+ describe(`segmented embedding (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let embedded: string[][];+ const embedFn = async (texts: string[]) => {+ embedded.push(texts);+ const v = Float32Array.from(await unitVector(engine, 3));+ return texts.map(() => v);+ };++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ }, 120_000);+ afterAll(async () => { await close?.(); });+ beforeEach(async () => {+ embedded = [];+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw('DELETE FROM page_segment_texts');+ await segmentPage(engine, SLUG, {+ generation: 2,+ title: TITLE,+ occurrences: [+ { id: 10, byteStart: 0, genFrom: 1, chunks: [{ text: 'first live row' }, { text: 'second live row' }] },+ { id: 20, byteStart: 4096, genFrom: 2, chunks: [{ text: 'appended row' }] },+ { id: 30, byteStart: 4096, genFrom: 1, genTo: 2, chunks: [{ text: 'retired row', retiredGeneration: 2 }] },+ { id: 40, byteStart: 8192, genFrom: 3, chunks: [{ text: 'staged row' }] },+ ],+ });+ });++ const vectored = async () => (await engine.executeRaw<{ chunk_text: string }>(+ `SELECT cc.chunk_text FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE p.slug = $1 AND cc.embedding IS NOT NULL ORDER BY cc.chunk_text`, [SLUG])).map(r => r.chunk_text);++ test('an append effect embeds only its occurrences, the sweep the rest of the live rows, never a segment or the body', async () => {+ const page = (await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: SLUG }))!;+ expect(page).toMatchObject({ slug: SLUG, title: TITLE, body_storage: 'segmented' });+ const exec = spyOn(engine, 'executeRaw');+ try {+ expect(await embedSegmentedPage(engine, page, { embedFn, occurrenceIds: [20] })).toEqual({ embedded: 1, complete: true });+ expect(await vectored()).toEqual(['appended row']);+ expect(await embedSegmentedPage(engine, page, { embedFn, batchRows: 1 })).toEqual({ embedded: 2, complete: true });+ for (const [sql] of exec.mock.calls) expect(String(sql)).not.toMatch(/page_segment_texts|compiled_truth|timeline_lead|truth_lead/);+ } finally { exec.mockRestore(); }+ expect(await vectored()).toEqual(['appended row', 'first live row', 'second live row']);+ expect(embedded.flat().some(t => /retired row|staged row/.test(t))).toBe(false);+ const provenance = embeddingInputContext(await embeddingWriteTarget(engine), TITLE, null, []);+ const [row] = await engine.executeRaw<{ embedding_input_hash: string }>(+ `SELECT embedding_input_hash FROM content_chunks WHERE chunk_text = 'appended row'`);+ expect(row!.embedding_input_hash).toBe(embeddingInputHash(provenance, plainEmbeddingTier(null), { chunk_text: 'appended row', chunk_source: 'compiled_truth' }));+ });++ test('embedStalePages routes a segmented page to the keyset sweep', async () => {+ const result = await embedStalePages(engine, [SLUG], 'default', { embedFn });+ expect(result.embedded).toBe(3);+ expect(await vectored()).toEqual(['appended row', 'first live row', 'second live row']);+ });++ test('an inline page is not a segmented embed page', async () => {+ await engine.putPage('notes/inline-embed', { type: 'note', title: 'Inline', compiled_truth: 'Inline body.', timeline: '', frontmatter: {} });+ expect(await readSegmentedEmbedPage(engine, { sourceId: 'default', slug: 'notes/inline-embed' })).toBeNull();+ });+ });+}diff --git a/test/large-pages/segmented-versions.test.ts b/test/large-pages/segmented-versions.test.tsnew file mode 100644index 0000000000..c016a27876--- /dev/null+++ b/test/large-pages/segmented-versions.test.ts@@ -0,0 +1,154 @@+/**+ * Wave B versions as manifests (spec 5).+ *+ * 1. Protects: a segmented page's version is an O(1) reference row (its body+ * generation, body_bytes and content_hash, NULL bodies; no segment or+ * chunk read); segmented retention keeps the newest+ * `versions.segmented_max_per_page` and prunes oldest-first while bytes+ * pinned beyond the live generation exceed+ * max(`versions.segmented_max_pinned_bytes`, body_bytes); inline history is+ * never pruned by it; a retained version keeps its generation's manifest+ * rows alive through `sweepSegments`; get_versions returns size and a+ * body_ref, never a body; revert_version refuses a segmented version with+ * `page_body_segmented` (PR 3 adds it).+ * 2. Fails when: a segmented version copies or reads the body, retention+ * prunes inline snapshots or keeps unbounded pinned history, or a revert+ * rebuilds a page from a NULL body.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { PAGE_BODY_CONFIG_KEYS } from '../../src/core/page-body/limits.ts';+import { operationsByName } from '../../src/core/operations.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { segmentPage } from '../helpers/segmented-chunks-fixture.ts';+import { testBackends } from '../helpers/test-backends.ts';++const SLUG = 'notes/segmented-history';+const KB = 1024;++for (const kind of testBackends()) {+ describe(`segmented versions (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ let pageId: number;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ }, 120_000);+ afterAll(async () => { await close?.(); });++ /**+ * Generation 1: occurrences 1 (live through every generation) and 2.+ * Generation 2 closes 2 and adds 3; generation 3 closes 3 and adds 4.+ * A version at generation 1 pins occurrence 2; at generation 2, occurrence 3.+ */+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.executeRaw('DELETE FROM page_segment_texts');+ await engine.executeRaw(`DELETE FROM config WHERE key IN ($1, $2)`, [PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage, PAGE_BODY_CONFIG_KEYS.versionsMaxPinnedBytes]);+ ({ pageId } = await segmentPage(engine, SLUG, {+ generation: 1,+ bodyBytes: 2 * KB,+ occurrences: [+ { id: 1, byteStart: 0, genFrom: 1, byteLen: KB, chunks: [{ text: 'opening passage' }] },+ { id: 2, byteStart: KB, genFrom: 1, genTo: 2, byteLen: 8 * KB, chunks: [{ text: 'first tail', retiredGeneration: 2 }] },+ { id: 3, byteStart: KB, genFrom: 2, genTo: 3, byteLen: 8 * KB, chunks: [{ text: 'second tail', retiredGeneration: 3 }] },+ { id: 4, byteStart: KB, genFrom: 3, byteLen: KB, chunks: [{ text: 'third tail' }] },+ ],+ }));+ });++ const atGeneration = (generation: number) => engine.executeRaw('UPDATE pages SET body_generation = $2 WHERE id = $1', [pageId, generation]);+ const segmentedVersions = async () => (await engine.executeRaw<{ body_generation: number }>(+ `SELECT body_generation FROM page_versions WHERE page_id = $1 AND body_storage = 'segmented' ORDER BY id`, [pageId])).map(r => Number(r.body_generation));++ test('a segmented version is an O(1) reference row that never reads segments or chunks', async () => {+ const exec = spyOn(engine, 'executeRaw');+ try {+ await engine.createVersion(SLUG);+ for (const [sql] of exec.mock.calls) expect(String(sql)).not.toMatch(/page_segment_texts|content_chunks/);+ } finally { exec.mockRestore(); }+ const [row] = await engine.executeRaw<Record<string, unknown>>('SELECT * FROM page_versions WHERE page_id = $1', [pageId]);+ expect(row).toMatchObject({ body_storage: 'segmented', compiled_truth: null, timeline: null, title: SLUG });+ expect(Number(row!.body_generation)).toBe(1);+ expect(Number(row!.body_bytes)).toBe(2 * KB);+ expect(row!.content_hash).toEqual(expect.any(String));+ });++ test('retention keeps the newest versions_max_per_page', async () => {+ await engine.setConfig(PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage, '2');+ for (const generation of [1, 2, 3]) { await atGeneration(generation); await engine.createVersion(SLUG); }+ expect(await segmentedVersions()).toEqual([2, 3]);+ });++ test('retention prunes oldest-first while pinned bytes exceed max(cap, body_bytes)', async () => {+ await engine.setConfig(PAGE_BODY_CONFIG_KEYS.versionsMaxPinnedBytes, String(10 * KB));+ await atGeneration(1); await engine.createVersion(SLUG);+ await atGeneration(2); await engine.createVersion(SLUG);+ // 8 KiB (generation 1) + 8 KiB (generation 2) pinned > 10 KiB: the oldest goes.+ expect(await segmentedVersions()).toEqual([2]);+ // The live generation pins nothing beyond itself.+ await atGeneration(3); await engine.createVersion(SLUG);+ expect(await segmentedVersions()).toEqual([2, 3]);+ });++ test('the byte cap is at least the page body_bytes', async () => {+ await engine.setConfig(PAGE_BODY_CONFIG_KEYS.versionsMaxPinnedBytes, String(KB));+ await engine.executeRaw('UPDATE pages SET body_bytes = $2 WHERE id = $1', [pageId, 64 * KB]);+ await atGeneration(1); await engine.createVersion(SLUG);+ await atGeneration(2); await engine.createVersion(SLUG);+ expect(await segmentedVersions()).toEqual([1, 2]);+ });++ test('inline history is never pruned by segmented retention', async () => {+ await engine.setConfig(PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage, '1');+ const inline = await engine.putPage('notes/inline-history', { type: 'note', title: 'Inline', compiled_truth: 'v0', timeline: '', frontmatter: {} });+ for (let i = 1; i <= 4; i++) {+ await engine.createVersion('notes/inline-history');+ await engine.putPage('notes/inline-history', { type: 'note', title: 'Inline', compiled_truth: `v${i}`, timeline: '', frontmatter: {} });+ }+ const rows = await engine.executeRaw('SELECT id FROM page_versions WHERE page_id = $1', [inline.id]);+ expect(rows).toHaveLength(4);+ });++ test('a retained version keeps its generation manifest rows alive through sweepSegments', async () => {+ await engine.setConfig(PAGE_BODY_CONFIG_KEYS.versionsMaxPerPage, '1');+ await atGeneration(1); await engine.createVersion(SLUG);+ await atGeneration(3); await engine.createVersion(SLUG);+ await engine.sweepSegments({ pageId, graceMs: 0 });+ const occurrences = (await engine.executeRaw<{ occurrence_id: number }>(+ 'SELECT occurrence_id FROM page_body_manifest WHERE page_id = $1 ORDER BY occurrence_id', [pageId])).map(r => Number(r.occurrence_id));+ // Generation 3 (the only version, and live) needs 1 and 4; 2 and 3 are dead.+ expect(occurrences).toEqual([1, 4]);+ });++ test('get_versions returns size and a body_ref for segmented versions, never a body', async () => {+ await engine.createVersion(SLUG);+ const ctx = { engine, config: { engine: engine.kind }, remote: false, dryRun: false, logger: { info() {}, warn() {}, error() {} } } as unknown as OperationContext;+ const [meta] = await operationsByName.get_versions!.handler(ctx, { slug: SLUG }) as Array<Record<string, unknown>>;+ expect(meta).toMatchObject({ body_storage: 'segmented', body_bytes: 2 * KB });+ expect(meta).not.toHaveProperty('compiled_truth');+ const [full] = await operationsByName.get_versions!.handler(ctx, { slug: SLUG, include_body: true }) as Array<Record<string, unknown>>;+ expect(full).not.toHaveProperty('compiled_truth');+ expect(full).not.toHaveProperty('timeline');+ expect(full!.body_ref).toEqual({ version_id: full!.id, total_bytes: 2 * KB,+ read: { tool: 'get_page', arguments: { slug: SLUG, version_id: full!.id, body: 'window' } } });+ });++ test('revertToVersion refuses a segmented version with page_body_segmented and writes nothing', async () => {+ const version = await engine.createVersion(SLUG);+ const before = await engine.executeRaw('SELECT body_generation, knowledge_revision FROM pages WHERE id = $1', [pageId]);+ await expect(engine.revertToVersion(SLUG, version.id)).rejects.toMatchObject({ code: 'page_body_segmented' });+ expect(await engine.executeRaw('SELECT body_generation, knowledge_revision FROM pages WHERE id = $1', [pageId])).toEqual(before);+ });+ });+}diff --git a/test/scripts/chunk-visibility-ratchet.test.ts b/test/scripts/chunk-visibility-ratchet.test.tsnew file mode 100644index 0000000000..5f601bb933--- /dev/null+++ b/test/scripts/chunk-visibility-ratchet.test.ts@@ -0,0 +1,128 @@+/**+ * Wave B large pages (spec 4.2): scripts/check-chunk-visibility.ts fails on a+ * new `FROM/JOIN content_chunks` reader without the generation predicate, on+ * stale, duplicate and malformed baseline rows and on an empty marker reason;+ * a covered reader (direct call, same-file helper, visibility clause with a+ * chunk alias, marker) never counts, and `--prune` only lowers rows.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';++const REPO = resolve(import.meta.dir, '..', '..');+const GUARD = join(REPO, 'scripts', 'check-chunk-visibility.ts');+const BASELINE = 'scripts/chunk-visibility-baseline.tsv';+const dirs: string[] = [];+afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++function tree(files: Record<string, string>): string {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-chunk-visibility-'));+ dirs.push(root);+ for (const [rel, body] of Object.entries({ [BASELINE]: '# baseline\n', ...files })) {+ mkdirSync(join(root, rel, '..'), { recursive: true });+ writeFileSync(join(root, rel), body);+ }+ return root;+}++function run(root: string, args: string[] = []) {+ const r = spawnSync('bun', [GUARD, ...args], { encoding: 'utf8', env: { ...process.env, GBRAIN_GUARD_ROOT: root } });+ return { code: r.status, out: `${r.stdout}\n${r.stderr}` };+}++describe('check-chunk-visibility.ts', () => {+ test('an uncovered reader fails with its file, lines and the fix; writes and prose never count', () => {+ const root = tree({+ 'src/core/reader.ts': [+ "export const a = 'SELECT id FROM content_chunks WHERE page_id = $1';",+ 'export const b = `SELECT p.slug FROM pages p JOIN content_chunks cc ON cc.page_id = p.id`;',+ "export const del = 'DELETE FROM content_chunks WHERE page_id = $1';",+ '// prose: rows from content_chunks are read elsewhere',+ ].join('\n'),+ });+ const r = run(root);+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL: src/core/reader.ts:1 2 content_chunks reader(s) without the chunk-visibility predicate (lines 1, 2), the baseline allows 0');+ for (const label of ["Fix: add ${chunkVisibleFilter('p', 'cc')}", 'Why:', 'See: scripts/check-chunk-visibility.ts (header)']) {+ expect(r.out).toContain(label);+ }+ });++ test('direct calls, same-file helpers, a chunk-aliased visibility clause and markers cover a reader', () => {+ const root = tree({+ 'src/core/covered.ts': [+ "import { chunkVisibleFilter, chunkGenerationFilter, chunkGenerationProbe } from './safe-chunks.ts';",+ "import { buildVisibilityClause } from './sql-ranking.ts';",+ "export const direct = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ${chunkVisibleFilter('p', 'cc')}`;",+ "export const probe = `SELECT 1 FROM content_chunks cc WHERE ${chunkGenerationProbe('cc')}`;",+ "const live = chunkGenerationFilter('p', 'cc');",+ 'const where = `AND ${live}`;',+ 'export const viaHelper = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE true ${where}`;',+ "export const clause = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ${buildVisibilityClause('p', 's', {}, 'cc')}`;",+ "export const sqlMarker = 'SELECT count(*) FROM content_chunks -- chunk-visibility-ok: storage statistics';",+ '// chunk-visibility-ok: code pages are never segmented',+ "export const lineMarker = 'SELECT id FROM content_chunks WHERE symbol_name_qualified = $1';",+ ].join('\n'),+ });+ const r = run(root);+ expect(r.out).toContain('check-chunk-visibility: ok (6 covered, 0 baselined content_chunks readers)');+ expect(r.code).toBe(0);+ });++ test('a visibility clause without a chunk alias does not cover a reader', () => {+ const root = tree({+ 'src/core/pages-only.ts': "export const q = `SELECT 1 FROM content_chunks cc JOIN pages p ON p.id = cc.page_id WHERE ${buildVisibilityClause('p', 's')}`;",+ });+ const r = run(root);+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL: src/core/pages-only.ts:1 1 content_chunks reader(s)');+ });++ test('an empty marker reason fails', () => {+ const root = tree({+ 'src/core/empty.ts': "// chunk-visibility-ok:\nexport const q = 'SELECT id FROM content_chunks';",+ });+ const r = run(root);+ expect(r.code).toBe(1);+ expect(r.out).toContain('FAIL: src/core/empty.ts:1 chunk-visibility-ok marker has no reason');+ });++ test('a baselined reader passes; a stale, duplicate or malformed row fails; --prune only lowers', () => {+ const reader = "export const a = 'SELECT id FROM content_chunks';\nexport const b = 'SELECT id FROM content_chunks';";+ expect(run(tree({ 'src/core/r.ts': reader, [BASELINE]: '# baseline\nsrc/core/r.ts\t2\n' })).code).toBe(0);++ const staleRoot = tree({ 'src/core/r.ts': reader, [BASELINE]: '# baseline\nsrc/core/r.ts\t3\nsrc/core/gone.ts\t1\n' });+ const stale = run(staleRoot);+ expect(stale.code).toBe(1);+ expect(stale.out).toContain('stale row: src/core/r.ts has 2 uncovered content_chunks reader(s), the row allows 3');+ expect(stale.out).toContain('stale row: src/core/gone.ts has 0 uncovered');+ expect(run(staleRoot, ['--prune']).code).toBe(0);+ expect(readFileSync(join(staleRoot, BASELINE), 'utf8')).toBe('# baseline\nsrc/core/r.ts\t2\n');+ expect(run(staleRoot).code).toBe(0);++ const dup = run(tree({ 'src/core/r.ts': reader, [BASELINE]: '# baseline\nsrc/core/r.ts\t2\nsrc/core/r.ts\t2\n' }));+ expect(dup.code).toBe(1);+ expect(dup.out).toContain('duplicate row for src/core/r.ts');++ const bad = run(tree({ 'src/core/r.ts': reader, [BASELINE]: '# baseline\nsrc/core/r.ts\ttwo\n' }));+ expect(bad.code).toBe(1);+ expect(bad.out).toContain("malformed row 'src/core/r.ts\ttwo'");++ const grown = tree({ 'src/core/r.ts': `${reader}\nexport const c = 'SELECT id FROM content_chunks';`, [BASELINE]: '# baseline\nsrc/core/r.ts\t2\n' });+ expect(run(grown).code).toBe(1);+ run(grown, ['--prune']);+ expect(readFileSync(join(grown, BASELINE), 'utf8')).toBe('# baseline\nsrc/core/r.ts\t2\n');+ });++ test('a missing baseline fails', () => {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-chunk-visibility-'));+ dirs.push(root);+ const r = run(root);+ expect(r.code).toBe(1);+ expect(r.out).toContain(`FAIL: ${BASELINE}:1 baseline file missing`);+ });+});