Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(#7172): plan a deferred replacement once, claim it while continuing, run group members' post-commit work, opt in the direct page writes
garrytan1bedf3e08bdc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80163e0254..0c6dbafabe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,7 +19,7 @@ identifiers and attribution are available in the pre-removal Git revision| Situation | Before | Now ||---|---|---|| An entry shifts unchanged passages to new indexes | each moved passage deleted and re-inserted (vector copied) | the row keeps its id and vector and changes index in place |-| A write whose passages need more than 5 inserted or renumbered rows | all of them in one statement inside the publication; on a slow index, 57014 on every attempt, then `write_interrupted` | the page commits first; its passages finish in post-commit transactions of at most 5 row writes each, then the projection is sealed |+| A managed put_page, edit_page, add_timeline_entry, tag write, import or sync whose passages need more than 5 inserted or renumbered rows | all of them in one statement inside the publication; on a slow index, 57014 on every attempt, then `write_interrupted` | the page commits first; its passages finish in post-commit transactions of at most 5 row writes each, then the projection is sealed || Search during those steps | n/a | the page's passages are hidden until the seal (as for any pending projection); the receipt says `searchable: "pending"` and turns `true` when sealed || The embedding step after a write, page signature missing or older format | every passage re-embedded (paid) | passages whose recorded embedding input is current keep their vectors; the page signature is restamped |@@ -35,7 +35,8 @@ The 5-row bound is derived in `src/core/page-state/chunk-moves.ts` (`CHUNK_ROW_W- `reuseStoredChunkVectors` matches a stored row by source and text at any index (its own index first), so a kept row can move.- New `src/core/page-state/chunk-moves.ts`: the row-write bound and the move planner (one UPDATE per wave; a cycle parks one row at a negative index).-- `continueDeferredProjection` runs the bounded steps after commit; the projection drain resumes a page whose steps were interrupted (queue reason `chunk_replacement_deferred`).+- `continueDeferredProjection` runs the bounded steps after commit, holding the page's queue row under a claim it renews each step (the lease a segmented projection claim uses); the projection drain resumes a page whose steps stopped (queue reason `chunk_replacement_deferred`). A group publication now runs its members' post-commit work, as a single publication does.+- Writes that wrap a page publication in their own (takes, the facts fence, maintenance pages) still replace passages in one transaction.- `readEmbeddingEffectProjection` accepts a vector whose recorded input hash is one the current page accepts, whatever the page-level signature says, and restamps the page.## [0.60.328.0] - 2026-10-20diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 1da2fb613d..8e9231366e 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,7 +17,7 @@ src/core/cycle.ts 3332 ratchet +2 GBRA-130 C-2 (#6946): the sync phase reads ansrc/core/cycle/synthesize.ts 3230 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); +3 wave 17 #6616: slug discovery and postprocessing share the canonical committed child outputs (loadCommittedSynthesisOutputs in synthesize-postprocess.ts; one call-site line, one parameter, one lookup line); lowered to 3224 by wave 17 #6642: the summary provenance section moved to summaryProvenanceLines in dream-provenance.ts; +6 GBRA-130 B-6 (#6860): surrogate-safe triage cuts (truncateUtf8) and the per-transcript verdict-cache write call site (logic in triage-backoff.ts VerdictCacheWrites)src/core/cycle/extract-atoms.ts 1658 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 count; GBRA-130 A-42 (#6804): dot-led atom stems and the legacy-slug adoption guardsrc/core/engine.ts 2832 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; +1 LHF wave 2 item 1: executeRaw opts gain jitOff/prepare (the JIT-off typed-search type check; logic in ops/search-type-filter.ts); +9 PR2 fix lane X: BrainEngine.keywordBoundedRead, one unscoped read under the keyword statement bound for the segmented-region read (interface member and its doc cannot move): 2823 + 9-src/core/import-file.ts 2064 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +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); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation+src/core/import-file.ts 2073 ratchet +2 W1 belief ledger: the legacy import is an unmanaged projection point (logic in belief/projection-point.ts); +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); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062; +2 Wave B lane 2q: ImportResult.searchable (interface field; the value comes from SegmentedImport.afterCommit);+2: pre-publication withdrawal validation; +9 #7172: kept chunk rows move to their new index and a bounded managed publication defers its chunk replacement (logic in page-state/chunk-moves.ts and page-state/projections.ts continueDeferredProjection)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 242 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); +1 Wave B append: pageAppendOperations import (spread shares the pages line); +1 Wave B upload sessions: pageUploadOperations import (spread shares the pages line)src/core/pglite-engine.ts 3085 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 imports; +7 LHF wave 2 item 5: request config snapshot delegate lines in getConfig/getAllConfig/setConfig/unsetConfig (logic in config-snapshot.ts); +3 PR2 fix lane B: logIngest stamps writer_version/writer_host_id/writer_segment_reader and getIngestLog names its columns (engine methods cannot move); integrated at the Wave B PR 2 master merge (v0.60.264.0): master 3072 + 3; +5 PR2 fix lane X: keywordBoundedRead runs the read on the engine itself (engine methods cannot move): 3075 + 5; +2 GBRA-130 B-6 (#6860): putDreamVerdict passes its payload through wellFormedJson (engine methods cannot move); +1 GBRA-130 A-1: held option on the stale-page list/count signatures (SQL in engine-sql/pages.ts); +1 GBRA-130 integration: the A-1 (links_extract_failure) and B-6 (wellFormedJson putDreamVerdict) engine hunks composed at the lane merge; +2 #6948: putPage runs assertOriginUnclaimed in its page transaction and restorePage runs assertRevivalUnclaimed (logic in persistence/origin-guard.ts; engine methods cannot move): 3080 + 2; GBRA-130 composed with #6948 at the master 0e0cd27b merge: re-summed to the merged line count (3085)diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex b53b4f66d9..431afcdf23 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1024,7 +1024,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },{ since: '0.60.328.0', id: 'google_api_access_probe', text: 'A managed Google source whose enabled services cannot name the account (an API disabled for the OAuth project, a scope not granted) now resolves it through the OAuth userinfo endpoint: the account pins, the services that work keep syncing, the run is `partial`, and the disabled API is reported as `api_not_enabled` instead of failing the whole sync. `connector_account_changed` is raised only when an account resolved and differs from the pin; when nothing can name the account (userinfo also failing), the sync fails with the underlying error, a network failure included, instead of refusing as an account change. `gbrain google setup` now probes every requested service before registering a source and stops (exit 2, `status: api_access_blocked`) naming each disabled API with its Google Cloud project and enable link, or each scope not granted, in one report. `gbrain google status` adds `accounts[].api_access` and exits 1 while a problem remains, and doctor adds `google_api_access`, read from what the last sync recorded. A Google 403 for insufficient authentication scopes is now `scope_missing` (before: `upstream`, and a calendar read named it `calendar_unreadable`).' },// #7172. `since` is restamped at the merge slot.- { since: 'TBD', text: 'A managed write (put_page, add_timeline_entry, a managed import or sync) whose passages need more than 5 inserted or renumbered rows commits the page first and finishes its passages in post-commit transactions of at most 5 row writes each, instead of writing them all inside the publication, where a slow index could end it 57014 `write_interrupted`. Search sees the page once the last step seals it; until then its receipt says `searchable: "pending"`, and `gbrain projections drain` finishes a page whose writer stopped. A passage whose text is unchanged keeps its row and vector when an entry above it moves it to another index.' },+ { since: 'TBD', text: 'A managed put_page, edit_page, add_timeline_entry, add_tag or remove_tag, managed import or sync whose passages need more than 5 inserted or renumbered rows commits the page first and finishes its passages in post-commit transactions of at most 5 row writes each, instead of writing them all inside the publication, where a slow index could end it 57014 `write_interrupted`. Search sees the page once the last step seals it; until then its receipt says `searchable: "pending"`, and `gbrain projections drain` finishes a page whose writer stopped. A passage whose text is unchanged keeps its row and vector when an entry above it moves it to another index.' },{ since: 'TBD', text: 'The embedding step after a managed write no longer re-embeds every passage of a page whose stored embedding signature is missing or in an older format: a passage whose recorded embedding input is still current keeps its vector and the page signature is restamped, so only passages whose text changed reach the embedding provider.' },];diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex c81f5d94dd..1fb0895e53 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -29,7 +29,7 @@ import { sanitizeText } from './batch-rows.ts';import { hasProtectedBody, OCR_REQUIRED_ERROR, provenanceDistrusted, safeChunksFilter } from './search/safe-chunks.ts';import { planEmbeddingReuse } from './embed-reuse.ts';import { reuseStoredChunkVectors, type KeptChunkRow } from './import-chunk-reuse.ts';-import { applyMoveWaves, CHUNK_ROW_WRITE_BUDGET, planMoveWaves, type ChunkMove } from './page-state/chunk-moves.ts';+import { applyMoveWaves, planImportChunkWrites } from './page-state/chunk-moves.ts';import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';// #3374 — import-path embeds ride the shared retry loop (429 retry-after +@@ -255,10 +255,7 @@ export async function importFromContent(prepare?: (prepared: import('./persistence/prepared-import.ts').PreparedContentImport) => Promise<ImportResult>;/** #5984, with `prepare`: the coordinator proves the base revision under its page guard, and the caller seals the text projection and checks the read-back (`contentHash`) from its own read after apply; apply skips all three. */coordinated?: boolean;- /**- * #7172, with `prepare`: the caller forwards `afterCommit` and seals nothing when apply returns `projectionPending`, so- * a chunk replacement over CHUNK_ROW_WRITE_BUDGET row writes commits its page pending and finishes after commit.- */+ /** #7172, with `prepare`: the caller forwards `afterCommit` and seals nothing on `projectionPending` (chunk-moves.ts). */boundedChunkWrites?: true;/** With `coordinated`: the caller's own read of this page (deleted rows included) just before, reused as the import base. */existingSnapshot?: import('./page-state/types.ts').PageSnapshot | null;@@ -765,19 +762,10 @@ export async function importFromContent(const kept = new Map([...(fresh !== chunks ? await reuseStoredVectors(tx, fresh, true) : [])].filter((entry): entry is [number, KeptChunkRow] => entry[1] !== null));const keptIds = [...kept.values()].map(row => row.id);- // #7172: a kept row whose chunk moved (an entry inserted above it) changes index in place. Each move and each- // inserted row is a row write (chunk-moves.ts); a managed publication makes at most CHUNK_ROW_WRITE_BUDGET of them- // and otherwise deletes the rows it does not keep, commits the page with its projection pending and finishes after- // commit (continueDeferredProjection).- const moves: ChunkMove[] = [...kept].filter(([i, row]) => row.chunk_index !== fresh[i]!.chunk_index)- .map(([i, row]) => ({ id: row.id, from: row.chunk_index, to: fresh[i]!.chunk_index,- projected_byte_start: fresh[i]!.projected_byte_start ?? null, projected_byte_end: fresh[i]!.projected_byte_end ?? null }));- const inserts = fresh.length - kept.size;- const bounded = !segmented && !!opts.prepare && opts.boundedChunkWrites === true;- const moveBudget = bounded ? Math.max(0, CHUNK_ROW_WRITE_BUDGET - inserts) : Number.POSITIVE_INFINITY;- const movePlan = planMoveWaves(moves, new Map([...kept.values()].map(row => [row.chunk_index, row.id])), moveBudget);- const deferChunks = bounded && chunks.length > 0 && (!movePlan.done || inserts > CHUNK_ROW_WRITE_BUDGET);- chunkReplacementDeferred = deferChunks;+ // #7172: a kept row whose chunk moved changes index in place; a managed publication over CHUNK_ROW_WRITE_BUDGET row+ // writes deletes the rows it does not keep, commits the page pending and finishes after commit (chunk-moves.ts).+ const chunkWrites = planImportChunkWrites(fresh, kept, !segmented && !!opts.prepare && opts.boundedChunkWrites === true);+ const deferChunks = chunkReplacementDeferred = chunkWrites.defer;let written: Page | undefined;await pipelined(tx, [() => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),@@ -841,7 +829,7 @@ export async function importFromContent(async () => {if (deferChunks) return;if (chunks.length > 0) {- if (movePlan.waves.length) await applyMoveWaves(tx, Number(pageId), movePlan.waves);+ await applyMoveWaves(tx, Number(pageId), chunkWrites.waves);const embeddingColumn = await stampEmbeddingInputs(tx, fresh, null,{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });await tx.upsertChunks(slug, kept.size ? fresh.filter((_, i) => !kept.has(i)) : fresh, { ...txOpts, ...(embeddingColumn ? { embeddingColumn } : {}), sealChunkerVersion: MARKDOWN_CHUNKER_VERSION,@@ -891,11 +879,9 @@ export async function importFromContent(persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);}if (segmented?.applied) return { pageId, sealed: !opts.coordinated && segmented.applied.complete, segmented: { complete: segmented.applied.complete } };- if (deferChunks) {- // The trigger queued this revision's projection; the reason routes a resident or drain rebuild to the bounded continuation.- await queuePageProjection(tx, txOpts.sourceId, slug, DEFERRED_CHUNK_REPLACEMENT);- return { pageId, sealed: false, projectionPending: true as const };- }+ // The reason routes a resident or drain rebuild of this revision to the bounded continuation.+ if (deferChunks) await queuePageProjection(tx, txOpts.sourceId, slug, DEFERRED_CHUNK_REPLACEMENT);+ if (deferChunks) return { pageId, sealed: false, projectionPending: true as const };return { pageId, sealed: !opts.coordinated && !opts.beforeCommit, ...(deferSeal ? { chunkerSeal: MARKDOWN_CHUNKER_VERSION } : {}) };};if (opts.prepare) return opts.prepare({diff --git a/src/core/page-state/chunk-moves.ts b/src/core/page-state/chunk-moves.tsindex fd12ec19ee..571be6c387 100644--- a/src/core/page-state/chunk-moves.ts+++ b/src/core/page-state/chunk-moves.ts@@ -1,4 +1,5 @@import type { BrainEngine } from '../engine.ts';+import type { ChunkInput } from '../types.ts';/*** #7172: the most row writes one page's chunk replacement makes in one transaction.@@ -24,9 +25,10 @@ export interface ChunkMove { id: number; from: number; to: number; projected_byt* The UPDATE statements (waves) that move `moves` without breaking the (page_id, chunk_index) unique index, using at* most `budget` row updates. `occupied` maps each index a remaining row holds to its id. A wave moves rows whose* target is free; when none is (a cycle), one row parks at the negative index `-1 - to` and lands later. `done` says- * every move fits.+ * every move fits; `pending` and `at` are the moves left and the occupied indexes once the waves ran.*/-export function planMoveWaves(moves: readonly ChunkMove[], occupied: ReadonlyMap<number, number>, budget: number): { waves: ChunkMove[][]; updates: number; done: boolean } {+export function planMoveWaves(moves: readonly ChunkMove[], occupied: ReadonlyMap<number, number>, budget: number):+ { waves: ChunkMove[][]; updates: number; done: boolean; pending: ChunkMove[]; at: Map<number, number> } {const at = new Map(occupied);let pending = moves.map(move => ({ ...move }));const waves: ChunkMove[][] = [];@@ -40,7 +42,22 @@ export function planMoveWaves(moves: readonly ChunkMove[], occupied: ReadonlyMapif (free.length) pending = pending.filter(move => !free.includes(move));else pending[0]!.from = wave[0]!.to;}- return { waves, updates, done: pending.length === 0 };+ return { waves, updates, done: pending.length === 0, pending, at };+}++/**+ * #7172: an import's chunk row writes. `kept` maps a new chunk's position in `fresh` to the stored row it keeps; a kept+ * row whose chunk sits at another index moves there (`waves`). With `bounded` (a managed publication), `defer` says the+ * moves and inserts pass CHUNK_ROW_WRITE_BUDGET, so the publication leaves them to `continueDeferredProjection`.+ */+export function planImportChunkWrites(fresh: readonly ChunkInput[], kept: ReadonlyMap<number, { id: number; chunk_index: number }>, bounded: boolean):+ { waves: ChunkMove[][]; defer: boolean } {+ const moves = [...kept].filter(([i, row]) => row.chunk_index !== fresh[i]!.chunk_index).map(([i, row]) => ({ id: row.id, from: row.chunk_index,+ to: fresh[i]!.chunk_index, projected_byte_start: fresh[i]!.projected_byte_start ?? null, projected_byte_end: fresh[i]!.projected_byte_end ?? null }));+ const inserts = fresh.length - kept.size;+ const plan = planMoveWaves(moves, new Map([...kept.values()].map(row => [row.chunk_index, row.id])),+ bounded ? Math.max(0, CHUNK_ROW_WRITE_BUDGET - inserts) : Number.POSITIVE_INFINITY);+ return { waves: plan.waves, defer: bounded && fresh.length > 0 && (!plan.done || inserts > CHUNK_ROW_WRITE_BUDGET) };}/** One UPDATE per wave; a landed row takes its new chunk's span, a parked row keeps its own until it lands. */diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex fb59e54ba4..5f1b1ef04f 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import type { ProgressReporter } from '../progress.ts';import type { Chunk, ChunkInput, ResolvedColumn, PageKind } from '../types.ts';@@ -174,6 +175,8 @@ async function readGuardedProjectionSnapshot(tx: BrainEngine, slug: string, sour/** #7172: the queue reason of a revision whose publication left its chunk replacement to `continueDeferredProjection`. */export const DEFERRED_CHUNK_REPLACEMENT = 'chunk_replacement_deferred';+/** #7172: `<claim>:<token>`, the reason while a continuation holds the replacement (renewed each step, as a segmented projection claim is). */+export const DEFERRED_CHUNK_CLAIM = 'chunk_replacement_continuing';/*** Which stored rows a projection of `chunks` keeps (#5553, A4): each row holding a new chunk at its own index, and@@ -223,63 +226,109 @@ async function planProjectionKeep(tx: BrainEngine, current: PageSnapshot, contexreturn { kept, moves, current: kept.filter(currentInput).map(chunk => Number(chunk.id)), provenanceModel: context.provenanceModel, column: context.column };}+/** #7172: a deferred chunk replacement's remaining row writes, planned once from what is stored and spent in steps. */+interface DeferredReplacement {+ current: PageSnapshot; pageId: number; column: ResolvedColumn; moves: ChunkMove[]; at: Map<number, number>; stale: number[]; inserts: ChunkInput[];+ /** `chunkRowsFingerprint` after the plan's last committed step: a step that finds another one plans again. */+ fingerprint: string;+}++/** The page's chunk rows as (id, index) pairs, hashed; no chunk text is read. */+async function chunkRowsFingerprint(tx: BrainEngine, pageId: number): Promise<string> {+ // chunk-visibility-ok: identity of a deferred replacement's rows (ids and indexes), never returned to a reader+ const [row] = await tx.executeRaw<{ f: string }>(`SELECT count(*)::text||':'||COALESCE(sum(hashtext(id::text||':'||chunk_index::text)::bigint),0)::text AS f+ FROM content_chunks WHERE page_id=$1`, [pageId]);+ return row!.f;+}++/** Reads the page under its guard and plans its replacement; the rows it does not keep are deleted here (no index entry). */+async function planDeferredReplacement(tx: BrainEngine, sourceId: string, slug: string): Promise<DeferredReplacement | null> {+ const prepared = await readGuardedProjectionSnapshot(tx, slug, sourceId, { allowUnsealed: true });+ if (!prepared || prepared.pageKind !== 'markdown' || prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision) return null;+ const current = prepared.snapshot;+ const pageId = Number(current.page.id);+ const { chunks } = await preparePageProjection(prepared);+ const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);+ const plan = await planProjectionKeep(tx, current, context, prepared.chunks, chunks);+ await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))', [pageId, plan.kept.map(chunk => Number(chunk.id))]);+ // chunk-visibility-ok: the kept rows of a deferred replacement whose vector the current page no longer accepts+ const stale = (await tx.executeRaw<{ id: number }>(`SELECT id FROM content_chunks WHERE page_id=$1 AND ${quoteIdentifier(context.column.name)} IS NOT NULL+ AND (model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR NOT(id=ANY($3::int[]))) ORDER BY chunk_index`,+ [pageId, plan.provenanceModel, plan.current])).map(row => Number(row.id));+ const moved = new Set(plan.moves.map(move => move.id));+ const occupied = new Set([...plan.kept.filter(row => !moved.has(Number(row.id))).map(row => row.chunk_index), ...plan.moves.map(move => move.to)]);+ return { current, pageId, column: context.column, moves: plan.moves, at: new Map(plan.kept.map(chunk => [chunk.chunk_index, Number(chunk.id)])), stale,+ inserts: chunks.filter(chunk => !occupied.has(chunk.chunk_index)), fingerprint: '' };+}+/*** #7172: one bounded step of a chunk replacement a publication deferred (the page committed with its text projection* pending, its search hiding the page's passages until the seal). Under the page guard, at the page's current- * revision, a step deletes the rows the projection does not keep (a delete adds no index entry) and then makes at most- * `budget` row writes, in this order: kept rows change index (`planMoveWaves`), kept rows whose input is no longer- * current lose their vector, and the missing chunks are inserted without vectors. The step that finds nothing left- * seals the projection. Idempotent: each step re-reads the page and plans from what is stored, so a crash between- * steps resumes where the last committed one left it. 'skipped' when the page is not an unsealed inline Markdown page.+ * revision, a step makes at most `budget` row writes, in this order: kept rows change index (`planMoveWaves`), kept+ * rows whose input is no longer current lose their vector, and the missing chunks are inserted without vectors; the+ * step that finds nothing left seals the projection. The plan (`state`) is made once from what is stored and carried+ * between steps only after a step commits; a step whose page revision or chunk rows differ from what the plan's last+ * step left plans again, so a crash, a concurrent step or a newer write resumes from the stored rows. Each step renews+ * the job's `updated_at`, the lease that keeps the resident's drain off a replacement being continued. 'skipped' when+ * the page is not an unsealed inline Markdown page.*/-export async function continueDeferredProjectionStep(engine: BrainEngine, sourceId: string, slug: string, budget = CHUNK_ROW_WRITE_BUDGET,- memo: { revision?: string; chunks?: ChunkInput[] } = {}): Promise<'sealed' | 'more' | 'skipped'> {- return engine.transaction(async tx => {+export async function continueDeferredProjectionStep(engine: BrainEngine, sourceId: string, slug: string,+ state: { plan?: DeferredReplacement; token?: string } = {}, budget = CHUNK_ROW_WRITE_BUDGET): Promise<'sealed' | 'more' | 'skipped' | 'held'> {+ const claim = `${DEFERRED_CHUNK_CLAIM}:${state.token ??= randomUUID()}`;+ const [step, next] = await engine.transaction(async (tx): Promise<['sealed' | 'more' | 'skipped' | 'held', DeferredReplacement?]> => {await tx.lockPageKeys([{ sourceId, slug }]);- const prepared = await readGuardedProjectionSnapshot(tx, slug, sourceId, { allowUnsealed: true });- if (!prepared || prepared.pageKind !== 'markdown' || prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision) return 'skipped';- const current = prepared.snapshot;- const pageId = Number(current.page.id);- // The chunks of one revision are computed once per continuation (`memo`), not once per step.- if (memo.revision !== current.revision) Object.assign(memo, { revision: current.revision, chunks: (await preparePageProjection(prepared)).chunks });- const chunks = memo.chunks!;- const context = await indexingContext(tx, current, prepared.maxChunkTokensOverride);- const plan = await planProjectionKeep(tx, current, context, prepared.chunks, chunks);- await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND NOT(id=ANY($2::int[]))', [pageId, plan.kept.map(chunk => Number(chunk.id))]);- const { waves, updates, done } = planMoveWaves(plan.moves, new Map(plan.kept.map(chunk => [chunk.chunk_index, Number(chunk.id)])), budget);- await applyMoveWaves(tx, pageId, waves);- if (!done) return 'more';- let left = budget - updates;- const col = quoteIdentifier(plan.column.name);- const stale = (await tx.executeRaw<{ id: number }>(`SELECT id FROM content_chunks WHERE page_id=$1 AND ${col} IS NOT NULL- AND (model IS DISTINCT FROM $2 OR embedded_text_hash <> md5(chunk_text) OR NOT(id=ANY($3::int[]))) ORDER BY chunk_index`,- [pageId, plan.provenanceModel, plan.current])).map(row => Number(row.id));- const nulled = stale.slice(0, left);+ const [head] = await tx.executeRaw<{ id: number; revision: string; sealed: boolean }>(`SELECT id, knowledge_revision::text AS revision,+ text_projection_revision IS NOT DISTINCT FROM knowledge_revision AS sealed FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL`, [sourceId, slug]);+ if (!head || head.sealed) return ['skipped'];+ const [held] = await tx.executeRaw(`SELECT 1 FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation+ WHERE s.id=$1 AND j.slug=$2 AND j.revision=$3::uuid AND split_part(j.reason,':',1)=$4 AND j.reason<>$5+ AND j.updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds'`, [sourceId, slug, head.revision, DEFERRED_CHUNK_CLAIM, claim]);+ if (held) return ['held'];+ const carried = state.plan?.current.revision === head.revision && state.plan.pageId === Number(head.id)+ && state.plan.fingerprint === await chunkRowsFingerprint(tx, Number(head.id)) ? state.plan : null;+ const base = carried ?? await planDeferredReplacement(tx, sourceId, slug);+ if (!base) return ['skipped'];+ const { current, pageId } = base;+ const waves = planMoveWaves(base.moves, base.at, budget);+ await applyMoveWaves(tx, pageId, waves.waves);+ let left = budget - waves.updates;+ const nulled = waves.done ? base.stale.slice(0, left) : [];if (nulled.length) {- await tx.executeRaw(`UPDATE content_chunks SET ${col}=NULL,embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,+ await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(base.column.name)}=NULL,embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL,embedding_pending_since=COALESCE(embedding_pending_since,now()) WHERE page_id=$1 AND id=ANY($2::int[])`, [pageId, nulled]);}- if (stale.length > nulled.length) return 'more';left -= nulled.length;- const moved = new Set(plan.moves.map(move => move.id));- const occupied = new Set([...plan.kept.filter(row => !moved.has(Number(row.id))).map(row => row.chunk_index), ...plan.moves.map(move => move.to)]);- const missing = chunks.filter(chunk => !occupied.has(chunk.chunk_index));- const inserts = missing.slice(0, left);- if (inserts.length) await tx.upsertChunks(slug, inserts, { sourceId, embeddingColumn: context.column, sealChunkerVersion: MARKDOWN_CHUNKER_VERSION, pageId, deferSeal: true });- if (missing.length > inserts.length) return 'more';+ const stale = base.stale.slice(nulled.length);+ const inserts = waves.done && !stale.length ? base.inserts.slice(0, left) : [];+ if (inserts.length) await tx.upsertChunks(slug, inserts, { sourceId, embeddingColumn: base.column, sealChunkerVersion: MARKDOWN_CHUNKER_VERSION, pageId, deferSeal: true });+ const job = [current.sourceIncarnation, slug, current.revision];+ if (!waves.done || stale.length || inserts.length < base.inserts.length) {+ await tx.executeRaw('UPDATE page_projection_jobs SET reason=$4,updated_at=now() WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [...job, claim]);+ return ['more', { ...base, moves: waves.pending, at: waves.at, stale, inserts: base.inserts.slice(inserts.length), fingerprint: await chunkRowsFingerprint(tx, pageId) }];+ }await sealImportedPage(tx, slug, sourceId, current, MARKDOWN_CHUNKER_VERSION, pageId);- await tx.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [current.sourceIncarnation, slug, current.revision]);- return 'sealed';+ await tx.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', job);+ return ['sealed'];});+ state.plan = next;+ return step;}-/** `continueDeferredProjectionStep` until the page is sealed, skipped, or `until` says stop (a resident's time budget). */-export async function continueDeferredProjection(engine: BrainEngine, sourceId: string, slug: string, until: () => boolean = () => false): Promise<'sealed' | 'more' | 'skipped'> {- const memo = {};- for (;;) {- const step = await continueDeferredProjectionStep(engine, sourceId, slug, CHUNK_ROW_WRITE_BUDGET, memo);- if (step !== 'more' || until()) return step;- }+/**+ * `continueDeferredProjectionStep` until the page is sealed, skipped, held by another continuation, or `until` says stop+ * (a resident's time budget). A continuation that stops early or fails hands its claim back, so the drain resumes it at once.+ */+export async function continueDeferredProjection(engine: BrainEngine, sourceId: string, slug: string, until: () => boolean = () => false): Promise<'sealed' | 'more' | 'skipped' | 'held'> {+ const state: { token?: string } = {};+ const release = () => engine.executeRaw(`UPDATE page_projection_jobs SET reason=$1 WHERE slug=$2 AND reason=$3`,+ [DEFERRED_CHUNK_REPLACEMENT, slug, `${DEFERRED_CHUNK_CLAIM}:${state.token}`]).catch(() => undefined);+ try {+ for (;;) {+ const step = await continueDeferredProjectionStep(engine, sourceId, slug, state);+ if (step !== 'more') return step;+ if (until()) { await release(); return step; }+ }+ } catch (error) { await release(); throw error; }}/** No provider work under the guard. Delayed derived results lose to newer content. */@@ -553,7 +602,9 @@ export const SEGMENTED_PROJECTION_LEASE_SECONDS = 60;*/export const SEGMENTED_PROJECTION_CLAIMED_SQL = `(split_part(j.reason,':',1)='${SEGMENTED_PROJECTION_CLAIM}' AND j.updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds')`;export const PROJECTION_RETRY_READY_SQL = "(j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds')"- + ` AND NOT ${SEGMENTED_PROJECTION_CLAIMED_SQL}`;+ + ` AND NOT ${SEGMENTED_PROJECTION_CLAIMED_SQL}`+ // #7172: a chunk replacement a continuation holds renews its claim each step (continueDeferredProjectionStep), under the same lease.+ + ` AND NOT (split_part(j.reason,':',1)='${DEFERRED_CHUNK_CLAIM}' AND j.updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds')`;export interface ProjectionRebuildFailure { source_id: string; slug: string; reason: string }@@ -760,7 +811,7 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =const pending = await tx.executeRaw<{ reason: string }>(`SELECT reason FROM page_projection_jobsWHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, observed);if (!pending.length) return null;- if (pending[0]!.reason === DEFERRED_CHUNK_REPLACEMENT) return 'deferred';+ if (pending[0]!.reason === DEFERRED_CHUNK_REPLACEMENT || pending[0]!.reason.split(':')[0] === DEFERRED_CHUNK_CLAIM) return 'deferred';const read = await readGuardedProjectionSnapshot(tx, job.slug, job.source_id, { allowUnsealed: true });if (!read) {const [segmented] = await tx.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2 AND body_storage='segmented' AND deleted_at IS NULL`,@@ -784,6 +835,7 @@ export async function rebuildPendingPageProjections(engine: BrainEngine, limit =const step = await continueDeferredProjection(engine, job.source_id, job.slug,() => opts.deadlineMs !== undefined && now() - startedAt >= opts.deadlineMs);if (step === 'sealed') rebuilt++;+ else if (step === 'held') superseded++;else {superseded++;// A skipped page (sealed meanwhile, or no longer inline Markdown) goes back to the ordinary rebuild.diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.tsindex 0f7ca821f7..53f82884be 100644--- a/src/core/persistence/group-publish.ts+++ b/src/core/persistence/group-publish.ts@@ -428,6 +428,8 @@ export async function publishGroup(engine: BrainEngine, rows: WriteRequest[], prreleaseCapacity?.();publishingBeside.delete(head.id);await lock.release();+ // As publishMutation does: each committed member's post-commit work (#7172: a deferred chunk replacement) runs after the lock.+ if (committed) for (const member of prepared) await member.afterCommit?.(engine).catch(() => undefined);}}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 8b5a8fdb27..86d32e953a 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -651,7 +651,7 @@ async function segmentedContentHash(engine: BrainEngine, snapshot: PageSnapshot,*/export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequest, _config: GBrainConfig,preparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,- options: { allowMissingFile?: boolean; coordinated?: boolean; clock?: ClaimPhaseClock } = {}): Promise<PreparedMutation> {+ options: { allowMissingFile?: boolean; coordinated?: boolean; clock?: ClaimPhaseClock; boundedChunkWrites?: true } = {}): Promise<PreparedMutation> {// Wave B (spec 6.2): a committed upload session prepares the put_page its staged parts hold.if (row.operation === 'put_page' && isStagingBodyRef(row.intent?.body_ref)) {signal?.throwIfAborted();@@ -791,7 +791,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wriconst lean = options.coordinated === true && !targetDeleted && row.operation !== 'restore_page' && !versionTags;enterClaimStep(clock, 'import_content', undefined, 'db');const result = await importFromContent(engine, row.slug, content, {- ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean, boundedChunkWrites: true,+ ...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean, boundedChunkWrites: options.boundedChunkWrites,segmentedOwner: { kind: row.operation === 'edit_page' ? 'edit' : 'put', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: observedRevision },...(lean ? { existingSnapshot: snapshot } : {}),// #6259: only owner-tier intents keep gate-owned markers; an ordinary put_page, local or remote, has them stripped.@@ -946,8 +946,7 @@ async function prepareInlineOrSegmentedMutation(unbounded: BrainEngine, row: Wristatus: noop ? 'skipped' : row.operation === 'restore_page' ? 'restored' : row.operation === 'revert_version' ? 'reverted' : 'created_or_updated',slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop, ...(projectionPending ? { projection: 'pending' } : {}),// Wave B: whether search sees a segmented write at commit; a pending one is re-read whenever its receipt is served (searchable.ts).- ...(segmentedWrite ? { searchable: isQuarantined(ready.parsedPage.frontmatter) ? false : projectionPending ? 'pending' : true }- : projectionPending ? { searchable: 'pending' } : {}),+ ...(segmentedWrite ? { searchable: isQuarantined(ready.parsedPage.frontmatter) ? false : projectionPending ? 'pending' : true } : projectionPending ? { searchable: 'pending' } : {}),...sizeState,...(ready.result.chunks === 0 && !projectionPending ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),diff --git a/src/core/persistence/semantic-pages.ts b/src/core/persistence/semantic-pages.tsindex 04483abe43..7b8bc8b5d2 100644--- a/src/core/persistence/semantic-pages.ts+++ b/src/core/persistence/semantic-pages.ts@@ -61,7 +61,7 @@ export async function prepareSemanticPageMutation(engine: BrainEngine, row: Writconst snapshot = flipped ? stored : (await wholeBodySnapshot(engine, stored, `${row.operation} (the write gate scans the whole body of an external_untrusted write)`))!;const prepared = flipped ?? await preparePageMutation(engine, row, config, {expectedRevision: snapshot.revision, tags, content: serializePageToMarkdown(snapshot.page, tags),- });+ }, undefined, { boundedChunkWrites: true });// #5251: a tag change leaves every chunk's text as it was, so the republication queues no// embedding effect; the stale sweep still picks up any chunk the publish left without a vector.return { ...prepared, deferEmbedding: true, apply: async tx => ({ ...await prepared.apply(tx), status: 'ok', tag }) };@@ -94,7 +94,7 @@ export async function prepareSemanticPageMutation(engine: BrainEngine, row: Writconst page = { ...snapshot.page, timeline: exact ? snapshot.page.timeline : spliceTimelineBlock(snapshot.page.timeline, entry.date, block) };const prepared = await preparePageMutation(engine, row, config, {expectedRevision: snapshot.revision, content: serializePageToMarkdown(page, snapshot.tags),- });+ }, undefined, { boundedChunkWrites: true });return { ...prepared, apply: async tx => {const outcome = await prepared.apply(tx);const inserted = await tx.addTimelineEntry(row.slug, { ...rendered.canonical, detail: rendered.detail }, { sourceId: row.source_id });diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 11a8a093ad..7fbd811d78 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -105,7 +105,7 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);if (row.operation === 'append_page') return (await import('./page-upload.ts')).withStagedBodyIf(e, row, async () => (await import('./page-append.ts')).prepareAppendMutation(e, row, cfg, signal, clock));if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal,- { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock });+ { coordinated: await writeSwitchOn(e, 'single_write_group').catch(() => true), clock, boundedChunkWrites: true });throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);}/**diff --git a/test/timeline-chunk-reuse.test.ts b/test/timeline-chunk-reuse.test.tsindex b661296932..1f0b7c2c15 100644--- a/test/timeline-chunk-reuse.test.ts+++ b/test/timeline-chunk-reuse.test.ts@@ -172,8 +172,9 @@ for (const kind of testBackends()) {expect((await pageState(slug)).sealed).toBe(false);const [job] = await brain.engine.executeRaw<{ reason: string }>("SELECT reason FROM page_projection_jobs WHERE slug=$1", [slug]);expect(job?.reason).toBe('chunk_replacement_deferred');- const drained = await rebuildPendingPageProjections(brain.engine, 10);- expect(drained.rebuilt).toBeGreaterThanOrEqual(1);+ // The drain resumes it from the stored rows: this call, or the resident's drain when it got there first (it holds the claim).+ await rebuildPendingPageProjections(brain.engine, 10);+ for (let i = 0; i < 600 && !(await pageState(slug)).sealed; i++) await new Promise(resolve => setTimeout(resolve, 100));await settle();await runEmbedCore(brain.engine, { stale: true, quiet: true } as never);const after = await rows(slug);