Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B PR 2 lane 2q: segmented creates searchable at commit up to 4 MiB, one projection with a searchable receipt above it; segment chunks keep headings with their section
garrytan25a64478f950
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex 4facb82fed..d90397d081 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -42,7 +42,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/links.ts` — the link-domain op module (`add_link`, `remove_link`, `get_links`, `get_backlinks`, `list_link_sources`, `traverse_graph`); `get_backlinks`' `type`/`group`/`limit`/`cursor` live in `backlinks-paged.ts`. Three load-bearing behaviors. (1) Pack vocabulary at the write surface: an EXPLICIT `link_type` on `add_link` must be declared by the active schema pack when one resolves (`schema-pack/write-vocabulary.ts`; no resolvable pack = no enforcement; omitted/empty link_type is the untyped-edge default and stays unchecked; the check runs before the dry-run return so dry runs preview the rejection). (2) `traverse_graph` output shape: trusted local no-filter callers (`ctx.remote === false`, no `link_type`/`direction`) keep the legacy `GraphNode[]` shape that `gbrain graph` renders; remote callers default to `direction: 'both'` and always receive explicit `GraphPath[]` edges, so a page whose typed edges are all inbound does not read as edge absence. An explicit `direction` param wins for every caller. Depth: default 5 (`DEFAULT_TRAVERSE_DEPTH`), except a remote call that let direction default to `both` ALSO defaults depth to `REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH` (2) — bidirectional path enumeration is combinatorial on entity hubs and this is the per-agent-turn path; a `link_type`-only remote call still takes both/2; an explicit depth is honored up to `TRAVERSE_DEPTH_CAP` (10, clamped with a warn). The edge walk runs through `engine.traversePathsDetailed`, and a hit on `TRAVERSE_PATH_ROW_CAP` (`engine-constants.ts`) surfaces as a stderr warn naming the cap (shallowest edges kept) — the `GraphPath[]` wire shape stays unchanged. Pinned by `test/traverse-graph-op-default.test.ts` + `test/traverse-paths-row-cap.test.ts`. (3) Link-read source scope: the three read ops take `source_id` (`parseSourceIdParam`, `__all__` admitted) and `all_sources` (equivalent to `__all__`; both together is `invalid_params`). `resolveLinkReadScope` composes `federatedSearchScope` (grant check, #5081 admission, unqualified no-grant widening to `localFederatedSourceIds`; a grant never widens), then `assertExplicitSourceLive` (so an archived source outside the caller's admission answers `permission_denied`, not `unknown_source`), then `linkReadScopeOpts` (remote scalar promoted to `sourceIds[]` for the engine's all-endpoints branch), then `readPolicyOpts`. A trusted local unqualified read that comes back as the federated `sourceIds[]` runs the scalar read once per federated source (set order, resolved source first) and merges de-duplicated on link identity, keeping the scalar branch's cross-source far endpoints; `traverse_graph` walks the federated set in one query because its scalar walk already scopes every node. A trusted local unqualified link read that returns nothing prints a stderr rerun hint naming sources outside the read that hold links for the slug (quiet under `json`, never for remote callers). CLI names: `links` (alias `get_links`), `backlinks`, `graph`. Pinned by `test/federated-link-reads-5827.test.ts`, `test/link-reads-thin-client-5827.serial.test.ts` and `test/e2e/federated-link-reads-postgres.test.ts`. `traverse_graph` `hops` (1-3 `{link_type, toward}`) runs a typed chain through `runRelationalChain` under the op's read scope, returns `{anchor, answers, paths, diagnostics}` with evidence edges (remote context sanitized), refuses `hops` combined with `depth`/`link_type`/`direction` and bad hops as `invalid_params` naming the parameter path, and emits a `relational_chain` notice with the next call when the chain finds nothing. Pinned by `test/traverse-graph-hops.test.ts`.-- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing.+- `src/core/ops/pages.ts` — page operations share source validation and the persistence coordinator. Replacements require `expected_revision` or explicit `force`; omitted preconditions permit creation only. The put_page description keeps `Keep a request_id UUID; retry with identical arguments` within its 1,460-character schema budget (pinned by `test/mcp-schema-budget.test.ts` minimum guidance; the description and the content param both keep the get_page include_content:true read that `test/mcp-tool-defs.test.ts` pins). `get_page` and `fetch` use `page-state/snapshot.ts` for exact/alias resolution, content, tags, revision and withdrawal overlays in one SQL snapshot; fuzzy fallback uses a short repeatable-read transaction with the same visibility and source ceilings. `get_page` `content_only` (`ops/get-page-projection.ts`) returns slug, source_id, type, title, revision, tags and content (keys pinned by `test/get-page-content-roundtrip-2225.test.ts`). A put_page `revision_conflict` (`ops/put-page-revision-source.ts`) whose expected_revision is the current revision of the same slug in another source the caller may read (grant via `federatedSearchScope`, private pages excluded for untrusted readers) names that source and gets a re-read fix; otherwise the refusal is unchanged. `get_page` adds `file_held` when sync holds the page's newer file (`persistence/held-reads.ts`; path for trusted local callers only). Missing migration dependencies and connection errors propagate. Capture freezes target/type/timestamp/provenance before admission and resolves same-ID replay first. `persistence/links-preparation.ts` prepares trusted automatic graph reconciliation outside locks, then installs it with canonical projections and the receipt; delayed oneshot reconciliation validates its originating revision. `persistence/page-advisories.ts` prepares bounded, content-free lint findings. Tests cover source/alias ownership, concurrent graph replacements, stale delayed reconciliation, private fences and durable retries. `list_pages` passes `listColumnsOnly` so `engine-sql/pages.ts:listPages` projects identity, type, title and dates without reading page bodies or frontmatter (`list-pages-columns-5154.test.ts`). `delete_page` accepts a strict boolean `purge` only from trusted local callers. Immediate purge uses the same durable journal, observed revision (or explicit `force`), stored/current authority and exact request-ID replay as other page mutations. Owner preparation resolves the recorded file from a coherent snapshot, including tombstones; file removal precedes hard deletion and receipt commitment in the guarded publication transaction. Failed publication preserves the prior active row or existing tombstone and never overwrites unexpected file bytes. The receipt reports the actual filesystem/database persistence outcome and warns that repository history, synced copies, exports and derived artifacts may retain content. The `gbrain delete <slug> --purge` flag derives from the operation contract. `list_pages` probes `limit + 1` rows: a local CLI caller gets a stderr truncation notice; every dispatched caller gets `_meta.pagination` (`truncated`, `limit`, `clamped_from?`, `next?`) and a remote caller whose page was truncated also gets the model-visible `listing_truncated` notice whose `fix.mcp` is the next-page call (`ops/list-pages-pagination.ts`; `next` is the `updated_asc` keyset or an offset). Test: `test/list-pages-truncation.test.ts`. An `updated_after` the database cannot cast (SQLSTATE 22007/22008, the shared `isDatetimeInputError` in `core/utils.ts` that the hybrid lexical arms also use) is `invalid_params` with a read-only list_pages fix, never echoing the value; other SQLSTATEs pass through (`test/list-pages-timestamp-input.test.ts`). put_page (dry runs included) refuses a new `.md`/`.mdx`-suffixed slug (`persistence/suffixed-slug.ts`). #6212: `delete_page` and `restore_page` (dry runs included) go through `persistence/page-mutations.ts:validateMutationSlug`, which admits a legacy stored slug (`ops/context.ts:isLegacyStoredPageSlug`: refused by today's grammar, still accepted by `validateSlug`) only when an existing row in the target source holds it; every other operation keeps `validatePageSlug`, and remote purge stays denied by `assertPurgeParams`. Large pages: `get_page` resolves its body mode first (`parseBodyRequest`, `src/core/ops/get-page-body.ts`) and returns `readPartialBody` for none/outline/window/auto-above-256 KB, `assertFullReadFits` guarding whole remote reads; `fetch` of a page over the inline size returns `fetchWindowResult` (window around the id's chunk anchor, `metadata.next_id`); remote `put_page` runs `assertLargePageAdmission` before queueing. A committed segmented write's outcome records `searchable` (`true`, `'pending'` when its projection runs after commit, `false` when quarantined); `persistence/searchable.ts:liveSearchable` re-reads a pending one whenever the receipt is served (the put_page reply in `page-mutations.ts`, `get_write_request`) and adds `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`test/large-pages/segmented-create-searchable.test.ts`).- `src/core/ops/get-page-body.ts` — get_page's body modes (`auto|full|none|outline|window`, selectors `lines`/`bytes`/`around_chunk_id`/`cursor`, `view: read|markdown`). `parseBodyRequest` fixes precedence (explicit body; include_content/content_only → full; a selector → window; the thin client and the local CLI → full; else auto) and rejects conflicting selectors. `readPartialBody` never fills compiled_truth/timeline/content: it slices the read projection (`readPageDocument`) or, for `view: markdown`, the round-trip markdown with its sha256; a window is re-measured as the final encoded frame and shrunk until it fits `resultByteCap`. `around_chunk_id` uses the stored span (`anchor: stored_span`), a unique text match (`located`), or returns the chunk alone (`chunk_only`). Cursors are revision-bound; a stale one is `revision_changed` with a same-offset fix. `readFetchWindow` / `fetchWindowResult` serve fetch's windowed shape; `LARGE_PAGES_CAPABILITY` is advertised by `get_brain_identity`. A segmented page (Wave B PR 2, spec 7.2) is never read whole: `full` is `page_body_segmented` locally (fix: `gbrain get`, which streams it) and `page_too_large_for_inline` over a transport (`segmentedFullReadError`), `auto` is the outline plus the first window, and `segmentedWindows` cuts every window, outline page and `around_chunk_id` from `page-window/segmented.ts`. A segmented `around_chunk_id` resolves only from the chunk's live occurrence and segment-relative span (a retired occurrence is `revision_changed`; no text match), and `body: 'none'` reports stored sums plus the tail digest without chunk counts.- `src/core/persistence/large-page-guard.ts` — put_page against a page over 256 KB: `assertLargePageAdmission` (remote, before queueing) refuses `force` without `expected_revision` (`revision_required`) and content under half the stored body (`page_shrink_refused`) unless `allow_shrink`; `assertLargePageReplacement` re-checks the parsed body against the locked snapshot in preparation (`page-prepare.ts`).- `src/core/ops/page-edit.ts` — the `edit_page` operation (write scope, starter surface, client slug-fence allowlist): validates edits, then submits through `submitPageMutation` like put_page; matching and the diff live in `persistence/page-edit.ts`.diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 23611d5570..810f17738b 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -346,6 +346,11 @@ Receipts include `request_id`, `state`, and `retry_after_ms`, with optionalrevision, outcome, persistence status, and timestamps. Terminal receipts have`retry_after_ms: null`. Private queued content, credential hashes, and recoverybytes are never part of the receipt.+A committed write of a page stored in segments also says whether search sees+it yet: `searchable: true`, or `searchable: "pending"` with+`searchable_retry_after_ms` and `searchable_fix` (read the receipt again) while+its chunks are built after commit; see+[when a segmented write is searchable](memory-boundaries.md#segmented-searchable).Nonterminal receipts may include a validated `diagnostic` with `age_ms`,`assessment` (`pending`, `blocked`, or `stalled`), a closed `reason`, anddiff --git a/docs/guides/memory-boundaries.md b/docs/guides/memory-boundaries.mdindex 4e2a34b56f..6d7fc92a75 100644--- a/docs/guides/memory-boundaries.md+++ b/docs/guides/memory-boundaries.md@@ -163,6 +163,19 @@ after that writer's last write. An older binary that writes without managedpersistence (a classic brain shared by several hosts) is not detected, soupgrade every host before turning the switch on.+<a id="segmented-searchable"></a>+**When a segmented write is searchable.** The receipt of a write that stores a+page in segments says `searchable`. A new page up to 4 MiB, and every rewrite of+a segmented page, is searchable when it commits (`searchable: true`). A larger+new page commits first and builds its chunks and keyword index right after,+about 10 seconds for 20 MB: its receipt says `searchable: "pending"`, with+`searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again+(`get_write_request`, `gbrain write-request -- <id>`). Read it at that interval+until it says `searchable: true`; search finds the page from then on. Until+then, search does not return the page. A quarantined page says+`searchable: false`. `gbrain import` waits for the build and reports+`searchable` in its result the same way.+While the switch is off (unset in this release, set to `off`, or held by anolder writer), new pages are stored inline up to 24 MiB as before.Pages already stored in segments stay readable and exportable; a write thatdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex dfc5a33a4c..dcfe1a741f 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 3224 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.tssrc/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 2062 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); +2 Wave B gem A: a coordinated demotion versions the segmented page before demoting it (createVersion order); lanes compose at 2062+src/core/import-file.ts 2064 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); +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)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/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 422cacfe43..af384c46b1 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -653,6 +653,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: 'A page over 24 MiB imported or synced from its file is no longer stamped `embed_skip` and `content_flag: oversized` for its size: while `content_sanity.bytes_block` is unset, a segmented page is judged against its page ceiling, and the markup check samples its head, middle and tail as it does for any large page. A `content_sanity.bytes_block` set above 24 MiB no longer holds such a file; one set below the page still stops its embedding.' },{ since: 'TBD', text: 'Forget and purge on a page stored in segments now rewrite and re-index only the segments that hold the struck or purged row.' },{ since: 'TBD', text: 'Export accepts a page stored in segments up to the page ceiling (was 32 MiB per page), streams it to disk, and still aborts rather than produce a partial export.' },+ { since: 'TBD', text: 'A write that stores a page in segments says in its receipt whether search sees it: `searchable: true` when it commits (every new page up to 4 MiB and every rewrite), or `searchable: "pending"` for a larger new page while its chunks are built after commit, with `searchable_retry_after_ms` and a `searchable_fix` that reads the receipt again (`get_write_request`) until it says `searchable: true`. A new page up to 4 MiB was previously searchable only once a post-commit build finished.' },+ { since: 'TBD', text: 'Chunks of a page stored in segments keep a Markdown heading with the text after it, so a section appended after a full last chunk re-embeds only its own chunk (was two). Inline pages chunk as before.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex 182872f310..8a419fbfb8 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -72,6 +72,12 @@ export interface ChunkOptions {maxTokens?: number;/** Record each chunk's projected UTF-8 byte span (TextChunk.byte_start/byte_end). Chunk text is unchanged. */spans?: boolean;+ /**+ * A Markdown heading line (or a run of them) joins the running chunk only together with the piece after it;+ * when that piece starts the next chunk, the headings start it too. Segmented pages only (segment-chunks.ts):+ * a section appended after a full last chunk then leaves that chunk's text, and its vector, unchanged.+ */+ headingsLead?: boolean;}export interface TextChunk {@@ -141,7 +147,7 @@ export function chunkProjectedText(stripped: string, opts?: ChunkOptions): TextC// Recursively split, then greedily merge to target sizeconst pieces = recursiveSplit(stripped, 0, chunkSize, 0);- const merged = greedyMerge(pieces, chunkSize);+ const merged = greedyMerge(pieces, chunkSize, opts?.headingsLead === true);const withOverlap = applyOverlap(merged, chunkOverlap);// v0.32.7: hard char cap. Catches pathological CJK + whitespace-less text// that the word-level pipeline can't bound (a single Chinese paragraph can@@ -474,7 +480,10 @@ function splitOnWhitespace(text: string, target: number, base: number): Piece[]* stats grow with it (concatWordStats), so each piece is counted once instead* of recounting the whole chunk on every merge.*/-function greedyMerge(pieces: Piece[], target: number): Run[] {+const HEADING_PIECE = /^#{1,6}[ \t][^\n]*$/;+const isHeadingPiece = (p: Piece) => HEADING_PIECE.test(p.text.trim());++function greedyMerge(pieces: Piece[], target: number, headingsLead = false): Run[] {if (pieces.length === 0) return [];const result: Run[] = [];@@ -486,7 +495,16 @@ function greedyMerge(pieces: Piece[], target: number): Run[] {for (let i = 1; i < pieces.length; i++) {const pieceStats = wordStats(pieces[i].text);const combinedStats = concatWordStats(currentStats, pieceStats);- if (wordCountOf(combinedStats) <= limit) {+ // A run of heading pieces is checked once, at its first piece, together with the piece after the run.+ let leads = false;+ if (headingsLead && isHeadingPiece(pieces[i]) && !isHeadingPiece(pieces[i - 1])) {+ let runStats = combinedStats;+ let j = i + 1;+ for (; j < pieces.length && isHeadingPiece(pieces[j]); j++) runStats = concatWordStats(runStats, wordStats(pieces[j].text));+ if (j < pieces.length) runStats = concatWordStats(runStats, wordStats(pieces[j].text));+ leads = j < pieces.length && wordCountOf(runStats) > limit;+ }+ if (!leads && wordCountOf(combinedStats) <= limit) {// `current` is this loop's own run: extend it in place (copying its segs per merge is quadratic in// pieces per chunk), and grow the last seg when the piece follows it directly in the projected text.const last = current.segs[current.segs.length - 1];diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 79511499d3..1901ca1da3 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -144,6 +144,8 @@ export interface ImportResult {/** Which flag tier fired, when `flagged` (`instruction_like`: the #5575 write gate). */flag_reason?: 'markup_heavy' | 'oversized' | 'instruction_like';gate?: WriteGateAssessment; // #5575: the write-gate assessment, when the caller passed writeGate+ /** Wave B, a segmented write imported outside the coordinator: whether search sees it on return (searchable.ts). */+ searchable?: boolean | 'pending';/** #5050: unchanged content below the safe-chunk fence was re-sealed; chunks left to embed. */resealed?: { pendingChunks: number; pendingChars: number };/**@@ -879,7 +881,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, segmented } : {}),+ apply: applyPrepared, ...(segmented ? { afterCommit: async (target: BrainEngine) => { await segmented.afterCommit(target); }, segmented } : {}),});await maintenanceTransaction(engine, applyPrepared, writeTrustOfGate(opts.writeGate)).catch(async (err: unknown) => {await abortSegmentedStaging(engine, segmented?.prepared);@@ -898,7 +900,7 @@ export async function importFromContent(}throw decorateEmbeddingDimError(err, slug, activeColName);});- await segmented?.afterCommit(engine);+ const searchable = await segmented?.afterCommit(engine);if (postCommitEmbedding && !noEmbed && chunks.length > 0) {@@ -923,7 +925,7 @@ export async function importFromContent(...(pageQuarantined ? { quarantined: true } : {}),...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}),...(typeWarning ? { type_warning: typeWarning } : {}),- ...(embeddingDeferred ? { embedding_deferred: true } : {}), ...fences.fields,+ ...(embeddingDeferred ? { embedding_deferred: true } : {}), ...fences.fields, ...(searchable !== undefined ? { searchable } : {}),};}diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 95273bb392..9d7e87044d 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -121,9 +121,11 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Wintent_kind: typeof row.intent?.kind === 'string' ? row.intent.kind : null, build: (row as { admitter_version?: string | null }).admitter_version ?? null }) : null;const { cliRenderContext, renderAction } = await import('../agent-output.ts');const render = ctx.remote === false ? cliRenderContext() : { transport: 'stdio' as const, isCallable: () => false, preapproved: () => false };+ const { liveSearchable } = await import('../persistence/searchable.ts');return {...publicWriteReceipt(receiptFor(row, facts)),operation: row.operation, source_id: row.source_id, slug: row.slug,+ ...await liveSearchable(ctx, { request_id: row.request_id, state: row.state, source_id: row.source_id, slug: row.slug, searchable: row.outcome?.searchable }),...(mismatch ? { owner_build: mismatch } : {}),...(diagnostic ? { write_error: row.error_code, write_error_message: diagnostic.message, write_error_reason: diagnostic.reason, suggestion: diagnostic.suggestion } : {}),...(terminal ? { diagnosis: { category: terminal.category, code: terminal.code, class: terminal.class, safe_actions: terminal.safe_actions, needs_human: terminal.needs_human,diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.tsindex 072e5f39a4..75e98159be 100644--- a/src/core/page-body/ingest.ts+++ b/src/core/page-body/ingest.ts@@ -22,7 +22,7 @@ import { readManagedMode } from '../persistence/managed-mode.ts';import { maintenanceAttribution, principalAttribution } from '../persistence/attribution.ts';import type { Principal } from '../persistence/model.ts';import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';-import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, STAGE_BATCH_BYTES } from './limits.ts';+import { BODY_LEAD_BYTES, BODY_STAGING_HARD_MS, BODY_STAGING_IDLE_MS, SEGMENTED_CREATE_SEAL_MAX_BYTES, STAGE_BATCH_BYTES } from './limits.ts';import type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,SegmentedBodyColumns, SegmentTextInput } from './types.ts';import { segmentStream, SEGMENTER_VERSION, type StoredRegion } from './segmenter.ts';@@ -79,9 +79,14 @@ export interface PreparedSegmentedBody {newGeneration: number;/** Create only: every manifest row, written in the publication transaction once the page row exists. */createRows: ManifestRowInput[] | null;+ /**+ * Create within SEGMENTED_CREATE_SEAL_MAX_BYTES (or quarantined): the chunk rows, prepared for `slug` and inserted by+ * the publication, which then seals. Null: the create publishes unsealed and its projection runs after commit.+ */+ createChunks: { slug: string; chunks: SegmentChunkInput[] } | null;closeOccurrences: number[];retireChunkOccurrences: number[];- /** Occurrences of the new generation that have no chunk rows after staging (create: all; chunked after publication). */+ /** Occurrences of the new generation that have no chunk rows after staging (a create without `createChunks`: all, chunked after publication). */unchunked: number;body: SegmentedBodyColumns;/** No manifest row changed: the write changes metadata only. */@@ -315,8 +320,11 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, stagingbody_flags: { ...input.flags, has_protected: hasProtected },};if (!input.live) {- return { stagingId, expectedGeneration, newGeneration, createRows: rows, closeOccurrences: [], retireChunkOccurrences: [],- unchunked: rows.length, body, bodyUnchanged: false, rows: { texts, manifest: rows.length, chunks: 0 }, stagedChunkIndexes: [] };+ const createChunks = input.chunking.quarantined || byteStart <= SEGMENTED_CREATE_SEAL_MAX_BYTES ? { slug: input.slug, chunks: [] as SegmentChunkInput[] } : null;+ if (createChunks) await stageOccurrenceChunks(engine, { pageId: 0, sourceId: input.sourceId, slug: input.slug, generation: newGeneration, occurrences: rows,+ title: input.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking, retiredOccurrences: [], hold: createChunks.chunks });+ return { stagingId, expectedGeneration, newGeneration, createRows: rows, createChunks, closeOccurrences: [], retireChunkOccurrences: [],+ unchunked: createChunks ? 0 : rows.length, body, bodyUnchanged: false, rows: { texts, manifest: rows.length, chunks: createChunks?.chunks.length ?? 0 }, stagedChunkIndexes: [] };}if (changed.length) await writes(exec => exec.stageManifestRows(changed));await faultPoint('segmented:manifest_staged', { sourceId: input.sourceId });@@ -327,7 +335,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, stagingawait faultPoint('segmented:chunks_staged', { sourceId: input.sourceId });const kept = new Set(rows.filter((_, i) => matched[i]).map(row => row.occurrenceId));retireChunkOccurrences.push(...chunkable.filter(row => kept.has(row.occurrenceId)).map(row => row.occurrenceId));- return { stagingId, expectedGeneration, newGeneration, createRows: null, closeOccurrences, retireChunkOccurrences,+ return { stagingId, expectedGeneration, newGeneration, createRows: null, createChunks: null, closeOccurrences, retireChunkOccurrences,unchunked: input.chunking.quarantined ? 0 : chunkable.length - chunks.occurrences, body,bodyUnchanged: changed.length === 0 && retireChunkOccurrences.length === 0, rows: { texts, manifest: changed.length, chunks: chunks.rows },stagedChunkIndexes: chunks.indexes };@@ -347,6 +355,12 @@ export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'executreturn rows.filter(row => !chunked.has(row.occurrenceId));}+/**+ * @internal Work stageOccurrenceChunks does, for the projection tests: segment text batches chunked (`batches`) and+ * chunk rows prepared (`chunks`), whoever stages them (a replace's preparation, a create's, or a projection).+ */+export const segmentChunkWork = { batches: 0, chunks: 0 };+/*** Chunk occurrences one text batch at a time (texts read back from* `page_segment_texts`), reuse vectors from the retired occurrences' rows, and@@ -358,7 +372,11 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageIdretiredOccurrences: readonly number[];/** Projection: each batch inserts under the page guard, after re-reading which occurrences still lack rows, so two projections never both chunk one;* a page whose generation moved past `generation` stops the projection before it inserts. */- guarded?: boolean }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {+ guarded?: boolean;+ /** A create's preparation: the chunks are collected here (its page row does not exist yet) and inserted by the publication. */+ hold?: SegmentChunkInput[];+ /** Guarded: runs in each batch's transaction (the projection renews its claim on the page's queue row). */+ renew?: (tx: BrainEngine) => Promise<unknown> }): Promise<{ rows: number; occurrences: number; indexes: number[] }> {if (input.chunking.quarantined || !input.occurrences.length) return { rows: 0, occurrences: 0, indexes: [] };const batchBytes = STAGE_BATCH_BYTES[engine.kind];const fenceBudget = newFenceChunkBudget();@@ -392,7 +410,10 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId}if (chunks.length && input.retiredOccurrences.length) await reuseSegmentChunkVectors(engine, { pageId: input.pageId,retiredOccurrences: input.retiredOccurrences, chunks, title: input.title, corpusGeneration: input.chunking.corpusGeneration, tier: input.chunking.tier });- if (chunks.length && !input.guarded) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));+ segmentChunkWork.batches++;+ segmentChunkWork.chunks += chunks.length;+ if (input.hold) input.hold.push(...chunks);+ else if (chunks.length && !input.guarded) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));let moved = false;if (chunks.length && input.guarded) rows -= chunks.length - await engine.transaction(async tx => {await tx.lockPageKeys([{ sourceId: input.sourceId, slug: input.slug }]);@@ -400,6 +421,7 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageIdif (Number(page?.body_generation) !== input.generation) { moved = true; return 0; }const open = new Set((await occurrencesWithoutChunks(tx, input.pageId, input.generation, batch)).map(row => row.occurrenceId));const still = chunks.filter(chunk => open.has(chunk.occurrence_id));+ await input.renew?.(tx);if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);return still.length;});diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.tsindex ffb7c00485..df360a8e20 100644--- a/src/core/page-body/limits.ts+++ b/src/core/page-body/limits.ts@@ -68,6 +68,16 @@ export const STAGE_BATCH_BYTES: Readonly<Record<'postgres' | 'pglite', number>>*/export const DEFAULT_FLIP_RETIRE_MAX_ROWS = 20_000;+/**+ * A segmented create of at most this many body bytes is searchable when its write commits: it chunks during preparation+ * (outside the transaction, the chunk inputs held in memory) and its publication inserts the chunk rows, one staging+ * statement's worth or a little more (STAGE_BATCH_BYTES), and seals. A larger create publishes unsealed and its projection runs after+ * commit (`searchable: 'pending'` on the receipt). The insert is the part the publication holds the page lock for:+ * about 0.3 s per MB on PGLite and 0.25 s on Postgres (a 20 MB chat page, 8,900 chunk rows): ~1.2 s at this bound,+ * ~7 s at 24 MiB, and 30 s to over a minute at the 128/256 MiB ceilings, with every write to the page waiting behind it.+ */+export const SEGMENTED_CREATE_SEAL_MAX_BYTES = 4 * 1024 ** 2;+/*** Snapshots of an inline page over the inline cap kept per page (Wave A). Each* one is a full copy of the body, so an append-heavy 24 MiB page would otherwisediff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.tsindex 9c6709ad93..769b0172e3 100644--- a/src/core/page-body/projection.ts+++ b/src/core/page-body/projection.ts@@ -8,6 +8,14 @@* projection job for a page left unsealed (crash, deferred retirement), and by* rebuilds.*+ * One process builds a page's projection at a time: it claims the page's+ * queue row (`SEGMENTED_PROJECTION_CLAIM`, renewed with each chunk batch), so+ * a write's post-commit build and the resident's queue route do not both+ * chunk the whole body; a claim left by a dead process lapses after+ * SEGMENTED_PROJECTION_LEASE_SECONDS, and a build that throws releases it+ * at once (the resident's queue route then marks its own failures+ * `rebuild_failed`).+ ** Retirement runs in bounded statements and deletes, as the flip does: rows of* occurrences outside the live generation, inline rows a promotion deferred,* and older duplicates of a live occurrence (a projection that raced a flip).@@ -18,7 +26,7 @@ import type { BrainEngine } from '../engine.ts';import { isQuarantined } from '../quarantine.ts';import { faultPoint } from '../persistence/fault-points.ts';import { sealSegmentedPage } from '../persistence/segmented-apply.ts';-import { PROJECTION_RETRY_READY_SQL } from '../page-state/projections.ts';+import { PROJECTION_RETRY_READY_SQL, SEGMENTED_PROJECTION_CLAIM, SEGMENTED_PROJECTION_LEASE_SECONDS } from '../page-state/projections.ts';import { occurrencesWithoutChunks, stageOccurrenceChunks } from './ingest.ts';import { DEFAULT_FLIP_RETIRE_MAX_ROWS } from './limits.ts';import type { JsonObject } from './types.ts';@@ -56,10 +64,32 @@ async function retireStaleChunks(engine: Pick<BrainEngine, 'executeRaw' | 'kind'}}+const JOB_OF_PAGE = 'source_incarnation=(SELECT incarnation FROM sources WHERE id=$1) AND slug=$2';++/** Claim the page's queue row; false when another process holds it. A page with no queued row is built unclaimed. */+async function claimProjection(engine: Pick<BrainEngine, 'executeRaw'>, ref: { sourceId: string; slug: string }): Promise<boolean> {+ const [job] = await engine.executeRaw<{ claimed: boolean }>(`WITH claimed AS (UPDATE page_projection_jobs SET reason='${SEGMENTED_PROJECTION_CLAIM}', updated_at=now()+ WHERE ${JOB_OF_PAGE} AND NOT (reason='${SEGMENTED_PROJECTION_CLAIM}' AND updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds') RETURNING 1)+ SELECT EXISTS (SELECT 1 FROM claimed) AS claimed WHERE EXISTS (SELECT 1 FROM claimed) OR EXISTS (SELECT 1 FROM page_projection_jobs WHERE ${JOB_OF_PAGE})`,+ [ref.sourceId, ref.slug]);+ return !job || job.claimed;+}+export async function buildSegmentedProjection(engine: BrainEngine, ref: { sourceId: string; slug: string },opts: { expectedRevision?: string } = {}): Promise<SegmentedProjectionResult> {const page = await readProjectionPage(engine, ref);if (!page || (opts.expectedRevision !== undefined && page.knowledge_revision !== opts.expectedRevision)) return { chunks: 0, retired: 0, sealed: false };+ if (page.text_projection_revision !== page.knowledge_revision && !await claimProjection(engine, ref)) return { chunks: 0, retired: 0, sealed: false };+ try {+ return await buildClaimedProjection(engine, ref, page);+ } catch (error) {+ await engine.executeRaw(`UPDATE page_projection_jobs SET reason='canonical_change', updated_at=now() WHERE ${JOB_OF_PAGE} AND reason='${SEGMENTED_PROJECTION_CLAIM}'`,+ [ref.sourceId, ref.slug]).catch(() => undefined);+ throw error;+ }+}++async function buildClaimedProjection(engine: BrainEngine, ref: { sourceId: string; slug: string }, page: ProjectionPage): Promise<SegmentedProjectionResult> {const generation = Number(page.body_generation);const pageId = Number(page.id);const liveRows = await engine.readManifest(pageId);@@ -68,7 +98,8 @@ export async function buildSegmentedProjection(engine: BrainEngine, ref: { sourcconst quarantined = isQuarantined(frontmatter);const unchunked = await occurrencesWithoutChunks(engine, pageId, generation, liveRows);const staged = await stageOccurrenceChunks(engine, { pageId, sourceId: ref.sourceId, slug: ref.slug, generation, occurrences: unchunked, title: page.title,- frontmatter, flags: page.body_flags ?? {}, chunking: { quarantined, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guarded: true });+ frontmatter, flags: page.body_flags ?? {}, chunking: { quarantined, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guarded: true,+ renew: tx => tx.executeRaw(`UPDATE page_projection_jobs SET updated_at=now() WHERE ${JOB_OF_PAGE} AND reason='${SEGMENTED_PROJECTION_CLAIM}'`, [ref.sourceId, ref.slug]) });await faultPoint('segmented:projection_staged', { sourceId: ref.sourceId });const sealed = await engine.transaction(async tx => {await tx.lockPageKeys([{ sourceId: ref.sourceId, slug: ref.slug }]);diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.tsindex 9be7954dfc..fb91b6537b 100644--- a/src/core/page-body/segment-chunks.ts+++ b/src/core/page-body/segment-chunks.ts@@ -85,7 +85,7 @@ export async function prepareSegmentChunks(segment: ChunkableSegment, opts: Segmconst wholeSegment = { raw_byte_start: 0, raw_byte_end: segment.bytes.length };if (projection.trim()) {- for (const c of chunkProjectedText(projection, { maxTokens, spans: true })) {+ for (const c of chunkProjectedText(projection, { maxTokens, spans: true, headingsLead: true })) {if (c.byte_start === undefined || c.byte_end === undefined) {push({ chunk_text: c.text, chunk_source: source, ...wholeSegment });continue;diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsindex be93c739c0..da43e4eba0 100644--- a/src/core/page-body/streamed-import.ts+++ b/src/core/page-body/streamed-import.ts@@ -387,5 +387,6 @@ async function importScanned(engine: BrainEngine, input: { file: FileHandle; bomreturn apply(tx);}, writeTrustOfGate(writeGate)).catch(async error => { await abort(); throw error; });await afterCommit(engine, applied);- return imported;+ const { segmentedPageSearchable } = await import('../persistence/searchable.ts');+ return { ...imported, searchable: disposition.quarantined ? false : await segmentedPageSearchable(engine, sourceId, slug) };}diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 776096c329..4a4edec5e1 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -414,11 +414,20 @@ const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources sconst statisticsDebt = new WeakMap<BrainEngine, { rebuilt: number; rows: number | null }>();/**- * #5401: a failed rebuild waits this long before the resident retries it. One- * fragment over `page_projection_jobs j`, shared by the consumer's idle probe- * and the resident's selector.+ * The queue reason of a segmented page whose projection a process is building (buildSegmentedProjection): the claim+ * holds while its `updated_at`, renewed with each chunk batch, is younger than SEGMENTED_PROJECTION_LEASE_SECONDS.*/-export const PROJECTION_RETRY_READY_SQL = "(j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds')";+export const SEGMENTED_PROJECTION_CLAIM = 'segmented_projecting';+export const SEGMENTED_PROJECTION_LEASE_SECONDS = 60;++/**+ * #5401: a failed rebuild waits this long before the resident retries it, and+ * a segmented projection another process holds is left to it. One fragment+ * over `page_projection_jobs j`, shared by the consumer's idle probe and the+ * resident's selector.+ */+export const PROJECTION_RETRY_READY_SQL = "(j.reason IS DISTINCT FROM 'rebuild_failed' OR j.updated_at<now()-interval '30 seconds')"+ + ` AND NOT (j.reason='${SEGMENTED_PROJECTION_CLAIM}' AND j.updated_at>=now()-interval '${SEGMENTED_PROJECTION_LEASE_SECONDS} seconds')`;export interface ProjectionRebuildFailure { source_id: string; slug: string; reason: string }diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 8fca85d5e4..37a60e4562 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -38,6 +38,7 @@ import { assertRestoreOrigin } from './detached-pages.ts';import { colonSlugWindowsRefusal, isWindowsColonTarget } from './native-file-target.ts';import { publishesDatabaseOnly } from './page-prepare.ts';import { materializedSnapshot } from './segmented-apply.ts';+import { liveSearchable } from './searchable.ts';import { cachedPreadmitBrain, dropPreadmitCache, preadmitReads, preadmitRecheckFailed } from './preadmit-cache.ts';import { pipelined } from '../page-state/transactions.ts';import { isMirrorOnlyPage, sourceMirrorReadOnly } from './mirror-read-only.ts';@@ -182,6 +183,21 @@ export function pendingAwareResponse(ctx: OperationContext, row: WriteRequest):}}+/**+ * A committed reply whose outcome left the projection pending says whether search sees the page now (searchable.ts), in+ * the reply and its `write_request`; `projection: 'pending'` stays only while it still is.+ */+async function withLiveSearchable(ctx: OperationContext, response: Record<string, unknown>): Promise<Record<string, unknown>> {+ if (response.searchable !== 'pending') return response;+ const live = await liveSearchable(ctx, response as Parameters<typeof liveSearchable>[1]);+ const settle = (fields: Record<string, unknown>) => {+ const { projection, ...rest } = fields;+ return { ...(live.searchable === 'pending' ? { projection } : {}), ...rest, ...live };+ };+ const receipt = response.write_request as Record<string, unknown> | undefined;+ return { ...settle(response), ...(receipt ? { write_request: settle(receipt) } : {}) };+}+/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice. */export function emitFenceNotice(ctx: Pick<OperationContext, 'emitNotice'>, response: Record<string, unknown>, slug?: string): void {const report = response.fences_normalized as FencesNormalized | undefined;@@ -209,7 +225,7 @@ export async function submitPageMutation(ctx: OperationContext,// cache could explain drops it and prepares the write once more, uncached, so it ends as it would without it.const cached = await preadmitReads(ctx.engine);let prepared = await preparePageAdmission(cached ? { ...ctx, engine: cached } : ctx, { ...input, params });- if (prepared.prior) return throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false);+ if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));const brainId = cached ? cachedPreadmitBrain(ctx.engine) : undefined;// Phase 4.4: the admission transaction runs on the warm single-write lane when it is free.const admit = (admission: WriteAdmission) => onPersistenceLane(ctx.engine, transaction => admitWrite(ctx.engine, admission, undefined, transaction),@@ -220,10 +236,10 @@ export async function submitPageMutation(ctx: OperationContext,if (!cached || !preadmitRecheckFailed(error)) throw error;dropPreadmitCache(ctx.engine);prepared = await preparePageAdmission(ctx, { ...input, params: { ...params, request_id: prepared.admission.requestId } });- if (prepared.prior) return throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false);+ if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));row = await admit(prepared.admission);}- const response = throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs())), false);+ const response = await withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, row, ctx.config, waitMs())), false));emitFenceNotice(ctx, response, row.slug);return { ...response, ...(prepared.typeWarning ? { type_warning: prepared.typeWarning } : {}), ...(prepared.slugAdvisory ? { slug_advisory: prepared.slugAdvisory } : {}) };}diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex f3a9032348..b107c3369c 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -644,11 +644,13 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequlet lowered: { proposal_ref: string } | null = null;let contested: string[] = [];let projectionPending = false;+ let segmentedWrite = false;if (!noop) {const prior = snapshot ? await storedPageTier(tx, row.source_id, row.slug) : null;// ENG-1: a managed fence edit keeps the page's tier; CEO-12: an agent rewrite that lowers a page files a queue item.const applied = await (isFenceEditWrite(row) ? withTrustKeep(tx, ['pages'], () => ready.apply(tx, lean ? preimage : undefined)) : ready.apply(tx, lean ? preimage : undefined));projectionPending = applied?.segmented?.complete === false;+ segmentedWrite = applied?.segmented !== undefined;lowered = prior ? await recordAgentPageLowering(tx, row, { tier: prior, revision: snapshot!.revision }) : null;// Mandatory metadata shares publication rollback; exact no-ops never heal it. These, and the// projections (facts, takes, timeline rows of the page the import just wrote live), are independent and sent together.@@ -698,6 +700,8 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ...(removedTimeline ? { timeline_rows_removed: timelineRowsRemovedAdvisory(row, removedTimeline) } : {}),status: 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 } : {}),...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/searchable.ts b/src/core/persistence/searchable.tsnew file mode 100644index 0000000000..4e768115cf--- /dev/null+++ b/src/core/persistence/searchable.ts@@ -0,0 +1,51 @@+/**+ * Wave B: when a segmented page write becomes searchable. A segmented write+ * records `searchable` in its committed outcome: `true` when its publication+ * sealed the text projection (every replace with its chunks staged, and every+ * create within SEGMENTED_CREATE_SEAL_MAX_BYTES), `'pending'` when the page+ * published unsealed and its projection is built after commit (a larger+ * create, a deferred retirement), `false` for a quarantined page. A pending+ * outcome is re-read here whenever the receipt is served (the put_page reply,+ * get_write_request): `true` once the page's projection is sealed, else+ * `'pending'` with the poll interval and the receipt read that tells.+ */+import type { OperationContext } from '../ops/contract.ts';+import { cliRenderContext, renderAction, type RenderContext } from '../agent-output.ts';++/** The poll interval for a pending projection: about 4 KB of body per millisecond of building it, within [1 s, 5 s]. */+export function searchableRetryAfterMs(bodyBytes: number): number {+ return Math.min(5_000, Math.max(1_000, Math.round(bodyBytes / 4_000)));+}++/** Whether search sees a segmented page now: its text projection is sealed at its current revision. */+export async function segmentedPageSearchable(engine: OperationContext['engine'], sourceId: string, slug: string): Promise<true | 'pending'> {+ const [page] = await engine.executeRaw<{ sealed: boolean }>(`SELECT text_projection_revision=knowledge_revision AS sealed FROM pages+ WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL`, [sourceId, slug]);+ return page?.sealed ? true : 'pending';+}++/**+ * The fields that replace a committed receipt's `searchable: 'pending'`, read now; empty when the receipt is not a+ * committed write with a pending projection.+ */+export async function liveSearchable(ctx: Pick<OperationContext, 'engine' | 'remote' | 'transport' | 'isCallable'>,+ receipt: { request_id: string; state: string; source_id: string; slug: string; searchable: unknown }): Promise<Record<string, unknown>> {+ if (receipt.state !== 'committed' || receipt.searchable !== 'pending') return {};+ const [page] = await ctx.engine.executeRaw<{ sealed: boolean; body_bytes: string | null }>(`SELECT text_projection_revision=knowledge_revision AS sealed,+ body_bytes::text AS body_bytes FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL`, [receipt.source_id, receipt.slug]);+ if (!page) return { searchable: false };+ if (page.sealed) return { searchable: true };+ const retryAfterMs = searchableRetryAfterMs(Number(page.body_bytes ?? 0));+ const render: RenderContext = ctx.remote === false ? cliRenderContext()+ : { transport: ctx.transport ?? 'stdio', isCallable: ctx.isCallable ?? (() => false), preapproved: () => false };+ return {+ searchable: 'pending',+ searchable_retry_after_ms: retryAfterMs,+ searchable_fix: renderAction({+ argv: ['gbrain', 'write-request', '--', receipt.request_id], mcp: { tool: 'get_write_request', arguments: { request_id: receipt.request_id } },+ consent: [], actor: 'agent', requires_exclusive: false,+ why: `The write committed, but search does not see ${receipt.slug} yet: its chunks and keyword index are built after commit. `+ + `Read this receipt again after ${retryAfterMs} ms; searchable turns true once search sees the page.`,+ }, render),+ };+}diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsindex 7955aff769..eabaf6fd4b 100644--- a/src/core/persistence/segmented-apply.ts+++ b/src/core/persistence/segmented-apply.ts@@ -5,9 +5,11 @@* everything heavy was staged by `prepareSegmentedBody`.** - Create: the page row (`createSegmentedPageShell`), its manifest rows and- * the flip 0 -> 1. The text projection stays unsealed (chunks of a page row- * that did not exist could not be staged); `buildSegmentedProjection` chunks- * it after commit, or the projection queue does after a crash.+ * the flip 0 -> 1. A create within SEGMENTED_CREATE_SEAL_MAX_BYTES inserts+ * the chunk rows its preparation held (`createChunks`) and the caller seals;+ * a larger one stays unsealed (chunks of a page row that did not exist could+ * not be staged) and `buildSegmentedProjection` chunks it after commit, or+ * the projection queue does after a crash.* - Replace (and promotion from inline): the flip G -> G+1 over the staged* rows, dropping chunk rows a dead preparation left under G+1; the caller* seals as its last revision-changing step when every occurrence has chunks@@ -32,6 +34,7 @@ import { pageSearchVectorSql } from '../fts-language.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { overlayCanonicalBodies, readPageSnapshot } from '../page-state/snapshot.ts';import { faultPoint } from './fault-points.ts';+import { segmentedPageSearchable } from './searchable.ts';import { stableJson } from './digest.ts';const BODY_KEYS = new Set(['compiled_truth', 'timeline', 'content']);@@ -147,9 +150,12 @@ export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyIretireInlineChunks: input.promotion, retireMaxRows: input.retireMaxRows, body: prepared.body, meta: input.meta });if (!prepared.createRows) await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND body_generation=$2 AND NOT (chunk_index = ANY($3::int[]))',[pageId, prepared.newGeneration, prepared.stagedChunkIndexes]);+ const createChunks = prepared.createChunks?.slug === input.slug ? prepared.createChunks.chunks : null;+ if (createChunks?.length) await tx.stageSegmentChunks(pageId, prepared.newGeneration, createChunks);await faultPoint('segmented:flipped', { sourceId: input.sourceId });await tx.setBodyStagingState(prepared.stagingId, 'committed', { commitRequestId: input.requestId ?? null });- return { pageId, complete: !prepared.createRows && !flip.retireDeferred && prepared.unchunked === 0, retireDeferred: flip.retireDeferred };+ const chunked = prepared.createRows ? createChunks !== null : prepared.unchunked === 0;+ return { pageId, complete: chunked && !flip.retireDeferred, retireDeferred: flip.retireDeferred };}/**@@ -184,8 +190,11 @@ export interface SegmentedImport {/** Set by apply. */applied: SegmentedApplied | null;apply(tx: BrainEngine, meta: SegmentedPageMeta, contextual: { mode: string; corpusGeneration: string | null }): Promise<SegmentedApplied>;- /** After commit: chunk and seal a page the apply left unsealed (create, deferred retirement); the projection queue retries a failure. */- afterCommit(engine: BrainEngine): Promise<void>;+ /**+ * After commit: chunk and seal a page the apply left unsealed (a create over SEGMENTED_CREATE_SEAL_MAX_BYTES, a deferred+ * retirement); the projection queue retries a failure. Resolves to whether search sees the page now (undefined: not applied).+ */+ afterCommit(engine: BrainEngine): Promise<boolean | 'pending' | undefined>;}/**@@ -223,10 +232,11 @@ export async function stageSegmentedImport(engine: BrainEngine, input: { slug: sreturn staged.applied;},afterCommit: async target => {- if (!staged.applied) return;+ if (!staged.applied) return undefined;if (!staged.applied.complete) await buildSegmentedProjection(target, { sourceId: input.sourceId, slug: input.slug }).catch(() => undefined);const pageId = staged.applied.pageId;await segmentWriteScope(target, input.sourceId).then(writes => writes(exec => exec.sweepSegments({ pageId }))).catch(() => undefined);+ return input.chunking.quarantined ? false : segmentedPageSearchable(target, input.sourceId, input.slug);} };return staged;}diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex 33ae24ad31..fe2ddee3fb 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -4591,6 +4591,7 @@"quarantined?: boolean | undefined","refusal?: ContentRefusal | undefined","resealed?: { pendingChunks: number; pendingChars: number; } | undefined",+ "searchable?: boolean | \"pending\" | undefined","skip_reason?: \"purged_content\" | \"content_rejected\" | \"file_too_large\" | \"frontmatter_slug_conflict\" | \"invalid_fence\" | \"invalid_frontmatter\" | \"parser_regression\" | \"rename_held\" | \"write_gate_rejected\" | \"malformed_path\" | \"slug_collision\" | undefined","slug: string","status: \"error\" | \"imported\" | \"skipped\"",diff --git a/test/large-pages/flip-crash.serial.test.ts b/test/large-pages/flip-crash.serial.test.tsindex 9a8b0bcfc4..2f48ea9023 100644--- a/test/large-pages/flip-crash.serial.test.ts+++ b/test/large-pages/flip-crash.serial.test.ts@@ -18,7 +18,7 @@ import { importFromContent } from '../../src/core/import-file.ts';import { installFaultHook, type FaultPoint } from '../../src/core/persistence/fault-points.ts';import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';import { rebuildPendingSegmentedProjections } from '../../src/core/page-body/projection.ts';-import { BODY_STAGING_HARD_MS } from '../../src/core/page-body/limits.ts';+import { BODY_STAGING_HARD_MS, SEGMENTED_CREATE_SEAL_MAX_BYTES } from '../../src/core/page-body/limits.ts';import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';let engine: PGLiteEngine;@@ -94,7 +94,7 @@ describe('replace: a crash at any step leaves the previous generation', () => {describe('create: a crash after the projection staged its chunks', () => {test('the page publishes unsealed, the projection queue seals it, and a second rebuild adds nothing', async () => {- const created = conversationPage(2 * 1024 * 1024, { seed: 31, needles: [{ at: 0.9, word: NEEDLE }] });+ const created = conversationPage(SEGMENTED_CREATE_SEAL_MAX_BYTES + 256 * 1024, { seed: 31, needles: [{ at: 0.9, word: NEEDLE }] });crashAt('segmented:projection_staged');const result = await importFromContent(engine, 'notes/fresh', created, { sourceId: 'default', noEmbed: true });installFaultHook(undefined);@@ -124,7 +124,7 @@ describe('create: a crash after the projection staged its chunks', () => {describe('replace of a page whose projection never ran', () => {test('the rewrite chunks every kept occurrence with the flip and seals the page', async () => {- const created = conversationPage(2 * 1024 * 1024, { seed: 41, needles: [{ at: 0.2, word: NEEDLE }] });+ const created = conversationPage(SEGMENTED_CREATE_SEAL_MAX_BYTES + 256 * 1024, { seed: 41, needles: [{ at: 0.2, word: NEEDLE }] });crashAt('segmented:projection_staged');await importFromContent(engine, 'notes/unchunked', created, { sourceId: 'default', noEmbed: true });installFaultHook(undefined);diff --git a/test/large-pages/segmented-append-reembed.test.ts b/test/large-pages/segmented-append-reembed.test.tsnew file mode 100644index 0000000000..3ddf9438dd--- /dev/null+++ b/test/large-pages/segmented-append-reembed.test.ts@@ -0,0 +1,91 @@+/**+ * An append to a segmented page re-embeds one chunk when it starts a new+ * section after a full last chunk (N14 large-page fidelity, Wave B PR 1: the+ * 2 MB chat's 1 KB append re-embedded 2 chunks).+ *+ * 1. Protects: the segment chunker keeps a Markdown heading with the piece+ * after it (chunkProjectedText `headingsLead`), so a day appended after a+ * last chunk with no room for the day's text leaves that chunk's text and+ * vector unchanged: the append embeds exactly its own chunk.+ * 2. Fails when: the greedy merge packs the new day's heading into the+ * previous chunk (it fits the word budget alone), which rewrites that+ * chunk's text and re-embeds it next to the new day's chunk.+ * 3. Existing coverage: segment-chunks.test.ts pins a one-segment page+ * against prepareMarkdownChunks; inline-chunks-golden.test.ts pins inline+ * pages, which keep the plain greedy merge.+ * 4. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { runEmbedCore } from '../../src/commands/embed.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { chunkProjectedText } from '../../src/core/chunkers/recursive.ts';+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const WORDS = ['launch', 'pricing', 'roadmap', 'hiring', 'metrics', 'retention', 'design', 'latency', 'budget', 'customer'];+/** One paragraph of exactly 100 words, unique per day and paragraph. */+const paragraph = (day: number, k: number) =>+ [`day${day}`, `para${k}`, ...Array.from({ length: 98 }, (_, i) => WORDS[(day * 7 + k * 3 + i) % WORDS.length])].join(' ') + '.';+/** A day: its heading and four paragraphs (403 words), so a chunk holds one day and has room for the next heading alone. */+const day = (d: number) => `## Day ${d}\n\n${[1, 2, 3, 4].map(k => paragraph(d, k)).join('\n\n')}\n\n`;++describe('headingsLead (pure)', () => {+ test('the next section\'s heading starts the next chunk; without the option it ends the previous one', () => {+ const text = day(1) + day(2) + day(3);+ const plain = chunkProjectedText(text, { chunkOverlap: 1 }).map(c => c.text);+ const leading = chunkProjectedText(text, { chunkOverlap: 1, headingsLead: true }).map(c => c.text);+ expect(plain[0]!.trimEnd().endsWith('## Day 2')).toBe(true);+ expect(leading[0]!.trimEnd().endsWith('## Day 2')).toBe(false);+ expect(leading[1]).toContain('## Day 2\n\nday2 para1');+ expect(leading.length).toBe(plain.length);+ });+});++for (const kind of testBackends()) {+ describe(`segmented append re-embeds one chunk (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const embedded: string[] = [];++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ const dims = (await resolveActiveEmbeddingColumnFromEngine(engine)).dimensions;+ await engine.setConfig('pages.segmented_storage', 'on');+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embedded.push(...values);+ return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };+ }) as never);+ }, 120_000);+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await close?.(); });++ test('a day appended after a full last chunk embeds only its own chunk', async () => {+ let body = '';+ let days = 0;+ while (Buffer.byteLength(body) < 1_300_000) body += day(++days);+ const slug = 'notes/append-reembed';+ await importFromContent(engine, slug, `---\ntitle: Daily log\ntype: note\n---\n\n${body}`, { noEmbed: true });+ const [page] = await engine.executeRaw<{ body_storage: string; sealed: boolean }>(+ 'SELECT body_storage, text_projection_revision = knowledge_revision AS sealed FROM pages WHERE slug = $1', [slug]);+ expect(page).toEqual({ body_storage: 'segmented', sealed: true });+ await runEmbedCore(engine, { stale: true, quiet: true });+ expect(embedded.length).toBeGreaterThan(100);++ embedded.length = 0;+ await importFromContent(engine, slug, `---\ntitle: Daily log\ntype: note\n---\n\n${body}${day(days + 1)}`, { noEmbed: true });+ await runEmbedCore(engine, { stale: true, quiet: true });+ expect(embedded.length).toBe(1);+ expect(embedded[0]).toContain(`## Day ${days + 1}`);+ }, 300_000);+ });+}diff --git a/test/large-pages/segmented-create-searchable.test.ts b/test/large-pages/segmented-create-searchable.test.tsnew file mode 100644index 0000000000..9c91e72d1e--- /dev/null+++ b/test/large-pages/segmented-create-searchable.test.ts@@ -0,0 +1,149 @@+/**+ * When a new segmented page becomes searchable (N14 large-page fidelity,+ * Wave B PR 1: a 20 MB create replied `write_pending`, then took 9.3 s more+ * to become searchable, with nothing in the receipt saying so).+ *+ * 1. Protects: a create within SEGMENTED_CREATE_SEAL_MAX_BYTES chunks during+ * preparation and seals in its publication, so the put_page reply says+ * `searchable: true` and keyword search finds text from its last segment+ * as soon as the call returns, with no post-commit projection; a larger+ * create's receipt says `searchable: 'pending'` with the poll interval and+ * the get_write_request read that tells, and that read turns+ * `searchable: true` exactly when search finds the page; one projection+ * builds it (the write's post-commit build claims the page's queue row, so+ * the resident's queue route does not chunk it a second time). A create+ * within the bound that dies inside its publication leaves nothing behind.+ * 2. Fails when: a small create publishes unsealed (its reply would depend on+ * the post-commit projection beating the reply deadline), the receipt has+ * no `searchable` contract, a receipt claims searchable before search sees+ * the page, or two projections chunk the same body.+ * 3. Existing coverage: segmented-embedding-paths.test.ts covers an unsealed+ * create recovered by the projection queue and `embed`.+ * 4. Runs on PGLite, and on Postgres when DATABASE_URL is set.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { registerLocalWriter, withVerifiedLocalRegistration } from '../../src/core/persistence/identity.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { installFaultHook } from '../../src/core/persistence/fault-points.ts';+import { segmentChunkWork } from '../../src/core/page-body/ingest.ts';+import { SEGMENTED_CREATE_SEAL_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { withEnv } from '../helpers/with-env.ts';+import { testBackends } from '../helpers/test-backends.ts';++const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-searchable-'));+const page = (bytes: number, needle: string) => `---\ntitle: Group chat\ntype: note\n---\n\n${conversationBody(bytes, { seed: 7, needles: [{ at: 0.995, word: needle }] })}\n`;++for (const kind of testBackends()) {+ describe(`a new segmented page is searchable when its receipt says so (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ }, 120_000);+ afterAll(async () => {+ await withEnv({ GBRAIN_HOME: home }, async () => { await disposePersistenceConsumer(engine); await close?.(); });+ });+ beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', 'on');+ });+ afterEach(() => installFaultHook(undefined));++ const call = (name: string, params: Record<string, unknown>) => withEnv({ GBRAIN_HOME: home }, async () => {+ const registration = await registerLocalWriter(engine, 'cli');+ const response = await withVerifiedLocalRegistration(engine, registration, () => dispatchToolCall(engine, name, params,+ { remote: false, config: { engine: engine.kind }, sourceId: 'default', logger: { info() {}, warn() {}, error() {} } } as never));+ return JSON.parse((response.content[0] as { text: string }).text) as Record<string, unknown>;+ });+ const found = async (needle: string, slug: string) => (await engine.searchKeyword(needle)).some(hit => hit.slug === slug);+ const pageChunks = async (slug: string) => Number((await engine.executeRaw<{ n: number }>(+ "SELECT count(*)::int AS n FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE p.source_id='default' AND p.slug=$1", [slug]))[0]!.n);++ test('a create within the inline-seal bound is searchable when put_page returns, with no post-commit projection', async () => {+ const slug = 'chats/inline-sealed';+ const needle = `zzsealed${kind}`;+ const content = page(2_000_000, needle);+ expect(Buffer.byteLength(content)).toBeLessThan(SEGMENTED_CREATE_SEAL_MAX_BYTES);+ let projections = 0;+ installFaultHook(point => { if (point === 'segmented:projection_staged') { projections++; throw new Error('post-commit projection blocked'); } });+ const reply = await call('put_page', { slug, content, request_id: randomUUID() });+ expect(reply.state).toBe('committed');+ expect(reply.searchable).toBe(true);+ expect(reply.projection).toBeUndefined();+ expect(await found(needle, slug)).toBe(true);+ expect(projections).toBe(0);+ expect(reply.chunks).toBe(await pageChunks(slug));+ }, 120_000);++ test('a create within the bound that dies inside its publication leaves no page and no chunk rows; its retry is searchable', async () => {+ const slug = 'chats/crashed-create';+ const needle = `zzcrashed${kind}`;+ const content = page(1_500_000, needle);+ installFaultHook(point => { if (point === 'segmented:flipped') throw new Error('publication died'); });+ await expect(importFromContent(engine, slug, content, { sourceId: 'default', noEmbed: true })).rejects.toThrow('publication died');+ installFaultHook(undefined);+ expect(await engine.executeRaw("SELECT 1 FROM pages WHERE source_id='default' AND slug=$1", [slug])).toEqual([]);+ expect(await engine.executeRaw('SELECT 1 FROM content_chunks c LEFT JOIN pages p ON p.id=c.page_id WHERE p.id IS NULL')).toEqual([]);+ expect(await found(needle, slug)).toBe(false);+ const retried = await importFromContent(engine, slug, content, { sourceId: 'default', noEmbed: true });+ expect(retried.searchable).toBe(true);+ expect(await found(needle, slug)).toBe(true);+ }, 120_000);++ test('a larger create says pending, and the documented wait reaches searchable; one projection chunks it', async () => {+ const slug = 'chats/projected';+ const needle = `zzpending${kind}`;+ const content = page(SEGMENTED_CREATE_SEAL_MAX_BYTES + 512 * 1024, needle);+ let release!: () => void;+ const held = new Promise<void>(resolve => { release = resolve; });+ let projections = 0;+ installFaultHook(async point => { if (point === 'segmented:projection_staged') { projections++; await held; } });+ segmentChunkWork.chunks = 0;+ const requestId = randomUUID();+ const reply = await call('put_page', { slug, content, request_id: requestId, wait_ms: 100 });+ expect(reply.searchable === undefined || reply.searchable === 'pending').toBe(true);++ let receipt = await call('get_write_request', { request_id: requestId });+ for (let i = 0; receipt.state !== 'committed' && i < 600; i++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ receipt = await call('get_write_request', { request_id: requestId });+ }+ expect(receipt.state).toBe('committed');+ expect(receipt.searchable).toBe('pending');+ expect(await found(needle, slug)).toBe(false);+ expect(receipt.searchable_retry_after_ms).toBeGreaterThanOrEqual(1_000);+ const fix = receipt.searchable_fix as { argv: string[]; next: string; mcp?: unknown };+ expect(fix.argv).toEqual(['gbrain', 'write-request', '--', requestId]);+ expect(fix.next).toBe('run');++ release();+ for (let i = 0; receipt.searchable === 'pending' && i < 600; i++) {+ await new Promise(resolve => setTimeout(resolve, 100));+ const hit = await found(needle, slug);+ receipt = await call('get_write_request', { request_id: requestId });+ if (hit) expect(receipt.searchable).toBe(true);+ }+ expect(receipt.searchable).toBe(true);+ expect(await found(needle, slug)).toBe(true);+ expect(projections).toBe(1);+ expect(segmentChunkWork.chunks).toBe(await pageChunks(slug));+ }, 180_000);+ });+}diff --git a/test/large-pages/segmented-embedding-paths.test.ts b/test/large-pages/segmented-embedding-paths.test.tsindex 224800937f..781dfe9e71 100644--- a/test/large-pages/segmented-embedding-paths.test.ts+++ b/test/large-pages/segmented-embedding-paths.test.ts@@ -26,7 +26,7 @@ import { importFromContent } from '../../src/core/import-file.ts';import { prepareEmbeddingProjections } from '../../src/core/embedding-readiness.ts';import { countSegmentedEmbedRows, embedSegmentedPage, readSegmentedEmbedPage } from '../../src/core/page-body/segmented-embedding.ts';import { estimatePageEmbedUsd, holdPageEmbedding, listBudgetLimitedPages, PAGE_EMBED_CAP_KEY, readPageSizeStates } from '../../src/core/page-embedding-budget.ts';-import { PAGE_INLINE_MAX_BYTES, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, SEGMENTED_PROMOTE_ABOVE_BYTES } from '../../src/core/page-body/limits.ts';+import { PAGE_INLINE_MAX_BYTES, SEGMENTED_CREATE_SEAL_MAX_BYTES, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, SEGMENTED_PROMOTE_ABOVE_BYTES } from '../../src/core/page-body/limits.ts';import { installFaultHook } from '../../src/core/persistence/fault-points.ts';import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';import { conversationPage } from '../helpers/conversation-page.ts';@@ -160,7 +160,7 @@ for (const kind of testBackends()) {const UNSEALED = 'notes/unsealed';beforeEach(async () => {installFaultHook(point => { if (point === 'segmented:projection_staged') throw new Error('projection died'); });- await importFromContent(engine, UNSEALED, conversationPage(SEGMENTED_PROMOTE_ABOVE_BYTES + 128 * 1024, { seed: 9 }), { sourceId: 'default', noEmbed: true });+ await importFromContent(engine, UNSEALED, conversationPage(SEGMENTED_CREATE_SEAL_MAX_BYTES + 128 * 1024, { seed: 9 }), { sourceId: 'default', noEmbed: true });installFaultHook(undefined);const page = await segmentedPageRow(engine, UNSEALED);await engine.executeRaw('DELETE FROM content_chunks WHERE page_id = $1', [page.id]);diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 51f253c6c4..bb83430999 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -78,7 +78,9 @@ test/large-pages/remote-get-page-privacy.test.tstest/large-pages/remote-window-privacy.test.tstest/large-pages/sealed-segmented-search.test.tstest/large-pages/segment-vector-reuse.test.ts+test/large-pages/segmented-append-reembed.test.tstest/large-pages/segmented-body-unreachable.test.ts+test/large-pages/segmented-create-searchable.test.tstest/large-pages/segmented-derived-parity.test.tstest/large-pages/segmented-derived-passes.test.tstest/large-pages/segmented-derived-work.test.ts