Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 1 lane 1c: segmented-body-unreachable test and helper; fit module-size ceilings

garrytane768f2a8382d
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 902ef453cc..8148584576 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -23,7 +23,7 @@ src/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown
src/core/pglite-engine.ts 3043 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import
src/core/postgres-engine.ts 3060 ratchet +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); ceiling rationale: docs/architecture/key-files/engines-2.md entry for src/core/postgres-engine.ts; evidence delivery: getChunkWindows scoped-read delegate + type import (+5; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +10 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3242 #5824: searchVector SQL moved to search/vector-statement.ts, +explainVectorSearch/runVectorAttempt (-156); +6 #5730: onpoisoned wiring on the instance/module/connection-manager pools + poisonedDiscards in getPoolDiagnostics (counter in pool-gauge.ts); +5 #5801: onCheckout observer seam (fires after reserve resolution / transaction-callback entry; listeners in pool-gauge.ts); lowered to 3119 #5889: searchTitles SQL moved to engine-sql/titles.ts (-133); lowered to 2914 F4a: getHealth SQL moved to engine-sql/health.ts (-216); +2 #5984: transactions track held page guards like PGLite (withHeldPageKeys), so repeated guards in one transaction cost no round trips; +1 #5984: traceSqlOptions import for the env-gated GBRAIN_SQL_TRACE bench hook (src/core/sql-trace.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2917 measured); +2 engine graduation (GBRA-50 G2a): initSchema sizing parameter (the source embedding layout sizes a fresh target); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2920 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 6 #6085: initSchema pins advisory lock 42, bootstrap, schema replay and unlock to one reserved backend when the DDL pool has more than one slot (gauge only, no long-hold permit), released in finally; wave 10 collector: lane E (#6085), lane G (#5375) and master compose at 2939; +2 #6110: search transactions pass jitOff to withScopedReadTransaction (SET LOCAL jit = off in postgres-engine/search-settings.ts); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +1 #5984 single-write fast path composes with the lane apply diet at 2944; +2 #5984 shared parameter types: the instance pool passes shared_types and initSchema clears them after migrations (helpers in db.ts); +2 #6276: the remote alias-resolving readPageSnapshot runs with JIT off (withScopedReadTransaction jitOff); +5 #6278: executeRaw timeoutMs delegate (statement in postgres-engine/bounded-statement.ts); +23 #6278 PR 1.5: cancelSettleMs() and the settle timer in runUnsafe that discards a reserved connection whose cancel a transaction-mode pooler never completed; +3 #6317 lane 2: getPoolDiagnostics().pool from the vendored driver (postgres-engine/pool-stats.ts) and the prepare mark; +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +1 GBRA-69 extract batching: replaceDerivedLinksBatch delegate (batch logic in derived-links.ts); +9 GBRA-75: getBacklinkCounts and getHealth statements run JIT-off through the private jitOffRead transaction helper (engine methods cannot move); +3 GBRA-75 wave 7: searchKeyword and searchVector start the once-per-engine background search statistics guard (logic in search/projection-statistics.ts); +7 GBRA-67: readPageSnapshotsBatch scoped-read delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages scoped-read delegate (SQL in engine-sql/pages.ts); +7 #6383: poolIncidents hooks on the instance/module/connection-manager pools (counter and lines in pool-gauge.ts, budget in db.ts) and stuckDiscards/buildFailures in getPoolDiagnostics; +3 GBRA-76: transaction/transactionDirect take TransactionOptions; transactionOn attaches the begin handle to withTransactionAbort (logic in postgres-engine/transaction-abort.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +1 #5227: schema.sql replay under withSchemaLockTimeout (wave 14 PR1); +1 driver desync tripwire: desyncDiscards in getPoolDiagnostics (counter and line in pool-gauge.ts); +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages scoped-read delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3027 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates, reads scoped (SQL in engine-sql/pages.ts); +12 wave 16 G5.1 (#6495): keywordStatementTimeout memo field, its connect/disconnect resets and the keywordStatementTimeoutSetting accessor, plus one awaited setting per keyword/chunk/CJK transaction (resolver in postgres-engine/keyword-statement-timeout.ts); wave 16 G5.1 gate fix: keywordStatementTimeoutSetting resolves the knob once per connection on the first keyword statement from the saved connect config (connect issues no statement for it; 3042 measured); +7 large pages Wave A sub-a: getChunkPage scoped-read delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type import
src/core/search/hybrid.ts 1648 ratchet +5 GBRA-81 item 5 per-stage search timings: HybridSearchOpts._timings (interface field) and the timer bindings and import in hybridSearch/hybridSearchCached (collector logic in search/stage-timings.ts); +2 W5 page-unit ranking cut: HybridSearchOpts.pageRankCut (logic in search/page-rank-cut.ts); +9 W3 confidence-gated reranking: HybridSearchOpts.rerankGate and the gate/lookup threading through rerankAndPin and sizeReturnPool (logic in search/hybrid/rerank-gate.ts, crag.ts gradePreRerank); re-summed at the W3 merge onto master v0.60.168.0 (1641 measured); +2 System One v1: HybridSearchOpts.decide (search/decide-stage.ts); refactor wave 1 split target (W4 hybrid, cut line); ceiling rationale: docs/architecture/key-files/core-search-1.md entry for src/core/search/hybrid.ts; +10 #5691: per-request embedding_query_prefix read once and threaded to the embeds and cache key; +5 green master wave (embedding opt-out): HybridSearchOpts._embeddingOptedOut (interface field) read once per request and threaded to the cache-lookup embed and the keyword-only gate; +24 P2 explain RRF attribution stamp in rrfFusionWeighted, backlink_count stamp, explain_target stage observations, explain/explainTarget opts; +14 fix wave 13 P4.8 #6400: lazyQueryEmbedDeadline (the query-embed deadline starts when the embed starts) and the _queryEmbedDeadline getter; +1 query facts arm: HybridSearchOpts.onQueryEmbedding (interface field; its one-line call is paid inside the ceiling) after the vector arms, so the facts arm reuses the query embedding without a second model call; re-summed at the master a08578ca5 merge (1591 master lines + 3 integration lines: the onQueryEmbedding hook)
-src/core/types.ts 2315 ratchet +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts)
+src/core/types.ts 2319 ratchet +4 Wave B PR 1 (1c): Page.body_storage/body_bytes (interface fields; guard logic in page-body/page-shape.ts); +8 W3 confidence-gated reranking: HybridSearchMeta.rerank_gate (RerankGateMeta in search/hybrid/rerank-gate.ts); re-summed at the W3 merge onto master v0.60.168.0 (2279 measured); +7 fix wave 11 W6.2/W6.3 (#5989, #6132): SearchOpts.hnswIterativeScan and cjkKeyword, the keyword_candidates_incomplete stage and HybridSearchMeta.keyword_candidates (logic in engine-sql/cjk-search.ts); +5 System One v1 retrieval lane: SearchResult injection_p/injection_suspected, HybridSearchMeta answerability, egress_denied degraded reason; +4 System One v1: SearchResult rerank_score_kind/decide_evidence, HybridSearchMeta decide/rerank; +3 wave review: PAGE_SORT_SQL.updated_asc source_id + id tiebreakers (total order under federated scopes); +5 #4881: OntologyReadOpts extends PageReadScope doc; +3 #4857: PAGE_SORT_SQL.slug total-order tiebreaker comment; grown v0.46.26.0 megawave: EvidenceOpts, pacing/usage result fields, PageFilters growth (#4352 #4218); wave-k: +9 SalienceOpts/AnomaliesOpts source scope (#3867); +20 2026-09 adversarial batch 2: keyword_relaxed_carried stage + relaxed_dropped meta field docs; +16 2026-09 fix wave: SearchResult.keyword_relaxed field + full fusion-demotion doc; (#3867); +9: #4648 rerank_passthrough degraded stage + empty_result_set/malformed_shape reasons | merged v0.48.1.0 true-up; +master v0.48 merge true-up (reranker succession: no_key preflight, reranker_skipped stage, readiness); corrective release: shared internal PageReadScope and PageReadPolicy; ranker wave v0.48.4.0: HybridSearchMeta relational_rerank_pin / keyword_arm_confidence / metadata_boost_gate + SearchResult.relational_pinned (+48 over master's peel); +12: #4681 Page.updated_at_iso + keyset cursor precision docs; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: public page revision fields; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: typed vector pool and readiness metadata; merged company ingestion/schema routing changes; retired provider integration removed; +1 write-path wave: 'created' effective-date source; +3 read-path wave: rerank_failed degraded stage + budget reason (closed vocabularies) and its recall classification note; +8 fw3-search: SearchOpts.source_boosts + keyword_arm_failed/title_arm_failed stages; +2 wave-2 W4: ChunkInput.embedding_input_hash (#5553); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +2 at the merge; evidence delivery: optional SearchResult.delivered (+2; shape in search/evidence-delivery.ts); +2 eval wave N1-3: OntologyReadOpts.visibility (remote world-only ontology reads); +4 #5827: GraphNode.source_id and GraphPath from_source_id/to_source_id; +2 #5824: SearchOpts.vectorLegacyGuard rollback switch; +7 #5154: PageFilters.listColumnsOnly (interface field); +11 Foundations 1 F1b: WriteAttributionView + AttributedPageVersion (get_versions / get_write_attribution read shapes); +1 #5988: SearchResult.stale carries the held-file detail (interface field); +6 retrieval feedback: SearchResult feedback_boost/content_hash/relational_path_edges stamps and RelationalFanoutRow.path_edges (interface fields); +2 RelationalFanoutOpts.wide (interface field); 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); P3 x P7 (v0.60.60.0) composition: deltas re-summed at the merge; 1 GBRA-49: temporal annotation field on link rows; +44 P7 ChainHopOpts/ChainHopEdge chain-hop contract types; P7 SearchResult.relational evidence + RelationalEvidence type + relational_plan meta + planner per-call overrides; +2 P7 SearchOpts.relationalChainSlots per-call override; +1 P7 ChainHopOpts.temporal (relationship-validity policy per hop); +1 green master wave: embedding_disabled degraded reason (closed vocabulary); +2 #5951: Chunk.source_id (get_chunks names each row's source); 1 P2 SearchResult explain fields (rrf attribution, blend_norm_rrf, score_details, backlink_count) + RrfAttribution (interface fields); +11 #5575 (L1b): PageReadScope minTrust/suppressFlagged, SearchResult trust_tier/origin/unconfirmed, TimelineOpts eligibility (interface fields cannot move); +8 #4772 (W14 PR3): BrainHealth.entity_types_status field (interface fields cannot move); +1 C4: question page type row; +6 entity anchoring: optional SearchResult.entity_anchored row stamp (logic in search/entity-anchor.ts); +4 query facts arm: optional SearchResult.fact_row and superseded_claim row fields (logic in search/facts-arm.ts); +2 query facts arm: SearchResult result_type/fact_id/page_slug/follow_up (fact rows are never page-shaped); +9 Cat 40 Hard fix wave (#6271): SearchResult matched_alias/evidence_omitted/provenance, SearchOpts.rankQuery, keyword_count_unavailable stage and rerank_failed reasons; +12 fix wave 15 P2.1 (#6500): PageFilters.slugAfter (single-source slug keyset, interface field + doc) and the updated_desc tiebreaker comment (the keyset walk lives in facts/conversation-enumeration.ts); +2 wave 16 G5.1 (#6495): EngineConfig.keyword_statement_timeout_ms (interface field + doc); +2 GBRA-92: EngineConfig.pglite_shared_buffers (interface field + doc); +11 large pages (Wave A): Chunk/ChunkInput projected_byte_start/end interface fields (span logic in chunkers/recursive.ts, page-window/document.ts)
src/core/minions/queue.ts 2528 ratchet grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; security: durable queued authority and confined filesystem dispatch; master integration: grown #4078 + megawave probe-liveness unlatch (#4310) + master private-queue lifecycle: recovery classifier + monotonic lease; harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: durable authority and delegated admission both enforced; typed readiness, configuration-blocked lifecycle and bounded release; +9: prune archives completed dream synthesis keys; +18 Lane D: deferJob (a deferral returns a job to delayed with no attempt counted and no stacktrace growth); the ceiling had 17 lines of slack; +5 agent operator follow-up Item 5 merged over master: claim-time spend fence token and legacy_default stamp (logic in minions/spend-authorization.ts)
src/commands/init.ts 1884 ratchet +2 fix wave 9 lane F #5253: leaving deferred setup also clears the DB-plane embedding_disabled row (both init branches); grown v0.46.x keyless capability notices; grown db-availability loop: initPostgresCore typed-failure extraction + --prefer-postgres ladder hook + pgvector rethrow fix; +1 at megawave/wave-k merge; +master-merge true-up; wave-k: merge; #3753 --force re-init engine-preservation guard; +1 wave-k merge-union brace (--prefer-postgres close); +10 ambient-writeback WP8: runWritebackNudge consent ask in both engine epilogues (logic lives in core/onboard/writeback-nudge.ts); +4: v0.48.2 reranker readiness at init + test seam; +1: v0.48.2 provider normalization; +3: v0.48.2 review fixes; master integration: +2: preserve typed PGLite busy errors in schema-only init; shared-skills integration on company-ingestion base; retired provider integration removed; retain stored-vector identity on re-init; -14: first-run bundle + quickstart registration helpers live in init-first-run.ts (writeback/skills asks folded into the bundle); +5 agent operator follow-up Item 2: --surface flag (value flag, parse, help line, module-level registration surface, type import) for the printed harness registration; +2 fix wave lane B3: both engine paths stamp a database init created as a fresh install for the behavior_changes notice (core/behavior-change-notice.ts); +4 GBRA-81 item 1: --search-mode value flag, its parse line, module-level choice, help line (picker logic lives in init-mode-picker.ts); +2 D8 funnel: a fresh init counts one clean_install when the opt-in funnel is on (core/funnel.ts)
src/commands/integrations.ts 1739 ratchet grown v0.46.26.0 megawave (#4039 connector compat) + 1 nosemgrep dataflow annotation (path-traversal audit); wave-k: exported heartbeatPath seam (#3900)
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 0e711de632..99ea3aac15 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -182,7 +182,7 @@ src/core/engine-sql/pages.ts listStalePagesForExtraction sql STREAM segmented pa
src/core/engine-sql/pages.ts PAGE_VERSION_COLUMNS sql SEGW lane 1e: versions of segmented pages carry no body
src/core/engine-sql/pages.ts putPage call:contentHash META hash of the incoming inline body
src/core/engine-sql/pages.ts putPage field SEGW incoming PageInput body (a string); see putPage sql
-src/core/engine-sql/pages.ts putPage sql SEGW blank-guard reads body_bytes for a segmented page and refuses a whole-body put over it with page_body_segmented
+src/core/engine-sql/pages.ts putPage sql SEGW blank-guard reads body_bytes for a segmented page (an empty put over it refuses); a non-empty put over a segmented row is refused by the body-storage CHECK
src/core/engine-sql/pages.ts refreshPageBody sql SEGW UPDATE of the body columns; the body-storage CHECK refuses it over a segmented row; callers assert first
src/core/engine-sql/pages.ts revertToVersion sql SEGW lane 1e: refuses a segmented page/version (revert deferred to PR 3)
src/core/engine-sql/pages.ts toDomainBankRow field LEAD maps sampled rows; segmented pages are never sampled
@@ -190,7 +190,7 @@ src/core/engine-sql/salience.ts listEnrichCandidates sql META
src/core/engine-sql/timeline.ts getTimeline sql NONE not the page body: SELECT * FROM pages inside a LATERAL used for the page id only
src/core/enrichment-service.ts enrichEntity call:putPage INLINE
src/core/enrichment-service.ts enrichEntity call:serializeMarkdown INLINE
-src/core/export-snapshot.ts readExportPage field STREAM
+src/core/export-snapshot.ts readExportPage field STREAM export refuses a segmented page: segmented page: getter throws page_body_segmented (streaming export in PR 2)
src/core/export-snapshot.ts readExportPage sql STREAM
src/core/extract-ner.ts extractNerLinks field STREAM
src/core/extract-takes-from-pages.ts extractTakesFromPages call:serializePageToMarkdown SEGW
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index e3cfda00fc..39a8704382 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -33,7 +33,6 @@ import { listPagesPagination, listingTruncatedNotice } from './list-pages-pagina
import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';
import { invalidParam, readFix } from './op-fix.ts';
import { isDatetimeInputError } from '../utils.ts';
-import { isSegmentedPage } from '../page-body/page-shape.ts';
import { rethrowNamingRevisionSource } from './put-page-revision-source.ts';
import {
assertExplicitSourceLive,
@@ -195,8 +194,7 @@ const get_page: Operation = {
// Only explicitly trusted local reads retain protected body sections.
// Holder grants and page-visibility opt-outs do not bypass this boundary.
const isUntrustedReader = ctx.remote !== false;
- // A segmented page keeps its throwing body getters: only body: 'none' answers it in Wave B PR 1.
- const visibleBody = isUntrustedReader && !isSegmentedPage(page)
+ const visibleBody = isUntrustedReader && page.body_storage !== 'segmented'
? stripPrivacyFencesForRemoteReader(page)
: page;
// v0.42 (#1699) agent-warning channel: surface the page's content_flag
diff --git a/src/core/types.ts b/src/core/types.ts
index 07497896b5..8542a010c0 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -1,5 +1,3 @@
-import type { BodyStorage } from './page-body/types.ts';
-
// Page types
// v0.38: `PageType` opens from a closed 23-element union to `string`. The
// closed union was always a fiction — every gbrain user accumulated organic
@@ -94,13 +92,8 @@ export interface Page {
timeline: string;
frontmatter: Record<string, unknown>;
content_hash?: string;
- /**
- * Wave B: where the body lives. On a `segmented` page `compiled_truth` and
- * `timeline` are getters that throw `page_body_segmented`
- * (`page-body/page-shape.ts`); read its size from `body_bytes`. Absent on
- * paths that do not project the column (an inline page).
- */
- body_storage?: BodyStorage;
+ /** Wave B: on a `segmented` page `compiled_truth`/`timeline` throw `page_body_segmented` (page-body/page-shape.ts); absent = inline. */
+ body_storage?: import('./page-body/types.ts').BodyStorage;
/** Wave B: UTF-8 bytes of truth + timeline; always set on a segmented page (`pageBodyBytes`). */
body_bytes?: number | null;
/** Source-relative canonical file identity; snapshot reads expose it for guarded import comparisons. */
diff --git a/test/helpers/segmented-page.ts b/test/helpers/segmented-page.ts
new file mode 100644
index 0000000000..9d70e04f2b
--- /dev/null
+++ b/test/helpers/segmented-page.ts
@@ -0,0 +1,109 @@
+/**
+ * Build a segmented page with the engine members directly (Wave B PR 1), independent of the
+ * streaming ingest: cut each region at line boundaries into segments of at most
+ * SEGMENT_MAX_BYTES, then create the shell, stage texts and manifest rows and flip to
+ * generation 1 in one transaction. Segment boundaries are deliberately naive (no
+ * protected-region or fence awareness); tests that need the segmenter's cuts use the ingest.
+ */
+import { createHash, randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { BODY_LEAD_BYTES, DEFAULT_FLIP_RETIRE_MAX_ROWS, SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import type { BodyRegion, JsonObject, ManifestRowInput, SegmentedPageMeta, SegmentTextInput } from '../../src/core/page-body/types.ts';
+import { boundedRawPrefix } from '../../src/core/page-window/bounded-lead.ts';
+import { contentHash } from '../../src/core/utils.ts';
+
+export interface SegmentedPageInput {
+ slug: string;
+ sourceId?: string;
+ truth: string;
+ timeline?: string;
+ meta?: Partial<SegmentedPageMeta>;
+ flags?: JsonObject;
+}
+
+export interface SegmentedPageState {
+ body_storage: string;
+ body_generation: number;
+ content_hash: string;
+ body_bytes: number;
+ compiled_truth: string | null;
+ timeline: string | null;
+ manifest: Array<{ occurrenceId: number; sha256: string; byteStart: number; byteLen: number; genTo: number | null }>;
+ texts: number;
+}
+
+/** Lines of `text` packed greedily into pieces of at most `max` UTF-8 bytes; a longer line is cut on a code point. */
+export function cutAtLines(text: string, max = SEGMENT_MAX_BYTES): string[] {
+ const pieces: string[] = [];
+ let current = '';
+ let currentBytes = 0;
+ for (const line of text.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
+ const bytes = Buffer.byteLength(line, 'utf8');
+ if (currentBytes + bytes > max && current) { pieces.push(current); current = ''; currentBytes = 0; }
+ if (bytes <= max) { current += line; currentBytes += bytes; continue; }
+ for (let rest = line; rest;) {
+ const head = boundedRawPrefix(rest, max);
+ pieces.push(head);
+ rest = rest.slice(head.length);
+ }
+ }
+ if (current) pieces.push(current);
+ return pieces;
+}
+
+const lineCount = (text: string) => (text.match(/\n/g)?.length ?? 0) + (text.endsWith('\n') || !text ? 0 : 1);
+
+/** Create `input.slug` as a segmented page at body_generation 1; returns its page id. */
+export async function createSegmentedPage(engine: BrainEngine, input: SegmentedPageInput): Promise<{ id: number }> {
+ const sourceId = input.sourceId ?? 'default';
+ const timeline = input.timeline ?? '';
+ const meta: SegmentedPageMeta = { type: 'note', title: input.slug, frontmatter: {}, ...input.meta };
+ const regions: Array<[BodyRegion, string[]]> = [['truth', cutAtLines(input.truth)], ['timeline', cutAtLines(timeline)]];
+ const pieces = regions.flatMap(([region, texts]) => texts.map(text => ({ region, text, bytes: Buffer.from(text, 'utf8') })));
+ return engine.transaction(async tx => {
+ const [source] = await tx.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);
+ const { id } = await tx.createSegmentedPageShell(input.slug, meta, { sourceId });
+ const stagingId = randomUUID();
+ const now = Date.now();
+ const totalBytes = pieces.reduce((n, p) => n + p.bytes.length, 0);
+ await tx.openBodyStaging({ id: stagingId, kind: 'import', principalKind: 'test', principalId: 'segmented-page-helper', clientRequestId: randomUUID(),
+ sourceId, sourceIncarnation: source!.incarnation, slug: input.slug, pageId: id, mode: 'create', baseRevision: null, baseGeneration: 0,
+ declaredBytes: totalBytes, declaredSha256: null, reservedBytes: totalBytes, idleExpiresAt: new Date(now + 3_600_000), hardExpiresAt: new Date(now + 7_200_000) });
+ const texts: SegmentTextInput[] = pieces.map(p => ({ sha256: createHash('sha256').update(p.bytes).digest(), body: p.bytes, lineCount: lineCount(p.text) }));
+ await tx.stageSegmentTexts(sourceId, texts);
+ const occurrences = await tx.allocateBodyOccurrenceIds(pieces.length);
+ let byteStart = 0, lineStart = 0;
+ const rows: ManifestRowInput[] = pieces.map((p, seq) => {
+ const row: ManifestRowInput = { pageId: id, occurrenceId: occurrences[seq]!, genFrom: 1, seq, region: p.region, sourceId, sha256: texts[seq]!.sha256,
+ byteStart, byteLen: p.bytes.length, lineStart, lineCount: texts[seq]!.lineCount, cutKind: seq === pieces.length - 1 ? 'eof' : 'forced',
+ entryState: {}, protectedRegions: [], factsSlots: [], staticProjBytes: p.bytes.length, staticProjLines: texts[seq]!.lineCount, outline: [],
+ dateMin: null, dateMax: null, hashState: new Uint8Array(32), stagingId };
+ byteStart += p.bytes.length;
+ lineStart += texts[seq]!.lineCount;
+ return row;
+ });
+ await tx.stageManifestRows(rows);
+ await tx.flipBodyGeneration({ pageId: id, expectedGeneration: 0, newGeneration: 1, stagingId, closeOccurrences: [], retireChunkOccurrences: [],
+ retireMaxRows: DEFAULT_FLIP_RETIRE_MAX_ROWS, meta, body: {
+ content_hash: contentHash({ ...meta, compiled_truth: input.truth, timeline }),
+ body_bytes: totalBytes, truth_bytes: Buffer.byteLength(input.truth, 'utf8'), body_lines: lineCount(input.truth) + lineCount(timeline),
+ segment_count: pieces.length, segmenter_version: 1,
+ truth_lead: boundedRawPrefix(input.truth, BODY_LEAD_BYTES), timeline_lead: boundedRawPrefix(timeline, BODY_LEAD_BYTES),
+ body_flags: input.flags ?? { has_protected: false },
+ } });
+ await tx.setBodyStagingState(stagingId, 'committed');
+ return { id };
+ });
+}
+
+/** What a mutation probe compares: the page's body columns, its live manifest and the source's segment texts. */
+export async function segmentedPageState(engine: BrainEngine, pageId: number, sourceId = 'default'): Promise<SegmentedPageState> {
+ const [page] = await engine.executeRaw<Record<string, unknown>>(
+ 'SELECT body_storage, body_generation, content_hash, body_bytes, compiled_truth, timeline FROM pages WHERE id=$1', [pageId]);
+ const [texts] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_segment_texts WHERE source_id=$1', [sourceId]);
+ const manifest = (await engine.readManifest(pageId)).map(r => ({ occurrenceId: Number(r.occurrenceId), sha256: Buffer.from(r.sha256).toString('hex'),
+ byteStart: Number(r.byteStart), byteLen: Number(r.byteLen), genTo: r.genTo }));
+ return { body_storage: String(page!.body_storage), body_generation: Number(page!.body_generation), content_hash: String(page!.content_hash),
+ body_bytes: Number(page!.body_bytes), compiled_truth: page!.compiled_truth as string | null, timeline: page!.timeline as string | null,
+ manifest, texts: Number(texts?.n ?? 0) };
+}
diff --git a/test/large-pages/segmented-body-unreachable.test.ts b/test/large-pages/segmented-body-unreachable.test.ts
new file mode 100644
index 0000000000..442451a218
--- /dev/null
+++ b/test/large-pages/segmented-body-unreachable.test.ts
@@ -0,0 +1,178 @@
+/**
+ * Wave B PR 1 (spec 1.5): a segmented page's body is unreachable as one string.
+ *
+ * 1. Protects: every engine read that returns a `Page` gives a segmented page body
+ * fields that throw `page_body_segmented` (property read, spread, JSON.stringify,
+ * assignment), so no caller sees '' where a multi-megabyte body lives; old-shape
+ * body writes over a segmented row are refused; every whole-body writer (spec top-25
+ * rows 11-19) refuses before it writes, leaving segments, manifest, body_generation
+ * and content_hash as they were. Inline pages read exactly as before.
+ * 2. Fails when: a read path builds a segmented page without the guard, a writer
+ * reaches the database or the file before refusing, or get_page body:'none' stops
+ * answering a segmented page from body_bytes.
+ * 3. PGLite always; PostgreSQL when DATABASE_URL is set (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { PostgresEngine } from '../../src/core/postgres-engine.ts';
+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';
+import { registerLocalWriter, withVerifiedLocalRegistration, type LocalRegistration } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { serializePageToMarkdown } from '../../src/core/markdown.ts';
+import { materializePageSnapshot } from '../../src/core/page-state/materialize.ts';
+import { writeTimelineEntryThrough } from '../../src/core/timeline-write-through.ts';
+import { preserveCanonicalFences } from '../../src/core/cycle/concept-publication.ts';
+import { assertInlineBody, isSegmentedPage, pageBodyBytes } from '../../src/core/page-body/page-shape.ts';
+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { assertSafeE2eDatabaseUrl } from '../helpers/db-guard.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { createSegmentedPage, cutAtLines, segmentedPageState } from '../helpers/segmented-page.ts';
+
+const SLUG = 'notes/segmented-example';
+const INLINE = 'notes/inline-example';
+const line = (i: number) => `- ${String(i).padStart(7, '0')} acme-example journal line with enough text to fill a segment quickly\n`;
+const TRUTH = `# Segmented example\n\n${Array.from({ length: 30_000 }, (_, i) => line(i)).join('')}`;
+const TIMELINE = `- **2026-10-01** | first entry\n- **2026-10-02** | second entry\n`;
+
+/** Asserts `run` throws the typed page_body_segmented error. */
+function expectSegmented(run: () => unknown): void {
+ let error: unknown;
+ try { run(); } catch (e) { error = e; }
+ expect((error as { code?: string } | undefined)?.code).toBe('page_body_segmented');
+}
+async function expectSegmentedAsync(run: () => Promise<unknown>): Promise<void> {
+ let error: unknown;
+ try { await run(); } catch (e) { error = e; }
+ expect((error as { code?: string } | undefined)?.code).toBe('page_body_segmented');
+}
+function expectUnreachable(page: object): void {
+ expect(isSegmentedPage(page as never)).toBe(true);
+ expectSegmented(() => (page as { compiled_truth: string }).compiled_truth);
+ expectSegmented(() => (page as { timeline: string }).timeline);
+ expectSegmented(() => ({ ...page }));
+ expectSegmented(() => JSON.stringify(page));
+ expectSegmented(() => structuredClone(page));
+ expectSegmented(() => { (page as { compiled_truth: string }).compiled_truth = ''; });
+}
+
+describe('cutAtLines', () => {
+ test('cuts at line ends into pieces of at most SEGMENT_MAX_BYTES and loses nothing', () => {
+ const pieces = cutAtLines(TRUTH);
+ expect(pieces.length).toBeGreaterThan(1);
+ expect(pieces.join('')).toBe(TRUTH);
+ for (const piece of pieces) expect(Buffer.byteLength(piece)).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);
+ for (const piece of pieces.slice(0, -1)) expect(piece.endsWith('\n')).toBe(true);
+ });
+});
+
+for (const kind of ['pglite', 'postgres'] as const) {
+ const suite = kind === 'postgres' && !process.env.DATABASE_URL ? describe.skip : describe;
+ suite(`${kind}: a segmented page body is unreachable`, () => {
+ let engine: BrainEngine;
+ let pageId: number;
+ let fixture: string;
+ let cli: LocalRegistration;
+ const sourceId = `segmented-unreachable-${kind}-${process.pid}`;
+
+ beforeAll(async () => {
+ engine = kind === 'postgres' ? new PostgresEngine() : new PGLiteEngine();
+ if (kind === 'postgres') assertSafeE2eDatabaseUrl(process.env.DATABASE_URL!);
+ await engine.connect(kind === 'postgres' ? { database_url: process.env.DATABASE_URL! } : {});
+ await engine.initSchema();
+ fixture = mkdtempSync(join(tmpdir(), 'gb-segmented-unreachable-'));
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [sourceId]);
+ ({ id: pageId } = await createSegmentedPage(engine, { slug: SLUG, sourceId, truth: TRUTH, timeline: TIMELINE }));
+ await engine.putPage(INLINE, { type: 'note', title: 'Inline', compiled_truth: 'Inline body.', timeline: '', frontmatter: {} }, { sourceId });
+ cli = await registerLocalWriter(engine, 'cli');
+ }, 120_000);
+
+ afterAll(async () => {
+ try {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('DELETE FROM pages WHERE source_id=$1', [sourceId]);
+ await engine.executeRaw('DELETE FROM page_segment_texts WHERE source_id=$1', [sourceId]);
+ await engine.executeRaw('DELETE FROM sources WHERE id=$1', [sourceId]);
+ } finally {
+ await engine.disconnect();
+ rmSync(fixture, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ const state = () => segmentedPageState(engine, pageId, sourceId);
+ const call = (name: string, params: Record<string, unknown>) => withEnv({ GBRAIN_HOME: join(fixture, 'home') }, async () => {
+ const response = await withVerifiedLocalRegistration(engine, cli, () => dispatchToolCall(engine, name, params, {
+ remote: false, config: { engine: kind }, sourceId, logger: { info() {}, warn() {}, error() {} },
+ }));
+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, unknown>;
+ });
+
+ test('the fixture is a segmented page with NULL body columns and its bytes in segments', async () => {
+ const s = await state();
+ expect(s).toMatchObject({ body_storage: 'segmented', body_generation: 1, compiled_truth: null, timeline: null,
+ body_bytes: Buffer.byteLength(TRUTH) + Buffer.byteLength(TIMELINE) });
+ expect(s.manifest.length).toBe(cutAtLines(TRUTH).length + cutAtLines(TIMELINE).length);
+ });
+
+ test('getPage, readPageSnapshot, readPageSnapshotsBatch and listPages return the page with throwing body fields', async () => {
+ expectUnreachable((await engine.getPage(SLUG, { sourceId }))!);
+ expectUnreachable((await engine.readPageSnapshot(SLUG, { sourceId }))!.page);
+ const batch = await engine.readPageSnapshotsBatch([{ slug: SLUG, sourceId }]);
+ expectUnreachable([...batch.snapshots.values()][0]!.page);
+ const listed = await engine.listPages({ sourceId });
+ expectUnreachable(listed.find(p => p.slug === SLUG)!);
+ const columnsOnly = await engine.listPages({ sourceId, listColumnsOnly: true });
+ expectUnreachable(columnsOnly.find(p => p.slug === SLUG)!);
+ });
+
+ test('size and storage stay readable; an inline page reads exactly as before', async () => {
+ const page = (await engine.getPage(SLUG, { sourceId }))!;
+ expect(page.body_storage).toBe('segmented');
+ expect(pageBodyBytes(page)).toBe(Buffer.byteLength(TRUTH) + Buffer.byteLength(TIMELINE));
+ expect(page.slug).toBe(SLUG);
+ const inline = (await engine.getPage(INLINE, { sourceId }))!;
+ expect(isSegmentedPage(inline)).toBe(false);
+ expect(() => assertInlineBody(inline, 'test')).not.toThrow();
+ expect(JSON.parse(JSON.stringify(inline))).toMatchObject({ compiled_truth: 'Inline body.', timeline: '' });
+ expect({ ...inline }.compiled_truth).toBe('Inline body.');
+ });
+
+ test('get_page body:none answers from body_bytes; a whole-body read refuses with page_body_segmented', async () => {
+ const none = await call('get_page', { slug: SLUG, body: 'none' });
+ expect(none).toMatchObject({ slug: SLUG, body: 'none', body_storage: 'segmented', size: { body_bytes: Buffer.byteLength(TRUTH) + Buffer.byteLength(TIMELINE) } });
+ expect(none).not.toHaveProperty('compiled_truth');
+ expect(await call('get_page', { slug: SLUG, body: 'full' })).toMatchObject({ error: 'page_body_segmented' });
+ const listed = await call('list_pages', { limit: 10 });
+ expect(JSON.stringify(listed)).toContain(SLUG);
+ });
+
+ test('the CHECK refuses an old-shape body write over a segmented row', async () => {
+ const before = await state();
+ await expect(engine.putPage(SLUG, { type: 'note', title: SLUG, compiled_truth: 'replacement', timeline: '', frontmatter: {} }, { sourceId })).rejects.toThrow();
+ await expect(engine.putPage(SLUG, { type: 'note', title: SLUG, compiled_truth: '', timeline: '', frontmatter: {} }, { sourceId })).rejects.toThrow(/segmented/);
+ await expect(engine.refreshPageBody(SLUG, sourceId, 'replacement', '', 'x'.repeat(64))).rejects.toThrow();
+ expect(await state()).toEqual(before);
+ });
+
+ test('mutation probe: every whole-body writer refuses before writing', async () => {
+ const before = await state();
+ const snapshot = (await engine.readPageSnapshot(SLUG, { sourceId }))!;
+ // Rows 15-18: preparers render the page as markdown before writing anything.
+ expectSegmented(() => serializePageToMarkdown(snapshot.page, snapshot.tags));
+ // Row 13: the withdrawal materializer.
+ await expectSegmentedAsync(() => materializePageSnapshot(engine, snapshot));
+ // Row 11: timeline write-through (DB and file).
+ await expectSegmentedAsync(() => writeTimelineEntryThrough(engine, SLUG, sourceId, { date: '2026-10-03', summary: 'probe' }));
+ // Row 19: concept and enrich fence preservation.
+ expectSegmented(() => preserveCanonicalFences(snapshot.page, '# replacement\n'));
+ // Row 12: tag and timeline writes through the persistence coordinator.
+ expect(await call('add_tag', { slug: SLUG, tag: 'probe', request_id: randomUUID() })).toMatchObject({ error: 'page_body_segmented' });
+ expect(await call('add_timeline_entry', { slug: SLUG, date: '2026-10-03', summary: 'probe', request_id: randomUUID() })).toMatchObject({ error: 'page_body_segmented' });
+ expect(await state()).toEqual(before);
+ });
+ });
+}
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 2957a4fab7..e9e3b57a49 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -63,6 +63,7 @@ test/import-inline-chunk-keep.test.ts
test/import-revision-concurrency.test.ts
test/keyword-statement-timeout-knob-6495.test.ts
test/lane-apply-pipelining.test.ts
+test/large-pages/segmented-body-unreachable.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts
test/links-attendance-blocked.test.ts