Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B review fixes: managed sync rename of a segmented page stages once; a streamed page shrunk below the ceiling imports again
garrytan411ebb898df2
diff --git a/docs/architecture/key-files/core-services-2-continued.md b/docs/architecture/key-files/core-services-2-continued.mdindex 655d67e8e0..f27ebadcc7 100644--- a/docs/architecture/key-files/core-services-2-continued.md+++ b/docs/architecture/key-files/core-services-2-continued.md@@ -16,4 +16,4 @@ The page-state concurrency foundation under `src/core/page-state/` and the share- `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).-- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.+- `src/core/page-body/page-shape.ts` — Wave B PR 1 (spec 1.5): segmented page bodies are unreachable as strings. `guardSegmentedBody` (called by `rowToPage` for a row with `body_storage = 'segmented'`, so by every snapshot and `getPage` read) replaces `compiled_truth` / `timeline` with enumerable getters and setters that throw `page_body_segmented`, so property reads, spread, `JSON.stringify`, `structuredClone` and assignment all fail loud instead of seeing an empty body. `isSegmentedPage`, `assertInlineBody(page, site)` (explicit refusal where a writer would otherwise act before a getter fires, e.g. SQL-only writers), `pageBodyBytes(page)` (`body_bytes` for segmented pages) and `pageBodySegmentedError`. `bodyUnread(page)` says a segmented page's body was not read back as strings (over the single-string ceiling, see `materializedPage`); such a body was written by the streamed import, which holds fenced files, so `fenceBody(page)` reads it as empty for the fence merges and `withoutBody(page)` copies the page's other fields for a render whose body comes from the incoming write (a shrunk file rewrites such a page: `test/large-pages/segmented-shrink-below-ceiling.test.ts`). `Page` stays one shape (`body_storage?`, `body_bytes?`); the static half is `scripts/check-page-body-readers.ts` with `scripts/page-body-readers-baseline.tsv` (docs/TESTING.md#page-body-readers). Pinned by `test/large-pages/segmented-body-unreachable.test.ts`.diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 0f9d54ebf3..d33d560e7d 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -39,7 +39,7 @@ src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 basrc/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/embed-stale.ts embedStaleForSource 303 TODO: large-pages A9/T3: per-page spend cap meters each page in embedOneKey (logic in core/page-embedding-budget.ts meterStaleBatch/spendGrant)src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/import-file.ts importFromContent 687 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts)+src/core/import-file.ts importFromContent 690 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts); +3 Wave B review: reuseSegments option (a rename re-preparation reuses the staged segmented body) and the remote fence merge over fenceBodysrc/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut itsrc/core/minions/handlers/subagent.ts makeSubagentHandler 887 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loopsrc/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 817 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loopdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 5be09f679d..b13efe324d 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,7 +17,7 @@ src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail runsrc/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2822 ratchet grown v0.46.26.0 megawave: relational/visibility/usage contract surface (#4352 #4218); grown wave-g (#4524 #4527): orphans-mode contract + removeLink deleted count; wave-k: +4 fail-closed TrajectoryOpts.remote contract doc (#3855), +2 FactListOpts.unconsolidatedOnly (#4070), +14 getAllConfig bulk-read contract (#3980); +1: getBacklinkCounts page-id contract doc (#4380); +9: FactListOpts.grep SQL pre-limit contract (#3851); +13: dream-verdict TTL contract (#4069); +33: softDeletePages batch soft-delete contract (#4587); +8: #4592 scoped getStats/getHealth contract doc; +5 read-time TTL validity contract docs (active vs history read semantics); +12: #4280 findOrphanPages type/quarantined metadata contract; +14: traversePathsDetailed row-cap contract (ship-review); +12: resolveSlugWithAliasDetailed owning-source contract (ship-review) | merged v0.48.1.0: master #4788 + wave traversePathsDetailed/resolveSlugWithAliasDetailed; master: | merged v0.48.1.0 true-up; corrective release: read-policy signatures and Chronicle scope; +7: #4882 listFactsSince entitySlug/sessionId composition doc; #5105: canonical page state shared module and transaction/snapshot delegates; #5105: guarded derived projection preparation and read seals; #5105: resident-stop registration and direct transaction contract; #5105: +1 raw preservation contract for legacy engine migration; merged company ingestion/schema routing changes; safety wave: fact embedding model and text identity contract; +5 write-path wave: findDuplicatePage excludeSlug + id-first ranking contract; +2 fw3 A14: addTag tagSource provenance contract; evidence delivery: getChunkWindows interface member + type import (+3); #5761: +4 markPagesAttendanceBlocked member + countStalePagesForExtraction attendance option; +4 #5888: FactListOpts.fingerprint + FactRow.fact_fingerprint contract (hot-memory duplicate collapse); +1 GBRA-49: LinkReadScope temporal opts on the link read contract; +4 #5984: upsertChunks sealChunkerVersion and createVersion preimage contract docs (round-trip diet); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2683 measured); +10 P7 relationalChainHop member + ChainHopOpts/ChainHopEdge imports (SQL in search/read-enrichment.ts); +14 contributor audit wave P0: listFactsKeyset member (delta facts keyset read contract) + FactRow.created_at_iso; +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); 3 P2 speaker attribution: FactAttribution type + FactRow/NewFact.attributed_to fields + findCandidateDuplicates attributedTo option contract; +4 #5984 lane apply diet: setPageAliases inline option and upsertChunks pageId contract docs; +10 #6278: executeRaw timeoutMs contract (transaction-local statement_timeout for bounded preparation reads); +2 GBRA-69: replaceDerivedLinksBatch member; master v0.60.136.0 merge into #5575 memory trust (both sides kept); +6 GBRA-67: readPageSnapshotsBatch interface member (BrainEngine signatures cannot move); +1 GBRA-75 wave 10: optional findDuplicatePages member (batched findDuplicatePage, contract in engine-sql/pages.ts); +4 FactListOpts/TrajectoryOpts.excludePrivate fact-provenance visibility contract (interface fields cannot move); +18 GBRA-76: TransactionOptions (abort signal) interface and the transaction/transactionDirect signatures (abort logic in postgres-engine/transaction-abort.ts); +2 W14 P3.11 (#4381): LinkBatchInput.resolution_type on top of W13; +1 C2: findCandidateDuplicates arm:'keyword' contract doc (facts.candidate_fusion); re-summed at the master 6ccf30c3e merge (2708 integration + 2707 master - 2707 base); +5 Cat 40 Hard fix wave F2 (#6271): countKeywordPages/searchKeywordPages BrainEngine signatures (SQL in engine-sql/keyword-pages.ts); +6 W15 P1.2 (#6454): countStaleFrontmatterKeyPages/listStaleFrontmatterKeyPages/stripStaleFrontmatterKeys contract (SQL in engine-sql/pages.ts); +2 large pages Wave A sub-a: getChunkPage signature (get_chunks paging; SQL in engine-sql/chunks.ts); +5 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows signatures + type import (SQL in engine-sql/chunks.ts); +2 Cat 40 next wave part 1: non-ranking link types on the relationalFanout/relationalChainHop/getBacklinkCounts/getAdjacencyBoosts contract docs (policy in link-ranking-policy.ts; re-summed at the 0.60.242.0 merge: master 2794 + 2); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2822-src/core/import-file.ts 2056 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056+src/core/import-file.ts 2060 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts); merge v0.60.248.0: Wave B PR 1 and master growth compose at 2056; +4 Wave B review: a rename re-preparation reuses the staged segmented body (reuseSegments option) and the remote fence merge reads an unread body as fence-free (fenceBody in page-body/page-shape.ts)src/core/migrate.ts 602 ratchet schema-migration runner only; migrations live in src/core/schema-migrations/ (W3); +3 #5216: resumable page revision backfill runs after every migration pass while pages.knowledge_revision is nullablesrc/core/operations.ts 240 ratchet peel target: containment sprint C4-C7; grown v0.46.26.0 megawave op wiring; +chat-connectors wiring (master merge); +5 v0.47 gmail-loops: loopsOperations spread + OP_AREAS; #5105: receipt operation registry wiring; shared-skills integration on company-ingestion base; +2 security wave: withOutputRedaction applied at op registration; +1 #5616: pageEditOperations import (spread shares the pages line); +1 Foundations 1 F1b: attributionOperations import (spread shares the admin line); +1 agent operator wave A6: ops/notices.ts import (mute_notice); +2 agent operator closeout A1: registerOpRoutes import + call (routing logic in fix-routing.ts); +2 retrieval feedback: feedbackOperations import and spread (ops/feedback.ts); +1 #6007: pageBatchOperations import (spread shares the pages line); +1 P5: wanted_pages area row; lowered GBRA-75 W11 cold start: OP_AREAS + finalize step moved to operation-load.ts (shared with the CLI per-op loader); +1 C4 pinned questions: questionsOperations import and spread (ops/questions.ts; its areas live in operation-load.ts OP_AREAS)src/core/pglite-engine.ts 3065 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; +22 Wave B lane 1a: segmented page storage delegations (allocateBodyOccurrenceIds..sweepSegments, SQL in engine-sql/page-body.ts) and their importsdiff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsvindex f0ca9ea23f..dabeff968d 100644--- a/scripts/page-body-readers-baseline.tsv+++ b/scripts/page-body-readers-baseline.tsv@@ -318,6 +318,7 @@ src/core/page-body/content-hash-stream.ts ContentHashStream.fromState field NONEsrc/core/page-body/content-hash-stream.ts streamingContentHash field NONE not a stored body: hashes an incoming page streamed region by regionsrc/core/page-body/ingest.ts materializeSegmentedBody field STREAM the segment reader's string form, for single-string write paths; callers materialize only bodies within PAGE_MAX_BYTESsrc/core/page-body/ingest.ts stageBody field NONE not a stored body: the write's region byte streams and the per-region leads it computes+src/core/page-body/page-shape.ts fenceBody field INLINE reads a body that is a string (inline or materialized); an unread segmented body holds no fences and reads as emptysrc/core/page-body/page-shape.ts pageBodyBytes field INLINE inline branch of pageBodyBytes; a segmented page answers body_bytessrc/core/page-body/schema.ts PAGE_GENERATION_BUMP_FN_SQL sql STREAM trigger DDL: compares the body columns of inline rows; segmented rows compare body_generation (lane 1a)src/core/page-body/streamed-import.ts importScanned field LEAD bounded heads of the streamed file's regions for the sanity and type checks; the body itself streams to the segmenter@@ -414,7 +415,7 @@ src/core/persistence/semantic-pages.ts prepareSemanticPageMutation call:serializsrc/core/persistence/semantic-pages.ts prepareSemanticPageMutation field SEGW assertInlineBody after the identity check (tag and timeline writes refuse)src/core/persistence/sync-prepare.ts prepareManagedSyncCode field INLINE code pages are never segmentedsrc/core/persistence/sync-prepare.ts prepareManagedSyncMutation call:serializePageToMarkdown SEGW lane 1d file-src/core/persistence/sync-prepare.ts prepareManagedSyncMutation field SEGW lane 1d file: preserveProtectedTakes; segmented page: getter throws page_body_segmented+src/core/persistence/sync-prepare.ts prepareManagedSyncMutation field SEGW lane 1d file: preserveProtectedTakes over fenceBody (an unread body is fence-free)src/core/persistence/takes-prepare.ts prepare call:serializePageToMarkdown SEGWsrc/core/persistence/writer-guard-schema.ts MANAGED_WRITER_GUARD_FUNCTION_SQL sql STREAM managed-writer guard tuple (lane 1a adds body_generation)src/core/pglite-engine.ts PGLiteEngine.putPage call:putPage SEGW delegation to engine-sql putPagediff --git a/src/core/fence-repair/import-step.ts b/src/core/fence-repair/import-step.tsindex 55ac0761e8..0b63d17f97 100644--- a/src/core/fence-repair/import-step.ts+++ b/src/core/fence-repair/import-step.ts@@ -16,6 +16,7 @@ import { parseTakesFence } from '../takes-fence.ts';import { screenFenceCtx, type ContentRefusal, type FenceScreen, type ImportScreenResult } from '../import-screen.ts';import type { ParsedMarkdown, ParseOpts } from '../markdown.ts';import { VERSION } from '../../version.ts';+import { fenceBody } from '../page-body/page-shape.ts';import { fencesNormalizeEnabled } from './config.ts';import { fenceRefusal, scanCanonicalFences, targetFenceRefusal } from './refusal.ts';import { effectiveVisibility } from '../search/private-visibility.ts';@@ -86,7 +87,7 @@ export async function applyImportFences(input: Omit<Parameters<typeof resolveImpscreen: ImportScreenResult; parsed: { compiled_truth: string; timeline: string; type: ParsedMarkdown['type']; frontmatter: ParsedMarkdown['frontmatter'] };existing: { id: number; compiled_truth: string; timeline?: string | null; deleted_at?: Date | null } | null;}): Promise<{ refused?: { slug: string; status: 'error'; chunks: 0; error: string; refusal: ContentRefusal; skip_reason: 'invalid_fence' }; fields: { fences_normalized?: FenceFix[]; fence_issues?: FenceIssueWire[] } }> {- const existing = input.existing && input.existing.deleted_at == null ? { id: input.existing.id, compiled_truth: input.existing.compiled_truth, timeline: input.existing.timeline ?? '' } : null;+ const existing = input.existing && input.existing.deleted_at == null ? { id: input.existing.id, ...fenceBody(input.existing) } : null;const fences = await resolveImportFences({ ...input, screen: (input.screen as { fences?: FenceScreen }).fences, existing });if (fences.refusal) return { refused: { slug: input.slug, status: 'error', chunks: 0, error: fences.refusal.message, refusal: fences.refusal, skip_reason: 'invalid_fence' }, fields: {} };if (fences.page) ({ compiled_truth: input.parsed.compiled_truth, timeline: input.parsed.timeline } = fences.page);diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex db1befdb8f..6fee57cbba 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -56,8 +56,9 @@ import { warnOncePerProcess, validateSlug, contentHash, contentHashLegacy, ATOMSimport { decorateEmbeddingDimError } from './embedding-dim-check.ts';import { resolveImportContextualMode } from './import-contextual-mode.ts';import { runGuardrails } from './guardrails.ts';+import { fenceBody } from './page-body/page-shape.ts';import { abortSegmentedStaging, bodyStorageOf, demoteSegmentedPage, materializedPage, materializedSnapshot, sealSegmentedPage, stageSegmentedImport,- stringWriteStorage } from './persistence/segmented-apply.ts';+ stringWriteStorage, type SegmentedImport } from './persistence/segmented-apply.ts';import type { SegmentedStagingOwner } from './page-body/ingest.ts';import type { PageBodyPolicy } from './page-body/limits.ts';import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';@@ -302,6 +303,8 @@ export async function importFromContent(ingested_via?: string | null;/** Wave B: who stages a segmented body (the journaled request's principal); unset: the local maintenance principal, kind `import`. */segmentedOwner?: SegmentedStagingOwner;+ /** Wave B: a segmented body an earlier preparation of this write staged (`PreparedContentImport.segmented`), reused when its inputs are unchanged. */+ reuseSegments?: SegmentedImport;/** Untrusted caller (remote MCP put_page: `ctx.remote !== false`); drives the remote fence merge and hidden rows. */remote?: boolean;/**@@ -446,8 +449,9 @@ export async function importFromContent(const fences = await applyImportFences({ engine, sourceId: sourceId ?? 'default', slug, mode: opts.fences ?? 'lenient', screened: opts.fenceScreen, screen, parsed, activePack: opts.activePack, remote: opts.remote === true, existing });if (fences.refused) return fences.refused;if (opts.remote === true && existing) {- parsed.compiled_truth = mergeHiddenFactRowsIntoBody(slug, parsed.compiled_truth, existing.compiled_truth);- parsed.timeline = mergeHiddenFactRowsIntoBody(slug, parsed.timeline, existing.timeline);+ const stored = fenceBody(existing);+ parsed.compiled_truth = mergeHiddenFactRowsIntoBody(slug, parsed.compiled_truth, stored.compiled_truth);+ parsed.timeline = mergeHiddenFactRowsIntoBody(slug, parsed.timeline, stored.timeline);}const { assertPreparedFactWithdrawals, preserveWithdrawnFenceRows } = await import('./facts/withdrawal.ts');parsed.compiled_truth = await preserveWithdrawnFenceRows(engine, sourceId ?? 'default', parsed.compiled_truth, slug);@@ -630,7 +634,7 @@ export async function importFromContent(const { mode: effectiveCRMode, corpusGeneration } = await resolveImportContextualMode(engine, sourceId ?? 'default', parsed.frontmatter, opts.prepare !== undefined);// Wave B: a body staged as segments publishes with the generation flip instead of putPage and the chunk replacement.const segmented = storage.policy && storage.storage === 'segmented' ? await stageSegmentedImport(engine, { slug, sourceId: sourceId ?? 'default', existing,- page: parsedPage, policy: storage.policy, owner: opts.segmentedOwner, baseRevision: (existing as { knowledge_revision?: string } | null)?.knowledge_revision ?? null,+ page: parsedPage, policy: storage.policy, owner: opts.segmentedOwner, reuse: opts.reuseSegments, baseRevision: (existing as { knowledge_revision?: string } | null)?.knowledge_revision ?? null,chunking: { quarantined: pageQuarantined, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' : 'none' } }) : null;// A13: an edit re-embeds only chunks whose embedding input changed. A stored@@ -873,7 +877,7 @@ export async function importFromContent(noop: false, contentHash: hash, result: { slug, status: 'imported', chunks: segmented ? segmented.prepared.rows.chunks : chunks.length, parsedPage,...(pageQuarantined ? { quarantined: true } : {}), ...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}), ...(disposition.gate ? { gate: disposition.gate } : {}), ...fences.fields },validate: tx => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),- apply: applyPrepared, ...(segmented ? { afterCommit: segmented.afterCommit } : {}),+ apply: applyPrepared, ...(segmented ? { afterCommit: segmented.afterCommit, segmented } : {}),});await maintenanceTransaction(engine, applyPrepared, writeTrustOfGate(opts.writeGate)).catch(async (err: unknown) => {await abortSegmentedStaging(engine, segmented?.prepared);diff --git a/src/core/page-body/page-shape.ts b/src/core/page-body/page-shape.tsindex dbf7710299..1ee79132ca 100644--- a/src/core/page-body/page-shape.ts+++ b/src/core/page-body/page-shape.ts@@ -29,6 +29,28 @@ export function isSegmentedPage(page: BodyShape): boolean {return page.body_storage === 'segmented';}+/**+ * True when the page's body fields are still the throwing getters: a segmented+ * page that was not read back as strings (`materializedPage` leaves a body over+ * the single-string ceiling unread). Such a body was written by the streamed+ * import, which holds files with facts or takes fences.+ */+export function bodyUnread(page: object): boolean {+ return Object.getOwnPropertyDescriptor(page, 'compiled_truth')?.get !== undefined;+}++/** The page's fields without its body, for a copy whose body comes from elsewhere (a page with an unread body cannot be spread). */+export function withoutBody<T extends object>(page: T): Omit<T, SegmentedBodyField> {+ const copy: Record<string, unknown> = {};+ for (const key of Object.keys(page)) if (key !== 'compiled_truth' && key !== 'timeline' && key !== 'content') copy[key] = (page as Record<string, unknown>)[key];+ return copy as Omit<T, SegmentedBodyField>;+}++/** The stored body a fence merge reads: an unread body holds no facts or takes fences, so it reads as empty. */+export function fenceBody(page: { compiled_truth: string; timeline?: string | null }): { compiled_truth: string; timeline: string } {+ return bodyUnread(page) ? { compiled_truth: '', timeline: '' } : { compiled_truth: page.compiled_truth, timeline: page.timeline ?? '' };+}+/** The refusal every whole-body path gives a segmented page; `site` names the path in the message. */export function pageBodySegmentedError(page: { slug?: string; source_id?: string }, site: string) {const slug = page.slug ?? '<unknown>';diff --git a/src/core/page-state/import-guard.ts b/src/core/page-state/import-guard.tsindex 586f77e242..ee6d671dd4 100644--- a/src/core/page-state/import-guard.ts+++ b/src/core/page-state/import-guard.ts@@ -4,6 +4,7 @@ import type { ParsedPage } from '../import-file.ts';import { opError } from '../ops/contract.ts';import { readFix } from '../ops/op-fix.ts';import { stableJson } from '../persistence/digest.ts';+import { bodyUnread } from '../page-body/page-shape.ts';import { assertPageRevision, type PageSnapshot } from './types.ts';/** Imported bytes are prepared outside transactions; publication still needs CAS. */@@ -36,11 +37,12 @@ export function sameCanonicalImport(existing: PageSnapshot | null, parsed: Parse* #5158: the stored content_hash digests frontmatter in insertion order, so a* file whose keys were only reordered hashes differently. This key-sorted* comparison of every canonical field and the exact tag set recognizes it as- * unchanged without touching the stored hash formula.+ * unchanged without touching the stored hash formula. A stored body left unread+ * (over the single-string ceiling) differs from any parsed body, which is within it.*/export async function sameContentAnyKeyOrder(engine: Pick<BrainEngine, 'getTags'>, existing: Page, existingTags: string[] | null,parsed: ParsedPage, sourceId: string): Promise<boolean> {- if (existing.deleted_at || existing.type !== parsed.type || existing.title !== parsed.title+ if (existing.deleted_at || bodyUnread(existing) || existing.type !== parsed.type || existing.title !== parsed.title|| existing.compiled_truth !== parsed.compiled_truth || (existing.timeline ?? '') !== (parsed.timeline ?? '')) return false;if (stableJson(canonicalFields(existing)) !== stableJson(canonicalFields(parsed))) return false;const tags = existingTags ?? await engine.getTags(existing.slug, { sourceId });diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 94b4a597c9..287e2a034a 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -11,6 +11,7 @@ import { parseTimelineEntries } from '../link-extraction.ts';import { extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, type ExtractedTimelineEntry } from '../timeline-extract.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { sanitizeForJsonb } from '../batch-rows.ts';+import { bodyUnread } from '../page-body/page-shape.ts';import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';import type { OperationError } from '../ops/contract.ts';import { protectedRegions } from '../fence-scan.ts';@@ -364,7 +365,9 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug* Prepare provider-free projections outside publication. `prior` is the* caller's snapshot at its observed revision; stored timeline rows and take* row numbers are pinned here so the publication transaction only removes- * what this writer actually edited.+ * what this writer actually edited. A prior body left unread (a segmented page+ * over the single-string ceiling, which holds no fences) contributes no rows of+ * its own: stored timeline rows and takes stay unless the new body changes them.*/export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {@@ -372,18 +375,19 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.const projectFences = !isQuarantined(page.frontmatter);+ const priorBody = prior && !bodyUnread(prior.page) ? prior.page : null;const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],- page, prior?.page ?? null, slug, writer, policy);+ page, priorBody, slug, writer, policy);const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete').map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' })));const refreshes = JSON.stringify(pinned.filter(row => row.action === 'refresh_detail').map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) })).filter(row => row.next !== row.detail));- const priorTakes = prior ? canonicalTakeRows(prior.page) : new Set<number>();+ const priorTakes = priorBody ? canonicalTakeRows(priorBody) : new Set<number>();// TE1 (#6188): when the prior takes fence does not parse, its stored rows count as prior canonical rows, so a// row Tier 1 normalized (same number, holder `system` -> `brain`) updates its stored take instead of colliding.- const priorCanonical = prior && [prior.page.compiled_truth, prior.page.timeline ?? ''].some(field => parseTakesFence(field).warnings.length)- ? new Set([...priorTakes, ...(await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM takes WHERE page_id=$1', [prior.page.id])).map(r => Number(r.row_num))])+ const priorCanonical = priorBody && [priorBody.compiled_truth, priorBody.timeline ?? ''].some(field => parseTakesFence(field).warnings.length)+ ? new Set([...priorTakes, ...(await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM takes WHERE page_id=$1', [priorBody.id])).map(r => Number(r.row_num))]): priorTakes;const newTakes = JSON.stringify(takes.filter(t => !priorCanonical.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));const takeRowsGone = [...priorTakes].filter(n => !takes.some(t => t.rowNum === n));diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 95af40691b..0917faddc4 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -19,6 +19,7 @@ import { isWriteTargetContained } from '../path-confine.ts';import { assertPageRevision } from '../page-state/types.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';+import { withoutBody } from '../page-body/page-shape.ts';import { importStreamedMarkdownFile, type StreamedPreparedImport } from '../page-body/streamed-import.ts';import { FRONTMATTER_HEAD_MAX_BYTES, readPageBodyPolicy, type PageBodyPolicy } from '../page-body/limits.ts';import { PAGE_MAX_BYTES } from '../page-size-policy.ts';@@ -254,7 +255,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri{ fix: receiptFix(row) });const tags = [...new Set([...(snapshot?.tags ?? []), ...(ready.parsedPage?.tags ?? [])])].sort();const rendered = imageBytes ?? (code ? content : serializePageToMarkdown({- ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,+ ...(snapshot ? withoutBody(snapshot.page) : { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,} as Page, tags));const project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');const mutation: PreparedMutation = { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.tsindex cd08c6d385..eeb825e1cb 100644--- a/src/core/persistence/prepared-import.ts+++ b/src/core/persistence/prepared-import.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { PageSnapshot } from '../page-state/types.ts';import type { ImportResult, ParsedPage } from '../import-file.ts';+import type { SegmentedImport } from './segmented-apply.ts';/*** #6007: what an apply reports to its caller. `pageId` is the page it@@ -27,4 +28,6 @@ export interface PreparedContentImport {apply(tx: BrainEngine, preimage?: PageSnapshot | null): Promise<PreparedImportApplied | void>;/** Wave B: runs after the publication committed (a segmented page left unsealed is chunked and sealed). */afterCommit?(engine: BrainEngine): Promise<void>;+ /** Wave B: the segmented body this preparation staged, for a later preparation of the same write to reuse (`importFromContent`'s `reuseSegments`). */+ segmented?: SegmentedImport;}diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsindex a6068fdbfd..3acbed0b8c 100644--- a/src/core/persistence/segmented-apply.ts+++ b/src/core/persistence/segmented-apply.ts@@ -31,6 +31,7 @@ import { PAGE_MAX_BYTES } from '../page-size-policy.ts';import { pageSearchVectorSql } from '../fts-language.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { faultPoint } from './fault-points.ts';+import { stableJson } from './digest.ts';const BODY_KEYS = new Set(['compiled_truth', 'timeline', 'content']);@@ -161,6 +162,8 @@ export async function abortSegmentedStaging(engine: BrainEngine, prepared: Prepa/** A string write staged as a segmented body: its apply runs in the write's transaction, its projection after commit. */export interface SegmentedImport {prepared: PreparedSegmentedBody;+ /** What the staging was prepared from; a later preparation of the same write with equal inputs reuses it (`stageSegmentedImport`'s `reuse`). */+ stagedFrom: { title: string; type: string; compiled_truth: string; timeline: string; key: string };/** Set by apply. */applied: SegmentedApplied | null;apply(tx: BrainEngine, meta: SegmentedPageMeta, contextual: { mode: string; corpusGeneration: string | null }): Promise<SegmentedApplied>;@@ -171,22 +174,31 @@ export interface SegmentedImport {/*** Stage a parsed page (the string write paths, bodies within the* single-string ceiling) as a segmented body: the in-memory regions are the- * seekable source, the existing page row (if any) is the diff base.+ * seekable source, the existing page row (if any) is the diff base. `reuse`+ * is an earlier, unpublished staging of the same write (a managed rename+ * prepares where the page stands, then again at its new slug inside the+ * publication): when it was prepared from equal inputs against the same live+ * generation, its staged rows publish under this slug and nothing is staged again.*/export async function stageSegmentedImport(engine: BrainEngine, input: { slug: string; sourceId: string; existing: Page | null;page: { title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown>; tags: readonly string[] };- policy: PageBodyPolicy; owner?: SegmentedStagingOwner; chunking: SegmentChunkingContext; baseRevision: string | null }): Promise<SegmentedImport> {+ policy: PageBodyPolicy; owner?: SegmentedStagingOwner; chunking: SegmentChunkingContext; baseRevision: string | null; reuse?: SegmentedImport }): Promise<SegmentedImport> {const live = input.existing ? await segmentedLivePage(engine, Number(input.existing.id)) : null;+ const { title, type, compiled_truth, timeline } = input.page;+ const stagedFrom = { title, type, compiled_truth, timeline, key: stableJson({ sourceId: input.sourceId, page: live && { id: live.id, generation: live.generation,+ storage: live.storage, flags: live.flags }, frontmatter: input.page.frontmatter, tags: input.page.tags, chunking: input.chunking }) };+ const prior = input.reuse?.stagedFrom;+ const reused = !!prior && prior.key === stagedFrom.key && prior.title === title && prior.type === type && prior.compiled_truth === compiled_truth && prior.timeline === timeline;let owner = input.owner;if (!owner) {const { principal } = await maintenanceAttribution(engine);owner = { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: input.baseRevision };}- const prepared = await prepareSegmentedBody(engine, { sourceId: input.sourceId, slug: input.slug, live, title: input.page.title, type: input.page.type,- frontmatter: input.page.frontmatter, tags: input.page.tags, truth: stringRegion(input.page.compiled_truth), timeline: stringRegion(input.page.timeline),- hasTimeline: input.page.timeline.length > 0, flags: stringBodyFlags(input.page.compiled_truth, input.page.timeline),- declaredBytes: Buffer.byteLength(input.page.compiled_truth, 'utf-8') + Buffer.byteLength(input.page.timeline, 'utf-8'), owner, chunking: input.chunking });- const staged: SegmentedImport = { prepared, applied: null,+ const prepared = reused ? input.reuse!.prepared : await prepareSegmentedBody(engine, { sourceId: input.sourceId, slug: input.slug, live, title, type,+ frontmatter: input.page.frontmatter, tags: input.page.tags, truth: stringRegion(compiled_truth), timeline: stringRegion(timeline),+ hasTimeline: timeline.length > 0, flags: stringBodyFlags(compiled_truth, timeline),+ declaredBytes: Buffer.byteLength(compiled_truth, 'utf-8') + Buffer.byteLength(timeline, 'utf-8'), owner, chunking: input.chunking });+ const staged: SegmentedImport = { prepared, stagedFrom, applied: null,apply: async (tx, meta, contextual) => {staged.applied = await applySegmentedBody(tx, { slug: input.slug, sourceId: input.sourceId, pageId: live?.id ?? null, prepared, meta,promotion: live?.storage === 'inline', retireMaxRows: input.policy.flipRetireMaxRows });diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex d51db5e8d6..07953c1e06 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -21,7 +21,8 @@ import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { sameCanonicalImport } from '../page-state/import-guard.ts';import { assertPageRevision } from '../page-state/types.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';-import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';+import { abortSegmentedStaging, materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';+import { fenceBody, withoutBody } from '../page-body/page-shape.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';import { prepareCanonicalProjections } from './canonical-projections.ts';import { digest, sha256 } from './digest.ts';@@ -602,7 +603,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WrenterClaimStep(clock, 'schema_pack', undefined, 'db');const pack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },{ remote: false, sourceId: row.source_id })).pack : await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null), activePack = pack?.manifest;- // A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug.+ // A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug (reusing an unchanged segmented staging).const renamed = moved && moved.slug !== row.slug ? moved : undefined;if (renamed) enterClaimStep(clock, 'rename_source', undefined, 'db');const base = renamed ? await materializedSnapshot(engine, await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true })) : snapshot;@@ -626,10 +627,11 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr}let importContent = p.content;if (row.authority.remote) {- const compiled_truth = preserveProtectedTakes(parsedInput.compiled_truth, base?.page.compiled_truth ?? '');- const timeline = preserveProtectedTakes(parsedInput.timeline ?? '', base?.page.timeline ?? '');+ const stored = base ? fenceBody(base.page) : null;+ const compiled_truth = preserveProtectedTakes(parsedInput.compiled_truth, stored?.compiled_truth ?? '');+ const timeline = preserveProtectedTakes(parsedInput.timeline ?? '', stored?.timeline ?? '');if (compiled_truth !== parsedInput.compiled_truth || timeline !== (parsedInput.timeline ?? '')) {- importContent = serializePageToMarkdown({ ...(base?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }),+ importContent = serializePageToMarkdown({ ...(base ? withoutBody(base.page) : { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }),...parsedInput, compiled_truth, timeline } as Page, parsedInput.tags);}}@@ -639,7 +641,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst importOptions = { ...source, noEmbed: true, remote: row.authority.remote, preserveGateMarkers: true, activePack, coordinated: true, fences: 'coordinated' as const, writeGate: await ownerGateInput(engine, row, parsedInput.frontmatter, p.sourcePath),...(importContent === p.content && screen.status === 'importable' ? { fenceScreen: screen.fences ?? null } : {}),filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true,- segmentedOwner: { kind: 'sync' as const, principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } };+ segmentedOwner: { kind: 'sync' as const, principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: base?.revision ?? null } };const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,prepare: async value => { prepared = value; return value.result; } }).catch(error => {if (!(error instanceof ContentSanityBlockError)) throw error;@@ -659,7 +661,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst parsed = parseMarkdown(p.content, `${row.slug}.md`, { activePack });resolveParsedSubtype(parsed, base?.page);const tags = [...new Set([...(base?.tags ?? []), ...ready.parsedPage.tags])].sort();- const renderedPage = { ...(base?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;+ const renderedPage = { ...(base ? withoutBody(base.page) : { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage } as Page;if (renamed && parsedInput.typeExplicit !== true) renderedPage.type = parsedInput.type;const canonical = (page: Pick<typeof parsed, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) => ({ type: page.type, title: page.title, body: page.compiled_truth,timeline: page.timeline ?? '', frontmatter: page.frontmatter, tags: [...new Set(tags)].sort() });@@ -678,12 +680,15 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');const importProvenance: SyncImportProvenanceBase = { source_id: row.source_id, incarnation: row.source_incarnation, origin: p.sourcePath!, raw_sha256: sha256(p.content!),...(p.blobOid ? { blob_oid: p.blobOid } : {}), working: p.working === true, gbrain_version: VERSION, ...(recovery?.length ? { recovery } : {}), parser: syncImportParser(pack?.identity ?? null) };+ // afterCommit follows the import that published: a rename publishes its re-preparation at the new slug.+ let published = ready;const preparedImport: SyncPreparedMutation = { observedRevision: snapshot?.revision ?? null, trust: await ownerImportTrust(engine, row, ready.parsedPage.frontmatter, p.sourcePath), importProvenance,// Tells the #5470 screen the content is unchanged; publication still queues its effects.contentUnchanged: ready.noop && !moved && !writeback,...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),validate: async tx => { await validate(tx); await ready.validate(tx); },- deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true, ...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),+ deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true,+ ...(ready.afterCommit || renamed ? { afterCommit: async (target: BrainEngine) => { await published.afterCommit?.(target); } } : {}),...(writeback ? { file: { root, path: join(root, p.path), content: canonicalFile, expectedBeforeHash: p.rawHash } } : {}),...(mirrorReadOnly ? { databaseOnlyReason: 'mirror_read_only' as const } : {}),apply: async (tx, preimage) => {@@ -695,12 +700,15 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr`Page ${renamed.slug} could not move to ${row.slug}.`);if (renamedType) await tx.executeRaw('UPDATE pages SET type=$3 WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug, renamedType]);let movedImport: PreparedContentImport | undefined;- await importFromContent(tx, row.slug, importContent, { ...importOptions, prepare: async value => { movedImport = value; return value.result; } });+ await importFromContent(tx, row.slug, importContent, { ...importOptions, reuseSegments: ready.segmented,+ prepare: async value => { movedImport = value; return value.result; } });if (!movedImport || movedImport.slug !== row.slug) throw syncPublicationRefusal('page_identity_changed', 'The renamed page could not be prepared at its new slug.', row, p,`Page ${renamed.slug} could not be prepared at ${row.slug}.`);+ if (movedImport.segmented?.prepared !== ready.segmented?.prepared) await abortSegmentedStaging(tx, ready.segmented?.prepared);await movedImport.validate(tx);applied = movedImport;}+ published = applied;// A moved page is versioned from its own (rename source) read.const installed = await applied.apply(tx, renamed ? undefined : preimage);// Hash no-ops still repair a missing physical origin under the same guard (a page write records it itself).diff --git a/test/large-pages/managed-sync-segmented-rename.test.ts b/test/large-pages/managed-sync-segmented-rename.test.tsnew file mode 100644index 0000000000..2759235b7f--- /dev/null+++ b/test/large-pages/managed-sync-segmented-rename.test.ts@@ -0,0 +1,122 @@+/**+ * Managed sync rename of a segmented page (Wave B).+ *+ * 1. Protects: a rename prepares the file where the page stands and, inside+ * the publication, again at its new slug. With unchanged inputs the second+ * preparation publishes the first one's staging (one staging per rename,+ * nothing staged inside the publication); when the move changes them (here+ * a title humanized from the slug), the first staging is aborted and the applied preparation's+ * afterCommit sweeps its rows. Either way the rename leaves no live staging+ * and no staged manifest rows behind, and the page is sealed and+ * round-trips byte-identical at its new slug.+ * 2. Fails when: the publication restages an unchanged body, the prepare-time+ * staging stays open or prepared after the rename publishes, or afterCommit+ * runs the import that did not publish.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationPage } from '../helpers/conversation-page.ts';+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-rename-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const original = conversationPage(1536 * 1024, { seed: 61 });+/** Every fourth body line edited: git still pairs the files as a rename, and most segments change. */+const edited = (text: string) => text.split('\n').map((line, i) => i > 6 && i % 4 === 0 && line ? `${line} edited` : line).join('\n');++function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string): void { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'test content'); }++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++async function syncedFixture(engine: BrainEngine) {+ const sourceId = `rename-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ writeFileSync(join(root, 'notes/big.md'), original);+ commit(root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ expect(await performManagedSync(engine, { sourceId, noPull: true })).toMatchObject({ status: 'first_sync', filesImported: 1 });+ return { sourceId, root };+}++async function stagings(engine: BrainEngine, sourceId: string) {+ return engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE source_id=$1', [sourceId]);+}++async function expectRenamed(engine: BrainEngine, sourceId: string, content: string) {+ const { page, body, hash } = await reconstructedPage(engine, 'notes/moved', sourceId);+ const parsed = parseMarkdown(content, 'notes/moved.md');+ expect(page.body_storage).toBe('segmented');+ expect(page.title).toBe(parsed.title);+ expect(body.compiled_truth).toBe(parsed.compiled_truth);+ expect(page.content_hash).toBe(hash);+ expect(page.text_projection_revision).toBe(page.knowledge_revision);+ expect(await engine.getPage('notes/big', { sourceId })).toBeNull();+ expect((await stagings(engine, sourceId)).filter(row => row.state === 'open' || row.state === 'prepared')).toEqual([]);+ expect(await engine.executeRaw('SELECT occurrence_id FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NOT NULL', [page.id])).toEqual([]);+}++test('an edited rename with unchanged identity publishes its prepare-time staging and stages once', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('pages.flip_retire_max_rows', '1');+ const f = await syncedFixture(engine);+ const before = (await stagings(engine, f.sourceId)).length;+ git(f.root, 'mv', 'notes/big.md', 'notes/moved.md');+ const content = edited(original);+ writeFileSync(join(f.root, 'notes/moved.md'), content);+ commit(f.root);+ expect(await performManagedSync(engine, { sourceId: f.sourceId, noPull: true })).toMatchObject({ status: 'synced', renamed: 1 });+ expect((await stagings(engine, f.sourceId)).length).toBe(before + 1);+ await expectRenamed(engine, f.sourceId, content);+ await disposePersistenceConsumer(engine);+ }+}), 300_000);++test('a rename whose title follows the slug aborts the prepare-time staging and sweeps its rows after commit', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('pages.flip_retire_max_rows', '1');+ const f = await syncedFixture(engine);+ git(f.root, 'mv', 'notes/big.md', 'notes/moved.md');+ const content = edited(original).replace('title: Conversation log\n', '');+ writeFileSync(join(f.root, 'notes/moved.md'), content);+ commit(f.root);+ expect(await performManagedSync(engine, { sourceId: f.sourceId, noPull: true })).toMatchObject({ status: 'synced', renamed: 1 });+ expect((await stagings(engine, f.sourceId)).map(row => row.state)).toContain('aborted');+ await expectRenamed(engine, f.sourceId, content);+ await disposePersistenceConsumer(engine);+ }+}), 300_000);diff --git a/test/large-pages/segmented-shrink-below-ceiling.test.ts b/test/large-pages/segmented-shrink-below-ceiling.test.tsnew file mode 100644index 0000000000..e37786b6fa--- /dev/null+++ b/test/large-pages/segmented-shrink-below-ceiling.test.ts@@ -0,0 +1,137 @@+/**+ * A segmented page over the single-string ceiling edited down to within it (Wave B).+ *+ * 1. Protects: a page imported streamed (body over PAGE_MAX_BYTES, its body+ * never read back as one string) is rewritten by the string paths once its+ * file shrinks: an unmanaged importFromContent (here demoting it inline),+ * a managed file import and a managed sync each publish the smaller body,+ * which round-trips byte-identical. The unread stored body compares unequal+ * to the new one and contributes no fence or timeline rows of its own.+ * 2. Fails when: a comparison, fence merge, page spread or canonical+ * projection reads the unread body and refuses with page_body_segmented.+ */+import { afterAll, beforeAll, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent, importFromFile } from '../../src/core/import-file.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { claimWorktree } from '../../src/core/persistence/ownership.ts';+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';+import { performManagedSync } from '../../src/core/persistence/sync-run.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { conversationPage } from '../helpers/conversation-page.ts';+import { reconstructedPage, segmentedPageRow } from '../helpers/segmented-page-checks.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-shrink-'));+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };+const huge = conversationPage(PAGE_MAX_BYTES + 1024 * 1024, { seed: 71 });+const shrunk = conversationPage(2 * 1024 * 1024, { seed: 71 });++function git(root: string, ...args: string[]): string { return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }+function commit(root: string): void { git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'test content'); }++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ await withEnv(env, async () => {+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }+ await closePostgres?.();+ });+ rmSync(home, { recursive: true, force: true });+});++async function managedSource(engine: BrainEngine, root: string) {+ const sourceId = `shrink-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,'{}')", [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ return sourceId;+}++async function expectStreamed(engine: BrainEngine, slug: string, sourceId: string) {+ const row = (await engine.executeRaw<{ body_bytes: string }>('SELECT body_bytes::text AS body_bytes FROM pages WHERE source_id=$1 AND slug=$2', [sourceId, slug]))[0];+ expect(Number(row?.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);+}++async function expectBody(engine: BrainEngine, slug: string, sourceId: string, content: string) {+ const { page, body, hash } = await reconstructedPage(engine, slug, sourceId);+ expect(page.body_storage).toBe('segmented');+ expect(body.compiled_truth).toBe(parseMarkdown(content, `${slug}.md`).compiled_truth);+ expect(page.content_hash).toBe(hash);+}++test('unmanaged: importFromContent rewrites a streamed page with a body within the ceiling', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ const dir = join(home, `unmanaged-${randomUUID().slice(0, 8)}`);+ mkdirSync(dir, { recursive: true });+ const file = join(dir, 'huge.md');+ writeFileSync(file, huge);+ const slug = `notes/shrink-${randomUUID().slice(0, 8)}`;+ expect(await importFromFile(engine, file, `${slug}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });+ await expectStreamed(engine, slug, 'default');+ const small = '---\ntitle: Conversation log\ntype: note\n---\n\nA short summary of the conversation.\n';+ expect(await importFromContent(engine, slug, small, { noEmbed: true })).toMatchObject({ slug, status: 'imported' });+ const page = await segmentedPageRow(engine, slug);+ expect(page.body_storage).toBe('inline');+ expect((await engine.getPage(slug))?.compiled_truth).toBe(parseMarkdown(small, `${slug}.md`).compiled_truth);+ }+}), 600_000);++test('managed import: a shrunk file publishes over a streamed page', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ const root = join(home, `import-${randomUUID().slice(0, 8)}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ const sourceId = await managedSource(engine, root);+ const file = join(root, 'notes/huge.md');+ writeFileSync(file, huge);+ expect(await importManagedFile(engine, file, 'notes/huge.md', { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ await expectStreamed(engine, 'notes/huge', sourceId);+ writeFileSync(file, shrunk);+ expect(await importManagedFile(engine, file, 'notes/huge.md', { sourceId, noEmbed: true })).toMatchObject({ slug: 'notes/huge', status: 'imported' });+ await expectBody(engine, 'notes/huge', sourceId, shrunk);+ await disposePersistenceConsumer(engine);+ }+}), 600_000);++test('managed sync: a shrunk file syncs over a streamed page', async () => withEnv(env, async () => {+ for (const engine of engines) {+ await disposePersistenceConsumer(engine);+ await engine.setConfig('pages.segmented_storage', 'on');+ const root = join(home, `sync-${randomUUID().slice(0, 8)}`);+ mkdirSync(join(root, 'notes'), { recursive: true });+ git(root, 'init', '-q');+ const file = join(root, 'notes/huge.md');+ writeFileSync(file, huge);+ commit(root);+ const sourceId = await managedSource(engine, root);+ expect(await importManagedFile(engine, file, 'notes/huge.md', { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ await disposePersistenceConsumer(engine);+ await performManagedSync(engine, { sourceId, noPull: true });+ await expectStreamed(engine, 'notes/huge', sourceId);+ writeFileSync(file, shrunk);+ commit(root);+ expect(await performManagedSync(engine, { sourceId, noPull: true })).toMatchObject({ status: 'synced', modified: 1 });+ await expectBody(engine, 'notes/huge', sourceId, shrunk);+ await disposePersistenceConsumer(engine);+ }+}), 600_000);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 803b52b54d..022d476660 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -65,9 +65,11 @@ test/keyword-statement-timeout-knob-6495.test.tstest/lane-apply-pipelining.test.tstest/large-pages/chunk-visibility.test.tstest/large-pages/managed-streamed-import.test.ts+test/large-pages/managed-sync-segmented-rename.test.tstest/large-pages/segment-vector-reuse.test.tstest/large-pages/segmented-body-unreachable.test.tstest/large-pages/segmented-embedding.test.ts+test/large-pages/segmented-shrink-below-ceiling.test.tstest/large-pages/segmented-versions.test.tstest/link-cross-source.test.tstest/link-preparation-shared-index.test.ts