Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

large pages PR 2 lane 2e2: fence-facts reconcile of a segmented page from its marker segments

garrytand6fcdff66cdf
diff --git a/docs/architecture/key-files/core-cycle.md b/docs/architecture/key-files/core-cycle.md
index 63f63671c7..b663b75aac 100644
--- a/docs/architecture/key-files/core-cycle.md
+++ b/docs/architecture/key-files/core-cycle.md
@@ -27,7 +27,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
Both paths prevent LLM-chosen titles that drift between extractions from piling up.
Atom identity: page-derived atoms fold the source-page slug into the slug hash (8 chars, NUL-separated) so two same-date pages emitting the same title get DISTINCT slugs; the source CONTENT hash is deliberately NOT folded (a reworded source still upserts rather than duping); transcript atoms keep the legacy title-only 6-char hash. `resolvePageAtomSlug` adopts a legacy-slug atom with a compatible binding in place on re-extraction (upgrade idempotency — no migration, no duplicate), while `assertAtomImportBinding` fail-closed refuses to reuse a slug bound to a DIFFERENT source locator. Both share `isCompatibleAtomBinding(frontmatter, sourcePageSlug)` — the ONE definition of compatible: bound to THIS source page, or carrying no `source_slug`/`source_path` at all (pre-binding-era adoption, not a clobber); a `source_path`-bound legacy transcript atom or a different `source_slug` is a different origin, and a non-atom page squatting on the slug is refused. `source_quote` is verified at extraction time against the exact `truncateUtf8` prompt prefix the model saw (`locateQuote` advances by full code points): located quotes persist original characters + [start,end) offsets + `source_quote_verified`; unlocatable quotes are dropped with the atom kept. Edges write before the completion flip; per-item drain failures stay typed (bounded, sanitized, reconcilable). Transcript items carry the same failure-count/tombstone machinery as pages, in the `extract_atoms_transcript_state` table (keyed `(source_id, file_path, content_hash)`, 16-char hash prefix, so an edit is a new row): `recordItemFailureCount` counts a transcript's malformed output or prompt-level provider block (`providerContentBlockReason`; never feeds the outage halt) toward `MAX_DETERMINISTIC_FAILURES`, a zero-yield transcript tombstones immediately (as pages do), and `tombstonedTranscriptsForHashes` is the batch read-side gate mirroring `atomsExistingForHashes` (fail-open on error). Reported as `tombstoned_transcripts` (paths), separate from the page-slug `tombstoned_for_failures`. Malformed managed output requires a newly approved protected-job retry identity; publication retry reuses retained output and original/current grants.
-- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`.
+- `src/core/cycle/extract-facts.ts` — source-scoped `## Facts` fence reconciliation. Rows are keyed by fence row number, never by claim text: a DB row whose `(row_num, claim)` is still in the fence keeps its id and has its other cells updated in place (ids from recall stay valid for forget; `source_session`, `created_at`, consolidation state and vectors survive), a row whose number left the fence or whose claim was rewritten is expired and detached (`row_num` NULL), never deleted, and only new row numbers insert. Duplicate ACTIVE rows with the same claim and source index once; a struck history row never collapses onto an active row with the same text, so a claim that reverts (NYC → SF → NYC) stays active. `superseded by #N` links resolve on every hop of a chain (`supersede-resolve.ts`; forgotten targets and cycles still resolve to NULL with a warning). Each run first fences the source's unfenced rows (`row_num IS NULL`, live entity page, never ontology observations: `dimension IS NULL`, #6264) through `facts/unfenced-facts.ts` and adds those pages to the run's reconcile set (`unfencedRowsFenced`); rows it cannot fence this run (canonical file not on this host, malformed fence, held page lock, a claim the fence codec cannot render) are named as `FACTS_FENCE_FAILED: <slug> (<reason>)` and keep their own page out of the destructive reconcile (the empty-fence guard, per page since #6278: `pendingLegacyRows` lists the pages, `legacyRowsPending` and `legacyPages` report them, and every other page of the source still reconciles; the page keeps its fact index because reconciliation would classify its `row_num IS NULL` rows as stale and expire them). The phantom-redirect pass moves rows by fence position and so still waits until the source has no unfenced rows. `runPhaseExtractFacts` (`cycle.ts`) then reports the reconcile counts of the pages that did reconcile and names the skipped pages in its summary. Rows with no backing page or checkout, and ontology observations, never gate. It then expires (without detaching) the active fence-owned rows of soft-deleted pages in the source; restoring the page re-activates them on its next reconcile. Previously embedded fact rows and their text/provenance remain intact when a full valid replacement embedding batch is unavailable; old vectors are never transplanted to changed text/model. Restrictive fence changes still expire removed/withdrawn claims and tighten visibility before deferral. Provider cancellation within database writes rolls back rather than publishing half a replacement. Keyless initial fact insertion remains supported; conversation-origin facts without a fence are not wiped by fence reconciliation. Each page reconciles in isolation: a page whose writes the database rejects rolls back, is reported as `<slug>: FACTS_RECONCILE_FAILED: …` (counted in `pagesFailed`, booked as a halt in the rollup), and later pages still reconcile. `facts.superseded_by` is `ON DELETE SET NULL`. On an unmanaged brain each reconcile records its outcome in `page_facts_reconcile` (`src/core/facts/reconcile-watermark.ts`): a complete reconcile (including a no-op) stamps the page's `knowledge_revision` inside the write transaction, after a `FOR SHARE` lock and a revision recheck (a moved page writes nothing and stays due); `deferred` (lock, stale cache, embedding deferral, rejected write), `invalid` (malformed or misplaced fence, not retried until the page changes) and `cancelled` leave it due. The dream cycle passes `drain`, so an incremental run also reconciles up to 250 due pages within 60 s, never-attempted first then oldest attempt, after settling in bulk the due pages with no fence marker and no fence rows; a fence imported by a standalone sync or removed from a page is therefore reconciled even when the cycle's own sync changed nothing. A direct call with `slugs: []` and no `drain` still reconciles nothing. Doctor's `extract_health` names unreconciled fence pages and unreadable fences on unmanaged brains. Tests: `test/extract-facts-reconcile-drain.test.ts` (Postgres race through `test/e2e/extract-facts-reconcile-drain-postgres.test.ts`), `test/e2e/fact-vector-repair-parity.test.ts`, `test/extract-facts-phase.test.ts`, `test/extract-facts-unfenced-rows.test.ts` (a mixed page, on PGLite and through the Postgres E2E), `test/extract-facts-poison-page.test.ts`, `test/extract-facts-stable-identity.test.ts`. On a managed brain the same reconcile runs after `managedDerivedFactsPreflight` (local writer, active source, before any embedding call): each page transaction and the deleted-page expiry commit inside `withDerivedFactsWrite` (coordinator source capability, page key locked); the facts receipt page is skipped, the rollup is still booked. It is distinct from the coordinated `extract_facts` operation and durable page backstop. Tests: `test/managed-facts-writers.test.ts`. Wave B PR 2 (lane 2e2): a segmented page reconciles like an inline one, its fences read from its marker segments (`segmentedFactsFenceView`), its write guarded by content hash and size, and its stale-cache check streamed against the canonical file (`segmentedBodyMatchesFile`, page-body/segment-facts.ts); test `test/large-pages/segmented-facts-reconcile.test.ts`. #6259: it and `extract-takes.ts` (both the DB walk and the file walk, which checks the stored page) skip a quarantined page, leaving rows projected before it was quarantined as they are. Test: `test/quarantine-fence-projection.test.ts`.
- `src/core/cycle/inline-drain.ts` — the dream cycle's private-queue drain. `runSubagentsInline(engine, queue, queueName, yieldDuringPhase?, handler?, lockMs?, concurrency?)` runs N independent `drainLoop`s (`dream.synthesize.inline_concurrency`, clamp [1,8], PGLite forced serial at the callsite) sharing the queue via the same SKIP-LOCKED claim fencing workers use — everything job-scoped (lockToken, abort, timeout timer, keepalive, renewTimer, outcome recording) stays loop-local. Pool hygiene: global housekeeping sweeps are leader-only (loop 0) while `promoteDelayed` runs in every loop; idle claim-poll backs off 1s→5s; a NON-retryable loop-level failure aborts siblings after their current child (a failing child is a job outcome, never a drain crash). Exit only when the queue holds no active/waiting/delayed child (a lease-full bounce's delayed backoff must not strand a child). Outcome routing mirrors the worker: `UnrecoverableError` → dead immediately; `RateLeaseUnavailableError` → `releaseLeaseFullJob` requeue without burning an attempt; timeout terminal. Handler invocation is wrapped in `withChatPhase('job:<name>')` (worker.ts parity) so each drained child's gateway spend is attributed to the CHILD — a bare `await handler(context)` inherits the caller's AsyncLocalStorage phase, and a cycle phase that wraps its own work (dream synthesize wraps `phase:synthesize`) would absorb every child's spend into the phase tag. `runDrainRenewalTick` (per-call AbortSignal + timeout + re-entrancy guard) and the null-safe nearest-rank `percentile()` telemetry helper are exported. Pinned by `test/cycle-synthesize-inline-concurrency.test.ts` (loop semantics) + `test/e2e/dream-synthesize-concurrency-postgres.test.ts` (real-Postgres exact-once + lease-ceiling).
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index bea1ef29c3..45288061d9 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -118,9 +118,9 @@ src/core/cycle/extract-atoms.ts discoverExtractablePages field STREAM see sql ro
src/core/cycle/extract-atoms.ts discoverExtractablePages sql STREAM minCompiledTruthChars is false for NULL: segmented pages are never discovered (skip until per-segment extraction, PR 4)
src/core/cycle/extract-atoms.ts minCompiledTruthChars sql STREAM false for a segmented page (NULL body): skip
src/core/cycle/extract-atoms.ts runPhaseExtractAtoms call:serializeMarkdown SEGW
-src/core/cycle/extract-facts.ts canonicalCacheState field STREAM segmented page: getter throws page_body_segmented
-src/core/cycle/extract-facts.ts planFenceReconcile field STREAM managed preparer: segmented page: getter throws page_body_segmented before any write
-src/core/cycle/extract-facts.ts runExtractFacts field STREAM segmented page skipped with warning FACTS_RECONCILE_SEGMENTED; its facts index is preserved (per-segment reconcile, PR 4)
+src/core/cycle/extract-facts.ts canonicalCacheState field INLINE inline arm; a segmented page compares its stored regions with the canonical file by length and SHA-256 (segmentedBodyMatchesFile)
+src/core/cycle/extract-facts.ts planFenceReconcile field NONE view.timeline is the parsed facts fence of the timeline section (FactsFenceView); a segmented page reads it from its marker segments (segmentedFactsFenceView)
+src/core/cycle/extract-facts.ts sameBody field INLINE inline arm; segmented pages compare content_hash and body_bytes
src/core/cycle/extract-takes.ts readPageTakes field INLINE inline arm; a segmented page streams through parseTakesFenceBlocks (page-body/segment-takes.ts)
src/core/cycle/grade-takes.ts GradeTakesPhase.process field STREAM
src/core/cycle/link-manifest.ts buildLinkManifest field STREAM
@@ -200,6 +200,7 @@ src/core/extract-timeline-from-meetings.ts extractTimelineFromMeetings sql STREA
src/core/extract/receipt-writer.ts writeReceipt call:putPage INLINE
src/core/facts-fence.ts factsFenceSection field SEGW
src/core/facts-fence.ts factsFenceSections field SEGW
+src/core/facts-fence.ts factsFenceView field INLINE inline arm; a segmented page reads its fences from its marker segments (segmentedFactsFenceView)
src/core/facts/backstop.ts runFactsBackstop field STREAM
src/core/facts/backstop.ts runPipeline field STREAM
src/core/facts/drain.ts estimateBacklogUsd sql META
@@ -317,6 +318,7 @@ src/core/page-body/ingest.ts stageBody field NONE not a stored body: the write's
src/core/page-body/page-shape.ts fenceBody field INLINE reads a body that is a string (inline or materialized); an unread segmented body holds no fences and reads as empty
src/core/page-body/page-shape.ts pageBodyBytes field INLINE inline branch of pageBodyBytes; a segmented page answers body_bytes
src/core/page-body/schema.ts PAGE_GENERATION_BUMP_FN_SQL sql STREAM trigger DDL: compares the body columns of inline rows; segmented rows compare body_generation (lane 1a)
+src/core/page-body/segment-facts.ts fileRegionDigests field NONE scan.truth / scan.timeline are BodyScanner regions of the canonical file, streamed from the file; not a page body
src/core/page-body/segment-ledger.ts overlaySegmentText field NONE not the page body: compiled_truth of overlayCanonicalBodies over one segment's text (at most one segment, never the whole body)
src/core/page-body/streamed-import.ts importScanned field LEAD bounded heads of the streamed file's regions for the sanity and type checks; the body itself streams to the segmenter
src/core/page-embedding-budget.ts planPageEmbedding field META lane 1e file: body_bytes for segmented pages
diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.ts
index 78bb483106..87565ce472 100644
--- a/src/core/cycle/extract-facts.ts
+++ b/src/core/cycle/extract-facts.ts
@@ -52,6 +52,7 @@ import { isQuarantined } from '../quarantine.ts';
import { existsSync, readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
+import type { Page } from '../types.ts';
import type { GBrainConfig } from '../config.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
import { isTerminal, type WriteRequest } from '../persistence/model.ts';
@@ -77,7 +78,8 @@ import {
import { writeReceipt } from '../extract/receipt-writer.ts';
import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.ts';
import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';
-import { factsFenceSection, factsFenceSections, parseFactsFence, FACTS_FENCE_BEGIN } from '../facts-fence.ts';
+import { factsFenceView } from '../facts-fence.ts';
+import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../page-body/segment-facts.ts';
import {
duplicateActiveFenceRows,
extractFactsFromFenceText,
@@ -207,6 +209,17 @@ async function syncSupersession(
return { warnings, changed };
}
+/** The pages-table body a reconcile read: its strings, or a segmented page whose body stays in its segments. */
+type CachedBody = { id: number; body_storage?: Page['body_storage']; compiled_truth: string | null; timeline: string | null };
+
+/** The body a reconcile planned from is still the stored one: the same strings, or the same segmented body (content hash and size). */
+function sameBody(current: Page, planned: Page): boolean {
+ if (isSegmentedPage(current) || isSegmentedPage(planned)) {
+ return isSegmentedPage(current) && isSegmentedPage(planned) && current.content_hash === planned.content_hash && current.body_bytes === planned.body_bytes;
+ }
+ return current.compiled_truth === planned.compiled_truth && current.timeline === planned.timeline;
+}
+
/**
* Destructive reconciliation may only trust the pages-table body when it
* still matches the canonical Markdown file. The fact writer deliberately
@@ -223,8 +236,7 @@ async function canonicalCacheState(
engine: BrainEngine,
slug: string,
sourceId: string,
- cachedCompiledTruth: string,
- cachedTimeline: string,
+ cached: CachedBody,
): Promise<'fresh' | 'stale' | 'unavailable'> {
// sync.write_through=off: the fence writers already treat the file as
// non-canonical (fence-write.ts legacy fallback), so a stale mirror file must
@@ -233,9 +245,10 @@ async function canonicalCacheState(
const target = await resolvePageWriteTarget(engine, slug, sourceId);
if (!target.ok || !existsSync(target.filePath)) return 'unavailable';
try {
+ if (isSegmentedPage(cached)) return await segmentedBodyMatchesFile(engine, cached, target.filePath);
const canonical = parseMarkdown(readFileSync(target.filePath, 'utf-8'), target.filePath);
- return canonical.compiled_truth === cachedCompiledTruth.trim()
- && canonical.timeline === cachedTimeline.trim()
+ return canonical.compiled_truth === (cached.compiled_truth ?? '').trim()
+ && canonical.timeline === (cached.timeline ?? '').trim()
? 'fresh'
: 'stale';
} catch {
@@ -247,17 +260,10 @@ async function refuseDestructiveReconcileOnStaleCache(
engine: BrainEngine,
slug: string,
sourceId: string,
- cachedCompiledTruth: string,
- cachedTimeline: string,
+ cached: CachedBody,
warnings: string[],
): Promise<boolean> {
- const state = await canonicalCacheState(
- engine,
- slug,
- sourceId,
- cachedCompiledTruth,
- cachedTimeline,
- );
+ const state = await canonicalCacheState(engine, slug, sourceId, cached);
if (state !== 'stale') return false;
warnings.push(
`${slug}: FACTS_PAGE_CACHE_STALE: canonical Markdown differs from the pages cache; ` +
@@ -356,6 +362,10 @@ async function listExistingFactsForPage(
);
}
+/** The page a reconcile plans from: its body as strings, or a segmented page whose fences are read from its segments. */
+type PageFenceInput = { id?: number; slug?: string; source_id?: string; body_storage?: Page['body_storage']; compiled_truth: string | null; timeline: string | null;
+ effective_date?: Date | string | null };
+
interface FenceReconcilePlan {
/** Rows the parsed fence carries (duplicates included), for the pages-with-facts count. */
fenceRows: number;
@@ -374,13 +384,13 @@ interface FenceReconcilePlan {
* not authoritative (warnings are appended): a warning-bearing parse or a
* fence in each section of the page (#6686: a split fence) preserves the page's existing index.
*/
-async function planFenceReconcile(db: BrainEngine, page: { compiled_truth: string | null; timeline: string | null; effective_date?: Date | string | null },
- slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {
+async function planFenceReconcile(db: BrainEngine, page: PageFenceInput, slug: string, sourceId: string, warnings: string[]): Promise<FenceReconcilePlan | null> {
+ const view = isSegmentedPage(page) ? await segmentedFactsFenceView(db, page) : factsFenceView(page);
// #6686: a lone fence below the timeline sentinel that parses cleanly is the page's fence, read where the writers
// edit it; one that does not parse keeps the #3625 guard below.
- const below = factsFenceSection(page) === 'timeline' ? parseFactsFence(page.timeline ?? '') : null;
+ const below = !view.sections.body && view.sections.timeline ? view.timeline : null;
const lone = below !== null && below.warnings.length === 0;
- const parsed = lone ? below : parseFactsFence(page.compiled_truth ?? '');
+ const parsed = lone ? below : view.body;
if (parsed.warnings.length > 0) {
// The parser deliberately skips malformed rows and returns any rows it
// could still recover. That partial result is not authoritative: using
@@ -391,9 +401,9 @@ async function planFenceReconcile(db: BrainEngine, page: { compiled_truth: strin
// #3625: a fence below the timeline sentinel lands in page.timeline, where
// parseFactsFence cannot see it; reading compiled_truth alone would treat
// its rows as deleted. timelineHasGenuineFactsFenceMarker explains the scan.
- if (!lone && timelineHasGenuineFactsFenceMarker(page.timeline ?? '')) {
+ if (!lone && view.timelineMarker) {
// #6686: a fence in each section (a writer added one above the sentinel) is merged by an explicit repair.
- if (factsFenceSections(page).body) {
+ if (view.sections.body) {
warnings.push(`${slug}: FACTS_FENCE_BELOW_SENTINEL: the page holds a ## Facts fence above the <!-- timeline --> sentinel and another below it `
+ `(a split fence), so extract_facts leaves its indexed facts as they are. Preview merging them into one with gbrain repair split-facts --source ${sourceId}, `
+ 'then apply the hash it prints.');
@@ -682,75 +692,6 @@ export interface ExtractFactsResult {
phantomsMorePending: boolean;
}
-/**
- * #3625 (adversarial review, 2 rounds): whether `timeline` contains a
- * GENUINE Facts fence marker, as opposed to the marker text merely being
- * mentioned inside a fenced code example or quoted prose. A naive
- * `.includes(FACTS_FENCE_BEGIN)` false-positives on both — e.g. a page
- * whose real fence WAS removed, but whose timeline documents the fence
- * syntax in a ```markdown code block or a `> ...` blockquote, would wrongly
- * be treated as "misplaced" and block a genuine deletion, leaving stale
- * facts indexed indefinitely.
- *
- * Round 1 tried reusing fence-scan.ts's scanFencedBlocks() + string removal
- * of its extracted fence bodies. Round-2 adversarial review broke that:
- * scanFencedBlocks normalizes line endings (splits on `\r\n|\r|\n`, joins
- * fence bodies with plain `\n`) and strips opener indentation before
- * returning fence text — so `stripped.split(fenceText).join('')` on the
- * ORIGINAL (un-normalized) string silently fails to match a CRLF or
- * indented code block, leaving the marker inside it undetected and still
- * false-positive. Reconstructed-text removal can't safely undo a lossy
- * normalization.
- *
- * Fix: a self-contained single-pass line scanner (mirroring fence-scan.ts's
- * own CommonMark-subset opener/closer grammar, applied directly against
- * `timeline.split(/\r\n|\r|\n/)` — ONE split, no re-normalization, no
- * text-based removal) that skips lines between a real ``` /~~~ opener and
- * its closer, then checks whether any remaining line, trimmed, exactly
- * equals the marker. A real fence marker is always written as its own line
- * (see FENCE_BODY-shaped output from fence-write.ts / upsertFactRow), so
- * exact-line-match — on lines outside any code fence — rules out both
- * hazards without needing a full markdown AST (mirrors
- * findTimelineSplitIndex's own `trimmed === sentinel` pattern for the same
- * class of problem on the timeline sentinel itself). An unclosed opener
- * runs to EOF (matches fence-scan.ts's documented behavior) — a marker
- * appearing after it is inside an ambiguous, unclosed block and is not
- * trusted as genuine.
- */
-function timelineHasGenuineFactsFenceMarker(timeline: string): boolean {
- if (!timeline.includes(FACTS_FENCE_BEGIN)) return false;
- const lines = timeline.split(/\r\n|\r|\n/);
- const OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
- const CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
- let i = 0;
- while (i < lines.length) {
- const line = lines[i]!;
- const open = OPEN_RE.exec(line);
- if (open) {
- const marker = open[1]!;
- const fenceChar = marker[0]!;
- const info = open[2]!.trim();
- // Mirrors fence-scan.ts: a backtick opener whose info string contains
- // a backtick is inline code, not a fence opener.
- if (!(fenceChar === '`' && info.includes('`'))) {
- let j = i + 1;
- for (; j < lines.length; j++) {
- const close = CLOSE_RE.exec(lines[j]!);
- if (close && close[1]![0] === fenceChar && close[1]!.length >= marker.length) {
- j++;
- break;
- }
- }
- i = j; // unclosed fence: j reaches lines.length, ending the scan
- continue;
- }
- }
- if (line.trim() === FACTS_FENCE_BEGIN) return true;
- i++;
- }
- return false;
-}
-
/**
* Empty-fence guard (Codex R2-#7; #2484; #2646; per page, #6278): the active
* unfenced rows the fence step left on live pages of this source, per page.
@@ -1012,11 +953,6 @@ export async function runExtractFacts(
revision = page.knowledge_revision ?? null;
// #6259: a quarantined page projects no fence facts; its existing index is left as it is.
if (isQuarantined(page.frontmatter as Record<string, unknown> | null)) return 'skipped';
- if (isSegmentedPage(page)) {
- result.warnings.push(`${slug}: FACTS_RECONCILE_SEGMENTED: the page body is stored in segments, which fence reconcile cannot read yet; its existing facts index is preserved`);
- return 'skipped';
- }
-
const plan = await planFenceReconcile(engine, page, slug, sourceId, result.warnings);
if (!plan) return 'invalid';
if (plan.fenceRows > 0) result.pagesWithFacts += 1;
@@ -1080,7 +1016,7 @@ export async function runExtractFacts(
opts.signal?.throwIfAborted();
if (watermark && !await lockReconcileRevision(tx, sourceId, slug, page.knowledge_revision ?? null)) return null;
const current = await tx.getPage(slug, { sourceId });
- if (!current || current.compiled_truth !== page.compiled_truth || current.timeline !== page.timeline) return null;
+ if (!current || !sameBody(current, page)) return null;
const written = await writeFenceReconcile(tx, sourceId, slug, plan, writes, opts.signal);
if (watermark && !deferInserts) await settleFactsReconcile(tx, sourceId, slug, 'complete', page.knowledge_revision ?? null);
return written;
@@ -1094,9 +1030,7 @@ export async function runExtractFacts(
const outcome = detach.length === 0 && expireInPlace.length === 0 && plan.updates.length === 0
? await apply()
: await underPageLock(slug, async () => {
- if (await refuseDestructiveReconcileOnStaleCache(
- engine, slug, sourceId, page.compiled_truth ?? '', page.timeline ?? '', result.warnings,
- )) return null;
+ if (await refuseDestructiveReconcileOnStaleCache(engine, slug, sourceId, page, result.warnings)) return null;
if (isAborted(opts.signal)) return null;
return apply();
}, opts, result.warnings);
diff --git a/src/core/facts-fence.ts b/src/core/facts-fence.ts
index 8466d9de75..a6432d6a03 100644
--- a/src/core/facts-fence.ts
+++ b/src/core/facts-fence.ts
@@ -645,6 +645,93 @@ export function upsertFactRow(
return { body: replaceOrInsertFactsFence(body, renderFactsTable(allRows)), rowNum: nextRowNum };
}
+/**
+ * #3625 (adversarial review, 2 rounds): whether `timeline` contains a
+ * GENUINE Facts fence marker, as opposed to the marker text merely being
+ * mentioned inside a fenced code example or quoted prose. A naive
+ * `.includes(FACTS_FENCE_BEGIN)` false-positives on both — e.g. a page
+ * whose real fence WAS removed, but whose timeline documents the fence
+ * syntax in a ```markdown code block or a `> ...` blockquote, would wrongly
+ * be treated as "misplaced" and block a genuine deletion, leaving stale
+ * facts indexed indefinitely.
+ *
+ * Round 1 tried reusing fence-scan.ts's scanFencedBlocks() + string removal
+ * of its extracted fence bodies. Round-2 adversarial review broke that:
+ * scanFencedBlocks normalizes line endings (splits on `\r\n|\r|\n`, joins
+ * fence bodies with plain `\n`) and strips opener indentation before
+ * returning fence text — so `stripped.split(fenceText).join('')` on the
+ * ORIGINAL (un-normalized) string silently fails to match a CRLF or
+ * indented code block, leaving the marker inside it undetected and still
+ * false-positive. Reconstructed-text removal can't safely undo a lossy
+ * normalization.
+ *
+ * Fix: a self-contained single-pass line scanner (mirroring fence-scan.ts's
+ * own CommonMark-subset opener/closer grammar, applied directly against
+ * `timeline.split(/\r\n|\r|\n/)` — ONE split, no re-normalization, no
+ * text-based removal) that skips lines between a real ``` /~~~ opener and
+ * its closer, then checks whether any remaining line, trimmed, exactly
+ * equals the marker. A real fence marker is always written as its own line
+ * (see FENCE_BODY-shaped output from fence-write.ts / upsertFactRow), so
+ * exact-line-match — on lines outside any code fence — rules out both
+ * hazards without needing a full markdown AST (mirrors
+ * findTimelineSplitIndex's own `trimmed === sentinel` pattern for the same
+ * class of problem on the timeline sentinel itself). An unclosed opener
+ * runs to EOF (matches fence-scan.ts's documented behavior) — a marker
+ * appearing after it is inside an ambiguous, unclosed block and is not
+ * trusted as genuine.
+ */
+export function timelineHasGenuineFactsFenceMarker(timeline: string): boolean {
+ if (!timeline.includes(FACTS_FENCE_BEGIN)) return false;
+ const lines = timeline.split(/\r\n|\r|\n/);
+ const OPEN_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
+ const CLOSE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i]!;
+ const open = OPEN_RE.exec(line);
+ if (open) {
+ const marker = open[1]!;
+ const fenceChar = marker[0]!;
+ const info = open[2]!.trim();
+ // Mirrors fence-scan.ts: a backtick opener whose info string contains
+ // a backtick is inline code, not a fence opener.
+ if (!(fenceChar === '`' && info.includes('`'))) {
+ let j = i + 1;
+ for (; j < lines.length; j++) {
+ const close = CLOSE_RE.exec(lines[j]!);
+ if (close && close[1]![0] === fenceChar && close[1]!.length >= marker.length) {
+ j++;
+ break;
+ }
+ }
+ i = j; // unclosed fence: j reaches lines.length, ending the scan
+ continue;
+ }
+ }
+ if (line.trim() === FACTS_FENCE_BEGIN) return true;
+ i++;
+ }
+ return false;
+}
+
+/**
+ * What the fence reconcile reads from a page body: each section's parsed fence, which sections hold a fence outside
+ * code (factsFenceSections) and whether the timeline holds a genuine begin marker line
+ * (timelineHasGenuineFactsFenceMarker). Built from the strings here; a segmented body builds it segment by segment
+ * (page-body/segment-facts.ts).
+ */
+export interface FactsFenceView {
+ body: FactsFenceParseResult;
+ timeline: FactsFenceParseResult;
+ sections: { body: boolean; timeline: boolean };
+ timelineMarker: boolean;
+}
+
+export function factsFenceView(page: { compiled_truth: string | null; timeline?: string | null }): FactsFenceView {
+ return { body: parseFactsFence(page.compiled_truth ?? ''), timeline: parseFactsFence(page.timeline ?? ''), sections: factsFenceSections(page),
+ timelineMarker: timelineHasGenuineFactsFenceMarker(page.timeline ?? '') };
+}
+
/**
* The ONE fence-placement rule, shared by every writer that materializes a
* fence into a page body (upsertFactRow, the phantom-redirect canonical
diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.ts
index aecac45be1..93cdd750cd 100644
--- a/src/core/page-body/segment-blocks.ts
+++ b/src/core/page-body/segment-blocks.ts
@@ -62,6 +62,11 @@ export interface BodyBlockOptions {
regions?: readonly BodyRegion[];
/** Text between two regions (default '\n', as in `${compiled_truth}\n${timeline}`). */
separator?: string;
+ /**
+ * Read only the runs this accepts (the manifest seqs of a block, and whether it is its region's first); it is asked
+ * as each run is reached, so it may depend on the blocks already read. A block after a skipped run has `at` NaN.
+ */
+ want?: (run: { seqs: readonly number[]; first: boolean }) => boolean;
}
/** `page_body_segmented`: a run a derived pass must read whole is over BLOCK_MAX_BYTES. */
@@ -90,6 +95,11 @@ export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug:
while (j + 1 < rows.length && forced.has(rows[j]!.seq)) j++;
const start = rows[i]!.byteStart;
const end = rows[j]!.byteStart + rows[j]!.byteLen;
+ if (opts.want && !opts.want({ seqs: rows.slice(i, j + 1).map(row => row.seq), first: i === 0 })) {
+ at = NaN;
+ i = j + 1;
+ continue;
+ }
if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, body.sourceId, end - start);
const parts: Buffer[] = [];
for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start, end, audience: 'trusted', region, body })) parts.push(piece.bytes);
diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.ts
new file mode 100644
index 0000000000..b24bad23a7
--- /dev/null
+++ b/src/core/page-body/segment-facts.ts
@@ -0,0 +1,172 @@
+/**
+ * Segmented page storage (Wave B, spec 8.2 fences, PR 2 full-pass mode): what
+ * the facts fence reconcile reads from a segmented body (FactsFenceView),
+ * without holding the body as one string.
+ *
+ * The view needs, per section, the first begin marker outside code, the first
+ * end marker outside code after it and the text between them, and whether a
+ * timeline line outside fenced code is the begin marker. Only runs holding a
+ * fence marker can change any of those, so only they are read: the live
+ * manifest rows that carry facts slots or whose segment text holds a marker
+ * (found in SQL, nothing transferred), plus every run with a forced cut (a
+ * marker may straddle one), and every run after an open fence until it
+ * closes. A block starts outside code (segment-blocks.ts), so each marker is
+ * located in its block exactly as in the joined section. The segmenter never
+ * cuts inside a fence, so a fence lies in one block: a fence longer than a
+ * segment is a run of forced cuts, which bodyBlocks joins up to
+ * BLOCK_MAX_BYTES and refuses above with `page_body_segmented`. Joining a
+ * fence across blocks is a fallback that keeps the same bound. A fence
+ * crossing a forced cut while the source has withdrawals refuses with
+ * `page_projection_stale` (read-range.ts).
+ *
+ * `segmentedBodyMatchesFile` is the stale-cache check (canonicalCacheState)
+ * for a segmented page: the canonical file's split regions, streamed from
+ * the file, against the stored regions, by length and SHA-256.
+ */
+import { createHash } from 'node:crypto';
+import { open } from 'node:fs/promises';
+import type { BrainEngine } from '../engine.ts';
+import { indexOfOutsideCode } from '../fence-scan.ts';
+import {
+ FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, timelineHasGenuineFactsFenceMarker, type FactsFenceView,
+} from '../facts-fence.ts';
+import { BodyScanner } from './body-scan.ts';
+import { readBodyRange } from './read-range.ts';
+import { BLOCK_MAX_BYTES, blockTooLargeError, bodyBlocks, readGarbageCollector, segmentedPassWork } from './segment-blocks.ts';
+import type { BodyRegion } from './types.ts';
+
+type FencePage = { id: number; slug: string; source_id: string };
+
+/** Live manifest seqs whose segment can hold (part of) a facts fence marker. */
+async function markerSeqs(engine: BrainEngine, pageId: number): Promise<Set<number>> {
+ const rows = await engine.executeRaw<{ seq: number }>(`SELECT m.seq FROM page_body_manifest m
+ JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256
+ WHERE m.page_id=$1 AND m.gen_to IS NULL AND m.staging_id IS NULL
+ AND (m.facts_slots<>'[]'::jsonb OR m.cut_kind='forced' OR position($2::bytea in t.body)>0 OR position($3::bytea in t.body)>0)`,
+ [pageId, Buffer.from(FACTS_FENCE_BEGIN, 'utf8'), Buffer.from(FACTS_FENCE_END, 'utf8')]);
+ return new Set(rows.map(row => Number(row.seq)));
+}
+
+/** parseFactsFence, factsFenceSections and (timeline) timelineHasGenuineFactsFenceMarker of one region, streamed. */
+async function regionFence(engine: BrainEngine, page: FencePage, region: BodyRegion, marked: ReadonlySet<number>) {
+ let fence: string[] | null = null;
+ let fenceChars = 0;
+ let endOnly = false;
+ let marker = false;
+ let parsedText: string | null = null;
+ const want = ({ seqs }: { seqs: readonly number[] }) => (fence !== null && parsedText === null)
+ || ((parsedText === null || region === 'timeline') && seqs.some(seq => marked.has(seq)));
+ for await (const { text, at } of bodyBlocks(engine, page, { regions: [region], want })) {
+ if (region === 'timeline') marker ||= timelineHasGenuineFactsFenceMarker(text);
+ if (parsedText !== null) continue;
+ let from = 0;
+ let search = 0;
+ if (!fence) {
+ const begin = indexOfOutsideCode(text, FACTS_FENCE_BEGIN);
+ if (begin === -1) {
+ // locateOutsideCode's end search with no begin starts at FACTS_FENCE_BEGIN.length - 1; a block after the
+ // first run sits past that (a segment holds at least SEGMENT_MIN_BYTES).
+ const floor = at === 0 ? FACTS_FENCE_BEGIN.length - 1 : 0;
+ endOnly ||= indexOfOutsideCode(text, FACTS_FENCE_END, floor) !== -1;
+ continue;
+ }
+ fence = [];
+ from = begin;
+ search = begin + FACTS_FENCE_BEGIN.length;
+ }
+ const end = indexOfOutsideCode(text, FACTS_FENCE_END, search);
+ const piece = text.slice(from, end === -1 ? text.length : end + FACTS_FENCE_END.length);
+ fenceChars += piece.length;
+ segmentedPassWork.carry += piece.length;
+ if (fenceChars > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.source_id, fenceChars);
+ fence.push(piece);
+ if (end !== -1) parsedText = fence.join('');
+ }
+ const reduced = parsedText ?? (fence ? FACTS_FENCE_BEGIN : endOnly ? `${'\n'.repeat(FACTS_FENCE_BEGIN.length)}${FACTS_FENCE_END}` : '');
+ return { parsed: parseFactsFence(reduced), holds: fence !== null, marker };
+}
+
+/** factsFenceView of a segmented page, reading only the runs that can hold a fence marker. */
+export async function segmentedFactsFenceView(engine: BrainEngine, page: { id?: number; slug?: string; source_id?: string }): Promise<FactsFenceView> {
+ const p = { id: Number(page.id), slug: page.slug ?? '', source_id: page.source_id ?? 'default' };
+ const marked = await markerSeqs(engine, p.id);
+ const truth = await regionFence(engine, p, 'truth', marked);
+ const timeline = await regionFence(engine, p, 'timeline', marked);
+ return { body: truth.parsed, timeline: timeline.parsed, sections: { body: truth.holds, timeline: timeline.holds }, timelineMarker: timeline.marker };
+}
+
+const FILE_READ_BYTES = 1024 * 1024;
+
+/** Each region's [bytes, SHA-256] as the file splits it (parseMarkdown's compiled_truth and timeline), streamed from the file. */
+async function fileRegionDigests(path: string): Promise<Record<BodyRegion, [number, string]> | null> {
+ const file = await open(path, 'r');
+ try {
+ const { size } = await file.stat();
+ const scanner = new BodyScanner(path);
+ const buffer = Buffer.alloc(FILE_READ_BYTES);
+ const collect = readGarbageCollector();
+ for (let at = 0; at < size;) {
+ const { bytesRead } = await file.read(buffer, 0, Math.min(FILE_READ_BYTES, size - at), at);
+ if (!bytesRead) break;
+ scanner.push(buffer.subarray(0, bytesRead));
+ segmentedPassWork.bytes += bytesRead;
+ collect(bytesRead);
+ at += bytesRead;
+ }
+ const scan = scanner.finish();
+ if (scan.kind !== 'ok') return null;
+ const digest = async (pieces: typeof scan.truth): Promise<[number, string]> => {
+ const sha = createHash('sha256');
+ let bytes = 0;
+ for (const piece of pieces) {
+ if ('text' in piece) {
+ const text = Buffer.from(piece.text, 'utf8');
+ sha.update(text);
+ bytes += text.length;
+ continue;
+ }
+ for (let at = piece.start; at < piece.end;) {
+ const { bytesRead } = await file.read(buffer, 0, Math.min(FILE_READ_BYTES, piece.end - at), at);
+ if (!bytesRead) break;
+ sha.update(buffer.subarray(0, bytesRead));
+ segmentedPassWork.bytes += bytesRead;
+ collect(bytesRead);
+ bytes += bytesRead;
+ at += bytesRead;
+ }
+ }
+ return [bytes, sha.digest('hex')];
+ };
+ return { truth: await digest(scan.truth), timeline: await digest(scan.timeline) };
+ } finally {
+ await file.close();
+ }
+}
+
+/** [bytes, SHA-256] of a stored region of a segmented page, as readPageSnapshot gives a trusted reader (the withdrawal overlay applied). */
+async function storedRegionDigest(engine: BrainEngine, pageId: number, region: BodyRegion): Promise<[number, string]> {
+ const sha = createHash('sha256');
+ let bytes = 0;
+ const collect = readGarbageCollector();
+ for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region })) {
+ sha.update(piece.bytes);
+ bytes += piece.bytes.length;
+ segmentedPassWork.bytes += piece.bytes.length;
+ collect(piece.bytes.length);
+ }
+ return [bytes, sha.digest('hex')];
+}
+
+/**
+ * Whether the canonical file at `path` splits into the stored body of a segmented page, region by region, as
+ * canonicalCacheState compares an inline page's strings. 'stale' when the file does not scan.
+ */
+export async function segmentedBodyMatchesFile(engine: BrainEngine, page: { id: number }, path: string): Promise<'fresh' | 'stale'> {
+ const file = await fileRegionDigests(path);
+ if (!file) return 'stale';
+ for (const region of ['truth', 'timeline'] as const) {
+ const stored = await storedRegionDigest(engine, Number(page.id), region);
+ if (stored[0] !== file[region][0] || stored[1] !== file[region][1]) return 'stale';
+ }
+ return 'fresh';
+}
diff --git a/src/core/sweep.ts b/src/core/sweep.ts
index b9efdeacb8..2d02dd176e 100644
--- a/src/core/sweep.ts
+++ b/src/core/sweep.ts
@@ -204,7 +204,7 @@ export async function runMaintenanceSweep(
// subquery) rather than every row a bulk-sync day may have touched.
const rows = await engine.executeRaw<{ slug: string }>(
`SELECT slug FROM (
- SELECT slug, compiled_truth, updated_at FROM pages
+ SELECT id, slug, compiled_truth, body_storage, updated_at FROM pages
WHERE source_id = $1
AND deleted_at IS NULL
AND updated_at >= $2::timestamptz
@@ -212,6 +212,8 @@ export async function runMaintenanceSweep(
LIMIT $4
) AS recent
WHERE compiled_truth LIKE $3
+ OR (body_storage = 'segmented' AND EXISTS (SELECT 1 FROM page_body_manifest m
+ WHERE m.page_id = recent.id AND m.gen_to IS NULL AND m.staging_id IS NULL AND m.facts_slots <> '[]'::jsonb))
ORDER BY updated_at DESC
LIMIT $5`,
[sourceId, cutoffIso, `%${FACTS_FENCE_BEGIN_MARKER}%`, FENCE_LIKE_SCAN_CAP, batchLimit],
diff --git a/test/large-pages/segmented-facts-reconcile.test.ts b/test/large-pages/segmented-facts-reconcile.test.ts
new file mode 100644
index 0000000000..9685668bc5
--- /dev/null
+++ b/test/large-pages/segmented-facts-reconcile.test.ts
@@ -0,0 +1,324 @@
+/**
+ * Wave B PR 2 lane 2e2 (spec 8.2 fences, full-pass mode): extract_facts
+ * reconciles the facts fence of a segmented page from its segments.
+ *
+ * 1. Protects: for pages over the inline threshold stored both inline
+ * (segmented storage off) and segmented (on), with a fence mid-body, a
+ * lone fence below the timeline sentinel, a fence in each section, an
+ * unbalanced fence, a marker quoted in code before the fence and a stray
+ * end marker before it, an end marker quoted in code inside the fence (the
+ * fence then crosses a segment cut), a begin marker split by a forced cut
+ * (balanced and unbalanced), a fence over several segments and a row longer than a segment (a forced cut
+ * inside the fence), runExtractFacts gives the same counts, warnings
+ * and facts rows, from an empty index and from a drifted one (a changed
+ * cell, a rewritten claim, a row the fence no longer holds);
+ * segmentedFactsFenceView equals factsFenceView of the strings, reading
+ * only the segments that hold a marker; segmentedBodyMatchesFile agrees
+ * with the inline stale-cache comparison; a fence longer than
+ * BLOCK_MAX_BYTES refuses with page_body_segmented and keeps the index.
+ * 2. Fails when: the reconcile skips segmented pages (FACTS_RECONCILE_SEGMENTED),
+ * a marker block is not read, a fence is parsed from a block where it
+ * spans more, a marker split by a forced cut is missed, the view reads
+ * segments without a marker, or an oversized fence is read whole.
+ * 3. Why existing coverage misses it: extract-facts tests use inline pages.
+ * Seams: none; the readSegmentTexts spy wraps the engine method.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';
+import { runMaintenanceSweep } from '../../src/core/sweep.ts';
+import { factsFenceView, FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../../src/core/facts-fence.ts';
+import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';
+import { materializedPage } from '../../src/core/persistence/segmented-apply.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+let dir: string;
+
+const HEADER = '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ + '|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n';
+const ROWS = [
+ '| 1 | ~~Works at Acme Example~~ | fact | 1.0 | world | medium | 2020-01-01 | | notes | superseded by #2 |',
+ '| 2 | Works at Beta Example | fact | 0.9 | world | high | 2022-01-01 | | notes | |',
+ '| 3 | Prefers short meetings | preference | 0.7 | private | low | | | chat | |',
+ '| 4 | Plans to ship in May | commitment | 0.8 | world | medium | 2026-03-01 | | chat | roadmap |',
+];
+const fence = (rows = ROWS) => `${FACTS_FENCE_BEGIN}\n${HEADER}${rows.join('\n')}\n${FACTS_FENCE_END}`;
+const prose = (bytes: number, seed: number) => conversationBody(bytes, { seed });
+/** A line that starts a segment (it does not fit the one before) and ends 10 bytes before its second forced cut, so a marker after it straddles that cut. */
+const STRADDLE = 'y'.repeat(2 * 1024 * 1024 - 10);
+
+/** Pages over the inline threshold, each with its fence away from the first segment. */
+const VARIANTS: Record<string, string> = {
+ body: `${prose(700_000, 1)}\n\n## Facts\n\n${fence()}\n\n${prose(700_000, 2)}\n`,
+ lone_timeline: `${prose(900_000, 3)}\n\n<!-- timeline -->\n\n${prose(500_000, 4)}\n\n## Facts\n\n${fence()}\n\n- **2026-01-02** | Met\n`,
+ split: `${prose(600_000, 5)}\n\n## Facts\n\n${fence(ROWS.slice(0, 2))}\n\n${prose(500_000, 6)}\n\n<!-- timeline -->\n\n${fence(ROWS.slice(2))}\n`,
+ unbalanced: `${prose(700_000, 7)}\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n${HEADER}${ROWS[1]}\n\n${prose(700_000, 8)}\n`,
+ quoted_first: `${prose(400_000, 9)}\n\n\`\`\`md\n${fence(ROWS.slice(0, 1))}\n\`\`\`\n\n${prose(500_000, 10)}\n\n## Facts\n\n${fence()}\n\n${prose(400_000, 11)}\n`,
+ forced_row: `${prose(700_000, 15)}\n\n## Facts\n\n${fence([ROWS[0], ROWS[1].replace('| |', `| ${'context words '.repeat(110_000)}|`), ROWS[2], ROWS[3]])}\n\n${prose(700_000, 16)}\n`,
+ long_fence: `${prose(500_000, 18)}\n\n## Facts\n\n${fence(Array.from({ length: 40 }, (_, i) => `| ${i + 1} | Long claim ${i + 1} | fact | 1.0 | world | medium | | | notes | ${'fence context '.repeat(1_100)}|`))}\n\n${prose(500_000, 19)}\n`,
+ end_quoted_inside: `${prose(400_000, 20)}\n\n## Facts\n\n${FACTS_FENCE_BEGIN}\n${HEADER}${ROWS[0]}\n${ROWS[1]}\n\n\`\`\`md\n${FACTS_FENCE_END}\n\`\`\`\n\n${prose(600_000, 21)}\n\n${ROWS[2]}\n${FACTS_FENCE_END}\n\n${prose(300_000, 22)}\n`,
+ straddled_begin: `${prose(700_000, 23)}\n\n## Facts\n\n${STRADDLE}${fence()}\n\n${prose(500_000, 24)}\n`,
+ straddled_unbalanced: `${prose(700_000, 25)}\n\n## Facts\n\n${STRADDLE}${FACTS_FENCE_BEGIN}\n${HEADER}${ROWS[1]}\n\n${prose(500_000, 26)}\n`,
+ stray_end_first: `${prose(400_000, 12)}\n\nOld end: \n\n${FACTS_FENCE_END}\n\n${prose(500_000, 13)}\n\n## Facts\n\n${fence()}\n\n${prose(400_000, 14)}\n`,
+};
+/**
+ * A fence longer than BLOCK_MAX_BYTES (8 MiB). The segmenter never cuts inside a fence, so it is one run of forced
+ * cuts, and every derived pass refuses a run that long (segment-blocks.ts).
+ */
+const OVERSIZED_FENCE = `${prose(400_000, 17)}\n\n## Facts\n\n${fence(Array.from({ length: 90 }, (_, i) => `| ${i + 1} | Claim ${i + 1} | fact | 1.0 | world | medium | | | notes | ${'row context '.repeat(8_500)}|`))}\n`;
+const page = (body: string) => `---\ntype: person\ntitle: Fence Example\n---\n\n${body}`;
+const slugOf = (variant: string, storage: 'inline' | 'segmented') => `people/fence-${variant.replace(/_/g, '-')}-${storage}`;
+
+beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'segmented-facts-'));
+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);
+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }
+ for (const engine of engines) {
+ for (const storage of ['inline', 'segmented'] as const) {
+ await engine.setConfig('pages.segmented_storage', storage === 'segmented' ? 'on' : 'off');
+ for (const [variant, body] of Object.entries(VARIANTS)) {
+ expect(await importFromContent(engine, slugOf(variant, storage), page(body), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ }
+ expect(await importFromContent(engine, slugOf('oversized', storage), page(OVERSIZED_FENCE), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ }
+ }
+}, 600_000);
+
+afterAll(async () => {
+ await withEnv({ GBRAIN_HOME: dir }, async () => { for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); } });
+ await closePostgres?.();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+async function stored(engine: BrainEngine, slug: string) {
+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;
+ return snapshot.page;
+}
+
+/** The page's facts rows without ids, timestamps or its slug. */
+async function factsOf(engine: BrainEngine, slug: string) {
+ const rows = await engine.executeRaw<Record<string, unknown>>(`SELECT row_num, fact, kind, visibility, notability, confidence, source, context,
+ valid_from, valid_until, expired_at IS NOT NULL AS expired, superseded_by IS NOT NULL AS superseded, entity_slug
+ FROM facts WHERE source_id='default' AND source_markdown_slug=$1 ORDER BY row_num NULLS LAST, fact`, [slug]);
+ // A row without a valid_from cell takes the write time (the page's effective date is the import time here).
+ const recent = (value: unknown) => value instanceof Date && Math.abs(Date.now() - value.getTime()) < 3_600_000;
+ return rows.map(row => ({ ...row, entity_slug: row.entity_slug === slug ? 'SELF' : row.entity_slug, valid_from: recent(row.valid_from) ? 'WRITE_TIME' : row.valid_from }));
+}
+
+async function reconcile(engine: BrainEngine, slug: string) {
+ const r = await runExtractFacts(engine, { slugs: [slug] });
+ return { inserted: r.factsInserted, updated: r.factsUpdated, deleted: r.factsDeleted, withFacts: r.pagesWithFacts,
+ warnings: r.warnings.map(w => w.replaceAll(slug, 'SLUG')) };
+}
+
+/** Drift the index: change a cell, rewrite a claim, add a row the fence does not hold. */
+async function drift(engine: BrainEngine, slug: string) {
+ await engine.executeRaw(`UPDATE facts SET notability='low' WHERE source_markdown_slug=$1 AND row_num=2`, [slug]);
+ await engine.executeRaw(`UPDATE facts SET fact='Plans to ship in June' WHERE source_markdown_slug=$1 AND row_num=4`, [slug]);
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, source_markdown_slug, row_num, confidence)
+ VALUES ('default', $1, 'Lives in Example City', 'fact', 'world', 'medium', 'notes', $1, 999, 1.0)`, [slug]);
+}
+
+describe('fence reconcile of a segmented page (full-pass mode)', () => {
+ test('each variant is segmented with its fence past the first segment', async () => {
+ for (const engine of engines) {
+ for (const variant of Object.keys(VARIANTS)) {
+ const p = await stored(engine, slugOf(variant, 'segmented'));
+ expect(p.body_storage).toBe('segmented');
+ expect((await stored(engine, slugOf(variant, 'inline'))).body_storage ?? 'inline').toBe('inline');
+ const [m] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL', [p.id]);
+ expect(m!.n).toBeGreaterThan(2);
+ }
+ }
+ }, 300_000);
+
+ test('segmentedFactsFenceView equals factsFenceView of the strings, reading only marker segments', async () => {
+ for (const engine of engines) {
+ for (const variant of Object.keys(VARIANTS)) {
+ const p = await stored(engine, slugOf(variant, 'segmented'));
+ const inline = await materializedPage(engine, p);
+ const original = engine.readSegmentTexts.bind(engine);
+ let reads = 0;
+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => { reads += shas.length; return original(sourceId, shas); }) as BrainEngine['readSegmentTexts'];
+ try {
+ expect(await segmentedFactsFenceView(engine, p)).toEqual(factsFenceView(inline));
+ } finally {
+ // The spy is an own property; deleting it restores the prototype method a transaction engine inherits.
+ delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;
+ }
+ // A segment can hold a marker, or sit in a run joined by a forced cut (a forced segment or the one after it).
+ const [marked] = await engine.executeRaw<{ n: number; all: number }>(`SELECT count(*) FILTER (WHERE marker OR forced OR after_forced)::int AS n, count(*)::int AS all
+ FROM (SELECT position($2::bytea in t.body)>0 OR position($3::bytea in t.body)>0 AS marker, m.cut_kind='forced' AS forced,
+ coalesce(lag(m.cut_kind='forced') OVER (ORDER BY m.seq), false) AS after_forced
+ FROM page_body_manifest m JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE m.page_id=$1 AND m.gen_to IS NULL) s`,
+ [p.id, Buffer.from(FACTS_FENCE_BEGIN), Buffer.from(FACTS_FENCE_END)]);
+ expect(reads).toBeGreaterThan(0);
+ expect(reads).toBeLessThanOrEqual(marked!.n);
+ expect(reads).toBeLessThan(marked!.all);
+ }
+ }
+ }, 300_000);
+
+ test('runExtractFacts gives the inline counts, warnings and rows, from an empty index and from a drifted one', async () => {
+ for (const engine of engines) {
+ for (const variant of Object.keys(VARIANTS)) {
+ const outcomes: Record<string, unknown>[] = [];
+ for (const storage of ['inline', 'segmented'] as const) {
+ const slug = slugOf(variant, storage);
+ await engine.executeRaw('UPDATE facts SET superseded_by=NULL WHERE source_markdown_slug=$1', [slug]);
+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug=$1', [slug]);
+ const fresh = await reconcile(engine, slug);
+ const afterFresh = await factsOf(engine, slug);
+ await drift(engine, slug);
+ const drifted = await reconcile(engine, slug);
+ outcomes.push({ fresh, afterFresh, drifted, afterDrift: await factsOf(engine, slug), again: await reconcile(engine, slug) });
+ }
+ expect(outcomes[1]).toEqual(outcomes[0]!);
+ if (variant === 'body') {
+ expect(outcomes[0]).toMatchObject({ fresh: { inserted: 4 }, drifted: { updated: 1 } });
+ expect((outcomes[0]!.afterDrift as unknown[]).length).toBeGreaterThan(4);
+ }
+ if (variant === 'unbalanced' || variant === 'split') expect((outcomes[0]!.fresh as { warnings: string[] }).warnings.length).toBeGreaterThan(0);
+ }
+ }
+ }, 600_000);
+
+ test('forced cuts: forced_row crosses one inside its fence; in the straddled variants no segment holds the whole begin marker', async () => {
+ for (const engine of engines) {
+ for (const variant of ['forced_row', 'straddled_begin', 'straddled_unbalanced']) {
+ const p = await stored(engine, slugOf(variant, 'segmented'));
+ const [m] = await engine.executeRaw<{ forced: number; begin: number }>(`SELECT count(*) FILTER (WHERE m.cut_kind='forced')::int AS forced,
+ count(*) FILTER (WHERE position($2::bytea in t.body)>0)::int AS begin
+ FROM page_body_manifest m JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE m.page_id=$1 AND m.gen_to IS NULL`,
+ [p.id, Buffer.from(FACTS_FENCE_BEGIN)]);
+ expect(m!.forced).toBeGreaterThan(0);
+ expect(m!.begin).toBe(variant === 'forced_row' ? 1 : 0);
+ }
+ }
+ }, 300_000);
+
+ test('a fence longer than BLOCK_MAX_BYTES refuses with page_body_segmented and keeps the index; the inline page reconciles', async () => {
+ for (const engine of engines) {
+ const inline = await reconcile(engine, slugOf('oversized', 'inline'));
+ expect({ inserted: inline.inserted, withFacts: inline.withFacts }).toEqual({ inserted: 90, withFacts: 1 });
+ const slug = slugOf('oversized', 'segmented');
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, visibility, notability, source, source_markdown_slug, row_num, confidence)
+ VALUES ('default', $1, 'Kept row', 'fact', 'world', 'medium', 'notes', $1, 1, 1.0)`, [slug]);
+ const before = await factsOf(engine, slug);
+ const r = await runExtractFacts(engine, { slugs: [slug] });
+ expect(r.pagesFailed).toBe(1);
+ expect(r.warnings.join('\n')).toMatch(/FACTS_RECONCILE_FAILED: .*a derived pass must read whole.*over its \d+-byte bound/);
+ expect(await factsOf(engine, slug)).toEqual(before);
+ }
+ }, 300_000);
+
+ test('the maintenance sweep picks a recently written segmented page with a facts fence for reconcile, as an inline one', async () => {
+ for (const engine of engines) {
+ const inserted: number[] = [];
+ for (const storage of ['inline', 'segmented'] as const) {
+ const slug = slugOf('body', storage);
+ await engine.executeRaw('UPDATE facts SET superseded_by=NULL WHERE source_markdown_slug=$1', [slug]);
+ await engine.executeRaw('DELETE FROM facts WHERE source_markdown_slug=$1', [slug]);
+ await engine.executeRaw(`UPDATE pages SET updated_at = CASE WHEN slug=$1 THEN now() ELSE now() - interval '30 days' END WHERE source_id='default'`, [slug]);
+ inserted.push((await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs: 600_000 })).factsReconciled);
+ }
+ expect(inserted).toEqual([4, 4]);
+ }
+ }, 300_000);
+
+ test('with a canonical checkout, a destructive reconcile runs when the file matches and refuses FACTS_PAGE_CACHE_STALE when it does not, both ways', async () => {
+ for (const engine of engines) {
+ const root = mkdtempSync(join(dir, 'checkout-'));
+ await engine.executeRaw(`UPDATE sources SET local_path=$1 WHERE id='default'`, [root]);
+ try {
+ const outcomes: unknown[] = [];
+ for (const storage of ['inline', 'segmented'] as const) {
+ const slug = slugOf('body', storage);
+ mkdirSync(join(root, 'people'), { recursive: true });
+ const outcome: unknown[] = [];
+ for (const content of [page(VARIANTS.body!), page(VARIANTS.body!.replace('Works at Beta Example', 'Works at Gamma Example'))]) {
+ writeFileSync(join(root, `${slug}.md`), content);
+ await reconcile(engine, slug);
+ await drift(engine, slug);
+ outcome.push(await reconcile(engine, slug), await factsOf(engine, slug));
+ }
+ outcomes.push(outcome);
+ }
+ expect(outcomes[1]).toEqual(outcomes[0]);
+ const [fresh, , stale] = outcomes[0] as Array<{ deleted: number; warnings: string[] }>;
+ expect(fresh!.deleted).toBeGreaterThan(0);
+ expect(stale!.warnings.some(w => w.includes('FACTS_PAGE_CACHE_STALE'))).toBe(true);
+ } finally {
+ await engine.executeRaw(`UPDATE sources SET local_path=NULL WHERE id='default'`);
+ }
+ }
+ }, 300_000);
+
+ test('on a managed brain the reconcile of a segmented page publishes through the fence-facts maintenance request', async () => {
+ for (const engine of engines) {
+ const sourceId = `fences-${engines.indexOf(engine)}`;
+ const root = join(dir, sourceId);
+ mkdirSync(join(root, 'people'), { recursive: true });
+ await withEnv({ GBRAIN_HOME: dir }, async () => {
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ await registerLocalWriter(engine, 'cli');
+ await claimWorktree(engine, sourceId, root);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ try {
+ writeFileSync(join(root, 'people/managed-fence.md'), page(VARIANTS.body!));
+ expect(await importManagedFile(engine, join(root, 'people/managed-fence.md'), 'people/managed-fence.md', { sourceId, noEmbed: true }))
+ .toMatchObject({ status: 'imported' });
+ const [p] = await engine.executeRaw<{ body_storage: string }>("SELECT body_storage FROM pages WHERE source_id=$1 AND slug='people/managed-fence'", [sourceId]);
+ expect(p!.body_storage).toBe('segmented');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('UPDATE facts SET superseded_by=NULL WHERE source_id=$1', [sourceId]);
+ await engine.executeRaw('DELETE FROM facts WHERE source_id=$1', [sourceId]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const result = await runExtractFacts(engine, { sourceId, slugs: ['people/managed-fence'] });
+ expect(result.warnings.filter(w => w.includes('SEGMENTED'))).toEqual([]);
+ expect(result.factsInserted).toBe(4);
+ const rows = await engine.executeRaw<{ row_num: number; fact: string }>(
+ 'SELECT row_num, fact FROM facts WHERE source_id=$1 AND expired_at IS NULL ORDER BY row_num', [sourceId]);
+ expect(rows.map(r => [Number(r.row_num), r.fact])).toEqual([[2, 'Works at Beta Example'], [3, 'Prefers short meetings'], [4, 'Plans to ship in May']]);
+ const kinds = await engine.executeRaw<{ kind: string }>("SELECT intent->>'kind' AS kind FROM persistence_requests WHERE source_id=$1 AND state='committed'", [sourceId]);
+ expect(kinds.map(k => k.kind)).toContain('managed_maintenance_fence_facts');
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ }
+ });
+ }
+ }, 300_000);
+
+ test('segmentedBodyMatchesFile agrees with the inline stale-cache comparison', async () => {
+ for (const engine of engines) {
+ for (const variant of ['body', 'lone_timeline']) {
+ const p = await stored(engine, slugOf(variant, 'segmented'));
+ const inline = await materializedPage(engine, p);
+ const path = join(dir, `${variant}.md`);
+ for (const content of [page(VARIANTS[variant]!), page(VARIANTS[variant]!.replace('Works at Beta Example', 'Works at Gamma Example'))]) {
+ writeFileSync(path, content);
+ const canonical = parseMarkdown(content, path);
+ const expected = canonical.compiled_truth === inline.compiled_truth.trim() && canonical.timeline === (inline.timeline ?? '').trim() ? 'fresh' : 'stale';
+ expect(await segmentedBodyMatchesFile(engine, p, path)).toBe(expected);
+ }
+ expect(await segmentedBodyMatchesFile(engine, p, path)).toBe('stale');
+ }
+ }
+ }, 300_000);
+});