Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B lane 1d: segmented stage + generation flip on the string write path, streamed import over the single-string ceiling, projection route, GC hooks, tests and bench
garrytanefb77a70bb1a
diff --git a/scripts/bench-large-pages.ts b/scripts/bench-large-pages.tsnew file mode 100644index 0000000000..7abfc5df5d--- /dev/null+++ b/scripts/bench-large-pages.ts@@ -0,0 +1,172 @@+/**+ * Wave B large-page bench: one seeded conversation-like page of `--size`+ * bytes through the streamed segmented import (`pages.segmented_storage` on,+ * embeddings off), on PGLite or Postgres. Prints one JSON summary:+ *+ * - `ingest_ms`: wall time of the streamed import (pass 1, pass 2, staging,+ * flip, projection), no provider calls.+ * - `rss`: peak RSS of a fresh child process ingesting `--size` and one+ * ingesting 10 MiB through the same path, and their difference (the slope:+ * ingest memory must not grow with the page).+ * - `rows`: segment texts, live manifest rows and chunk rows the ingest wrote.+ * - `append_10kb`: time and rows written by re-importing the file with 10 KB+ * appended (only the tail should be restaged).+ * - `concurrent_small_put`: latency of small page writes (the put_page import+ * core, `importFromContent`) issued back to back while the large ingest runs.+ *+ * Run it under a memory cap so a regression fails instead of swapping:+ * sudo systemd-run --scope -p MemoryMax=3G bun scripts/bench-large-pages.ts --size 100MB+ * sudo systemd-run --scope -p MemoryMax=3G env DATABASE_URL=postgresql://... bun scripts/bench-large-pages.ts --size 100MB --engine postgres+ * Flags: --size <N>[KB|MB|GB] (default 100MB), --engine pglite|postgres (default pglite; postgres reads DATABASE_URL), --json.+ */+import { spawnSync } from 'node:child_process';+import { appendFileSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../src/core/engine.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { readPageBodyPolicy } from '../src/core/page-body/limits.ts';+import { importStreamedMarkdownFile } from '../src/core/page-body/streamed-import.ts';+import { conversationBody, conversationPage } from '../test/helpers/conversation-page.ts';++const SLUG = 'bench/large-page';++function arg(name: string, fallback: string): string {+ const at = process.argv.indexOf(name);+ return at >= 0 && process.argv[at + 1] ? process.argv[at + 1]! : fallback;+}++function parseSize(raw: string): number {+ const match = /^(\d+(?:\.\d+)?)\s*(KB|MB|GB|B)?$/i.exec(raw.trim());+ if (!match) throw new Error(`--size ${raw}: expected a number with KB, MB or GB`);+ const unit = { B: 1, KB: 1024, MB: 1024 ** 2, GB: 1024 ** 3 }[(match[2] ?? 'B').toUpperCase() as 'B' | 'KB' | 'MB' | 'GB'];+ return Math.round(Number(match[1]) * unit);+}++async function openEngine(kind: string, dir: string): Promise<BrainEngine> {+ if (kind === 'postgres') {+ const url = process.env.DATABASE_URL;+ if (!url) throw new Error('--engine postgres needs DATABASE_URL (a disposable database: the bench deletes its page).');+ const { PostgresEngine } = await import('../src/core/postgres-engine.ts');+ const engine = new PostgresEngine();+ await engine.connect({ database_url: url });+ await engine.initSchema();+ return engine;+ }+ const { PGLiteEngine } = await import('../src/core/pglite-engine.ts');+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: join(dir, 'brain.pglite') });+ await engine.initSchema();+ return engine;+}++async function count(engine: BrainEngine, sql: string, params: unknown[]): Promise<number> {+ const [row] = await engine.executeRaw<{ n: number | string }>(sql, params);+ return Number(row?.n ?? 0);+}++async function pageRows(engine: BrainEngine) {+ const [page] = await engine.executeRaw<{ id: number; body_generation: number | string }>('SELECT id, body_generation FROM pages WHERE slug=$1', [SLUG]);+ if (!page) throw new Error('the bench page was not imported');+ const id = Number(page.id);+ const generation = Number(page.body_generation);+ return {+ generation,+ texts: await count(engine, 'SELECT count(*) AS n FROM page_segment_texts WHERE source_id=$1', ['default']),+ manifest: await count(engine, 'SELECT count(*) AS n FROM page_body_manifest WHERE page_id=$1 AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2)', [id, generation]),+ manifestAtGeneration: await count(engine, 'SELECT count(*) AS n FROM page_body_manifest WHERE page_id=$1 AND gen_from=$2', [id, generation]),+ chunks: await count(engine, 'SELECT count(*) AS n FROM content_chunks WHERE page_id=$1 AND retired_generation IS NULL', [id]),+ chunksAtGeneration: await count(engine, 'SELECT count(*) AS n FROM content_chunks WHERE page_id=$1 AND body_generation=$2', [id, generation]),+ };+}++async function ingest(engine: BrainEngine, file: string) {+ const stat = statSync(file);+ const policy = await readPageBodyPolicy(engine);+ if (stat.size > policy.maxBytes) throw new Error(`--size ${stat.size} is over this engine's ceiling ${policy.maxBytes} (pages.max_bytes).`);+ const result = await importStreamedMarkdownFile(engine, file, `${SLUG}.md`, { noEmbed: true }, stat, policy);+ if (result.status !== 'imported') throw new Error(`the bench page was not imported: ${result.error ?? result.status}`);+ return result;+}++const round = (n: number) => Math.round(n * 10) / 10;++/** Child mode: ingest `--file` in a fresh process (the parent generated it) and report its peak RSS. */+async function child(file: string, kind: string): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-bench-large-'));+ const engine = await openEngine(kind, dir);+ try {+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1', [SLUG]);+ await ingest(engine, file);+ process.stdout.write(JSON.stringify({ peak_rss_bytes: process.resourceUsage().maxRSS * 1024 }) + '\n');+ } finally {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ }+}++function childRss(file: string, kind: string): number {+ const run = spawnSync(process.execPath, [import.meta.path, '--child', file, '--engine', kind], { encoding: 'utf8', env: process.env, maxBuffer: 1 << 20 });+ if (run.status !== 0) throw new Error(`child ingest of ${file} failed:\n${run.stderr}`);+ return JSON.parse(run.stdout.trim().split('\n').pop()!).peak_rss_bytes;+}++async function main(): Promise<void> {+ const size = parseSize(arg('--size', '100MB'));+ const kind = arg('--engine', 'pglite');+ if (process.argv.includes('--child')) return child(arg('--child', ''), kind);++ const dir = mkdtempSync(join(tmpdir(), 'gbrain-bench-large-'));+ const engine = await openEngine(kind, dir);+ try {+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.executeRaw('DELETE FROM pages WHERE slug=$1 OR slug LIKE $2', [SLUG, 'bench/small-%']);+ const file = join(dir, 'page.md');+ writeFileSync(file, conversationPage(size, { seed: 1 }));++ const latencies: number[] = [];+ let ingesting = true;+ const small = (async () => {+ for (let i = 0; ingesting; i++) {+ const t0 = performance.now();+ await importFromContent(engine, `bench/small-${i % 50}`, `---\ntitle: Small ${i}\ntype: note\n---\n\nA short note, revision ${i}.\n`, { sourceId: 'default', noEmbed: true });+ latencies.push(performance.now() - t0);+ }+ })();+ const t0 = performance.now();+ await ingest(engine, file);+ const ingestMs = performance.now() - t0;+ ingesting = false;+ await small;+ const rows = await pageRows(engine);++ appendFileSync(file, `\n\n${conversationBody(10 * 1024, { seed: 2 })}\n`);+ const t1 = performance.now();+ await ingest(engine, file);+ const appendMs = performance.now() - t1;+ const appended = await pageRows(engine);++ latencies.sort((a, b) => a - b);+ const pct = (p: number) => latencies.length ? round(latencies[Math.min(latencies.length - 1, Math.floor(latencies.length * p))]!) : null;+ const reference = join(dir, 'page-10mib.md');+ writeFileSync(file, conversationPage(size, { seed: 1 }));+ writeFileSync(reference, conversationPage(10 * 1024 * 1024, { seed: 1 }));+ const rssLarge = childRss(file, kind);+ const rssSmall = childRss(reference, kind);+ const report = {+ engine: kind, size_bytes: statSync(file).size, ingest_ms: round(ingestMs),+ rss: { peak_bytes: rssLarge, peak_10mib_bytes: rssSmall, slope_bytes: rssLarge - rssSmall },+ rows: { texts: rows.texts, manifest: rows.manifest, chunks: rows.chunks },+ append_10kb: { ms: round(appendMs), texts: appended.texts - rows.texts, manifest: appended.manifestAtGeneration, chunks: appended.chunksAtGeneration },+ concurrent_small_put: { writes: latencies.length, p50_ms: pct(0.5), p95_ms: pct(0.95), max_ms: pct(1) },+ };+ if (process.argv.includes('--json')) process.stdout.write(JSON.stringify(report) + '\n');+ else process.stdout.write(JSON.stringify(report, null, 2) + '\n');+ } finally {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+ }+}++await main();diff --git a/scripts/function-size-baseline.tsv b/scripts/function-size-baseline.tsvindex 2b98089d9a..90da712807 100644--- a/scripts/function-size-baseline.tsv+++ b/scripts/function-size-baseline.tsv@@ -19,7 +19,7 @@ src/commands/eval-longmemeval.ts runEvalLongMemEval 740 seed: W5 baseline, refacsrc/commands/extract-conversation-facts.ts processPage 320 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5918: one read of the page's conversation_segment_gap_minutes shared by both splitIntoSegments calls (validation lives in pageSegmentGapMinutes); +12 fix wave 9 lane P (#5025, D-N2): not-extractable skip call (decision in facts/conversation-skip.ts) and the email-thread segment gapsrc/commands/extract-conversation-facts.ts runExtractConversationFactsCore 355 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 #5757: managed flag threaded into ExtractCoreState; +4 #5823: shared default-cap wiring and structured budget reason/model; decision logic is in facts/conversation-budget.ts; +2 #5330: strict-eligibility read and the enumeration filter through the shared predicate (rule lives in facts/conversation-types.ts); lowered to 355 at the wave-9 follow-ups merge (zero result via emptyExtractConversationFactsResult)src/commands/extract.ts runExtract 398 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/commands/import.ts runImport 972 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts)+src/commands/import.ts runImport 973 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +4 GBRA-40 F4b: planner-stats refresh every import.analyze_every_pages files (logic in planner-stats.ts); +6 #5988: onFileResult hook so full sync holds content refusals (logic in commands/sync/holds.ts); +3 #5988: heldPaths skip so a full sync never imports a rename destination it held this run (logic in commands/sync/holds.ts); +1 Wave B lane 1d (TODO wave-b PR 1): reads the segmented-storage policy once per run for the streamed import of files over the single-string ceilingsrc/commands/mcp-expose.ts runPublish 443 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/migrate-engine.ts runMigrateEngine 405 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)src/commands/serve.ts installStdioLifecycle 323 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +7 GBRA-40 Lane D: facts drain install call and its shutdown stop (logic in installFactsDrain); +1 engine graduation (GBRA-50 G3): onShutdownReady hook for the graduation hand-off (logic in installGraduationHandoff)@@ -39,7 +39,7 @@ src/core/cycle/synthesize-concepts.ts runPhaseSynthesizeConcepts 498 seed: W5 basrc/core/cycle/synthesize.ts runPhaseSynthesizeInner 1048 +1 #5575 I2: output refs take their transcript taint before the provenance stamp (the stamp line stays the signal-guarded literal cycle-abort pins); seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 #5854: publish_pending from postprocess, a pending summary publish deferred instead of failing the phase; +1 fix wave 11 #6160: oneshot_task_prefixes on the child job datasrc/core/embed-stale.ts embedStaleForSource 303 TODO: large-pages A9/T3: per-page spend cap meters each page in embedOneKey (logic in core/page-embedding-budget.ts meterStaleBatch/spendGrant)src/core/facts/backstop.ts runPipelineBodyInner 358 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1)-src/core/import-file.ts importFromContent 671 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker)+src/core/import-file.ts importFromContent 687 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +2 wave 8 lane D1 #5158: key-order fallback equality and legacy-hash ordering; lowered to 807 (#5988: screen and sanity config peeled to core/import-screen.ts); +1 #6007: the prepared apply reports its written page and seal (PreparedImportApplied) so put_page skips a re-read and a second seal; +1 #5333: embed-skip transition defeats the unchanged fast paths (the stale-marker clear stays inside the sanity block); +3 #6188: Tier 1 fence step in place before the hidden-row merge (logic in fence-repair/import-step.ts); -146 #5575: content-sanity/write-gate disposition moved to import-screen.ts settleContentDisposition; +4 TODO: large-pages A6/T33: a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors and embeds through the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); +16 Wave B lane 1d (TODO wave-b PR 1): a body above the inline threshold takes the segmented stage and generation flip at the storage step (logic in persistence/segmented-apply.ts)src/core/minions/handlers/subagent-oneshot.ts runSubagentOneshot 378 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +1 fix wave 9 lane B #4921: the oneshot sub-budget is passed as the call timeoutMs so the 300 s gateway backstop cannot cut itsrc/core/minions/handlers/subagent.ts makeSubagentHandler 887 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loopsrc/core/minions/handlers/subagent.ts makeSubagentHandler>subagentHandlerInner 817 seed: W5 baseline, refactor wave 1 (decomposition deferred to wave 2, plan D1); +3 fix wave 9 lane B #4921: per-turn timeout read once, passed to oneshot and gateway loopdiff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex 902ef453cc..f228299004 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -17,7 +17,7 @@ src/core/cycle.ts 3314 ratchet +2 System One v1 S9: extract_facts phase tail runsrc/core/cycle/synthesize.ts 3228 ratchet +26 System One v1 S7/S8: triage and grounding decide delegation (triage-decide.ts, grounding-decide.ts); merged waves; grown v0.46.26.0 megawave + master rolling lease via shared throttled renewer; grown wave-g (#4506): cycle summaries can stay out of the source repo; +18: expired-verdict sweep + DeepSeek judge thinking pin (#4069); +47: #4077 cooperative-abort threading; +110: eval fix wave F6 spend surfacing (withChatPhase wrap, triage/child token telemetry, zero-page counter); +32: F1b quote-verify call site + kill switch; +2: F1a/F3/F4a OUTPUT POLICY rules; +59: F2 verified-segment rescue (gate at report construction, rescue knobs, telemetry); +19: rubric v2 peak-scoring + docblock rescue branch; +50: #4337 summary link-sample cap + dream_created_cycle_date preserve-on-rerun; +5: #4348 resolveCycleDate wiring (local-day summary bucketing); +3 round-3 rebase true-up; +55: #4805 synth-v2 completion skip (findSynthV2Completion + prefix-parameterized loadSuccessfulSynthesisKeys); +10: #4886 mode-aware buildSynthesisPrompt (oneshot children drop tool-use/final-prose guidance); #5105: small legacy writer/refusal and shared revision CAS delegates; +4: merge of #5666 durable synthesis completions with the v0.59.18.0 verify-epoch wiring; +7 #5413/#5471 discovery exclusions (self-capture session ids, dream output directories); +6 fix wave 2 (v0.60.5.0) integration: W7 paid-loop breaker check before submission and released-key daily-cap count on top of the W1b discovery exclusions; +6 v0.60.5.0 master-merge true-up: the wave-2 growth (+13 W1b, +6 W7) re-summed over master v0.59.18.0 at 3222 lines with no slack; +76 fix wave 3: per-run USD gate + fail-closed daily cap (C-13), child first-write ownership for stamp/reverse-write (C-8, #5685), cycle-date prompt hint (C-15), opt-in attribution rule (#5425); fix wave 3 x fix wave 2 (v0.60.5.0) composition: +19 at the merge; +2 #5806 triageNow clock seam forwarded to triage (interface field + call-site option); +4 #5854: a postprocess or summary publish still pending after its wait is deferred (publish_pending warn, no cooldown stamp; helper in synthesize-postprocess.ts); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); Foundations 2 Lane C: maintenanceTransaction import (attributed summary page); +14 #5490 review: a triage verdict a chat_fallback_chain model gave is used for the run but not cached (TriageResult.answeredBy, judge-client marker, guarded putDreamVerdict); lowered to 3200 by wave 9 lane W #5145: completion-key helpers (findLegacyCompletion, findSynthV2Completion, loadSuccessfulSynthesisKeys) peeled to synthesize-completion.ts with the new pre-triage partition; +13 P2 extraction.date_grounding: transcript observation date line instead of a run-date "Today's date" (config field + prompt arg); +1 fix wave 11 #6160: oneshot_task_prefixes on the child job data; +18 fix wave 12 #6069: unreliable-verdict backoff in runTriagePass (report code, pass backoff count, triage details entry; marker logic in triage-backoff.ts); +1 fix wave 12 #6242: SYNTH_PHASE_FAIL keeps an OperationError's suggestion and code (OperationError import)src/core/cycle/extract-atoms.ts 1654 ratchet crossed the 1500 unlisted cap in the atoms/extraction fix wave: +21 embed-aware cost gate (#4878), +65 atoms-array anchor scan (#4913); peel candidate: the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) into extract-atoms-parse.ts; +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); the parse block (parseAtomsOutcome / parseArrayAtOffset / atomsFromParsedArray) is peeled into extract-atoms-parse.ts (-193, fix wave 10 lane B); +35: #4853 transcript-origin atoms link to their conversation page; +130: #4916 transcript failure-count/tombstone (extract_atoms_transcript_state, TODOS P2(b)); wave composition: #4916 transcript-state skip + #4948 zero-atom prompt + #4943 meetings source-id summed; +3: wave review — a later `[]` is an honest zero-yield, a non-atom-shaped array is a counted failure; +13: wave review — explicit budget keeps the cap over an unpriced embed route ($0-priced); +14: wave review — transcript-state write errors surfaced, missing table warns once; merged reliability/shared-skills source integration; +37 fix wave 3: stable undated atom dates + stale-atom retirement (C-14); +3 #5525: effectiveVisibility stamped on non-managed atoms; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +3 at the merge; +6 fix wave 3 lane A (#5601): accepted-pending atom batches count as progress (helper in persistence/accepted-pending.ts); +4 fix wave 4: #5705 transcript-as-data system prompt lines and its message helper, #5627 response schema import (the atom-type list moved to extract-atoms-schema.ts); +30 #5809/#5832: drain hard/soft stop signals (ExtractAtomsOpts.signal/stopSignal, pre-commit abort checks, no strike or post-stop writes after a hard stop) and the cancellable backlog count; +1 #5812: transcript items are paste-stripped (corpusTextForExtraction import) before the input cut; +1 #5820: extract_atoms discovery passes selfCaptureSessionIds like synthesize; +10 #5856/#5854: drain attempt state (one BudgetTracker + one publish wait across batches) and the opt-in connector email/meeting exclusion (predicate in connector-atoms.ts); +1 Foundations 2 Lane C: maintenanceTransaction import (attributed stale-atom retirement); +5 fix wave 9 lane P (#5041): opt-in atom write-through hook and retired-atom slugs returned for file removal (logic in derived-write-through.ts); +17 #5031: same-page case-insensitive atom adoption fallback (one page-atom scan per source page per run); +12 P2 atomsPrompt helper: extraction.date_grounding source observation date + rule in the atoms prompt; +4 GBRA-75: octet_length-bounded body-length predicate (minCompiledTruthChars) for discovery and the backlog countsrc/core/engine.ts 2820 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); +26 Wave B PR 1: segmented page storage members (allocateBodyOccurrenceIds..sweepSegments) + page-body type import (SQL in engine-sql/page-body.ts)-src/core/import-file.ts 2032 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+src/core/import-file.ts 2056 ratchet +2: pre-publication withdrawal validation; grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); security: durable queued authority and confined filesystem dispatch; master integration: grown v0.46.26.0 megawave: OCR budget + image import + embed-retry rewire (#3973 #3374); grown wave-g (#4530): per-model chunk-token cap wiring; +24 #4548: row-level visibility-aware fence merge on remote write-back (replaces the #2044 whole-block swap + #4553/#4555 warn-only paths); +7 #4546: merge extended to the timeline-embedded fence; +5 #4107: maybeOcr gates on the OCR model's provider; +3 #3893; +7: #4702 disabled_patterns pass-through to the sanity gate; composition true-up (fix-wave multi-train); +8 #4903: importCodeFile writes source_path so the full-sync reconcile can see code pages; -11: wave review — local fence append replaced by facts-fence.replaceOrInsertFactsFence (#4756 rule); harness support: boundary wiring to shared grants, isolated setup, withdrawal and delegated guards; merged v0.49: withdrawal preservation after data-only frontmatter parsing; #5105: small legacy writer/refusal and shared revision CAS delegates; #5105: +8 prepared contextual retrieval policy and retry boundary wiring; upstream integration: preserve independently reviewed master additions with branch facade extraction; #5252 wave: shared provider-free Markdown and code preparation; merged company ingestion/schema routing changes; master retrieval/projection integration with company ingestion; shared content: prepare managed image imports without bypassing canonical publication; +29 write-path wave: identity move/collision wiring (logic in import-identity.ts), deferred embedding on provider failure, image index completeness, file-time date anchor; +22 fw3 A13: markdown re-import reuses unchanged chunk vectors under the seal/wrapper/signature/protected-fence gate; +2 fw3 A12: importFromFile firstCommitAt option; +3 fw3 A14: managed imports keep add-only tags; +4 #5675: record the file origin move inference binds to (logic in import-identity.ts); fw3 integration: A12/A13/A14 (+27) and #5675 (+4) compose; +17 wave-2 W4: safe-chunk re-seal of unchanged legacy markdown/code pages (#5050 #5247) and embedding-input provenance on inline imports (#5553); -1 fix wave 2 (v0.60.5.0) integration: W4 delta re-summed over the merged master line count; fix wave 3 x fix wave 2 (v0.60.5.0) composition: +16 at the merge; +11 #4616: markdown and code imports keep the usable vectors of a partially refused batch and leave refused chunks for embed --stale; lowered to 2230: #5621 contextual-mode resolution peeled to core/import-contextual-mode.ts (shared with gbrain repair contextual-mode); +2 wave 8 lane D1 #5158: key-order fallback equality call (comparison lives in page-state/import-guard.ts); +1 F1c: direct imports run in maintenanceTransaction (write attribution; helper in persistence/attribution.ts); lowered to 2178: #5988 content screen and content-sanity config peeled to core/import-screen.ts; +1 #6007: the prepared apply returns its page id and seal (PreparedImportApplied); +1 #5333: trusted imports drop a stale oversized embed_skip/content_flag the gate no longer sets, and an embed_skip transition defeats both unchanged fast paths; wave 10 collector: lane E (#5333) and the other lanes compose at 2183; grown #6188 (+17): fence options interface, result fields and the Tier 1 step call (logic in fence-repair/import-step.ts); +2 #5984 single-write fast path: the coordinated existingSnapshot option (interface field) composes with the lane apply diet at 2202; +1 GBRA-69: a coordinated apply defers its chunker seal to the caller (sealImportedPage in page-state/projections.ts); lowered to 2023: #5001 the edge-mapping loop moved to code-chunks.ts mapCodeEdges (shared with the prepared apply); W14 P3.13 (#5001) lowered 2049→2023 by moving the edge loop to mapCodeEdges; +2 W13 PR1 on top (2025 measured); +2 #6529: the unchanged-image skip path records source_path (refreshSourcePath, as #4588 does for Markdown); +4 large pages A6/T33: code files keep CODE_FILE_MAX_BYTES, a page over PAGE_INLINE_MAX_BYTES commits with NULL vectors for the metered stale sweep; +1 #6722: an embed_skip page is chunked and never embedded (noEmbed folds the marker); merge v0.60.240.0: large pages and master growth compose at 2032; +24 Wave B lane 1d: the segmented storage step (stage before publication, flip in the apply, seal and post-commit projection; logic in persistence/segmented-apply.ts and page-body/ingest.ts) and the streamed-import dispatch over the single-string ceiling (logic in page-body/streamed-import.ts)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 3043 ratchet +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); 4 Foundations 2 Lane F: autocommit write statements take the WAL checkpoint guard (classifier writesWal in pglite-engine/checkpoint-guard.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +5 agent operator gate fixes: repair-failed marker gate before the lock and the marker record after a failed auto-repair (logic in pglite-repair.ts, refusal in pglite-repair-consent.ts); +1 System One v1 evals: search arms clamp to searchLimitCap() (import of search/eval-pool-depth.ts; eval-only --eval-pool-depth, production cap unchanged); refactor wave 1 split target (W1 engine-sql); E1 bootstrap moved to engine-sql/bootstrap.ts; ceiling rationale: docs/architecture/key-files/engines-1.md entry for src/core/pglite-engine.ts; evidence delivery: getChunkWindows delegate + type import (+3; SQL in engine-sql/chunks.ts); #5761: +4 markPagesAttendanceBlocked delegate (SQL in engine-sql/pages.ts); +12 eval wave N1-2/N1-3: mergeOntologyFact same-stint noop check + ontology visibility filter in the grandfathered ontology methods; lowered to 3213 #5824: searchVector SQL moved to search/vector-statement.ts (-166); lowered to 3117 #5889: searchTitles SQL moved to engine-sql/titles.ts (-108); lowered to 2915 F4a: getHealth SQL moved to engine-sql/health.ts (-202); +6 F4b: planner-sensitive reads call beforePlannerRead/plannerRead (logic in planner-stats.ts); +52 engine graduation (GBRA-50 G2a): marker/tombstone checks before and after the kernel lock (logic in persistence/graduation-custody.ts), lock-retaining close and held-lock open (engine lifecycle methods cannot move); +1 #5984: upsertChunks guards pass the per-transaction config memo (transactionMemo in page-state/transactions.ts); v0.60.58.0 merge: #5984 diet growth re-summed over v0.60.57.0 (2983 measured); +4 P7 relationalChainHop delegate; +8 contributor audit wave P0: listFactsKeyset delegate (SQL in engine-sql/facts.ts); +1 #5375: get_versions limit/include_body type import (GetVersionsOpts, PageVersionRows); +2 #5984 lane apply diet: putPage/setPageAliases write inline in the caller's page transaction (engine methods cannot move); +4 GBRA-69: replaceDerivedLinksBatch delegate (logic in derived-links.ts); +5 GBRA-67: readPageSnapshotsBatch delegate (batch logic in page-snapshot-batch.ts); +1 GBRA-75 wave 10: findDuplicatePages delegate (SQL in engine-sql/pages.ts); +2 GBRA-76: transaction/transactionDirect take TransactionOptions and refuse an already-aborted signal before BEGIN; +2 #4772 (W14 PR3): entityTypes HealthDeps delegate + import (policy in schema-pack/entity-types.ts, SQL in engine-sql/health.ts); +2 W14 P3.12 (#4772): entityTypes HealthDeps delegate + import on top of W13; +11 Cat 40 Hard fix wave F2 (#6271) on top: countKeywordPages/searchKeywordPages delegations (SQL in engine-sql/keyword-pages.ts) and the rankQuery score parameter (3023 measured); +3 W15 P1.2 (#6454): three one-line stale-frontmatter-key delegates (SQL in engine-sql/pages.ts); +6 large pages Wave A sub-a: getChunkPage delegate (SQL in engine-sql/chunks.ts); +11 #6696 B3: readEmbeddingStateCounts/listEmbeddingStateRows delegations + type importdiff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex b62bee1d4d..b5926745ae 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -242,6 +242,7 @@ test/jobs-stats-backpressure.serial.test.ts global-state global-state: patches ptest/jobs-stats-divergence.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/jobs-stats-private-queue.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/keyword-relaxed-fusion.serial.test.ts R2 R2: mock.module(../src/core/embedding.ts) replaces modules for every file in the process+test/large-pages/flip-crash.serial.test.ts global-state global-state: installs the process-wide persistence fault hook (installFaultHook) to stop a segmented write at each crash windowtest/link-reads-thin-client-5827.serial.test.ts R2 R2: mock.module(../src/core/config.ts, ../src/core/mcp-client.ts) replaces modules for every file in the processtest/llm-intent-hybrid-integration.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gatewaytest/loops-close-fact.serial.test.ts global-state global-state: process-wide test seams __setChatTransportForTests; configureGateway changes the process-wide AI gateway; patches process stdout/stderr/consolediff --git a/src/commands/import.ts b/src/commands/import.tsindex dfa192f8d8..2fea42b6f4 100644--- a/src/commands/import.ts+++ b/src/commands/import.ts@@ -46,6 +46,7 @@ import { estimateCostFromChars, lookupEmbeddingPrice } from '../core/embedding-pimport { getEmbeddingModel } from '../core/ai/gateway.ts';import { managedRootMarkerFor } from '../core/persistence/root-registry.ts';import { readManagedMode } from '../core/persistence/ownership.ts';+import { readPageBodyPolicy } from '../core/page-body/limits.ts';/** Return a refusal when an import target lies outside every admitted root. */export function configuredRootImportError(dir: string, configuredRoots: string[]): string | null {@@ -461,6 +462,7 @@ export async function runImport(} catch {importActivePack = undefined;}+ const bodyPolicy = await readPageBodyPolicy(engine);const workersIdx = args.indexOf('--workers');const workersArg = workersIdx !== -1 ? args[workersIdx + 1] : null;@@ -726,7 +728,7 @@ export async function runImport(? await importManagedFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, signal, slugRoot: opts.slugRoot }): isImageFilePath(relativePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true'? await importImageFile(eng, filePath, importRelPath, { noEmbed, sourceId })- : await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, firstCommitAt: firstCommits?.get(filePath) });+ : await importFile(eng, filePath, importRelPath, { noEmbed, sourceId, activePack: importActivePack, bodyPolicy, firstCommitAt: firstCommits?.get(filePath) });// An import that landed while cancellation arrived is still complete.// Account for it before stopping, so resume never loses a successful path.noteTypeWarning((result as { type_warning?: Parameters<typeof noteTypeWarning>[0] }).type_warning); fenceTally.note(importRelPath, result);diff --git a/src/core/content-sanity.ts b/src/core/content-sanity.tsindex d5f5420a05..4e6a669cf0 100644--- a/src/core/content-sanity.ts+++ b/src/core/content-sanity.ts@@ -394,6 +394,8 @@ export function assessContentSanity(opts: {timeline: string;/** Post-parseMarkdown title. Some patterns key on title alone. */title: string;+ /** UTF-8 bytes of the whole body when `compiled_truth`/`timeline` hold only its head (a streamed page over the single-string ceiling). */+ body_bytes?: number;/** Effective warn threshold; defaults to DEFAULT_BYTES_WARN. */bytes_warn?: number;/** Effective block threshold; defaults to DEFAULT_BYTES_BLOCK. */@@ -437,7 +439,7 @@ export function assessContentSanity(opts: {// octet_length() does at the DB layer, so the two surfaces agree on// the same page (D2 parity).const body = opts.compiled_truth + (opts.timeline ? '\n' + opts.timeline : '');- const bytes = Buffer.byteLength(body, 'utf-8');+ const bytes = opts.body_bytes ?? Buffer.byteLength(body, 'utf-8');const oversize = bytes > bytes_block;// Head-slice for pattern evaluation. Cost stays O(SCAN_HEAD_BYTES)diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 9c32cd3d1f..db1befdb8f 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -56,6 +56,10 @@ import { warnOncePerProcess, validateSlug, contentHash, contentHashLegacy, ATOMSimport { decorateEmbeddingDimError } from './embedding-dim-check.ts';import { resolveImportContextualMode } from './import-contextual-mode.ts';import { runGuardrails } from './guardrails.ts';+import { abortSegmentedStaging, bodyStorageOf, demoteSegmentedPage, materializedPage, materializedSnapshot, sealSegmentedPage, stageSegmentedImport,+ stringWriteStorage } from './persistence/segmented-apply.ts';+import type { SegmentedStagingOwner } from './page-body/ingest.ts';+import type { PageBodyPolicy } from './page-body/limits.ts';import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';/**@@ -296,6 +300,8 @@ export async function importFromContent(source_kind?: string | null;source_uri?: string | null;ingested_via?: string | null;+ /** Wave B: who stages a segmented body (the journaled request's principal); unset: the local maintenance principal, kind `import`. */+ segmentedOwner?: SegmentedStagingOwner;/** Untrusted caller (remote MCP put_page: `ctx.remote !== false`); drives the remote fence merge and hidden rows. */remote?: boolean;/**@@ -407,8 +413,8 @@ export async function importFromContent(// engine.putPage defaults to 'default' when sourceId is unset, so the read// mirrors that default instead of matching the slug in ANY source (the// unscoped-check/scoped-write bug class).- const existingSnapshot = !opts.prepare ? null : opts.coordinated && opts.existingSnapshot !== undefined ? opts.existingSnapshot : await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });- const existing = opts.prepare ? existingSnapshot?.page ?? null : await engine.getPage(slug, { sourceId: sourceId ?? 'default', includeDeleted: true });+ const existingSnapshot = !opts.prepare ? null : await materializedSnapshot(engine, opts.coordinated && opts.existingSnapshot !== undefined ? opts.existingSnapshot : await engine.readPageSnapshot(slug, { sourceId: sourceId ?? 'default', includeDeleted: true }));+ const existing = opts.prepare ? existingSnapshot?.page ?? null : await materializedPage(engine, await engine.getPage(slug, { sourceId: sourceId ?? 'default', includeDeleted: true }));if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);const collisionOwner = collidingSlugOwner(existing, slug, opts.sourceRoot, opts.sourcePath);@@ -599,7 +605,9 @@ export async function importFromContent(// Preserve the importer projection (including fenced code and zero-chunk// dispositions) in the provider-free path used by background rebuilds too.- const chunks = await prepareFenceAwareMarkdownChunks(engine, sourceId ?? 'default', slug, parsed);+ const bodyBytes = Buffer.byteLength(parsed.compiled_truth, 'utf-8') + Buffer.byteLength(parsed.timeline ?? '', 'utf-8');+ const storage = await stringWriteStorage(engine, bodyBytes, bodyStorageOf(existing));+ const chunks = storage.storage === 'segmented' ? [] : await prepareFenceAwareMarkdownChunks(engine, sourceId ?? 'default', slug, parsed);// Embedding failures propagate unless onPostCommitEmbedding lets the caller// report enrichment separately from the already-persisted content.@@ -620,6 +628,10 @@ export async function importFromContent(// #3885: the real source row applies (a stored `sources set-cr-mode`); the// inline path demotes per_chunk_synopsis to the free title tier.const { mode: effectiveCRMode, corpusGeneration } = await resolveImportContextualMode(engine, sourceId ?? 'default', parsed.frontmatter, opts.prepare !== undefined);+ // Wave B: a body staged as segments publishes with the generation flip instead of putPage and the chunk replacement.+ const segmented = storage.policy && storage.storage === 'segmented' ? await stageSegmentedImport(engine, { slug, sourceId: sourceId ?? 'default', existing,+ page: parsedPage, policy: storage.policy, owner: opts.segmentedOwner, baseRevision: (existing as { knowledge_revision?: string } | null)?.knowledge_revision ?? null,+ chunking: { quarantined: pageQuarantined, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' : 'none' } }) : null;// A13: an edit re-embeds only chunks whose embedding input changed. A stored// vector is reused for a chunk with the same source and text when its@@ -635,9 +647,9 @@ export async function importFromContent(// A large page commits with NULL vectors; the stale sweep embeds it under the// per-page cap and the sampled junk check, so no provider call holds the write.const noEmbed = opts.noEmbed || isEmbedSkipped(parsed.frontmatter);- const largePage = isLargePageBytes(Buffer.byteLength(parsed.compiled_truth, 'utf-8') + Buffer.byteLength(parsed.timeline ?? '', 'utf-8'));+ const largePage = isLargePageBytes(bodyBytes);const postCommitEmbedding = largePage ? undefined : opts.onPostCommitEmbedding;- const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !postCommitEmbedding && chunks.length > 0+ const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !postCommitEmbedding && chunks.length > 0 && bodyStorageOf(existing) !== 'segmented'&& !(opts.prepare && modeRequiresSynopsis(effectiveCRMode)) && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`);const reuseCtx = { slug, sourceId: sourceId ?? 'default', title: parsed.title, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' as const : 'none' as const };const reuseStoredVectors = (exec: BrainEngine, into: ChunkInput[], keepUnembedded = false) => reuseStoredChunkVectors(exec, into, { ...reuseCtx, prepared: !!opts.prepare, keepUnembedded });@@ -667,7 +679,7 @@ export async function importFromContent(// commit with NULL vectors and no embedding signature, and the stale sweep// (`gbrain embed --stale`, sync's embed pass, the cycle) embeds them once// the provider recovers.- let embeddingDeferred = largePage && !noEmbed && chunks.length > 0;+ let embeddingDeferred = largePage && !noEmbed && (chunks.length > 0 || (segmented !== null && !pageQuarantined));if (!opts.onPostCommitEmbedding && !largePage) {try {await embedChunks();@@ -715,6 +727,7 @@ export async function importFromContent(});if (existing && !preimage) await tx.createVersion(slug, txOpts); // reads the page itself, so before the page write+ if (!segmented && bodyStorageOf(existing) === 'segmented') await demoteSegmentedPage(tx, Number(existing!.id));// Every import keeps each stored row that is identical to its new chunk and// writes only the rest, so an edit rewrites only the chunks it changed. The// reuse is re-read here, under the page lock, so a kept row is one this@@ -727,6 +740,9 @@ export async function importFromContent(() => assertPreparedFactWithdrawals(tx, txOpts.sourceId, parsed.compiled_truth, parsed.timeline || '', slug),async () => { if (existing && preimage) await tx.createVersion(slug, { ...txOpts, preimage }); },async () => {+ if (segmented) return segmented.apply(tx, { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter, page_kind: 'markdown',+ effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filenameForChain, source_path: opts.sourcePath ?? null,+ source_kind: opts.source_kind ?? null, source_uri: opts.source_uri ?? originUri, ingested_via: opts.ingested_via ?? null }, { mode: effectiveCRMode, corpusGeneration });written = await tx.putPage(slug, {type: parsed.type,title: parsed.title,@@ -758,14 +774,14 @@ export async function importFromContent(},// Replace every derived row atomically. Only vectors the A13 reuse gate above admitted carry over; a new// seal otherwise inherits nothing from an older index, whose contextual vector may have included a private sibling.- () => keptIds.length ? tx.executeRaw(`DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)+ async () => segmented ? undefined : keptIds.length ? tx.executeRaw(`DELETE FROM content_chunks WHERE page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2)AND NOT (id = ANY($3::int[]))`, [slug, txOpts.sourceId, keptIds]) : tx.deleteChunks(slug, txOpts),// Alias projection and readback share the page commit. A later writer can// no longer turn a successful import into a postcommit verification error.() => writePageAliases(tx, slug, sourceId ?? 'default', parsed, opts.activePack, mentionPolicy),]);- const pageId = written && written.deleted_at == null ? written.id : undefined;- const deferSeal = opts.coordinated === true && pageId !== undefined;+ const pageId = segmented?.applied ? segmented.applied.pageId : written && written.deleted_at == null ? written.id : undefined;+ const deferSeal = opts.coordinated === true && pageId !== undefined && !segmented;await pipelined(tx, [async () => {// Tag reconciliation (A14): frontmatter tags carry tag_source='frontmatter'.@@ -798,11 +814,12 @@ export async function importFromContent(} else {// Seal only the completed, full-body sanitized replacement (the upsert above seals its own); a// body-only write or a failed transaction must never certify old stored fragments.- if (!deferSeal) await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3', [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);+ if (!deferSeal && !segmented) await tx.executeRaw('UPDATE pages SET chunker_version = $1 WHERE source_id = $2 AND slug = $3', [MARKDOWN_CHUNKER_VERSION, txOpts.sourceId, slug]);}},]);- if (!opts.coordinated) await sealPageTextProjection(tx, slug, txOpts.sourceId);+ if (!opts.coordinated && !segmented) await sealPageTextProjection(tx, slug, txOpts.sourceId);+ if (!opts.coordinated && segmented?.applied?.complete) await sealSegmentedPage(tx, segmented.applied.pageId);// v0.19.0 E1 — doc↔impl linking: if this markdown page cites code paths// (e.g. 'src/core/sync.ts:42'), create bidirectional edges to the code@@ -848,16 +865,18 @@ export async function importFromContent(// guard. Deferred provider results cannot replace newer text or chunks.persistedProjection = await readProjectionSnapshot(tx, slug, txOpts.sourceId);}+ if (segmented?.applied) return { pageId, sealed: !opts.coordinated && segmented.applied.complete, segmented: { complete: segmented.applied.complete } };return { pageId, sealed: !opts.coordinated && !opts.beforeCommit, ...(deferSeal ? { chunkerSeal: MARKDOWN_CHUNKER_VERSION } : {}) };};if (opts.prepare) return opts.prepare({slug, parsedPage, observedRevision: (existing as (typeof existing & { knowledge_revision?: string }) | null)?.knowledge_revision ?? null,- noop: false, contentHash: hash, result: { slug, status: 'imported', chunks: chunks.length, parsedPage,+ 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,+ apply: applyPrepared, ...(segmented ? { afterCommit: segmented.afterCommit } : {}),});await maintenanceTransaction(engine, applyPrepared, writeTrustOfGate(opts.writeGate)).catch(async (err: unknown) => {+ await abortSegmentedStaging(engine, segmented?.prepared);// #4287: name the dimension-mismatch rollback instead of letting the bare// pgvector message ("expected N dimensions, not M") surface with no code,// no consequence and no fix. S2: name the registry-ACTIVE column the@@ -873,6 +892,7 @@ export async function importFromContent(}throw decorateEmbeddingDimError(err, slug, activeColName);});+ await segmented?.afterCommit(engine);if (postCommitEmbedding && !noEmbed && chunks.length > 0) {@@ -892,7 +912,7 @@ export async function importFromContent(return {slug,status: 'imported',- chunks: chunks.length,+ chunks: segmented ? segmented.prepared.rows.chunks : chunks.length,parsedPage,...(pageQuarantined ? { quarantined: true } : {}),...(pageFlagged ? { flagged: true, flag_reason: pageFlagReason } : {}),@@ -990,6 +1010,8 @@ export async function importFromFile(activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };/** Git first-commit date of the file (opt-in, see git-first-commit.ts); an undated page's fallback anchor. */firstCommitAt?: Date;+ /** Wave B: the segmented-storage policy, read once per command; with the switch on, a Markdown file over the single-string ceiling imports streamed. Absent: it refuses as before. */+ bodyPolicy?: PageBodyPolicy;} = {},): Promise<ImportResult> {// Defense-in-depth: reject symlinks before reading content.@@ -1001,6 +1023,8 @@ export async function importFromFile(const stat = statSync(filePath);const maxBytes = importSizeLimit(relativePath);if (stat.size > maxBytes) {+ const policy = opts.bodyPolicy;+ if (policy?.segmented && !isCodeFilePath(relativePath) && stat.size <= policy.maxBytes) return (await import('./page-body/streamed-import.ts')).importStreamedMarkdownFile(engine, filePath, relativePath, opts, stat, policy);return { slug: relativePath, status: 'skipped', chunks: 0, error: `File too large (${stat.size} bytes)`,refusal: { code: 'file_too_large', message: `File too large (${stat.size} bytes, max ${maxBytes}).` }, skip_reason: 'file_too_large' };}@@ -2015,7 +2039,7 @@ export async function importImageFile(let warnedBrainTimeZone = false;/** `brain.timezone` (IANA) for offset-less frontmatter datetimes; unset or invalid reads them as UTC. */-async function loadBrainTimeZone(engine: BrainEngine): Promise<string | undefined> {+export async function loadBrainTimeZone(engine: BrainEngine): Promise<string | undefined> {const configured = (await engine.getConfig('brain.timezone').catch(() => null))?.trim();if (!configured || isValidTimeZone(configured)) return configured || undefined;if (!warnedBrainTimeZone) process.stderr.write(`[import] invalid brain.timezone "${configured}"; reading naive datetimes as UTC\n`);diff --git a/src/core/import-screen.ts b/src/core/import-screen.tsindex 346661ea07..6d4842b014 100644--- a/src/core/import-screen.ts+++ b/src/core/import-screen.ts@@ -111,6 +111,8 @@ export interface ContentDispositionContext {stripped: boolean;/** #5575: tier and origin of this write; absent skips the write gate. */writeGate?: WriteGateInput;+ /** Wave B: the whole body's bytes when `parsed` holds only its head (a streamed page). */+ bodyBytes?: number;}export interface ContentDisposition {@@ -160,7 +162,7 @@ export async function settleContentDisposition(engine: BrainEngine, parsed: Pars// Disposition for the high-confidence junk path: quarantine (hide) by// default, or reject (throw → sync-failure) when the operator opts in.const junkDisposition = sanityCfg.junkDisposition;- const sanityResult = await carryStoredQuarantineOverride(engine, parsed, assessImportSanity(parsed, sanityCfg), { slug, sourceId, stripped: ctx.stripped });+ const sanityResult = await carryStoredQuarantineOverride(engine, parsed, assessImportSanity(parsed, sanityCfg, ctx.bodyBytes), { slug, sourceId, stripped: ctx.stripped });if (!sanityDisabled && !sanityResult.shouldQuarantine && sanityResult.flag_reason !== 'oversized' && (parsed.frontmatter[EMBED_SKIP_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') {delete parsed.frontmatter[EMBED_SKIP_KEY];if ((parsed.frontmatter[CONTENT_FLAG_KEY] as { reason?: unknown } | undefined)?.reason === 'oversized') delete parsed.frontmatter[CONTENT_FLAG_KEY];@@ -317,9 +319,11 @@ export function stripGateOwnedMarkers(parsed: Pick<ParsedMarkdown, 'frontmatter'}/** #6259: a page carrying a current `quarantine_override` keeps the classifier's verdict off (see quarantine-override.ts). */-export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'title' | 'type'> & { frontmatter?: Record<string, unknown> }, cfg: ImportSanityConfig): ContentSanityResult {+export function assessImportSanity(page: Pick<ParsedMarkdown, 'compiled_truth' | 'timeline' | 'title' | 'type'> & { frontmatter?: Record<string, unknown> }, cfg: ImportSanityConfig,+ bodyBytes?: number): ContentSanityResult {return withQuarantineOverride(assessContentSanity({compiled_truth: page.compiled_truth,+ ...(bodyBytes !== undefined ? { body_bytes: bodyBytes } : {}),timeline: page.timeline ?? '',title: page.title,bytes_warn: cfg.cs.bytes_warn,diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.tsnew file mode 100644index 0000000000..72b551d4ca--- /dev/null+++ b/src/core/page-body/ingest.ts@@ -0,0 +1,370 @@+/**+ * Segmented page ingest (Wave B, spec 3.1-3.3): turns a page body (the stored+ * stream of its truth region, then its timeline region) into staged segment+ * texts, a diff against the live manifest and staged manifest and chunk rows,+ * all outside the publication transaction. Memory is O(segment): the regions+ * arrive as byte streams, texts are flushed in STAGE_BATCH_BYTES statements and+ * chunking reads the staged texts back one batch at a time.+ *+ * Diff (spec 3.3 step 3): a new segment whose `(sha256, entry_state)` matches a+ * live occurrence keeps that occurrence id; it keeps its row too when every+ * coordinate (seq, offsets, hash midstate) is unchanged, else it gets a new+ * row with the same id (shifted). Other segments get fresh ids. Live+ * occurrences left unmatched retire. `content_hash` resumes from the hash+ * midstate of the last row of the unchanged prefix (1.4).+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { stableJson } from '../persistence/digest.ts';+import { faultPoint } from '../persistence/fault-points.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 type { BodyRegion, BodyStagingKind, BodyStorage, JsonObject, ManifestRow, ManifestRowInput, SegmentChunkInput,+ SegmentedBodyColumns, SegmentTextInput } from './types.ts';+import { segmentStream, SEGMENTER_VERSION, type SegmentOut } from './segmenter.ts';+import { initialEntryState } from './entry-state.ts';+import { ContentHashStream } from './content-hash-stream.ts';+import { prepareSegmentChunks } from './segment-chunks.ts';+import { reuseSegmentChunkVectors } from '../import-chunk-reuse.ts';++const utf8 = new TextDecoder('utf-8', { fatal: true });++/** The live page a segmented write replaces (null: create). */+export interface SegmentedLivePage { id: number; generation: number; storage: BodyStorage; title: string; type: string }++/** Who stages, for the `page_body_stagings` row (a GC root while open). */+export interface SegmentedStagingOwner { kind: BodyStagingKind; principalKind: string; principalId: string; baseRevision: string | null }++export interface SegmentedBodyInput {+ sourceId: string;+ slug: string;+ live: SegmentedLivePage | null;+ title: string;+ type: string;+ frontmatter: JsonObject;+ tags: readonly string[];+ /** The stored stream of each region (sanitized, valid UTF-8). */+ truth: AsyncIterable<Uint8Array>;+ timeline: AsyncIterable<Uint8Array>;+ /** Page-global facts known at EOF (pass 1): `fence_trust`, `timeline_split`, ... */+ flags: JsonObject;+ /** Body bytes as declared by the source (exact for strings, the file size for streams). */+ declaredBytes: number;+ owner: SegmentedStagingOwner;+ /** Chunking inputs for a replace (a create chunks after publication). */+ chunking: SegmentChunkingContext;+}++export interface SegmentChunkingContext {+ /** Quarantined pages keep no chunks, as inline pages. */+ quarantined: boolean;+ corpusGeneration: string | null;+ tier: 'title' | 'none';+}++export interface PreparedSegmentedBody {+ stagingId: string;+ /** The live body generation the diff read (0 for create). */+ expectedGeneration: number;+ newGeneration: number;+ /** Create only: every manifest row, written in the publication transaction once the page row exists. */+ createRows: ManifestRowInput[] | null;+ closeOccurrences: number[];+ retireChunkOccurrences: number[];+ /** Occurrences of the new generation that have no chunk rows after staging (create: all; chunked after publication). */+ unchunked: number;+ body: SegmentedBodyColumns;+ /** No manifest row changed: the write changes metadata only. */+ bodyUnchanged: boolean;+ rows: { texts: number; manifest: number; chunks: number };+ /** `chunk_index` of every chunk row this preparation staged; the flip drops any other row staged under `newGeneration` (a dead preparation's). */+ stagedChunkIndexes: number[];+}++/** A region of a string as a byte stream, sliced on code-point boundaries. */+export async function* stringRegion(text: string, sliceChars = 256 * 1024): AsyncIterable<Uint8Array> {+ const encoder = new TextEncoder();+ for (let at = 0; at < text.length;) {+ let end = Math.min(text.length, at + sliceChars);+ const last = text.charCodeAt(end - 1);+ if (end < text.length && last >= 0xd800 && last <= 0xdbff) end--;+ yield encoder.encode(text.slice(at, end));+ at = end;+ }+}++/** The longest UTF-8 prefix of `bytes` within `max` bytes that ends on a code-point boundary, decoded. */+export function utf8Prefix(bytes: Uint8Array, max: number): string {+ let end = Math.min(bytes.length, max);+ if (end < bytes.length) while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;+ return utf8.decode(bytes.subarray(0, end));+}++/** scanMarkdownCode's trust of a stored region: 'void' when a fence is left open or a longer opener sits inside one. */+export function regionFenceTrust(text: string): 'trusted' | 'void' {+ const walk: FenceWalk = { opener: null, mispaired: false };+ for (let at = 0; at <= text.length;) {+ let end = text.indexOf('\n', at);+ if (end < 0) end = text.length;+ for (const line of text.slice(at, end).split('\r')) stepFenceWalk(walk, line);+ at = end + 1;+ }+ return walk.opener || walk.mispaired ? 'void' : 'trusted';+}++/** `body_flags` of a page whose stored regions are strings (pass 1's fence trust, for the in-memory path). */+export function stringBodyFlags(truth: string, timeline: string): JsonObject {+ return { fence_trust: regionFenceTrust(truth), timeline_fence_trust: regionFenceTrust(timeline) };+}++const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');+const sameBytes = (a: Uint8Array, b: Uint8Array) => Buffer.from(a).equals(Buffer.from(b));+const occurrenceKey = (sha256: Uint8Array, entryState: unknown) => `${hex(sha256)}|${stableJson(entryState)}`;++/** Every coordinate of a live row equals the row the new segment would get, so the row stays. */+function rowUnchanged(live: ManifestRow, next: ManifestRowInput): boolean {+ return live.seq === next.seq && live.region === next.region && Number(live.byteStart) === next.byteStart+ && live.byteLen === next.byteLen && Number(live.lineStart) === next.lineStart && live.cutKind === next.cutKind+ && sameBytes(live.hashState, next.hashState) && stableJson(live.protectedRegions) === stableJson(next.protectedRegions)+ && stableJson(live.factsSlots) === stableJson(next.factsSlots) && stableJson(live.outline) === stableJson(next.outline)+ && live.staticProjBytes === next.staticProjBytes && live.staticProjLines === next.staticProjLines+ && live.dateMin === next.dateMin && live.dateMax === next.dateMax;+}++async function sourceIncarnation(engine: Pick<BrainEngine, 'executeRaw'>, sourceId: string): Promise<string> {+ const [row] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [sourceId]);+ if (!row) throw new Error(`Source ${sourceId} not found.`);+ return row.incarnation;+}++/** Open the staging row every segmented write records (kind, principal, base); returns its id. */+export async function openSegmentedStaging(engine: BrainEngine, input: Pick<SegmentedBodyInput, 'sourceId' | 'slug' | 'live' | 'declaredBytes' | 'owner'>): Promise<string> {+ const id = randomUUID();+ const now = Date.now();+ await engine.openBodyStaging({+ id, kind: input.owner.kind, principalKind: input.owner.principalKind, principalId: input.owner.principalId, clientRequestId: randomUUID(),+ sourceId: input.sourceId, sourceIncarnation: await sourceIncarnation(engine, input.sourceId), slug: input.slug,+ pageId: input.live?.id ?? null, mode: input.live ? 'replace' : 'create', baseRevision: input.owner.baseRevision,+ baseGeneration: input.live?.generation ?? null, declaredBytes: input.declaredBytes, declaredSha256: null, reservedBytes: 0,+ idleExpiresAt: new Date(now + BODY_STAGING_IDLE_MS), hardExpiresAt: new Date(now + BODY_STAGING_HARD_MS),+ });+ return id;+}++/**+ * Pass 2 for one write: segment both regions, hash, stage texts, diff against+ * the live manifest, stage the changed manifest rows and (replace) the chunks+ * of every occurrence the new generation lacks. A failure aborts the staging.+ */+export async function prepareSegmentedBody(engine: BrainEngine, input: SegmentedBodyInput): Promise<PreparedSegmentedBody> {+ const stagingId = await openSegmentedStaging(engine, input);+ try {+ return await stageBody(engine, input, stagingId);+ } catch (error) {+ await engine.setBodyStagingState(stagingId, 'aborted').catch(() => undefined);+ throw error;+ }+}++async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, stagingId: string): Promise<PreparedSegmentedBody> {+ const live = input.live?.storage === 'segmented' ? input.live : null;+ const liveRows = live ? await engine.readManifest(live.id) : [];+ const byKey = new Map<string, ManifestRow[]>();+ for (const row of liveRows) {+ const key = occurrenceKey(row.sha256, row.entryState);+ byKey.set(key, [...(byKey.get(key) ?? []), row]);+ }+ const batchBytes = STAGE_BATCH_BYTES[engine.kind];+ const expectedGeneration = input.live?.generation ?? 0;+ const newGeneration = expectedGeneration + 1;+ const pageId = input.live?.id ?? 0;+ let prefixIntact = !!live && live.title === input.title && live.type === input.type;+ let hasher: ContentHashStream | null = null;+ const resume = (index: number) => index === 0 ? ContentHashStream.begin({ title: input.title, type: input.type })+ : ContentHashStream.fromState(liveRows[index - 1]!.hashState);+ const pending: SegmentTextInput[] = [];+ let pendingBytes = 0;+ const flushTexts = async () => {+ if (!pending.length) return;+ await engine.stageSegmentTexts(input.sourceId, pending.splice(0));+ pendingBytes = 0;+ if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));+ };+ const rows: ManifestRowInput[] = [];+ const used = new Set<ManifestRow>();+ const matched: Array<ManifestRow | null> = [];+ let texts = 0, byteStart = 0, lineStart = 0, truthBytes = 0, lines = 0;+ const leads: Record<BodyRegion, string> = { truth: '', timeline: '' };+ let hasProtected = false;+ for (const region of ['truth', 'timeline'] as const) {+ const stream = region === 'truth' ? input.truth : input.timeline;+ let first = true;+ for await (const segment of segmentStream(stream, initialEntryState({ region }), { region }) as AsyncIterable<SegmentOut>) {+ const seq = rows.length;+ if (first) { leads[region] = utf8Prefix(segment.bytes, BODY_LEAD_BYTES); first = false; }+ const text = utf8.decode(segment.bytes);+ const key = occurrenceKey(segment.sha256, segment.entryState);+ const prior = liveRows[seq];+ const prefixRow = prefixIntact && prior && prior.region === region && Number(prior.byteStart) === byteStart+ && occurrenceKey(prior.sha256, prior.entryState) === key ? prior : null;+ let hashState: Uint8Array;+ if (prefixRow) hashState = prefixRow.hashState;+ else {+ hasher ??= resume(prefixIntact ? seq : 0);+ prefixIntact = false;+ if (region === 'truth') hasher.pushTruth(text); else hasher.pushTimeline(text);+ hashState = hasher.exportState();+ }+ const row: ManifestRowInput = {+ pageId, occurrenceId: 0, genFrom: newGeneration, seq, region, sourceId: input.sourceId, sha256: segment.sha256,+ byteStart, byteLen: segment.bytes.length, lineStart, lineCount: segment.lineCount, cutKind: segment.cutKind,+ entryState: segment.entryState as JsonObject, protectedRegions: segment.regions, factsSlots: segment.factsSlots,+ staticProjBytes: segment.staticProjBytes, staticProjLines: segment.staticProjLines, outline: segment.outline,+ dateMin: segment.dateMin, dateMax: segment.dateMax, hashState, stagingId,+ };+ const candidates = byKey.get(key)?.filter(candidate => !used.has(candidate)) ?? [];+ const match = candidates.find(candidate => candidate.seq === seq) ?? candidates[0] ?? null;+ if (match) used.add(match);+ matched.push(match);+ if (!match) {+ pending.push({ sha256: segment.sha256, body: segment.bytes, lineCount: segment.lineCount });+ pendingBytes += segment.bytes.length;+ texts++;+ if (pendingBytes >= batchBytes) await flushTexts();+ }+ if (segment.regions.length) hasProtected = true;+ rows.push(row);+ byteStart += segment.bytes.length;+ lineStart += segment.lineCount;+ lines += segment.lineCount;+ if (region === 'truth') truthBytes += segment.bytes.length;+ }+ }+ await flushTexts();+ await faultPoint('segmented:texts_staged', { sourceId: input.sourceId });+ const contentHash = (hasher ?? resume(prefixIntact ? rows.length : 0)).finish({ frontmatter: input.frontmatter, tags: [...input.tags] });++ const fresh = rows.filter((_, i) => !matched[i]);+ const ids = fresh.length ? await engine.allocateBodyOccurrenceIds(fresh.length) : [];+ fresh.forEach((row, i) => { row.occurrenceId = ids[i]!; });+ const changed: ManifestRowInput[] = [];+ const closeOccurrences: number[] = [];+ rows.forEach((row, i) => {+ const match = matched[i];+ if (!match) { changed.push(row); return; }+ row.occurrenceId = Number(match.occurrenceId);+ if (input.live && rowUnchanged(match, row)) return;+ changed.push(row);+ closeOccurrences.push(row.occurrenceId);+ });+ const retireChunkOccurrences = liveRows.filter(row => !used.has(row)).map(row => Number(row.occurrenceId));+ closeOccurrences.push(...retireChunkOccurrences);+ const body: SegmentedBodyColumns = {+ content_hash: contentHash, body_bytes: byteStart, truth_bytes: truthBytes, body_lines: lines, segment_count: rows.length,+ segmenter_version: SEGMENTER_VERSION, truth_lead: leads.truth, timeline_lead: leads.timeline,+ body_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: [] };+ }+ if (changed.length) await engine.stageManifestRows(changed);+ await faultPoint('segmented:manifest_staged', { sourceId: input.sourceId });+ const chunkable = await occurrencesWithoutChunks(engine, input.live.id, expectedGeneration, rows);+ const chunks = await stageOccurrenceChunks(engine, { pageId: input.live.id, sourceId: input.sourceId, generation: newGeneration,+ occurrences: chunkable, title: input.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking,+ retiredOccurrences: retireChunkOccurrences });+ await 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,+ 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 };+}++/**+ * The rows of `rows` whose occurrence has no live chunk row at `generation`: new+ * occurrences, and kept ones a crashed or deferred projection never chunked.+ */+export async function occurrencesWithoutChunks(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, generation: number,+ rows: readonly ManifestRowInput[]): Promise<ManifestRowInput[]> {+ if (!rows.length) return [];+ const chunked = new Set((await engine.executeRaw<{ occurrence_id: number }>(`SELECT DISTINCT occurrence_id FROM content_chunks+ WHERE page_id=$1 AND occurrence_id=ANY($2::bigint[]) AND body_generation<=$3 AND retired_generation IS NULL`,+ [pageId, rows.map(row => row.occurrenceId), generation])).map(row => Number(row.occurrence_id)));+ return rows.filter(row => !chunked.has(row.occurrenceId));+}++/**+ * Chunk occurrences one text batch at a time (texts read back from+ * `page_segment_texts`), reuse vectors from the retired occurrences' rows, and+ * stage the chunk rows under `generation`. Shared by a replace's preparation+ * and the post-publication projection.+ */+export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId: number; sourceId: string; generation: number;+ occurrences: readonly ManifestRowInput[]; title: string; frontmatter: JsonObject; flags: JsonObject; chunking: SegmentChunkingContext;+ retiredOccurrences: 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. */+ guard?: { slug: string } }): 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];+ let rows = 0, done = 0;+ const indexes: number[] = [];+ for (let start = 0; start < input.occurrences.length;) {+ let end = start, bytes = 0;+ while (end < input.occurrences.length && (end === start || bytes + input.occurrences[end]!.byteLen <= batchBytes)) bytes += input.occurrences[end++]!.byteLen;+ const batch = input.occurrences.slice(start, end);+ start = end;+ const texts = await engine.readSegmentTexts(input.sourceId, batch.map(row => row.sha256));+ const chunks: SegmentChunkInput[] = [];+ for (const row of batch) {+ const text = texts.get(hex(row.sha256));+ if (text === undefined) throw new Error(`Segment text ${hex(row.sha256)} of page ${input.pageId} is missing.`);+ for (const chunk of prepareSegmentChunks({ ...row, text: utf8.decode(text) }, { flags: input.flags, frontmatter: input.frontmatter })) {+ chunks.push({ ...chunk, occurrence_id: row.occurrenceId });+ }+ }+ 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 });+ const guard = input.guard;+ if (chunks.length && !guard) indexes.push(...await engine.stageSegmentChunks(input.pageId, input.generation, chunks));+ if (chunks.length && guard) rows -= chunks.length - await engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: input.sourceId, slug: guard.slug }]);+ 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));+ if (still.length) await tx.stageSegmentChunks(input.pageId, input.generation, still);+ return still.length;+ });+ rows += chunks.length;+ done += batch.length;+ if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));+ }+ return { rows, occurrences: done, indexes };+}++/** The stored body of `pageId` at `generation` (default live), region by region, one segment at a time. */+export async function* readSegmentedBody(engine: BrainEngine, pageId: number, sourceId: string,+ opts: { generation?: number } = {}): AsyncIterable<{ region: BodyRegion; bytes: Uint8Array }> {+ const rows = await engine.readManifest(pageId, opts.generation === undefined ? {} : { generation: opts.generation });+ const batchBytes = STAGE_BATCH_BYTES[engine.kind];+ for (let start = 0; start < rows.length;) {+ let end = start, bytes = 0;+ while (end < rows.length && (end === start || bytes + rows[end]!.byteLen <= batchBytes)) bytes += rows[end++]!.byteLen;+ const batch = rows.slice(start, end);+ start = end;+ const texts = await engine.readSegmentTexts(sourceId, batch.map(row => row.sha256));+ for (const row of batch) {+ const text = texts.get(hex(row.sha256));+ if (text === undefined) throw new Error(`Segment text ${hex(row.sha256)} of page ${pageId} is missing.`);+ yield { region: row.region, bytes: text };+ }+ }+}++/** The whole body of a segmented page as strings. Only for pages within the single-string ceiling (callers check `body_bytes`). */+export async function materializeSegmentedBody(engine: BrainEngine, pageId: number, sourceId: string): Promise<{ compiled_truth: string; timeline: string }> {+ const parts: Record<BodyRegion, string[]> = { truth: [], timeline: [] };+ for await (const part of readSegmentedBody(engine, pageId, sourceId)) parts[part.region].push(utf8.decode(part.bytes));+ return { compiled_truth: parts.truth.join(''), timeline: parts.timeline.join('') };+}diff --git a/src/core/page-body/projection.ts b/src/core/page-body/projection.tsindex 66933e623e..355a6040ee 100644--- a/src/core/page-body/projection.ts+++ b/src/core/page-body/projection.ts@@ -3,15 +3,113 @@* occurrence that has no chunk rows at the page's live body generation, stage* them, retire rows of occurrences no longer live, and seal the text* projection when the page is still at `expectedRevision` (or its current- * revision). Reads one segment at a time. Used after a segmented create (whose- * chunks cannot be staged before the page row exists), by the projection job- * for a page left unsealed (crash, deferred retirement), and by rebuilds.+ * revision). Reads one segment batch at a time. Used after a segmented create+ * (whose chunks cannot be staged before the page row exists), by the+ * projection job for a page left unsealed (crash, deferred retirement), and by+ * rebuilds.+ *+ * Retirement runs in bounded statements: 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) get `retired_generation` = the+ * live generation, so they leave every reader's visibility filter at once and+ * GC deletes them later. Nothing is deleted here.*/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 { occurrencesWithoutChunks, stageOccurrenceChunks } from './ingest.ts';+import type { JsonObject } from './types.ts';export interface SegmentedProjectionResult { chunks: number; retired: number; sealed: boolean }-export async function buildSegmentedProjection(_engine: BrainEngine, _ref: { sourceId: string; slug: string },- _opts?: { expectedRevision?: string }): Promise<SegmentedProjectionResult> {- throw new Error('buildSegmentedProjection: implemented by Wave B lane 1d');+/** Chunk rows one retirement statement marks. */+const RETIRE_BATCH_ROWS = 5_000;++interface ProjectionPage {+ id: number; body_generation: number | string; knowledge_revision: string; text_projection_revision: string | null;+ title: string; frontmatter: JsonObject | null; body_flags: JsonObject | null; timeline_lead: string | null;+}++async function readProjectionPage(engine: Pick<BrainEngine, 'executeRaw'>, ref: { sourceId: string; slug: string }): Promise<ProjectionPage | null> {+ const [page] = await engine.executeRaw<ProjectionPage>(`SELECT id, body_generation, knowledge_revision::text AS knowledge_revision,+ text_projection_revision::text AS text_projection_revision, title, frontmatter, body_flags, timeline_lead+ FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL AND body_storage='segmented'`, [ref.sourceId, ref.slug]);+ return page ?? null;+}++/** Retire, in bounded batches, chunk rows the live generation does not hold: other occurrences, inline rows, older duplicates. */+async function retireStaleChunks(engine: Pick<BrainEngine, 'executeRaw' | 'kind'>, pageId: number, generation: number, live: readonly number[]): Promise<number> {+ let retired = 0;+ for (;;) {+ const rows = await engine.executeRaw<{ id: number }>(`UPDATE content_chunks c SET retired_generation=$2,+ body_generation=COALESCE(c.body_generation, 0)+ WHERE c.id IN (SELECT s.id FROM content_chunks s WHERE s.page_id=$1 AND s.retired_generation IS NULL+ AND (s.body_generation IS NULL+ OR (s.body_generation<=$2 AND NOT (s.occurrence_id=ANY($3::bigint[])))+ OR (s.body_generation<=$2 AND EXISTS (SELECT 1 FROM content_chunks n WHERE n.page_id=s.page_id AND n.occurrence_id=s.occurrence_id+ AND n.retired_generation IS NULL AND n.body_generation>s.body_generation AND n.body_generation<=$2)))+ LIMIT $4)+ RETURNING c.id`, [pageId, generation, live, RETIRE_BATCH_ROWS]);+ retired += rows.length;+ if (rows.length < RETIRE_BATCH_ROWS) return retired;+ if (engine.kind === 'pglite') await new Promise(resolve => setImmediate(resolve));+ }+}++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 };+ const generation = Number(page.body_generation);+ const pageId = Number(page.id);+ const liveRows = await engine.readManifest(pageId);+ const retired = await retireStaleChunks(engine, pageId, generation, liveRows.map(row => Number(row.occurrenceId)));+ const frontmatter = page.frontmatter ?? {};+ const quarantined = isQuarantined(frontmatter);+ const unchunked = await occurrencesWithoutChunks(engine, pageId, generation, liveRows);+ const staged = await stageOccurrenceChunks(engine, { pageId, sourceId: ref.sourceId, generation, occurrences: unchunked, title: page.title,+ frontmatter, flags: page.body_flags ?? {}, chunking: { quarantined, corpusGeneration: null, tier: 'none' }, retiredOccurrences: [], guard: { slug: 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 }]);+ const current = await readProjectionPage(tx, ref);+ if (!current || current.knowledge_revision !== page.knowledge_revision || Number(current.body_generation) !== generation) return false;+ if (current.text_projection_revision !== current.knowledge_revision) await sealSegmentedPage(tx, pageId, current.timeline_lead ?? '');+ return true;+ });+ return { chunks: staged.rows, retired, sealed };+}++/**+ * The projection queue's segmented route: the queued rows of live segmented+ * pages (failed rows after their retry window), rebuilt by+ * `buildSegmentedProjection` at the queued revision. A failure marks the row+ * `rebuild_failed` like the inline route; a page whose revision moved is+ * left to the row the trigger queued for its new revision.+ */+export async function rebuildPendingSegmentedProjections(engine: BrainEngine, limit: number,+ opts: { deadlineMs?: number; now?: () => number } = {}): Promise<{ rebuilt: number; failed: number }> {+ const now = opts.now ?? Date.now;+ const startedAt = now();+ const jobs = await engine.executeRaw<{ source_id: string; source_incarnation: string; slug: string; revision: string }>(`SELECT s.id AS source_id,+ j.source_incarnation::text AS source_incarnation, j.slug, j.revision::text AS revision+ FROM page_projection_jobs j JOIN sources s ON s.incarnation=j.source_incarnation AND NOT s.archived+ JOIN pages p ON p.source_id=s.id AND p.slug=j.slug AND p.deleted_at IS NULL AND p.body_storage='segmented'+ WHERE ${PROJECTION_RETRY_READY_SQL} ORDER BY j.updated_at, j.slug LIMIT $1`, [Math.max(1, limit)]);+ let rebuilt = 0, failed = 0;+ for (const [index, job] of jobs.entries()) {+ if (opts.deadlineMs !== undefined && index > 0 && now() - startedAt >= opts.deadlineMs) break;+ try {+ if (!(await buildSegmentedProjection(engine, { sourceId: job.source_id, slug: job.slug }, { expectedRevision: job.revision })).sealed) continue;+ rebuilt++;+ await engine.executeRaw('DELETE FROM page_projection_jobs WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid', [job.source_incarnation, job.slug, job.revision]);+ } catch {+ failed++;+ await engine.executeRaw(`UPDATE page_projection_jobs SET reason='rebuild_failed', updated_at=now()+ WHERE source_incarnation=$1::uuid AND slug=$2 AND revision=$3::uuid`, [job.source_incarnation, job.slug, job.revision]);+ }+ }+ return { rebuilt, failed };}diff --git a/src/core/page-body/streamed-import.ts b/src/core/page-body/streamed-import.tsnew file mode 100644index 0000000000..1d273ef3bc--- /dev/null+++ b/src/core/page-body/streamed-import.ts@@ -0,0 +1,327 @@+/**+ * Streamed import of a Markdown file above the single-string ceiling (Wave B,+ * spec 3.1, integrator decision 1): with `pages.segmented_storage` on, a file+ * over `PAGE_MAX_BYTES` and at most `readPageBodyPolicy().maxBytes` is read+ * twice through one descriptor and never held as one string. Pass 1+ * (`BodyScanner`) parses the bounded head and decides the timeline split and+ * fence trust; pass 2 streams the stored regions through the segmenter, the+ * hash and the staging (`prepareSegmentedBody`). The publication runs in one+ * maintenance transaction, as `importFromContent` does on an unmanaged brain.+ *+ * Every `importFromFile` / `importFromContent` step either runs here on the+ * head or per segment, or holds the file as `file_too_large` (today's refusal+ * of the same file), so nothing is stored that the string path would not store:+ *+ * - runs: symlink and malformed-path refusals; BOM strip; frontmatter+ * inference (head: the first 20 lines must be in it); the frontmatter holds+ * and the path-authoritative slug; gate-owned marker strip (a quarantine+ * override binds the whole body, so it is dropped: fail closed); content+ * sanity (junk patterns read a 2 KB head, size from the stored byte count);+ * NUL strip (per segment); type preservation and subtype; provenance,+ * effective date, tags, frontmatter aliases; the content hash (resumed per+ * segment); the no-op skip; identity dedup by hash (an external `id` holds);+ * code-reference edges (per line, skipped when the body has protected+ * regions); the read-back check and the gate receipt.+ * - holds: a registered guardrail (it reads the whole payload); the+ * content-sanity prose pass (it runs only when `bytes_block` is above the+ * body size); a write gate that applies to the source's tier; facts or takes+ * fences (fence normalization, withdrawal and purge preservation parse the+ * whole body); derived entity aliases (a linkable page type); NUL bytes (the+ * size check needs the stored byte count before the hash); invalid UTF-8+ * (the string path decodes it lossily); a file that changes between passes.+ */+import { open, type FileHandle } from 'node:fs/promises';+import { constants } from 'node:fs';+import { basename, resolve } from 'node:path';+import type { BrainEngine } from '../engine.ts';+import type { ImportResult } from '../import-file.ts';+import { BodyScanner, type BodyPiece, type BodyScan } from './body-scan.ts';+import { FRONTMATTER_HEAD_MAX_BYTES, SEGMENT_MAX_BYTES, type PageBodyPolicy } from './limits.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';+import { classifyImportHold, resolveParsedSubtype, type ParsedMarkdown } from '../markdown.ts';+import { loadImportSanityConfig, settleContentDisposition, stripGateOwnedMarkers } from '../import-screen.ts';+import { DEFAULT_BYTES_BLOCK, SCAN_HEAD_BYTES } from '../content-sanity.ts';+import { QUARANTINE_OVERRIDE_KEY } from '../quarantine-override.ts';+import { hasGuardrails } from '../guardrails.ts';+import { DEFAULT_WRITE_GATE_CONFIG, writeGateApplies } from '../write-gate.ts';+import { assertSourceFilePath, assertSourceFilesystemActive } from '../minions/source-filesystem.ts';+import { assertUnmanagedCanonicalWriter } from '../persistence/maintenance.ts';+import { maintenanceAttribution, maintenanceTransaction, ownerSourceGateInput, trustMarkerChanged, writeTrustOfGate } from '../persistence/attribution.ts';+import { assertImportBase } from '../page-state/import-guard.ts';+import { stabilizeSafetyAssessments } from '../persistence/reconcile-safety.ts';+import { collidingSlugOwner, decideImportIdentity, fileOriginUri } from '../import-identity.ts';+import { classifyStoredType } from '../schema-pack/type-usage.ts';+import { addPageTags } from '../page-state/tags.ts';+import { computeEffectiveDate, fallbackCreatedAt } from '../effective-date.ts';+import { writePageAliases } from '../mentions/pass.ts';+import { linkableTypesFor, readMentionPolicy, type PackTypes } from '../mentions/policy.ts';+import { resolveImportContextualMode } from '../import-contextual-mode.ts';+import { suffixedFrontmatterSlugHold } from '../persistence/suffixed-slug.ts';+import { logSlugFallback } from '../audit-slug-fallback.ts';+import { extractCodeRefs } from '../link-extraction.ts';+import { hasMalformedPathSegment, slugifyCodePath, slugifyPath } from '../sync.ts';+import { isEmbedSkipped } from '../embed-skip.ts';+import { sanitizeText } from '../batch-rows.ts';+import { applySegmentedBody, sealSegmentedPage, segmentedLivePage } from '../persistence/segmented-apply.ts';+import { buildSegmentedProjection } from './projection.ts';+import { prepareSegmentedBody, utf8Prefix } from './ingest.ts';+import type { JsonObject } from './types.ts';++const READ_BYTES = 1024 * 1024;+const FENCE_MARKER = /gbrain:(facts|takes):begin/;++type StreamedImportOptions = {+ noEmbed?: boolean;+ inferFrontmatter?: boolean;+ sourceId?: string;+ forceRechunk?: boolean;+ activePack?: { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };+ firstCommitAt?: Date;+};++/** Today's refusal of a file over the single-string ceiling, naming the step that needs the whole body. */+function hold(slug: string, size: number, reason: string): ImportResult {+ const message = `File too large (${size} bytes, max ${PAGE_MAX_BYTES}): ${reason}, which needs the whole body as one string.`;+ return { slug, status: 'skipped', chunks: 0, error: message, refusal: { code: 'file_too_large', message }, skip_reason: 'file_too_large' };+}++/** Bytes `[start, end)` of the virtual stream: `prefix` (inferred frontmatter), then the file after its BOM. */+async function* readVirtual(file: FileHandle, bom: number, prefix: Uint8Array, start: number, end: number): AsyncIterable<Uint8Array> {+ if (start < prefix.length) yield prefix.subarray(start, Math.min(end, prefix.length));+ for (let at = Math.max(start, prefix.length); at < end;) {+ const buffer = Buffer.allocUnsafe(Math.min(READ_BYTES, end - at));+ const { bytesRead } = await file.read(buffer, 0, buffer.length, at - prefix.length + bom);+ if (bytesRead === 0) throw new Error('The file shrank while it was imported.');+ yield buffer.subarray(0, bytesRead);+ at += bytesRead;+ }+}++/** One stored region: its pieces in order, NUL bytes stripped (`sanitizeText` on a valid UTF-8 stream), every chunk passed to `inspect`. */+async function* regionStream(pieces: readonly BodyPiece[], read: (start: number, end: number) => AsyncIterable<Uint8Array>,+ inspect: (bytes: Uint8Array) => void): AsyncIterable<Uint8Array> {+ for (const piece of pieces) {+ const parts = 'text' in piece ? [Buffer.from(sanitizeText(piece.text), 'utf8')] : read(piece.start, piece.end);+ for await (const part of parts) {+ const bytes = part.includes(0) ? part.filter(byte => byte !== 0) : part;+ inspect(bytes);+ yield bytes;+ }+ }+}++/** The first `max` bytes of a region (NUL-free), as text cut on a code-point boundary. */+async function regionHead(pieces: readonly BodyPiece[], read: (start: number, end: number) => AsyncIterable<Uint8Array>, max: number): Promise<string> {+ const parts: Uint8Array[] = [];+ let bytes = 0;+ for await (const part of regionStream(pieces, (start, end) => read(start, Math.min(end, start + max)), () => undefined)) {+ parts.push(part);+ bytes += part.length;+ if (bytes >= max) break;+ }+ return utf8Prefix(Buffer.concat(parts), max);+}++/**+ * Code references by line (as `extractCodeRefs` over the whole body finds+ * them): complete lines are scanned as they arrive; a line longer than one+ * segment is skipped.+ */+class CodeRefLines {+ readonly refs = new Map<string, { path: string; line?: number }>();+ private carry = '';+ private readonly decoder = new TextDecoder();++ push(bytes: Uint8Array): void {+ const text = this.carry + this.decoder.decode(bytes, { stream: true });+ const cut = text.lastIndexOf('\n');+ if (cut < 0) { this.carry = text.length > SEGMENT_MAX_BYTES ? '' : text; return; }+ this.scan(text.slice(0, cut));+ this.carry = text.slice(cut + 1);+ }++ end(): void {+ this.scan(this.carry + this.decoder.decode());+ this.carry = '';+ }++ private scan(text: string): void {+ for (const ref of extractCodeRefs(text)) this.refs.set(`${ref.path}:${ref.line ?? ''}`, ref);+ }+}++/** Pass 1 over the virtual stream; `prefix` is inferred frontmatter (empty when none). */+async function scanFile(file: FileHandle, bom: number, prefix: Uint8Array, size: number, relativePath: string, opts: StreamedImportOptions) {+ const scanner = new BodyScanner(relativePath, { validate: true, ...(opts.activePack ? { activePack: opts.activePack } : {}) });+ if (prefix.length) scanner.push(prefix);+ for await (const part of readVirtual(file, bom, new Uint8Array(0), 0, size - bom)) scanner.push(part);+ return scanner.finish();+}++/** Frontmatter inference on the head, exactly as on the whole file when the head holds its first 20 lines; else null (undecidable). */+async function inferredPrefix(file: FileHandle, bom: number, size: number, relativePath: string): Promise<Uint8Array | null> {+ const buffer = Buffer.alloc(Math.min(FRONTMATTER_HEAD_MAX_BYTES, size - bom));+ await file.read(buffer, 0, buffer.length, bom);+ const raw = utf8Prefix(buffer, buffer.length);+ const head = raw.slice(0, raw.lastIndexOf('\n') + 1);+ if (head.split('\n').length <= 20 || !head.trim()) return null;+ const { applyInference } = await import('../frontmatter-inference.ts');+ const { content, inferred } = applyInference(relativePath, head);+ return Buffer.from(inferred.skipped ? '' : content.slice(0, content.length - head.length), 'utf8');+}++export async function importStreamedMarkdownFile(engine: BrainEngine, filePath: string, relativePath: string, opts: StreamedImportOptions,+ stat: { size: number; mtimeMs: number; birthtime: Date; mtime: Date }, policy: PageBodyPolicy): Promise<ImportResult> {+ if (hasMalformedPathSegment(relativePath)) {+ return { slug: '', status: 'skipped', skip_reason: 'malformed_path', chunks: 0,+ error: `Path "${relativePath}" contains bracket or control characters and cannot be imported. Rename the file to import it.` };+ }+ await assertUnmanagedCanonicalWriter(engine, 'direct content import');+ const expectedSlug = slugifyPath(relativePath);+ const file = await open(assertSourceFilePath(filePath), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));+ try {+ const opened = await file.stat();+ if (!opened.isFile() || opened.size !== stat.size || opened.mtimeMs !== stat.mtimeMs) return hold(expectedSlug, stat.size, 'the file changed while it was opened');+ const size = opened.size;+ const bomBytes = Buffer.alloc(3);+ await file.read(bomBytes, 0, 3, 0);+ const bom = bomBytes[0] === 0xef && bomBytes[1] === 0xbb && bomBytes[2] === 0xbf ? 3 : 0;+ const prefix = opts.inferFrontmatter !== false ? await inferredPrefix(file, bom, size, relativePath) : new Uint8Array(0);+ if (!prefix) return hold(expectedSlug, size, 'frontmatter inference reads the first 20 lines, and they are not within the file head');+ const scan = await scanFile(file, bom, prefix, size, relativePath, opts);+ if (scan.kind === 'frontmatter_head_unbounded') {+ return { slug: expectedSlug, status: 'skipped', chunks: 0, error: scan.message, refusal: { code: 'invalid_frontmatter', message: scan.message }, skip_reason: 'invalid_frontmatter' };+ }+ if (scan.kind === 'invalid_utf8') return hold(expectedSlug, size, `the file is not valid UTF-8 at byte ${scan.offset} (the text path decodes it lossily)`);+ return await importScanned(engine, { file, bom, prefix, size, scan, relativePath, filePath, expectedSlug, stat, policy, opts });+ } finally {+ await file.close();+ }+}++async function importScanned(engine: BrainEngine, input: { file: FileHandle; bom: number; prefix: Uint8Array; size: number; scan: BodyScan;+ relativePath: string; filePath: string; expectedSlug: string; stat: { mtimeMs: number; birthtime: Date; mtime: Date }; policy: PageBodyPolicy; opts: StreamedImportOptions }): Promise<ImportResult> {+ const { file, bom, prefix, size, scan, relativePath, expectedSlug, opts } = input;+ const sourceId = opts.sourceId ?? 'default';+ const parsed = { ...scan.parsed, compiled_truth: '', timeline: '' } as ParsedMarkdown;+ const frontmatterHold = classifyImportHold(parsed);+ if (frontmatterHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: frontmatterHold.message, refusal: frontmatterHold, skip_reason: 'invalid_frontmatter' };+ let slug = expectedSlug;+ if (!expectedSlug || parsed.slug !== expectedSlug) {+ if (!expectedSlug ? !parsed.slug : slugifyPath(parsed.slug) !== expectedSlug) {+ const { slugConflictHoldMessage } = await import('../import-file.ts');+ return !expectedSlug+ ? { slug: '', status: 'skipped', chunks: 0, error: `Filename "${relativePath}" produces no usable slug. Add a "slug:" to the frontmatter, or rename the file to include at least one letter or number (any script).` }+ : { slug: expectedSlug, status: 'skipped', chunks: 0, error: `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expectedSlug}" (from ${relativePath}). Remove the frontmatter "slug:" line or move the file.`,+ refusal: { code: 'frontmatter_slug_conflict', key: 'slug', message: slugConflictHoldMessage(relativePath, expectedSlug) }, skip_reason: 'frontmatter_slug_conflict' };+ }+ const suffixHold = await suffixedFrontmatterSlugHold(engine, sourceId, relativePath, parsed.slug);+ if (suffixHold) return { slug: expectedSlug, status: 'skipped', chunks: 0, error: suffixHold.message, refusal: suffixHold, skip_reason: suffixHold.code };+ slug = parsed.slug;+ logSlugFallback(slug, relativePath, expectedSlug ? 'normalization-equivalent identity restore' : 'path slugified empty');+ }+ if (hasGuardrails()) return hold(slug, size, 'a registered guardrail reads the whole payload');+ if (scan.bodyFlags.has_nul) return hold(slug, size, 'NUL bytes change the stored size the content gate measures');+ const read = (start: number, end: number) => readVirtual(file, bom, prefix, start, end);+ parsed.title = sanitizeText(parsed.title);+ delete parsed.frontmatter[QUARANTINE_OVERRIDE_KEY];+ const writeGate = await ownerSourceGateInput(engine, sourceId, parsed.frontmatter);+ stripGateOwnedMarkers(parsed, { preserveGateMarkers: true, writeGate });+ const sanity = await loadImportSanityConfig(engine);+ if (writeGateApplies(writeGate.tier, sanity.writeGate ?? DEFAULT_WRITE_GATE_CONFIG)) return hold(slug, size, `the write gate scans the whole body of a ${writeGate.tier} page`);+ const bodyBytes = scan.truthBytes + (scan.timelineBytes ? 1 + scan.timelineBytes : 0);+ if (!sanity.disabled && (sanity.cs.bytes_block ?? DEFAULT_BYTES_BLOCK) >= bodyBytes) return hold(slug, size, 'the content-sanity prose pass samples the whole body below content_sanity.bytes_block');+ const truthHead = await regionHead(scan.truth, read, SCAN_HEAD_BYTES * 4);+ const head = { ...parsed, compiled_truth: truthHead, timeline: truthHead.length >= SCAN_HEAD_BYTES ? '' : await regionHead(scan.timeline, read, SCAN_HEAD_BYTES * 4) };+ const disposition = await settleContentDisposition(engine, head, { slug, sourceId, stripped: false, writeGate, bodyBytes });+ const existing = await engine.getPage(slug, { sourceId, includeDeleted: true });+ if (existing?.deleted_at) return hold(slug, size, 'restoring a deleted page rewrites its body through the inline writer');+ if (existing) stabilizeSafetyAssessments(parsed.frontmatter, existing.frontmatter);+ const sourceRoot = resolve(input.filePath, ...relativePath.split(/[\\/]/).map(() => '..'));+ const collisionOwner = collidingSlugOwner(existing, slug, sourceRoot, relativePath);+ if (collisionOwner) {+ process.stderr.write(`[import] slug collision: ${relativePath} and ${collisionOwner} both map to ${slug} in source ${sourceId}; keeping ${collisionOwner}. Rename one file to import both.\n`);+ return { slug, status: 'skipped', chunks: 0, skip_reason: 'slug_collision' };+ }+ if (parsed.typeExplicit !== true && existing) parsed.type = existing.type;+ resolveParsedSubtype(parsed, existing);+ const typeClass = parsed.typeExplicit === true && opts.activePack ? classifyStoredType(parsed.type, opts.activePack) : null;+ const typeWarning = typeClass?.kind === 'alias_of' ? { kind: 'alias_of' as const, type: parsed.type, canonical: typeClass.canonical, directory: typeClass.directory }+ : typeClass?.kind === 'undeclared' ? { kind: 'undeclared' as const, type: parsed.type } : undefined;+ const mentionPolicy = await readMentionPolicy(engine).catch(() => null);+ if (mentionPolicy?.enabled && linkableTypesFor((opts.activePack as PackTypes | undefined) ?? null, mentionPolicy).includes(parsed.type)) {+ return hold(slug, size, `derived entity aliases of a ${parsed.type} page read the whole body`);+ }+ const fmId = (parsed.frontmatter as Record<string, unknown>).id;+ if (typeof fmId === 'string' && fmId.length > 0) return hold(slug, size, 'identity dedup by frontmatter id compares whole bodies');+ parsed.tags.sort();+ const { mode, corpusGeneration } = await resolveImportContextualMode(engine, sourceId, parsed.frontmatter, false);+ const { principal } = await maintenanceAttribution(engine);+ const live = existing ? await segmentedLivePage(engine, Number(existing.id)) : null;+ let fenced = false;+ const codeRefs = new CodeRefLines();+ let carry = '';+ const inspect = (bytes: Uint8Array) => {+ const text = carry + Buffer.from(bytes).toString('latin1');+ if (FENCE_MARKER.test(text)) fenced = true;+ carry = text.slice(-24);+ codeRefs.push(bytes);+ };+ assertSourceFilesystemActive();+ const prepared = await prepareSegmentedBody(engine, { sourceId, slug, live, title: parsed.title, type: parsed.type, frontmatter: parsed.frontmatter as JsonObject,+ tags: parsed.tags, truth: regionStream(scan.truth, read, inspect),+ timeline: (async function* () { codeRefs.end(); carry = ''; yield* regionStream(scan.timeline, read, inspect); })(),+ flags: { fence_trust: scan.bodyFlags.fence_trust, timeline_fence_trust: scan.bodyFlags.timeline_fence_trust, timeline_split: scan.bodyFlags.timeline_split },+ declaredBytes: scan.truthBytes + scan.timelineBytes,+ owner: { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: existing?.knowledge_revision ?? null },+ chunking: { quarantined: disposition.quarantined, corpusGeneration, tier: mode === 'title' ? 'title' : 'none' } });+ codeRefs.end();+ const abort = async () => { await engine.setBodyStagingState(prepared.stagingId, 'aborted').catch(() => undefined); };+ const after = await file.stat();+ if (after.size !== size || after.mtimeMs !== input.stat.mtimeMs) { await abort(); return hold(slug, size, 'the file changed while it was imported (import it again)'); }+ if (fenced) { await abort(); return hold(slug, size, 'facts and takes fences are normalized and checked against withdrawals over the whole body'); }+ const hash = prepared.body.content_hash;+ if (existing && !existing.deleted_at && !opts.forceRechunk && existing.content_hash === hash && existing.text_projection_revision === existing.knowledge_revision+ && isEmbedSkipped(existing.frontmatter) === isEmbedSkipped(parsed.frontmatter) && !trustMarkerChanged(existing.frontmatter, parsed.frontmatter)) {+ await abort();+ return { slug, status: 'skipped', chunks: 0, ...(typeWarning ? { type_warning: typeWarning } : {}) };+ }+ const identity = await decideImportIdentity(engine, { sourceId, slug, hash, frontmatterId: null, sourcePath: relativePath, sourceRoot, body: { title: parsed.title, compiled_truth: '', timeline: '' } });+ if (identity.kind === 'shared_hash') process.stderr.write(`[import] WARNING: ${relativePath} shares content_hash with ${identity.dupSlug} in source ${sourceId}. Indexing both.\n`);+ const nowDate = new Date();+ const { loadBrainTimeZone } = await import('../import-file.ts');+ const filename = basename(relativePath, '.md');+ const { date: effectiveDate, source: effectiveDateSource } = computeEffectiveDate({ slug, frontmatter: parsed.frontmatter, filename, timeZone: await loadBrainTimeZone(engine),+ updatedAt: existing?.updated_at ?? nowDate,+ createdAt: fallbackCreatedAt({ existing, fileTimes: { birthtime: input.stat.birthtime, mtime: input.stat.mtime, firstCommit: opts.firstCommitAt }, now: nowDate }) });+ const meta = { type: parsed.type, title: parsed.title, frontmatter: parsed.frontmatter as JsonObject, page_kind: 'markdown' as const,+ effective_date: effectiveDate, effective_date_source: effectiveDateSource, import_filename: filename, source_path: relativePath,+ source_kind: null, source_uri: fileOriginUri(existing?.source_uri, sourceRoot, relativePath), ingested_via: null };+ const linkOpts = { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId };+ const refs = prepared.body.body_flags.has_protected ? [] : [...codeRefs.refs.values()];+ const applied = await maintenanceTransaction(engine, async tx => {+ await assertImportBase(tx, slug, sourceId, existing);+ if (existing) await tx.createVersion(slug, { sourceId });+ const result = await applySegmentedBody(tx, { slug, sourceId, pageId: live?.id ?? null, prepared, meta, promotion: live?.storage === 'inline', retireMaxRows: input.policy.flipRetireMaxRows });+ await tx.updatePageContextualRetrievalState(slug, sourceId, mode, corpusGeneration);+ await tx.executeRaw(`DELETE FROM tags t USING pages p WHERE p.id = t.page_id AND p.source_id = $1 AND p.slug = $2+ AND t.tag_source = 'frontmatter' AND NOT (t.tag = ANY($3::text[]))`, [sourceId, slug, parsed.tags]);+ await addPageTags(tx, result.pageId, parsed.tags, 'frontmatter');+ await writePageAliases(tx, slug, sourceId, { ...parsed, compiled_truth: '', timeline: '' }, opts.activePack, mentionPolicy);+ if (result.complete) await sealSegmentedPage(tx, result.pageId);+ for (const ref of refs) {+ const codeSlug = slugifyCodePath(ref.path);+ await tx.transaction(savepoint => savepoint.addLink(slug, codeSlug, ref.line ? `cited at ${ref.path}:${ref.line}` : ref.path, 'documents', 'markdown', slug, 'compiled_truth', linkOpts)).catch(() => undefined);+ await tx.transaction(savepoint => savepoint.addLink(codeSlug, slug, ref.path, 'documented_by', 'markdown', slug, 'compiled_truth', linkOpts)).catch(() => undefined);+ }+ const { verifyPageReadable } = await import('../import-file.ts');+ await verifyPageReadable(tx, slug, hash, sourceId, 'importStreamedMarkdownFile');+ await disposition.persistReceipt(tx, { existed: !!existing });+ return result;+ }, writeTrustOfGate(writeGate)).catch(async error => { await abort(); throw error; });+ if (!applied.complete) await buildSegmentedProjection(engine, { sourceId, slug }).catch(() => undefined);+ await engine.sweepSegments({ pageId: applied.pageId }).catch(() => undefined);+ return { slug, status: 'imported', chunks: prepared.rows.chunks,+ ...(disposition.quarantined ? { quarantined: true } : {}), ...(disposition.flagged ? { flagged: true, flag_reason: disposition.flagReason } : {}),+ ...(disposition.gate ? { gate: disposition.gate } : {}), ...(typeWarning ? { type_warning: typeWarning } : {}) };+}diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex c7b82d6508..917ec83703 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -398,7 +398,7 @@ export async function preparePageProjection(prepared: ProjectionSnapshot) {const PROJECTION_JOB_PROBES = `CROSS JOIN LATERAL (SELECT s.id FROM sources sWHERE s.incarnation=j.source_incarnation AND NOT s.archived OFFSET 0) sCROSS JOIN LATERAL (SELECT p.page_kind FROM pages p WHERE p.source_id=s.id AND p.slug=j.slug- AND p.deleted_at IS NULL AND p.page_kind IN ('markdown','code') OFFSET 0) p`;+ AND p.deleted_at IS NULL AND p.page_kind IN ('markdown','code') AND p.body_storage IS DISTINCT FROM 'segmented' OFFSET 0) p`;/*** Rebuilds between statistics refreshes, per engine. Like autovacuum's analyzediff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex d552cb0ccf..fb271ec386 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -1,6 +1,6 @@import type { BrainEngine, ReservedConnection } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, independentGroup, publicationGroupKey, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, vacuumPersistenceQueues } from './journal.ts';+import { claimableWriteSql, foregroundPrioritySql, claimGroupFollowers, claimNextLaneHead, claimNextWrite, independentGroup, publicationGroupKey, floorPreparationAttempts, hasClaimableWrite, getWriteRequestById, releaseUnpublishedClaim, renewWriteClaim, sweepSegmentStorage, vacuumPersistenceQueues } from './journal.ts';import { finishPreparationStalled, finishUnpublishedFailure, preparationAbortReason, recoverPublication, type PreparedMutation } from './coordinator.ts';import { localHostId } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX, publishSingleWrite, singleWrite } from './group-publish.ts';@@ -12,6 +12,7 @@ import { isTerminal, type WriteRequest } from './model.ts';import { ownerExceptionLogText } from './publication-failure.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';+import { rebuildPendingSegmentedProjections } from '../page-body/projection.ts';import { publicationConcurrency } from './pool-capacity.ts';import { claimedHeadOrder } from './sync-window.ts';import { laneClaim, laneOf, laneRoots, laneTask } from './sync-lanes.ts';@@ -104,8 +105,11 @@ export async function runResidentProjectionInvocation(engine: BrainEngine, hostI// Advisory and bounded by the caller's signal: a probe that cannot answer// (for example behind a table lock) counts as a waiting write.const writesWaiting = publicationConcurrency(engine) > 0 && await hasClaimableWrite(engine, hostId, excludeRoots, signal).catch(() => true);- return rebuildPendingPageProjections(engine, writesWaiting ? WRITE_WAITING_PROJECTION_PAGES : RESIDENT_PROJECTION_PAGES,- { deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now, retryCooldown: true });+ const pages = writesWaiting ? WRITE_WAITING_PROJECTION_PAGES : RESIDENT_PROJECTION_PAGES;+ // Wave B: queued segmented pages are rebuilt first, through their own route (one segment batch at a time).+ const startedAt = now();+ await rebuildPendingSegmentedProjections(engine, pages, { deadlineMs: RESIDENT_PROJECTION_BUDGET_MS, now });+ return rebuildPendingPageProjections(engine, pages, { deadlineMs: Math.max(0, RESIDENT_PROJECTION_BUDGET_MS - (now() - startedAt)), now, retryCooldown: true });}const PARKED_WORKER: Promise<void> = Promise.resolve();@@ -539,7 +543,8 @@ export class PersistenceConsumer implements PersistenceConsumerLike {if (!this.maintenanceWorker && (Date.now() >= this.nextMaintenance || this.publishedSinceMaintenance >= this.maintenanceVolume)) {this.nextMaintenance = Date.now() + 60_000;this.publishedSinceMaintenance = 0;- this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => vacuumPersistenceQueues(this.engine))+ this.maintenanceWorker = runCompactionPass(this.engine, { hostId: this.hostId, notice: this.opts.drainNotice }).then(() => sweepSegmentStorage(this.engine).catch(error => this.report(error)))+ .then(() => vacuumPersistenceQueues(this.engine)).then(rows => { this.maintenanceVolume = 50 + Math.ceil(rows * 0.2); }).catch(error => this.report(error)).finally(() => { this.maintenanceWorker = undefined; });}diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 76389a8806..5ae6464960 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -72,6 +72,11 @@ interface PreparedMutationBase {validate?(tx: BrainEngine): Promise<void>;/** #5575: the tier and origin of the rows apply writes; absent: the request's channel tier (trust/channel.ts). */trust?: WriteTrust;+ /**+ * Wave B: runs once the publication committed and its recovery record is cleared (a segmented page's+ * deferred projection and segment GC). Best effort: the projection queue and GC converge after a failure.+ */+ afterCommit?(engine: BrainEngine): Promise<void>;}/*** A page file target; `publishMode` (Google pages) is the exact mode it publishes with, and its created directories get 0700.@@ -425,6 +430,13 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr});await hooks.boundary?.('after_commit', done);if (recovery) await clearResolvedRecovery(engine, row.id, done);+ if (done.state === 'committed' && prepared.afterCommit) {+ releaseCapacity?.();+ releaseCapacity = null;+ await lock?.release();+ lock = null;+ await prepared.afterCommit(engine).catch(() => undefined);+ }return done;} catch (error) {if (recovery) {@@ -545,6 +557,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdawait faultPoint('publication_recovery:before_clear', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });await clearResolvedRecovery(engine, id);row = (await getWriteRequestById(engine, id))!;+ if (row.page_id !== null && row.state === 'committed') await engine.sweepSegments({ pageId: Number(row.page_id) }).catch(() => undefined);}return row;} finally { releaseCapacity?.(); await lock?.release(); }diff --git a/src/core/persistence/fault-points.ts b/src/core/persistence/fault-points.tsindex df0f15d25d..b667951b40 100644--- a/src/core/persistence/fault-points.ts+++ b/src/core/persistence/fault-points.ts@@ -4,7 +4,7 @@* recovery path must finish: publication boundaries, after an effect's side* effect but before its completion is recorded, before a recovery record is* cleared, between sync checkpoints, after the consumer prepared a- * claimed request, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, and (`stuck_recovery:*`) between the steps of a stuck-recovery resolution. Production never installs a hook, so every call is a+ * claimed request, (`lane:applied`) when a lane group has applied its pages and waits for its commit turn, (`stuck_recovery:*`) between the steps of a stuck-recovery resolution, and (`segmented:*`) between the stages of a segmented write. Production never installs a hook, so every call is a* no-op there; the gate's workers install one that SIGKILLs or stalls the* process at a chosen point.*/@@ -22,7 +22,10 @@ export type FaultPoint = `publication:${PublicationBoundary}` | `effect:${Effect| 'purge:sweep_chunk' | 'purge:carrying_lookup'// #6650: `gbrain repair stuck-recovery` (recovery-resolve.ts): after the backup is durable (before its journal step), after the prior// bytes are written (before their journal step), after a --keep disk write is abandoned (its journal step written), and after recoverPublication returns.- | 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered';+ | 'stuck_recovery:backed_up' | 'stuck_recovery:written' | 'stuck_recovery:abandoned' | 'stuck_recovery:recovered'+ // Wave B segmented writes (spec 3.4 crash windows): after the texts, the staged manifest rows and the staged chunks of a+ // preparation, after the generation flip (inside the publication transaction), and after a projection staged its chunks (before its seal).+ | 'segmented:texts_staged' | 'segmented:manifest_staged' | 'segmented:chunks_staged' | 'segmented:flipped' | 'segmented:projection_staged';/*** `signal` (#6278, `consumer:preparing` only): the preparation's abort signal, so* a stalling hook can model both the reporter's cases: a preparer that honoursdiff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 110137d019..95c9e438fb 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -16,6 +16,7 @@ import { pageFencesNormalized } from '../fence-repair/report.ts';import { isWriteTargetContained } from '../path-confine.ts';import { assertPageRevision } from '../page-state/types.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';+import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { getWorktreeBinding } from './ownership.ts';import { localHostId } from './identity.ts';@@ -176,7 +177,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri`${p.sourcePath} now normalizes to different content or slug than import request ${row.request_id} accepted for ${row.slug}, so it published nothing. Import it again to publish the current file.`,{ fix: reimportFix(p.inputPath, row.source_id) });const source = { sourceId: row.source_id };- const snapshot = screen ? screen.snapshot : await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ const snapshot = await materializedSnapshot(engine, screen ? screen.snapshot : await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }));assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',@@ -194,7 +195,8 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri: code? await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true, prepare }): await importFromContent(engine, row.slug, p.content, { ...source, noEmbed: true, remote: false, preserveGateMarkers: true, prepare, fences: 'coordinated', writeGate: await ownerGateInput(engine, row, parseMarkdown(p.content, row.slug).frontmatter, p.sourcePath),- coordinated: true, existingSnapshot: snapshot, activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true });+ coordinated: true, existingSnapshot: snapshot, activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true,+ segmentedOwner: { kind: 'import', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } });if (!prepared && result.refusal?.code === 'invalid_fence') throw managedImportRefusal(result.refusal, p.sourcePath);if (!prepared) throw opError('invalid_params', result.error ?? 'The file could not be prepared.',`${p.sourcePath} was rejected while preparing import request ${row.request_id} for source ${row.source_id}; nothing was published. Fix the file content or frontmatter named in the message, then import it again.`,@@ -213,6 +215,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wriconst project = code || image ? undefined : await prepareCanonicalProjections(engine, ready.parsedPage!, row.slug, row.source_id, snapshot, 'file');const mutation: PreparedMutation = { observedRevision: ready.observedRevision, noop: ready.noop && p.targetHash === sha256(rendered),trust: await ownerImportTrust(engine, row, ready.parsedPage?.frontmatter, p.sourcePath), deferEmbedding: image || p.noEmbed, validate: async tx => { await checkPaths(tx); await ready.validate(tx); },+ ...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),file: { root, path, content: rendered, expectedBeforeHash: p.targetHash },apply: async tx => {const applied = await ready.apply(tx);@@ -226,7 +229,8 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wriif (!ready.noop) {await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);await project(tx, final?.page.id);- if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);+ if (applied?.segmented) { if (applied.segmented.complete && live) await sealSegmentedPage(tx, Number(live.page.id)); }+ else if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);}mutation.postimage = final;diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 5c749e71c3..b3f5dbdbad 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -941,6 +941,19 @@ export async function vacuumPersistenceQueues(engine: BrainEngine): Promise<numbreturn Number(requests?.rows ?? 0);}+/**+ * Wave B segment GC (spec 3.5), run by the resident owner next to the queue+ * vacuum: expires body stagings past their deadlines (their staged manifest+ * and chunk rows go with them), deletes retired chunk rows and manifest rows+ * no retained generation needs, and unreferenced segment texts past the grace+ * window. A brain that never staged a segment pays one existence probe.+ */+export async function sweepSegmentStorage(engine: BrainEngine): Promise<void> {+ const [row] = await engine.executeRaw<{ present: boolean }>(+ 'SELECT EXISTS (SELECT 1 FROM page_body_stagings) OR EXISTS (SELECT 1 FROM page_segment_texts) AS present');+ if (row?.present) await engine.sweepSegments({ expireStagings: true });+}+/*** #6696 (A9): compaction drops the intent, and a sync receipt's `intent.runId`* is how a resumed run finds what it committed. A receipt of a run whosediff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 717e365be7..ff8232be6a 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -39,6 +39,7 @@ import type { PreparedMutation } from './coordinator.ts';import type { SqlEngine, WriteRequest } from './model.ts';import { isUnboundSourcePage } from './unbound-source.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';+import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';import { pipelined } from '../page-state/transactions.ts';import { overlayCanonicalBodies } from '../page-state/snapshot.ts';import { materializeTimeline, prepareCanonicalProjections, type TimelineRowsRemoved } from './canonical-projections.ts';@@ -398,11 +399,13 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequconst source = { sourceId: row.source_id };// A coordinated (single-write) preparation sends its independent reads together; the first refusal in this order is reported.const together = options.coordinated ? engine : { kind: 'sequential' };- const [, snapshot, pack] = await pipelined(together, [+ const [, stored, pack] = await pipelined(together, [() => assertKnowledgePublicationAllowed(engine, row),() => engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }),() => loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null),]) as [unknown, PageSnapshot | null, Awaited<ReturnType<typeof loadActivePackForEngine>> | null];+ // Wave B: a segmented page within the single-string ceiling is compared and merged as strings.+ const snapshot = await materializedSnapshot(unbounded, stored);signal?.throwIfAborted();enterClaimStep(clock, 'revision_check');assertPageRevision(snapshot, preparedIntent ? { expectedRevision: preparedIntent.expectedRevision } : engineMutationPrecondition(parseMutationPrecondition(p)));@@ -509,6 +512,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequenterClaimStep(clock, 'import_content', undefined, 'db');const result = await importFromContent(engine, row.slug, content, {...source, noEmbed: true, remote: row.authority.remote, activePack, fences: projected ? 'coordinated' : 'lenient', coordinated: lean,+ segmentedOwner: { kind: row.operation === 'edit_page' ? 'edit' : 'put', principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: observedRevision },...(lean ? { existingSnapshot: snapshot } : {}),// #6259: only owner-tier intents keep gate-owned markers; an ordinary put_page, local or remote, has them stripped.preserveGateMarkers: !row.authority.remote && (p.kind === 'managed_maintenance_page' || p.kind === 'managed_quarantine_clear'),@@ -599,16 +603,18 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ// An inferred mode is pinned with the first origin it mints, so later pages cannot flip the inference (#5610).const pinMode = sourcePath && mintMode && scannerSourcePath(file!.root, file!.root) && !await readSlugRootMode(engine, row.source_id) ? mintMode : undefined;const publication: PreparedMutation = { observedRevision, noop, additionalPageKeys:links?.pageKeys, file, ...databaseOnly,- ...(core ? { exclusiveSources: core.exclusiveSources } : {}), ...(trust ? { trust } : {}),+ ...(core ? { exclusiveSources: core.exclusiveSources } : {}), ...(trust ? { trust } : {}), ...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),validate: async tx => { await ready.validate(tx); await core?.validate(tx); }, apply: async (tx, preimage) => {let autoLinks: Awaited<ReturnType<NonNullable<typeof links>['apply']>> | undefined;let removedTimeline: TimelineRowsRemoved | null = null;let lowered: { proposal_ref: string } | null = null;let contested: string[] = [];+ let projectionPending = 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;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.@@ -636,7 +642,8 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequconst final = await tx.readPageSnapshot(row.slug, { ...source, includeDeleted: true });const live = final && final.page.deleted_at == null ? final : null;await verifyPageReadable(tx, row.slug, ready.contentHash!, row.source_id, 'importFromContent', live?.page ?? null);- if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);+ if (applied?.segmented) { if (applied.segmented.complete && live) await sealSegmentedPage(tx, Number(live.page.id)); }+ else if (applied?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, applied.chunkerSeal, applied.pageId);else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);if (core) await core.record(tx, final?.revision ?? null);publication.postimage = final;@@ -644,7 +651,8 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequif (targetDeleted) await tx.softDeletePage(row.slug, source);// Index installation and terminal receipt share this transaction. The import sealed the projection// as its last revision-changing step; only a later revision change (restore, tags, links, delete) reseals.- if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);+ if (applied?.segmented) { if (applied.segmented.complete && applied.pageId !== undefined) await sealSegmentedPage(tx, applied.pageId); }+ else if (!(applied?.sealed && row.operation !== 'restore_page' && !versionTags && !links && !targetDeleted)) await sealPageTextProjection(tx, row.slug, row.source_id);if (core) await core.record(tx, (await tx.readPageSnapshot(row.slug, source))?.revision ?? null);}}@@ -655,7 +663,7 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequreturn { ...advisories, ...(autoLinks ? {auto_links:autoLinks} : {}), ...(coreUsage ? { core: coreUsage } : {}),...(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,+ slug: row.slug, source_id: row.source_id, chunks: ready.result.chunks, noop, ...(projectionPending ? { projection: 'pending' } : {}),...sizeState,...(ready.result.chunks === 0 ? {chunk_skip_reason: noop ? 'write_skipped': isEmbedSkipped(ready.parsedPage.frontmatter) || isQuarantined(ready.parsedPage.frontmatter) ? 'embed_skip' : 'empty_body'} : {}),diff --git a/src/core/persistence/prepared-import.ts b/src/core/persistence/prepared-import.tsindex 473808ef5b..cd08c6d385 100644--- a/src/core/persistence/prepared-import.ts+++ b/src/core/persistence/prepared-import.ts@@ -9,7 +9,9 @@ import type { ImportResult, ParsedPage } from '../import-file.ts';* timeline. `chunkerSeal`: a coordinated apply left the page's chunker version* to the caller, which stamps it with its text seal (`sealImportedPage`).*/-export interface PreparedImportApplied { pageId?: number; sealed: boolean; chunkerSeal?: number }+export interface PreparedImportApplied { pageId?: number; sealed: boolean; chunkerSeal?: number;+ /** Wave B: the apply published a segmented body; when `complete` the caller seals it with `sealSegmentedPage`, never the inline seals. */+ segmented?: { complete: boolean } }/** Parsing/provider work is complete. apply must run under the coordinator's transaction. */export interface PreparedContentImport {@@ -23,4 +25,6 @@ export interface PreparedContentImport {validate(tx: BrainEngine): Promise<void>;/** `preimage` (#5984): the publisher's guarded read of this page at the observed revision (see PreparedMutation.apply). */apply(tx: BrainEngine, preimage?: PageSnapshot | null): Promise<PreparedImportApplied | void>;+ /** Wave B: runs after the publication committed (a segmented page left unsealed is chunked and sealed). */+ afterCommit?(engine: BrainEngine): Promise<void>;}diff --git a/src/core/persistence/segmented-apply.ts b/src/core/persistence/segmented-apply.tsnew file mode 100644index 0000000000..65f1b6492c--- /dev/null+++ b/src/core/persistence/segmented-apply.ts@@ -0,0 +1,193 @@+/**+ * Segmented page publication (Wave B, spec 3.4): the statements a segmented+ * write runs inside its publication transaction (managed: the coordinator's+ * `publicationTransaction`; unmanaged: the importer's own transaction), after+ * 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.+ * - 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+ * and the flip retired its rows in the transaction.+ * - Demotion (an inline write onto a segmented page): the page row becomes an+ * inline row with an empty body in the same transaction as the inline write;+ * the live manifest rows close (versions keep theirs) and segmented chunk+ * rows go with the inline chunk replacement.+ */+import type { BrainEngine } from '../engine.ts';+import type { Page } from '../types.ts';+import type { PageSnapshot } from '../page-state/types.ts';+import type { SegmentedPageMeta } from '../page-body/types.ts';+import type { PreparedSegmentedBody, SegmentChunkingContext, SegmentedLivePage, SegmentedStagingOwner } from '../page-body/ingest.ts';+import { materializeSegmentedBody, prepareSegmentedBody, stringBodyFlags, stringRegion } from '../page-body/ingest.ts';+import { buildSegmentedProjection } from '../page-body/projection.ts';+import { maintenanceAttribution } from './attribution.ts';+import { readPageBodyPolicy, chooseBodyStorage, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, type PageBodyPolicy } from '../page-body/limits.ts';+import { SEGMENTED_CHUNKER_VERSION } from '../page-body/segment-chunks.ts';+import { PAGE_MAX_BYTES } from '../page-size-policy.ts';+import { pageSearchVectorSql } from '../fts-language.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { faultPoint } from './fault-points.ts';++const BODY_KEYS = new Set(['compiled_truth', 'timeline', 'content']);++/** A page row's storage class without touching its (possibly throwing) body getters. */+export function bodyStorageOf(page: object | null | undefined): 'inline' | 'segmented' | null {+ if (!page) return null;+ return (page as { body_storage?: string }).body_storage === 'segmented' ? 'segmented' : 'inline';+}++/** The live page a segmented write diffs against, read by id (metadata only). */+export async function segmentedLivePage(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<SegmentedLivePage> {+ const [row] = await engine.executeRaw<{ id: number; body_generation: number | string; body_storage: string; title: string; type: string }>(+ 'SELECT id, body_generation, body_storage, title, type FROM pages WHERE id=$1', [pageId]);+ if (!row) throw new Error(`Page ${pageId} not found.`);+ return { id: Number(row.id), generation: Number(row.body_generation), storage: row.body_storage === 'segmented' ? 'segmented' : 'inline', title: row.title, type: row.type };+}++/**+ * A copy of a segmented page with its body read back as strings, for the+ * single-string write paths (put_page, capture, coordinated sync and import of+ * files within the ceiling) that compare against or merge into the stored+ * body. A body above the single-string ceiling is returned as is: any step+ * that reads it refuses with `page_body_segmented` (its throwing getters), so+ * such a page is rewritten only by a streamed import.+ */+export async function materializedPage<T extends Page>(engine: BrainEngine, page: T): Promise<T>;+export async function materializedPage<T extends Page>(engine: BrainEngine, page: T | null): Promise<T | null>;+export async function materializedPage<T extends Page>(engine: BrainEngine, page: T | null): Promise<T | null> {+ if (!page || bodyStorageOf(page) !== 'segmented' || typeof Object.getOwnPropertyDescriptor(page, 'compiled_truth')?.value === 'string') return page;+ if (Number((page as { body_bytes?: number | string | null }).body_bytes ?? 0) > PAGE_MAX_BYTES) return page;+ const copy: Record<string, unknown> = {};+ for (const key of Object.keys(page)) if (!BODY_KEYS.has(key)) copy[key] = (page as Record<string, unknown>)[key];+ Object.assign(copy, await materializeSegmentedBody(engine, Number(page.id), page.source_id));+ return copy as T;+}++/** `materializedPage` over a snapshot (null passes through). */+export async function materializedSnapshot(engine: BrainEngine, snapshot: PageSnapshot | null): Promise<PageSnapshot | null> {+ if (!snapshot || bodyStorageOf(snapshot.page) !== 'segmented') return snapshot;+ return { ...snapshot, page: await materializedPage(engine, snapshot.page) };+}++/**+ * The storage class of a string write: reads the policy only when the class+ * could be segmented (a body over the demote bound, or a segmented page), so+ * small inline writes issue no extra statement.+ */+export async function stringWriteStorage(engine: BrainEngine, bodyBytes: number, current: 'inline' | 'segmented' | null):+ Promise<{ storage: 'inline' | 'segmented'; policy: PageBodyPolicy | null }> {+ if (bodyBytes <= SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES && current !== 'segmented') return { storage: 'inline', policy: null };+ const policy = await readPageBodyPolicy(engine);+ return { storage: chooseBodyStorage({ policy, bodyBytes, current, pageKind: 'markdown' }), policy };+}++export interface SegmentedApplyInput {+ slug: string;+ sourceId: string;+ /** Null for create. */+ pageId: number | null;+ prepared: PreparedSegmentedBody;+ meta: SegmentedPageMeta;+ /** The page was inline before this write (promotion): its inline chunk rows retire. */+ promotion: boolean;+ retireMaxRows: number;+ /** The persistence request committing the staging, when the write is journaled. */+ requestId?: string | null;+}++/** `complete`: every occurrence has chunks and the flip retired the old rows, so the caller seals as its last step (`sealSegmentedPage`). */+export interface SegmentedApplied { pageId: number; complete: boolean; retireDeferred: boolean }++/** Seal a segmented page's text projection at its current revision (chunks visible, title + timeline lead searchable). */+export async function sealSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number, timelineLead?: string): Promise<void> {+ const lead = timelineLead ?? (await tx.executeRaw<{ timeline_lead: string | null }>('SELECT timeline_lead FROM pages WHERE id=$1', [pageId]))[0]?.timeline_lead ?? '';+ await tx.executeRaw(`UPDATE pages SET text_projection_revision=knowledge_revision, chunker_version=$3,+ search_vector=${pageSearchVectorSql('title', '$2')} WHERE id=$1`, [pageId, sanitizeRemoteBody(lead), SEGMENTED_CHUNKER_VERSION]);+}++/** The segmented branch of a page write's apply, inside the publication transaction. */+export async function applySegmentedBody(tx: BrainEngine, input: SegmentedApplyInput): Promise<SegmentedApplied> {+ const { prepared } = input;+ let pageId = input.pageId;+ if (prepared.createRows) {+ pageId = (await tx.createSegmentedPageShell(input.slug, input.meta, { sourceId: input.sourceId })).id;+ await tx.stageManifestRows(prepared.createRows.map(row => ({ ...row, pageId: pageId! })));+ }+ if (pageId === null) throw new Error(`Segmented replace of ${input.slug} has no page id.`);+ const flip = await tx.flipBodyGeneration({ pageId, expectedGeneration: prepared.expectedGeneration, newGeneration: prepared.newGeneration,+ stagingId: prepared.stagingId, closeOccurrences: prepared.closeOccurrences, retireChunkOccurrences: prepared.retireChunkOccurrences,+ retireInlineChunks: 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]);+ 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 };+}++/**+ * Demotion: turn a segmented page row into an inline row with an empty body+ * (the caller's inline write fills it in the same transaction). The live+ * manifest rows close at the next generation, so versions that pin earlier+ * generations keep theirs; the segmented chunk rows are deleted with the+ * inline write's chunk replacement.+ */+export async function demoteSegmentedPage(tx: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<void> {+ await tx.executeRaw(`UPDATE page_body_manifest SET gen_to=(SELECT body_generation+1 FROM pages WHERE id=$1)+ WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL`, [pageId]);+ await tx.executeRaw(`UPDATE pages SET body_storage='inline', compiled_truth='', timeline='', truth_lead=NULL, timeline_lead=NULL,+ body_bytes=NULL, truth_bytes=NULL, body_lines=NULL, segment_count=NULL, segmenter_version=NULL, body_flags=NULL,+ body_generation=body_generation+1 WHERE id=$1 AND body_storage='segmented'`, [pageId]);+ await tx.executeRaw('DELETE FROM content_chunks WHERE page_id=$1 AND occurrence_id IS NOT NULL', [pageId]);+}++/** Abort a staging whose write will not publish (best effort: expiry collects it anyway). */+export async function abortSegmentedStaging(engine: BrainEngine, prepared: PreparedSegmentedBody | null | undefined): Promise<void> {+ if (prepared) await engine.setBodyStagingState(prepared.stagingId, 'aborted').catch(() => undefined);+}++/** A string write staged as a segmented body: its apply runs in the write's transaction, its projection after commit. */+export interface SegmentedImport {+ prepared: PreparedSegmentedBody;+ /** 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>;+}++/**+ * Stage a parsed page (the string write paths, bodies within the+ * single-string ceiling) as a segmented body: the in-memory regions are the+ * seekable source, the existing page row (if any) is the diff base.+ */+export async function stageSegmentedImport(engine: BrainEngine, input: { slug: string; sourceId: string; existing: Page | null;+ page: { title: string; type: string; compiled_truth: string; timeline: string; frontmatter: Record<string, unknown>; tags: readonly string[] };+ policy: PageBodyPolicy; owner?: SegmentedStagingOwner; chunking: SegmentChunkingContext; baseRevision: string | null }): Promise<SegmentedImport> {+ const live = input.existing ? await segmentedLivePage(engine, Number(input.existing.id)) : null;+ let owner = input.owner;+ if (!owner) {+ const { principal } = await maintenanceAttribution(engine);+ owner = { kind: 'import', principalKind: principal.kind, principalId: principal.id, baseRevision: input.baseRevision };+ }+ const prepared = await prepareSegmentedBody(engine, { sourceId: input.sourceId, slug: input.slug, live, title: input.page.title, type: input.page.type,+ frontmatter: input.page.frontmatter, tags: input.page.tags, truth: stringRegion(input.page.compiled_truth), timeline: stringRegion(input.page.timeline),+ flags: stringBodyFlags(input.page.compiled_truth, input.page.timeline),+ declaredBytes: Buffer.byteLength(input.page.compiled_truth, 'utf-8') + Buffer.byteLength(input.page.timeline, 'utf-8'), owner, chunking: input.chunking });+ const staged: SegmentedImport = { prepared, applied: null,+ apply: async (tx, meta, contextual) => {+ staged.applied = await applySegmentedBody(tx, { slug: input.slug, sourceId: input.sourceId, pageId: live?.id ?? null, prepared, meta,+ promotion: live?.storage === 'inline', retireMaxRows: input.policy.flipRetireMaxRows });+ await tx.updatePageContextualRetrievalState(input.slug, input.sourceId, contextual.mode, contextual.corpusGeneration);+ return staged.applied;+ },+ afterCommit: async target => {+ if (!staged.applied) return;+ if (!staged.applied.complete) await buildSegmentedProjection(target, { sourceId: input.sourceId, slug: input.slug }).catch(() => undefined);+ await target.sweepSegments({ pageId: staged.applied.pageId }).catch(() => undefined);+ } };+ return staged;+}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 24e00fb229..6a09cd9932 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -21,6 +21,7 @@ import { SOURCE_CONFIG_OBJECT_SQL } from '../source-config-sql.ts';import { sameCanonicalImport } from '../page-state/import-guard.ts';import { assertPageRevision } from '../page-state/types.ts';import { sealImportedPage, sealPageTextProjection } from '../page-state/projections.ts';+import { materializedSnapshot, sealSegmentedPage } from './segmented-apply.ts';import { pipelined, transactionMemo } from '../page-state/transactions.ts';import { prepareCanonicalProjections } from './canonical-projections.ts';import { digest, sha256 } from './digest.ts';@@ -545,7 +546,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr} };const source = { sourceId: row.source_id };enterClaimStep(clock, 'page_snapshot', undefined, 'db');- const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });+ const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true }));assertPageRevision(snapshot, { expectedRevision: p.expected_revision }); // null asserts the admitted-absent page is still absent (#5385)const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug);@@ -586,7 +587,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr// A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug.const renamed = moved && moved.slug !== row.slug ? moved : undefined;if (renamed) enterClaimStep(clock, 'rename_source', undefined, 'db');- const base = renamed ? await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true }) : snapshot;+ const base = renamed ? await materializedSnapshot(engine, await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true })) : snapshot;if (renamed && (base?.page.id !== renamed.pageId || base.revision !== renamed.revision || base.page.deleted_at != null)) {throw syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,`Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);@@ -619,7 +620,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wr// #6188: the import reuses this screen's fence verdict for the same bytes (one fence scan per file at prepare).const importOptions = { ...source, noEmbed: true, remote: row.authority.remote, preserveGateMarkers: true, activePack, coordinated: true, fences: 'coordinated' as const, writeGate: await ownerGateInput(engine, row, parsedInput.frontmatter, p.sourcePath),...(importContent === p.content && screen.status === 'importable' ? { fenceScreen: screen.fences ?? null } : {}),- filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };+ filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true,+ segmentedOwner: { kind: 'sync' as const, principalKind: row.principal_kind, principalId: row.principal_id, baseRevision: snapshot?.revision ?? null } };const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,prepare: async value => { prepared = value; return value.result; } }).catch(error => {if (!(error instanceof ContentSanityBlockError)) throw error;@@ -661,7 +663,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: WrcontentUnchanged: ready.noop && !moved && !writeback,...(renamed ? { additionalPageKeys: [{ sourceId: row.source_id, slug: renamed.slug }] } : {}),validate: async tx => { await validate(tx); await ready.validate(tx); },- deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true,+ deferEmbedding: p.processingOptions?.noEmbed || p.embedDeferred === true, ...(ready.afterCommit ? { afterCommit: ready.afterCommit } : {}),...(writeback ? { file: { root, path: join(root, p.path), content: canonicalFile, expectedBeforeHash: p.rawHash } } : {}),...(mirrorReadOnly ? { databaseOnlyReason: 'mirror_read_only' as const } : {}),apply: async (tx, preimage) => {@@ -694,7 +696,8 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrasync () => { if (!applied.noop || p.companyApproval) await project(tx, final?.page.id); },async () => {if (applied.noop) return;- if (installed?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, installed.chunkerSeal, installed.pageId);+ if (installed?.segmented) { if (installed.segmented.complete && live) await sealSegmentedPage(tx, Number(live.page.id)); }+ else if (installed?.chunkerSeal !== undefined) await sealImportedPage(tx, row.slug, row.source_id, live, installed.chunkerSeal, installed.pageId);else if (live) await sealPageTextProjection(tx, row.slug, row.source_id, live);},() => releaseHold(tx),diff --git a/test/e2e/large-pages-10mb.test.ts b/test/e2e/large-pages-10mb.test.tsnew file mode 100644index 0000000000..15424abf6b--- /dev/null+++ b/test/e2e/large-pages-10mb.test.ts@@ -0,0 +1,100 @@+/**+ * Wave B E2E: a 10 MB page through the segmented write path, on PGLite and+ * (with DATABASE_URL) Postgres, `pages.segmented_storage` forced on.+ *+ * 1. Protects: keyword recall of a needle at every decile of the body; the+ * body reconstructed from the manifest hashes to the input body; a 10 KB+ * append by rewrite writes at most the tail's chunk rows and leaves every+ * kept chunk's vector in place (an embedder would see only new chunk+ * texts); rows staged for a write that has not flipped stay out of search.+ * 2. Fails when: a segment or chunk is lost or duplicated at scale, the+ * projection misses a region, an append rechunks the whole page, or+ * staged chunks reach keyword search.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';+import { abortSegmentedStaging, stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';+import { fakeEmbedPage, reconstructedPage, segmentedPageRow, visibleChunks } from '../helpers/segmented-page-checks.ts';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';++const SLUG = 'notes/ten-mb';+const NEEDLES = Array.from({ length: 10 }, (_, d) => ({ at: d / 10 + 0.05, word: `zqxdecile${d}needle` }));+const content = conversationPage(10 * 1024 * 1024, { seed: 101, needles: NEEDLES });+const sha = (text: string) => createHash('sha256').update(text).digest('hex');++async function hits(engine: BrainEngine, word: string): Promise<number> {+ return (await engine.searchKeyword(word, { limit: 20 })).filter(hit => hit.slug === SLUG).length;+}++function suite(name: string, connect: () => Promise<BrainEngine>, disconnect: (engine: BrainEngine) => Promise<void>, skip = false) {+ (skip ? describe.skip : describe)(`10 MB segmented page — ${name}`, () => {+ let engine: BrainEngine;+ beforeAll(async () => {+ engine = await connect();+ await engine.setConfig('pages.segmented_storage', 'on');+ const result = await importFromContent(engine, SLUG, content, { sourceId: 'default', noEmbed: true });+ expect(result.status).toBe('imported');+ }, 600_000);+ afterAll(async () => { await disconnect(engine); });++ test('a needle at every decile is found by keyword search', async () => {+ for (const needle of NEEDLES) expect(await hits(engine, needle.word)).toBe(1);+ }, 120_000);++ test('the body reconstructed from the manifest hashes to the input body, and content_hash to contentHash', async () => {+ const parsed = parseMarkdown(content, `${SLUG}.md`);+ const { page, body, hash } = await reconstructedPage(engine, SLUG);+ expect(page.body_storage).toBe('segmented');+ expect(sha(body.compiled_truth)).toBe(sha(parsed.compiled_truth));+ expect(sha(body.timeline)).toBe(sha(parsed.timeline));+ expect(page.content_hash).toBe(hash);+ }, 120_000);++ test('staged rows of an unflipped write stay out of search', async () => {+ const before = await segmentedPageRow(engine, SLUG);+ const edited = parseMarkdown(`${content.trimEnd()}\n\n${conversationBody(32 * 1024, { seed: 7, needles: [{ at: 0.5, word: 'zqxstagedneedle' }] })}\n`, `${SLUG}.md`);+ const staged = await stageSegmentedImport(engine, { slug: SLUG, sourceId: 'default', existing: await engine.getPage(SLUG, { sourceId: 'default' }),+ page: { ...edited, timeline: edited.timeline ?? '' }, policy: await readPageBodyPolicy(engine), baseRevision: before.knowledge_revision,+ chunking: { quarantined: false, corpusGeneration: null, tier: 'none' } });+ expect(staged.prepared.rows.chunks).toBeGreaterThan(0);+ expect(await hits(engine, 'zqxstagedneedle')).toBe(0);+ expect((await segmentedPageRow(engine, SLUG)).body_generation).toBe(before.body_generation);+ await abortSegmentedStaging(engine, staged.prepared);+ }, 300_000);++ test('a 10 KB append by rewrite writes at most the tail chunks and keeps every other vector', async () => {+ const before = await segmentedPageRow(engine, SLUG);+ await fakeEmbedPage(engine, before.id);+ const rowsBefore = await engine.readManifest(before.id);+ const tail = new Set(rowsBefore.slice(-2).map(row => Number(row.occurrenceId)));+ const tailChunks = (await visibleChunks(engine, before.id)).filter(chunk => tail.has(Number(chunk.occurrence_id))).length;++ const appended = `${content.trimEnd()}\n\n${conversationBody(10 * 1024, { seed: 202 })}\n`;+ const result = await importFromContent(engine, SLUG, appended, { sourceId: 'default', noEmbed: true });+ expect(result.status).toBe('imported');+ expect(result.chunks).toBeLessThanOrEqual(tailChunks + 4);+ const { page, hash } = await reconstructedPage(engine, SLUG);+ expect(page.content_hash).toBe(hash);+ const kept = new Set(rowsBefore.slice(0, -2).map(row => Number(row.occurrenceId)));+ const chunks = await visibleChunks(engine, page.id);+ expect(chunks.filter(chunk => kept.has(Number(chunk.occurrence_id))).every(chunk => chunk.embedded)).toBe(true);+ expect(chunks.filter(chunk => !chunk.embedded).length).toBeLessThanOrEqual(result.chunks);+ for (const needle of NEEDLES) expect(await hits(engine, needle.word)).toBe(1);+ }, 300_000);+ });+}++suite('PGLite', async () => {+ const engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ return engine;+}, engine => engine.disconnect());++suite('Postgres', async () => { await setupDB(); return getEngine(); }, () => teardownDB(), !hasDatabase());diff --git a/test/helpers/conversation-page.ts b/test/helpers/conversation-page.tsnew file mode 100644index 0000000000..2911e4de15--- /dev/null+++ b/test/helpers/conversation-page.ts@@ -0,0 +1,45 @@+/**+ * A seeded conversation-like Markdown page of about `bytes` UTF-8 bytes (Wave B+ * large-page tests and `scripts/bench-large-pages.ts`): day headers, speaker+ * turns between placeholder names, paragraphs of varied length, now and then a+ * fenced code block, and an optional unique needle word at chosen fractions of+ * the body. No gbrain fences, NUL bytes or real names. Deterministic per seed.+ */+const WORDS = ['launch', 'pricing', 'roadmap', 'hiring', 'metrics', 'retention', 'design', 'latency', 'budget', 'customer',+ 'review', 'deploy', 'support', 'contract', 'migration', 'onboarding', 'feedback', 'forecast', 'incident', 'partner'];+const SPEAKERS = ['alice-example', 'bob-example', 'carol-example'];++function rng(seed: number): () => number {+ let state = seed >>> 0 || 1;+ return () => {+ state ^= state << 13; state >>>= 0;+ state ^= state >>> 17;+ state ^= state << 5; state >>>= 0;+ return state / 0x1_0000_0000;+ };+}++/** The body only (no frontmatter); needles land at the first turn past each fraction. */+export function conversationBody(bytes: number, opts: { seed?: number; needles?: ReadonlyArray<{ at: number; word: string }> } = {}): string {+ const next = rng(opts.seed ?? 42);+ const pending = [...(opts.needles ?? [])].sort((a, b) => a.at - b.at);+ const parts: string[] = [];+ let size = 0;+ let day = 0;+ while (size < bytes) {+ let turn = '';+ if (size === 0 || next() < 0.02) turn += `## Day ${++day}\n\n`;+ const words = Array.from({ length: 12 + Math.floor(next() * 60) }, () => WORDS[Math.floor(next() * WORDS.length)]);+ if (pending.length && size >= pending[0]!.at * bytes) words.splice(Math.floor(words.length / 2), 0, pending.shift()!.word);+ turn += `**${SPEAKERS[Math.floor(next() * SPEAKERS.length)]}**: ${words.join(' ')}.\n\n`;+ if (next() < 0.03) turn += '```ts\nconst total = items.reduce((sum, item) => sum + item.value, 0);\n```\n\n';+ parts.push(turn);+ size += Buffer.byteLength(turn, 'utf8');+ }+ return parts.join('').trimEnd();+}++/** A whole file: frontmatter (title, type note) plus `conversationBody`. */+export function conversationPage(bytes: number, opts: { seed?: number; title?: string; needles?: ReadonlyArray<{ at: number; word: string }> } = {}): string {+ return `---\ntitle: ${opts.title ?? 'Conversation log'}\ntype: note\n---\n\n${conversationBody(bytes, opts)}\n`;+}diff --git a/test/helpers/segmented-page-checks.ts b/test/helpers/segmented-page-checks.tsnew file mode 100644index 0000000000..d1e6acba8a--- /dev/null+++ b/test/helpers/segmented-page-checks.ts@@ -0,0 +1,43 @@+/**+ * Read-back checks for segmented pages (Wave B lane 1d tests): the live body+ * reconstructed from the manifest with the `contentHash` of that page, the+ * chunk rows readers can see, and a stand-in for a finished embedding pass.+ */+import type { BrainEngine } from '../../src/core/engine.ts';+import { materializeSegmentedBody } from '../../src/core/page-body/ingest.ts';+import { contentHash } from '../../src/core/utils.ts';++export interface SegmentedPageRow { id: number; body_storage: string; body_generation: number; content_hash: string; title: string; type: string;+ frontmatter: Record<string, unknown>; knowledge_revision: string; text_projection_revision: string | null }++export async function segmentedPageRow(engine: BrainEngine, slug: string, sourceId = 'default'): Promise<SegmentedPageRow> {+ const [row] = await engine.executeRaw<SegmentedPageRow>(`SELECT id, body_storage, body_generation, content_hash, title, type, frontmatter,+ knowledge_revision::text AS knowledge_revision, text_projection_revision::text AS text_projection_revision FROM pages WHERE source_id=$1 AND slug=$2`, [sourceId, slug]);+ if (!row) throw new Error(`page ${slug} not found`);+ return { ...row, id: Number(row.id), body_generation: Number(row.body_generation) };+}++/** The live body from the manifest, and `contentHash` of the page it makes (the stored hash must equal it). */+export async function reconstructedPage(engine: BrainEngine, slug: string, sourceId = 'default') {+ const page = await segmentedPageRow(engine, slug, sourceId);+ const body = await materializeSegmentedBody(engine, page.id, sourceId);+ const tags = (await engine.executeRaw<{ tag: string }>('SELECT tag FROM tags WHERE page_id=$1 ORDER BY tag', [page.id])).map(row => row.tag);+ return { page, body, hash: contentHash({ title: page.title, type: page.type, compiled_truth: body.compiled_truth, timeline: body.timeline, frontmatter: page.frontmatter, tags }) };+}++/** Chunk rows of the live generation (not retired, not staged past the page's generation). */+export async function visibleChunks(engine: BrainEngine, pageId: number): Promise<Array<{ occurrence_id: number | null; embedded: boolean }>> {+ const rows = await engine.executeRaw<{ occurrence_id: number | string | null; embedded: boolean }>(`SELECT c.occurrence_id, c.embedding IS NOT NULL AS embedded+ FROM content_chunks c JOIN pages p ON p.id=c.page_id+ WHERE c.page_id=$1 AND c.retired_generation IS NULL AND (c.body_generation IS NULL OR c.body_generation<=p.body_generation)`, [pageId]);+ return rows.map(row => ({ occurrence_id: row.occurrence_id === null ? null : Number(row.occurrence_id), embedded: row.embedded }));+}++/** Give every chunk row of the page a constant vector, as a completed embedding pass would. */+export async function fakeEmbedPage(engine: BrainEngine, pageId: number): Promise<void> {+ const [column] = await engine.executeRaw<{ type: string }>(`SELECT format_type(atttypid, atttypmod) AS type FROM pg_attribute+ WHERE attrelid='content_chunks'::regclass AND attname='embedding'`);+ const dims = Number(/\((\d+)\)/.exec(column?.type ?? '')?.[1]);+ if (!dims) throw new Error(`content_chunks.embedding has no dimension: ${column?.type}`);+ await engine.executeRaw('UPDATE content_chunks SET embedding = array_fill(0.01::float4, ARRAY[$2::int])::vector WHERE page_id=$1', [pageId, dims]);+}diff --git a/test/large-pages/flip-crash.serial.test.ts b/test/large-pages/flip-crash.serial.test.tsnew file mode 100644index 0000000000..4f88e4fdb1--- /dev/null+++ b/test/large-pages/flip-crash.serial.test.ts@@ -0,0 +1,123 @@+/**+ * Wave B crash windows of a segmented write (spec 3.4, lane 1d).+ *+ * 1. Protects: a write that dies after any staging step, inside the flip, or+ * after a create's projection staged its chunks leaves the page exactly at+ * its previous generation: the body reconstructed from the live manifest,+ * `content_hash` and keyword search all show the old content; the dead+ * staging's rows are swept; an unsealed create converges through the+ * projection queue without duplicating chunks.+ * 2. Fails when: a staged manifest or chunk row leaks into the live view, the+ * flip commits partially, the projection queue misses an unsealed page, or+ * a rebuild chunks an occurrence twice.+ * Serial: installs the process-wide fault hook.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+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 { conversationBody, conversationPage } from '../helpers/conversation-page.ts';++let engine: PGLiteEngine;+const NEEDLE = 'zqxflipneedle';+const original = conversationPage(2 * 1024 * 1024, { seed: 21 });+const rewritten = `${original.trimEnd()}\n\n${conversationBody(32 * 1024, { seed: 22, needles: [{ at: 0.5, word: NEEDLE }] })}\n`;++class Crash extends Error {}+function crashAt(point: FaultPoint): void {+ installFaultHook(async reached => { if (reached === point) throw new Crash(point); });+}++async function livePage(slug: string) {+ const [row] = await engine.executeRaw<{ id: number; body_generation: number; content_hash: string; knowledge_revision: string; text_projection_revision: string | null }>(+ `SELECT id, body_generation, content_hash, knowledge_revision::text AS knowledge_revision, text_projection_revision::text AS text_projection_revision+ FROM pages WHERE slug=$1`, [slug]);+ return row ? { ...row, id: Number(row.id), body_generation: Number(row.body_generation) } : null;+}++async function stagedRows(pageId: number) {+ const manifest = await engine.executeRaw('SELECT 1 FROM page_body_manifest WHERE page_id=$1 AND staging_id IS NOT NULL', [pageId]);+ const chunks = await engine.executeRaw('SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE c.page_id=$1 AND c.body_generation>p.body_generation', [pageId]);+ return manifest.length + chunks.length;+}++async function searchHits(word: string, slug: string): Promise<number> {+ return (await engine.searchKeyword(word, { limit: 20 })).filter(hit => hit.slug === slug).length;+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);++afterAll(async () => { await engine.disconnect(); });++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', 'on');+});++afterEach(() => { installFaultHook(undefined); });++describe('replace: a crash at any step leaves the previous generation', () => {+ for (const point of ['segmented:texts_staged', 'segmented:manifest_staged', 'segmented:chunks_staged', 'segmented:flipped'] as const) {+ test(point, async () => {+ await importFromContent(engine, 'notes/flip', original, { sourceId: 'default', noEmbed: true });+ const before = (await livePage('notes/flip'))!;+ const bodyBefore = await materializeSegmentedBody(engine, before.id, 'default');++ crashAt(point);+ await expect(importFromContent(engine, 'notes/flip', rewritten, { sourceId: 'default', noEmbed: true })).rejects.toBeInstanceOf(Crash);+ installFaultHook(undefined);++ const after = (await livePage('notes/flip'))!;+ expect(after.body_generation).toBe(before.body_generation);+ expect(after.content_hash).toBe(before.content_hash);+ expect(after.knowledge_revision).toBe(before.knowledge_revision);+ expect(await materializeSegmentedBody(engine, after.id, 'default')).toEqual(bodyBefore);+ expect(await searchHits(NEEDLE, 'notes/flip')).toBe(0);++ await engine.sweepSegments({ pageId: after.id, expireStagings: true, now: new Date(Date.now() + BODY_STAGING_HARD_MS + 60_000) });+ expect(await stagedRows(after.id)).toBe(0);++ const retried = await importFromContent(engine, 'notes/flip', rewritten, { sourceId: 'default', noEmbed: true });+ expect(retried.status).toBe('imported');+ expect((await livePage('notes/flip'))!.body_generation).toBe(before.body_generation + 1);+ expect(await searchHits(NEEDLE, 'notes/flip')).toBe(1);+ }, 180_000);+ }+});++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 }] });+ crashAt('segmented:projection_staged');+ const result = await importFromContent(engine, 'notes/fresh', created, { sourceId: 'default', noEmbed: true });+ installFaultHook(undefined);+ expect(result.status).toBe('imported');++ const unsealed = (await livePage('notes/fresh'))!;+ expect(unsealed.body_generation).toBe(1);+ expect(unsealed.text_projection_revision).not.toBe(unsealed.knowledge_revision);+ const queued = await engine.executeRaw('SELECT 1 FROM page_projection_jobs WHERE slug=$1', ['notes/fresh']);+ expect(queued.length).toBe(1);++ expect((await rebuildPendingSegmentedProjections(engine, 10)).rebuilt).toBe(1);+ const sealed = (await livePage('notes/fresh'))!;+ expect(sealed.text_projection_revision).toBe(sealed.knowledge_revision);+ expect(await engine.executeRaw('SELECT 1 FROM page_projection_jobs WHERE slug=$1', ['notes/fresh'])).toEqual([]);+ expect(await searchHits(NEEDLE, 'notes/fresh')).toBe(1);++ const perOccurrence = async () => engine.executeRaw<{ occurrence_id: number; n: number }>(+ `SELECT occurrence_id, count(*)::int AS n FROM content_chunks WHERE page_id=$1 AND retired_generation IS NULL GROUP BY occurrence_id ORDER BY occurrence_id`, [sealed.id]);+ const once = await perOccurrence();+ await engine.executeRaw(`INSERT INTO page_projection_jobs(source_incarnation, slug, revision, reason)+ SELECT s.incarnation, $1, p.knowledge_revision, 'canonical_change' FROM pages p JOIN sources s ON s.id=p.source_id WHERE p.slug=$1`, ['notes/fresh']);+ await rebuildPendingSegmentedProjections(engine, 10);+ expect(await perOccurrence()).toEqual(once);+ }, 180_000);+});diff --git a/test/large-pages/segmented-ingest.test.ts b/test/large-pages/segmented-ingest.test.tsnew file mode 100644index 0000000000..d420b6630b--- /dev/null+++ b/test/large-pages/segmented-ingest.test.ts@@ -0,0 +1,168 @@+/**+ * Wave B segmented ingest on PGLite (lane 1d): the string write path stages a+ * body above the inline threshold as segments and publishes it with the+ * generation flip; a file above the single-string ceiling imports streamed.+ *+ * 1. Protects: create, replace, no-op rewrite and append-by-rewrite of a+ * segmented page; promote/demote hysteresis; the streamed import of a file+ * over PAGE_MAX_BYTES (switch on) and its refusal (switch off); that+ * `content_hash` equals `contentHash` of the reconstructed page; that staged+ * rows stay invisible until the flip.+ * 2. Fails when: a flip loses or duplicates a segment, the hash stream+ * diverges from `contentHash`, an append rewrites more than the tail, a+ * staged row reaches the live manifest, or hysteresis flips class early.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent, importFromFile } from '../../src/core/import-file.ts';+import { parseMarkdown } from '../../src/core/markdown.ts';+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';+import { readPageBodyPolicy, SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES, SEGMENTED_PROMOTE_ABOVE_BYTES } from '../../src/core/page-body/limits.ts';+import { abortSegmentedStaging, stageSegmentedImport } from '../../src/core/persistence/segmented-apply.ts';+import { conversationBody, conversationPage } from '../helpers/conversation-page.ts';+import { fakeEmbedPage, reconstructedPage, segmentedPageRow, visibleChunks } from '../helpers/segmented-page-checks.ts';++let engine: PGLiteEngine;+let dir: string;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ dir = mkdtempSync(join(tmpdir(), 'gbrain-segmented-ingest-'));+}, 120_000);++afterAll(async () => {+ await engine.disconnect();+ rmSync(dir, { recursive: true, force: true });+});++beforeEach(async () => {+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', 'on');+});++describe('string path: create, no-op, append', () => {+ const content = conversationPage(3 * 1024 * 1024, { seed: 7 });++ test('create publishes a segmented page whose manifest reproduces the parsed body and whose hash is contentHash', async () => {+ const result = await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });+ expect(result.status).toBe('imported');+ const parsed = parseMarkdown(content, 'notes/big.md');+ const { page, body, hash } = await reconstructedPage(engine, 'notes/big');+ expect(page.body_storage).toBe('segmented');+ expect(page.body_generation).toBe(1);+ expect(body.compiled_truth).toBe(parsed.compiled_truth);+ expect(body.timeline).toBe(parsed.timeline);+ expect(page.content_hash).toBe(hash);+ expect(page.text_projection_revision).toBe(page.knowledge_revision);+ expect((await visibleChunks(engine, page.id)).length).toBeGreaterThan(0);+ }, 120_000);++ test('a no-op rewrite publishes nothing', async () => {+ await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });+ const before = await segmentedPageRow(engine, 'notes/big');+ const result = await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });+ expect(result.status).toBe('skipped');+ const after = await segmentedPageRow(engine, 'notes/big');+ expect(after.body_generation).toBe(before.body_generation);+ expect(after.knowledge_revision).toBe(before.knowledge_revision);+ }, 120_000);++ test('a 10 KB append rewrites only the tail: earlier occurrences, their chunks and vectors are kept', async () => {+ await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });+ const before = await segmentedPageRow(engine, 'notes/big');+ const rowsBefore = await engine.readManifest(before.id);+ await fakeEmbedPage(engine, before.id);+ const tailOccurrences = new Set(rowsBefore.slice(-2).map(row => Number(row.occurrenceId)));+ const tailChunks = (await visibleChunks(engine, before.id)).filter(chunk => tailOccurrences.has(Number(chunk.occurrence_id))).length;++ const appended = `${content.trimEnd()}\n\n${conversationBody(10 * 1024, { seed: 99 })}\n`;+ const result = await importFromContent(engine, 'notes/big', appended, { sourceId: 'default', noEmbed: true });+ expect(result.status).toBe('imported');+ const { page, body, hash } = await reconstructedPage(engine, 'notes/big');+ expect(page.body_generation).toBe(before.body_generation + 1);+ expect(body.compiled_truth).toBe(parseMarkdown(appended, 'notes/big.md').compiled_truth);+ expect(page.content_hash).toBe(hash);++ const rowsAfter = await engine.readManifest(page.id);+ const kept = rowsBefore.slice(0, -2).map(row => Number(row.occurrenceId));+ expect(rowsAfter.slice(0, kept.length).map(row => Number(row.occurrenceId))).toEqual(kept);+ expect(result.chunks).toBeLessThanOrEqual(tailChunks + 4);+ const chunks = await visibleChunks(engine, page.id);+ const keptSet = new Set(kept);+ expect(chunks.filter(chunk => keptSet.has(Number(chunk.occurrence_id))).every(chunk => chunk.embedded)).toBe(true);+ expect(chunks.filter(chunk => !chunk.embedded).length).toBeLessThanOrEqual(result.chunks);+ }, 180_000);++ test('staged rows stay out of the live manifest and the page until the flip', async () => {+ await importFromContent(engine, 'notes/big', content, { sourceId: 'default', noEmbed: true });+ const before = await segmentedPageRow(engine, 'notes/big');+ const liveBefore = await engine.readManifest(before.id);+ const visibleBefore = (await visibleChunks(engine, before.id)).length;+ const existing = await engine.getPage('notes/big', { sourceId: 'default' });+ const edited = parseMarkdown(`${content.trimEnd()}\n\n${conversationBody(64 * 1024, { seed: 5 })}\n`, 'notes/big.md');+ const staged = await stageSegmentedImport(engine, { slug: 'notes/big', sourceId: 'default', existing,+ page: { ...edited, timeline: edited.timeline ?? '' }, policy: await readPageBodyPolicy(engine), baseRevision: before.knowledge_revision,+ chunking: { quarantined: false, corpusGeneration: null, tier: 'none' } });+ expect((await engine.readManifest(before.id, { stagingId: staged.prepared.stagingId })).length).toBeGreaterThan(0);+ expect(await engine.readManifest(before.id)).toEqual(liveBefore);+ const after = await segmentedPageRow(engine, 'notes/big');+ expect(after.body_generation).toBe(before.body_generation);+ expect(after.content_hash).toBe(before.content_hash);+ const staleChunks = await engine.executeRaw('SELECT 1 FROM content_chunks c JOIN pages p ON p.id=c.page_id WHERE c.page_id=$1 AND c.body_generation>p.body_generation', [before.id]);+ expect((await visibleChunks(engine, before.id)).length).toBe(visibleBefore);+ expect(staleChunks.length).toBe(staged.prepared.rows.chunks);+ await abortSegmentedStaging(engine, staged.prepared);+ }, 120_000);+});++describe('promote / demote hysteresis', () => {+ const sized = (bytes: number) => conversationPage(bytes, { seed: 3 });++ test('inline up to the promote bound, segmented above it, kept segmented above the demote bound, inline at or under it', async () => {+ await importFromContent(engine, 'notes/grow', sized(SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES + 64 * 1024), { sourceId: 'default', noEmbed: true });+ expect((await segmentedPageRow(engine, 'notes/grow')).body_storage).toBe('inline');+ await importFromContent(engine, 'notes/grow', sized(SEGMENTED_PROMOTE_ABOVE_BYTES + 128 * 1024), { sourceId: 'default', noEmbed: true });+ const promoted = await reconstructedPage(engine, 'notes/grow');+ expect(promoted.page.body_storage).toBe('segmented');+ expect(promoted.page.content_hash).toBe(promoted.hash);+ expect((await visibleChunks(engine, promoted.page.id)).every(chunk => chunk.occurrence_id !== null)).toBe(true);+ await importFromContent(engine, 'notes/grow', sized(SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES + 128 * 1024), { sourceId: 'default', noEmbed: true });+ expect((await segmentedPageRow(engine, 'notes/grow')).body_storage).toBe('segmented');+ const small = sized(SEGMENTED_DEMOTE_AT_OR_BELOW_BYTES - 64 * 1024);+ await importFromContent(engine, 'notes/grow', small, { sourceId: 'default', noEmbed: true });+ const demoted = await segmentedPageRow(engine, 'notes/grow');+ expect(demoted.body_storage).toBe('inline');+ expect((await engine.getPage('notes/grow', { sourceId: 'default' }))!.compiled_truth).toBe(parseMarkdown(small, 'notes/grow.md').compiled_truth);+ expect(await engine.readManifest(demoted.id)).toEqual([]);+ expect((await visibleChunks(engine, demoted.id)).every(chunk => chunk.occurrence_id === null)).toBe(true);+ }, 240_000);+});++describe('streamed import above the single-string ceiling', () => {+ test('switch on: a ~26 MiB file round-trips byte-identical from the manifest; switch off: refused as today', async () => {+ const content = conversationPage(PAGE_MAX_BYTES + 2 * 1024 * 1024, { seed: 11 });+ const file = join(dir, 'huge.md');+ writeFileSync(file, content);+ const parsed = parseMarkdown(content, 'notes/huge.md');++ await engine.setConfig('pages.segmented_storage', 'off');+ const refused = await importFromFile(engine, file, 'notes/huge.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });+ expect(refused.status).toBe('skipped');+ expect(refused.refusal?.code).toBe('file_too_large');+ expect(await engine.getPage('notes/huge', { sourceId: 'default' })).toBeNull();++ await engine.setConfig('pages.segmented_storage', 'on');+ const imported = await importFromFile(engine, file, 'notes/huge.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });+ expect(imported.status).toBe('imported');+ const { page, body, hash } = await reconstructedPage(engine, 'notes/huge');+ expect(page.body_storage).toBe('segmented');+ expect(body.compiled_truth).toBe(parsed.compiled_truth);+ expect(body.timeline).toBe(parsed.timeline);+ expect(page.content_hash).toBe(hash);+ }, 600_000);+});