Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(large-pages): incremental per-segment links, mentions, timeline and fence derivations (Wave B PR 4 lane 4a)
garrytan950c64dae7d2
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f3dbaeb083..edfe089bc7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1022,6 +1022,10 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },+ // PR 4 (Wave B incremental derivation, transcripts)+ // PR 4 4a+ { since: 'TBD', text: 'Links, mentions, timeline entries and facts/takes fences of a large (segmented) page are now kept per segment, so a write reads only the segments it changed, and an append reads its new tail instead of the whole page. A rewrite of the whole page does the same work as before. The results are unchanged.' },+ { since: 'TBD', text: 'Forgetting, purging or withdrawing a fact on a large page now also deletes the stored link, mention, timeline and fence results of the segment that held it, in the same transaction. A purge counts them as `page_segment_derivations`.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/cycle/extract-facts.ts b/src/core/cycle/extract-facts.tsindex 88879feea8..c2432c63d5 100644--- a/src/core/cycle/extract-facts.ts+++ b/src/core/cycle/extract-facts.ts@@ -83,7 +83,7 @@ import { writeReceipt } from '../extract/receipt-writer.ts';import { fenceUnfencedFacts, planUnfencedFacts } from '../facts/unfenced-facts.ts';import { classifyRunStop, upsertExtractRollup } from '../extract/rollup-writer.ts';import { factsFenceView } from '../facts-fence.ts';-import { segmentedBodyMatchesFile, segmentedFactsFenceView } from '../page-body/segment-facts.ts';+import { incrementalFactsFenceView, segmentedBodyMatchesFile } from '../page-body/segment-facts.ts';import {duplicateActiveFenceRows,extractFactsFromFenceText,@@ -390,7 +390,8 @@ interface FenceReconcilePlan {* fence in each section of the page (#6686: a split fence) preserves the page's existing index.*/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);+ // A segmented page's view comes from its fences rows: only runs changed since their row was written are read.+ const view = isSegmentedPage(page) ? await incrementalFactsFenceView(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 = !view.sections.body && view.sections.timeline ? view.timeline : null;diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex 7de177c373..d3d4b027ad 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -118,7 +118,7 @@ const ROWS: readonly Row[] = [['page_mention_state', 'out_of_scope', 'no_memory_text', 'source_id'],['page_projection_jobs', 'out_of_scope', 'no_memory_text', 'slug reason'],['page_purges', 'out_of_scope', 'text_free_ledger', 'source_id content_hash slug'],- ['page_segment_derivations', 'out_of_scope', 'probed_reported', 'pipeline segment_sha256 context_hash state output receipt', 'output receipt'],+ ['page_segment_derivations', 'swept', 'segment_derivations', 'pipeline segment_sha256 context_hash state output receipt', 'output receipt'],['page_segment_texts', 'swept', 'segment_texts', 'source_id sha256 body', 'body'],['page_view_digests', 'out_of_scope', 'no_memory_text', 'revision view audience sha256'],['page_versions', 'swept', 'page_versions', 'compiled_truth frontmatter timeline title type tags source_path write_principal_kind write_principal_id archived_principal_kind archived_principal_id trust_tier write_origin body_storage content_hash'],diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.tsindex 02648007d0..2506e6f406 100644--- a/src/core/facts/purge.ts+++ b/src/core/facts/purge.ts@@ -245,7 +245,7 @@ const SEGMENTED_VERSION_CARRIES = `EXISTS (SELECT 1 FROM page_body_manifest m JOAND strpos(lower(convert_from(t.body,'UTF8')),$2)>0)`;/** What the body rewrites changed: slugs rewritten, segmented pages touched, and the segment texts they stopped referencing. */-interface BodyRewrites { rewritten: string[]; segmented: number[]; unsealed: string[]; replaced: Uint8Array[] }+interface BodyRewrites { rewritten: string[]; segmented: number[]; unsealed: string[]; replaced: Uint8Array[]; derivations: number }/*** Drop purged rows from each affected page's stored body. Each page is versioned first (the rewrite advances its@@ -253,7 +253,7 @@ interface BodyRewrites { rewritten: string[]; segmented: number[]; unsealed: str* generation (spec 11), and its version of the old revision references that generation.*/export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pages: PurgePlan['pages']): Promise<BodyRewrites> {- const out: BodyRewrites = { rewritten: [], segmented: [], unsealed: [], replaced: [] };+ const out: BodyRewrites = { rewritten: [], segmented: [], unsealed: [], replaced: [], derivations: 0 };if (!pages.length) return out;const rows = await tx.executeRaw<Record<string, unknown>>(`SELECT p.*,COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id),'[]'::jsonb) AS purge_tagsFROM pages p WHERE p.source_id=$1 AND p.id=ANY($2::int[]) ORDER BY p.slug`, [sourceId, pages.map(p => p.page_id)]);@@ -269,6 +269,7 @@ export async function rewritePageBodies(tx: BrainEngine, sourceId: string, pagesif (preimage) await createPageVersion(tx, slug, sourceId, preimage);out.rewritten.push(slug);out.replaced.push(...done.replaced);+ out.derivations += done.derivations;if (!done.sealed) out.unsealed.push(slug);continue;}@@ -541,7 +542,7 @@ export async function submitPurgeFactMutation(ctx: OperationContext, params: Rectargets: pages.map(page => ({ slug: page.slug, page_id: Number(page.id), revision: page.knowledge_revision })) })]);counts = { facts, takes, chunks, page_versions: versions.redacted, pages: rewritten.length, persistence_requests: intents,query_cache: cache, decide_review: review, open_loops: loops, take_proposals: proposals, core_edit_notices: notices,- write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts,+ write_gate_holds: holdIds.length, write_gate_receipts: gateReceipts, page_segment_texts: segments.texts, page_segment_derivations: bodies.derivations,page_body_stagings: segments.stagings, page_body_staging_parts: segments.parts, persistence_requests_cancelled: segments.cancelled,derived_hidden: Object.values(derived.hidden).reduce((a, b) => a + b, 0) };derivedHidden = derived;diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 79e58bc5aa..8794556705 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -41,8 +41,11 @@** A segmented page (body in segments, NULL body columns) is scanned block by* block (page-body/segment-blocks.ts), the title first, keeping each target's- * first mention: a name whose tokens straddle a segment cut (a blank line,- * heading, dated line or message boundary) is not matched. A gazetteer change+ * first mention, and incrementally: each run's mentions are stored on its+ * page_segment_derivations row keyed by its text, the gazetteer's digest and+ * the scan options, so only runs that changed are read again. A name whose+ * tokens straddle a segment cut (a blank line, heading, dated line or message+ * boundary) is not matched. A gazetteer change* marks every segmented page in scope due (no SQL prefilter reads its body).* Derived aliases are still refreshed for inline entity pages only.*/@@ -55,7 +58,9 @@ import {buildGazetteer, findMentionedEntities, gazetteerEntryKeys, tokenizeTitle,type FindMentionsOpts, type Gazetteer, type GazetteerEntry, type GazetteerEntryKey, type Mention,} from '../by-mention.ts';-import { bodyBlocks } from '../page-body/segment-blocks.ts';+import { bodyBlocks, detachedValue } from '../page-body/segment-blocks.ts';+import { commitRuns, derivationScope, keyDigest, planRuns, readRuns, SegmentDerivationRaced, type DeriveRun } from '../page-body/segment-derive.ts';+import { canonicalJson } from '../belief/keys.ts';import { linkableTypesFor, loadSourcePack, parseNameList, readMentionPolicy, type MentionPolicy, type PackTypes } from './policy.ts';import { deriveEntityAliases, type DerivedAlias } from './aliases.ts';import { normalizeAliasList } from '../search/alias-normalize.ts';@@ -238,7 +243,52 @@ async function disableSource(engine: BrainEngine, managed: boolean, sourceId: stinterface DuePage { id: number; slug: string; source_id: string; revision: string; title: string | null; type: string | null;compiled_truth: string | null; timeline: string | null; mention_ignore: unknown; frontmatter?: Record<string, unknown> | null; body_storage?: string }-/** findMentionedEntities over `${title}\n\n${compiled_truth}\n\n${timeline}`; a segmented body is scanned block by block. */+/** What one run of a segmented body holds for the mention pass: its UTF-16 length and each target's first mention in it (offset run-local). */+interface MentionRunOutput { chars: number; mentions: Mention[] }++const gazetteerDigests = new WeakMap<Gazetteer, string>();++/** A digest of every gazetteer entry (all fields), computed once per gazetteer object: the input a body run's mentions depend on. */+function gazetteerDigest(gazetteer: Gazetteer): string {+ let digest = gazetteerDigests.get(gazetteer);+ if (digest === undefined) {+ digest = keyDigest(canonicalJson([...gazetteer].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))));+ gazetteerDigests.set(gazetteer, digest);+ }+ return digest;+}++/**+ * The body mentions of a segmented page per run (spec 8.2 mentions), in page order: runs whose rows match the gazetteer,+ * the scan options and their text are reused, the others are scanned block by block and stored. Null when the page is+ * not segmented.+ */+async function segmentedRunMentions(engine: BrainEngine, p: { id: number; slug: string; source_id: string }, gazetteer: Gazetteer,+ opts: FindMentionsOpts): Promise<Array<{ run: DeriveRun; output: MentionRunOutput }> | null> {+ const scope = await derivationScope(engine, p);+ if (!scope) return null;+ const inputs = { extractor: MENTION_EXTRACTOR_VERSION, gazetteer: gazetteerDigest(gazetteer), opts, separator: '\n\n' };+ const plan = await planRuns<MentionRunOutput>(engine, 'mentions', scope, () => inputs);+ const fresh = new Map(plan.todo.map(run => [run.index, { chars: 0, mentions: [] as Mention[], seen: new Set<string>() }]));+ await readRuns(engine, scope, new Set(fresh.keys()), (run, block) => {+ const out = run && fresh.get(run.index);+ if (!out) return;+ for (const m of findMentionedEntities(block.text, gazetteer, opts)) {+ if (out.seen.has(`${m.source_id}\0${m.slug}`)) continue;+ out.seen.add(`${m.source_id}\0${m.slug}`);+ out.mentions.push(detachedValue({ ...m, offset: m.offset + out.chars }));+ }+ out.chars += block.text.length;+ }, { separator: '\n\n' });+ const outputs = new Map([...fresh].map(([index, { chars, mentions }]) => [index, { chars, mentions }]));+ await commitRuns(engine, 'mentions', scope, outputs, () => inputs);+ return scope.runs.map(run => ({ run, output: outputs.get(run.index) ?? plan.current.get(run.index)! }));+}++/**+ * findMentionedEntities over `${title}\n\n${compiled_truth}\n\n${timeline}`; a segmented body is scanned block by block,+ * incrementally (segmentedRunMentions), or in a full pass when its body moves during the read.+ */export async function pageMentions(engine: BrainEngine,p: { id: number; slug: string; source_id: string; title: string | null; compiled_truth?: string | null; timeline?: string | null; body_storage?: string | null },gazetteer: Gazetteer, opts: FindMentionsOpts): Promise<Mention[]> {@@ -251,7 +301,20 @@ export async function pageMentions(engine: BrainEngine,};add(findMentionedEntities(p.title ?? '', gazetteer, opts), 0);const base = (p.title ?? '').length + 2;- for await (const block of bodyBlocks(engine, p, { separator: '\n\n' })) add(findMentionedEntities(block.text, gazetteer, opts), base + block.at);+ const runs = await segmentedRunMentions(engine, p, gazetteer, opts).catch(error => {+ if (error instanceof SegmentDerivationRaced) return null;+ throw error;+ });+ if (!runs) {+ for await (const block of bodyBlocks(engine, p, { separator: '\n\n' })) add(findMentionedEntities(block.text, gazetteer, opts), base + block.at);+ return [...found.values()];+ }+ let at = base;+ for (const { run, output } of runs) {+ if (run.region === 'timeline' && (run.index === 0 || runs[run.index - 1]!.run.region === 'truth')) at += 2;+ add(output.mentions, at);+ at += output.chars;+ }return [...found.values()];}diff --git a/src/core/page-body/segment-derive.ts b/src/core/page-body/segment-derive.tsnew file mode 100644index 0000000000..4f3a22a13f--- /dev/null+++ b/src/core/page-body/segment-derive.ts@@ -0,0 +1,310 @@+/**+ * Incremental derivation over a segmented page (Wave B spec 8.1, 8.2, PR 4 lane 4a): the shared driver the unpaid+ * pipelines (links, mentions, timeline, fences) use instead of a full pass over every block.+ *+ * The unit of work is a run: the live manifest rows of one region joined by forced cuts, which bodyBlocks reads+ * together (segment-blocks.ts), so every block a run yields starts where the parsers start fresh. A run's result is+ * stored on its first occurrence's page_segment_derivations row; its other occurrences get a row naming that first+ * occurrence. Each row's context hash covers the run's composition (every member's sha and entry state, its region and+ * whether it opens it), the page's withdrawal ledger and segmenter version, and the page-level inputs the pipeline+ * passes, so a run whose rows all match is current and the work left is found from manifest metadata alone.+ *+ * A run is read only when it is due (or a pipeline asks for a neighbour as context). The read checks that the body+ * generation and the ledger it planned from are still the page's; otherwise it throws SegmentDerivationRaced and the+ * caller falls back to its full pass, so a row never pairs one generation's metadata with another's text.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { canonicalJson } from '../belief/keys.ts';+import { planSegmentDerivations, segmentDerivationContextHash, type LiveSegment, type SegmentDerivationInput, type SegmentDerivationKind,+ type SegmentDerivationRow } from './derivations.ts';+import { bodyBlocks, type BodyBlock } from './segment-blocks.ts';+import { ledgerApplies, readBodyLedger } from './segment-ledger.ts';+import { SEGMENTER_VERSION } from './segmenter.ts';+import type { BodyRegion, ManifestRow } from './types.ts';++/** Bump a kind's version to re-derive every page's rows of that kind once. */+export const SEGMENT_PIPELINE_VERSIONS = { links: 1, mentions: 1, timeline: 1, fences: 1 } as const satisfies Partial<Record<SegmentDerivationKind, number>>;+export type UnpaidDerivationKind = keyof typeof SEGMENT_PIPELINE_VERSIONS;++/** @internal Runs derived (and their occurrences) and runs reused per kind, for the work-volume tests. Counts, not time. */+export const segmentDeriveWork: Record<UnpaidDerivationKind, { derived: number; occurrences: number; reused: number }> = {+ links: { derived: 0, occurrences: 0, reused: 0 }, mentions: { derived: 0, occurrences: 0, reused: 0 },+ timeline: { derived: 0, occurrences: 0, reused: 0 }, fences: { derived: 0, occurrences: 0, reused: 0 },+};++export interface DeriveRun {+ index: number;+ region: BodyRegion;+ /** The run opens its region. */+ first: boolean;+ seqs: number[];+ occurrences: number[];+ shas: Uint8Array[];+ entryStates: unknown[];+ bytes: number;+}++export interface DerivationScope {+ pageId: number;+ slug: string;+ sourceId: string;+ generation: number;+ runs: DeriveRun[];+ /** SHA-256 of the withdrawal ledger when one applies to the page (the overlay changes text), else null. */+ ledgerKey: string | null;+ stale: boolean;+}++export interface SegmentedDerivationPage { id: number; slug: string; source_id: string }++/** The page's body moved (another generation, another ledger) between the plan and the read. */+export class SegmentDerivationRaced extends Error {+ constructor(slug: string) {+ super(`Segmented page ${slug} changed while its derivations were read.`);+ this.name = 'SegmentDerivationRaced';+ }+}++const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknown : v;+const bytesOf = (v: unknown) => v instanceof Uint8Array ? new Uint8Array(v) : new Uint8Array(Buffer.from(String(v).replace(/^\\x/, ''), 'hex'));+const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');++async function ledgerKey(engine: BrainEngine, page: SegmentedDerivationPage): Promise<string | null> {+ const ledger = await readBodyLedger(engine, page.source_id, page.slug);+ return ledgerApplies(ledger) ? createHash('sha256').update(canonicalJson(ledger)).digest('hex') : null;+}++/** The live runs of a segmented page from its manifest rows (no segment text), or null when it is not segmented. */+export async function derivationScope(engine: BrainEngine, page: SegmentedDerivationPage): Promise<DerivationScope | null> {+ const [state] = await engine.executeRaw<{ body_storage: string; body_generation: string; segmenter_version: number | null }>(+ 'SELECT body_storage, body_generation::text AS body_generation, segmenter_version FROM pages WHERE id=$1', [page.id]);+ if (state?.body_storage !== 'segmented') return null;+ const generation = Number(state.body_generation);+ const rows = await engine.executeRaw<{ seq: number; occurrence_id: string; region: BodyRegion; sha256: unknown; entry_state: unknown; cut_kind: string; byte_len: number }>(+ `SELECT seq, occurrence_id::text AS occurrence_id, region, sha256, entry_state, cut_kind, byte_len FROM page_body_manifest+ WHERE page_id=$1 AND staging_id IS NULL AND gen_from<=$2 AND (gen_to IS NULL OR gen_to>$2) ORDER BY seq`, [page.id, generation]);+ const runs: DeriveRun[] = [];+ for (const region of ['truth', 'timeline'] as const) {+ const own = rows.filter(row => row.region === region);+ for (let i = 0; i < own.length;) {+ let j = i;+ while (j + 1 < own.length && own[j]!.cut_kind === 'forced') j++;+ const members = own.slice(i, j + 1);+ runs.push({ index: runs.length, region, first: i === 0, seqs: members.map(row => Number(row.seq)), occurrences: members.map(row => Number(row.occurrence_id)),+ shas: members.map(row => bytesOf(row.sha256)), entryStates: members.map(row => toJson(row.entry_state)), bytes: members.reduce((n, row) => n + Number(row.byte_len), 0) });+ i = j + 1;+ }+ }+ return { pageId: page.id, slug: page.slug, sourceId: page.source_id, generation, runs, ledgerKey: await ledgerKey(engine, page),+ stale: Number(state.segmenter_version) !== SEGMENTER_VERSION };+}++/** The identity of a run's stored text and of its place in its region. */+export function runIdentity(run: DeriveRun): unknown {+ return [run.region, run.first, run.shas.map(hex), run.entryStates];+}++/** Per member occurrence, the context hash of `run` for `kind` under the page-level `inputs`. */+export function runContextHashes(kind: UnpaidDerivationKind, scope: DerivationScope, run: DeriveRun, inputs: Record<string, unknown>): Uint8Array[] {+ const page = { ...inputs, run: runIdentity(run), ledger: scope.ledgerKey, stale: scope.stale };+ return run.entryStates.map((entryState, i) => segmentDerivationContextHash(kind, { entryState, page: { ...page, member: i } }));+}++export interface RunPlan<O> {+ /** Runs to derive, in page order. */+ todo: DeriveRun[];+ /** Outputs of the runs whose rows all match, by run index. */+ current: Map<number, O>;+}++/** Split a page's runs into due and current for `kind`, given each run's page-level inputs (`inputsOf`) and its rows (`read`, else read here). */+export async function planRuns<O>(engine: BrainEngine, kind: UnpaidDerivationKind, scope: DerivationScope,+ inputsOf: (run: DeriveRun) => Record<string, unknown>, read?: readonly SegmentDerivationRow[]): Promise<RunPlan<O>> {+ const result = splitRuns<O>(kind, scope, inputsOf, read ?? await engine.readSegmentDerivations(scope.pageId, { kind }));+ segmentDeriveWork[kind].reused += result.current.size;+ return result;+}++function splitRuns<O>(kind: UnpaidDerivationKind, scope: DerivationScope, inputsOf: (run: DeriveRun) => Record<string, unknown>,+ rows: readonly SegmentDerivationRow[]): RunPlan<O> {+ const live: LiveSegment[] = [];+ for (const run of scope.runs) {+ const hashes = runContextHashes(kind, scope, run, inputsOf(run));+ run.occurrences.forEach((occurrenceId, i) => live.push({ occurrenceId, sha256: run.shas[i]!, contextHash: hashes[i]! }));+ }+ const plan = planSegmentDerivations(kind, SEGMENT_PIPELINE_VERSIONS[kind], live, rows);+ const settled = new Map(plan.current.map(row => [row.occurrenceId, row]));+ const result: RunPlan<O> = { todo: [], current: new Map() };+ for (const run of scope.runs) {+ const first = settled.get(run.occurrences[0]!);+ if (first && run.occurrences.every(id => settled.has(id))) result.current.set(run.index, first.output as O);+ else result.todo.push(run);+ }+ return result;+}++/**+ * Read the blocks of the runs `wanted` names (a set of indices, or a predicate asked as each run is reached, in order),+ * in page order, handing each to `onBlock` with its run; the region separator between truth and timeline is handed+ * with run null. Runs not wanted are never read. Throws SegmentDerivationRaced when the page's generation or ledger+ * moved from the scope's.+ */+export async function readRuns(engine: BrainEngine, scope: DerivationScope, wanted: ReadonlySet<number> | ((run: DeriveRun) => boolean),+ onBlock: (run: DeriveRun | null, block: BodyBlock) => void | Promise<void>, opts: { separator?: string } = {}): Promise<void> {+ if (typeof wanted !== 'function' && !wanted.size) return;+ const wants = typeof wanted === 'function' ? wanted : (run: DeriveRun) => wanted.has(run.index);+ const bySeq = new Map(scope.runs.map(run => [run.seqs[0]!, run]));+ let current: DeriveRun | null = null;+ const page = { id: scope.pageId, slug: scope.slug, source_id: scope.sourceId };+ for await (const block of bodyBlocks(engine, page, {+ ...(opts.separator !== undefined ? { separator: opts.separator } : {}),+ want: ({ seqs }) => {+ const run = bySeq.get(seqs[0]!);+ if (!run || run.seqs.length !== seqs.length || run.seqs.some((seq, i) => seq !== seqs[i])) throw new SegmentDerivationRaced(scope.slug);+ current = wants(run) ? run : null;+ return current !== null;+ },+ })) await onBlock(block.region === null ? null : current, block);+ await assertScopeCurrent(engine, scope);+}++/** The page still has the scope's generation and ledger. */+export async function assertScopeCurrent(engine: BrainEngine, scope: DerivationScope): Promise<void> {+ const [state] = await engine.executeRaw<{ body_generation: string; body_storage: string }>(+ 'SELECT body_generation::text AS body_generation, body_storage FROM pages WHERE id=$1', [scope.pageId]);+ if (state?.body_storage !== 'segmented' || Number(state.body_generation) !== scope.generation+ || await ledgerKey(engine, { id: scope.pageId, slug: scope.slug, source_id: scope.sourceId }) !== scope.ledgerKey) throw new SegmentDerivationRaced(scope.slug);+}++/**+ * Store the outputs of derived runs (`outputs` by run index, under the inputs `inputsOf` gives) and delete the rows of+ * occurrences no longer live. The first occurrence of a run holds its output; the others name it.+ */+export async function commitRuns(engine: BrainEngine, kind: UnpaidDerivationKind, scope: DerivationScope, outputs: ReadonlyMap<number, unknown>,+ inputsOf: (run: DeriveRun) => Record<string, unknown>): Promise<void> {+ await storeRuns(engine, kind, scope, outputs, inputsOf);+ await engine.retireSegmentDerivations(scope.pageId, scope.runs.flatMap(run => run.occurrences), { kind });+}++async function storeRuns(engine: BrainEngine, kind: UnpaidDerivationKind, scope: DerivationScope, outputs: ReadonlyMap<number, unknown>,+ inputsOf: (run: DeriveRun) => Record<string, unknown>): Promise<void> {+ const rows: SegmentDerivationInput[] = [];+ for (const [index, output] of outputs) {+ const run = scope.runs[index]!;+ const hashes = runContextHashes(kind, scope, run, inputsOf(run));+ segmentDeriveWork[kind].derived++;+ segmentDeriveWork[kind].occurrences += run.occurrences.length;+ run.occurrences.forEach((occurrenceId, i) => rows.push({ pageId: scope.pageId, kind, occurrenceId, version: SEGMENT_PIPELINE_VERSIONS[kind],+ segmentSha256: run.shas[i]!, contextHash: hashes[i]!, state: 'done', output: i === 0 ? output : { run: run.occurrences[0] }, receipt: null }));+ }+ if (rows.length) await engine.upsertSegmentDerivations(rows);+}++/** Runs per batch of streamRuns: rows and texts of at most this many runs are held at once. */+const STREAM_BATCH_RUNS = 2;++/** How streamRuns derives one due run: `start` makes its empty output, `block` folds each of its blocks in. */+export interface RunDeriver<O> {+ start(run: DeriveRun): O;+ block(output: O, block: BodyBlock): void;+}++/**+ * planRuns, deriving and visiting for a kind whose outputs are large (one entry per timeline line), holding the rows of+ * at most STREAM_BATCH_RUNS runs and one due run's output at a time. The rows are read in batches to find the due runs;+ * then one read of the body (readRuns) derives each due run in page order, stores it and hands it to `visit`, and the+ * current runs before it are handed over from their rows, read again in batches. Every block read also goes to+ * `onBlock`. A current run whose rows changed in between throws SegmentDerivationRaced. Rows of occurrences no longer+ * live are deleted at the end.+ */+export async function streamRuns<O>(engine: BrainEngine, kind: UnpaidDerivationKind, scope: DerivationScope,+ inputsOf: (run: DeriveRun) => Record<string, unknown>, deriver: RunDeriver<O>, visit: (run: DeriveRun, output: O) => void,+ onBlock?: (run: DeriveRun | null, block: BodyBlock) => void): Promise<void> {+ const batchRows = (runs: readonly DeriveRun[]) => engine.readSegmentDerivations(scope.pageId, { kind, occurrenceIds: runs.flatMap(run => run.occurrences) });+ const due = new Set<number>();+ for (let at = 0; at < scope.runs.length; at += STREAM_BATCH_RUNS) {+ const batch = scope.runs.slice(at, at + STREAM_BATCH_RUNS);+ for (const run of (await planRuns<O>(engine, kind, { ...scope, runs: batch }, inputsOf, await batchRows(batch))).todo) due.add(run.index);+ }+ let next = 0;+ const handOver = async (until: number) => {+ while (next < until) {+ const batch = scope.runs.slice(next, Math.min(until, next + STREAM_BATCH_RUNS)).filter(run => !due.has(run.index));+ const plan = splitRuns<O>(kind, { ...scope, runs: batch }, inputsOf, await batchRows(batch));+ if (plan.todo.length) throw new SegmentDerivationRaced(scope.slug);+ for (const run of batch) visit(run, plan.current.get(run.index)!);+ next = Math.min(until, next + STREAM_BATCH_RUNS);+ }+ };+ let deriving: { run: DeriveRun; output: O } | null = null;+ const finish = async () => {+ if (!deriving) return;+ const { run, output } = deriving;+ deriving = null;+ await storeRuns(engine, kind, scope, new Map([[run.index, output]]), inputsOf);+ visit(run, output);+ next = run.index + 1;+ };+ const begin = async (run: DeriveRun, block: BodyBlock) => {+ await finish();+ await handOver(run.index);+ deriving = { run, output: deriver.start(run) };+ deriver.block(deriving.output, block);+ };+ await readRuns(engine, scope, due, (run, block) => {+ onBlock?.(run, block);+ if (!run) return;+ if (deriving?.run !== run) return begin(run, block);+ deriver.block(deriving.output, block);+ });+ await finish();+ await handOver(scope.runs.length);+ await engine.retireSegmentDerivations(scope.pageId, scope.runs.flatMap(run => run.occurrences), { kind });+}++/** Bytes of neighbouring runs whose link rows a rewrite also drops: a link excerpt reaches 120 units past its block. */+const LINK_REACH_BYTES = 4096;++/**+ * Delete the derivation rows that may hold text a fence rewrite (forget, purge; spec 11) replaced, in the caller's+ * transaction: every kind's rows of each run holding a rewritten row (a run's output sits on its first occurrence),+ * and the links rows of the runs on either side up to LINK_REACH_BYTES away, whose candidate excerpts can reach into+ * it. `rows` is the generation's manifest in order; `spans` the rewritten index ranges. Returns the rows deleted.+ */+export async function deleteRewrittenDerivations(engine: BrainEngine, pageId: number,+ rows: ReadonlyArray<Pick<ManifestRow, 'occurrenceId' | 'region' | 'cutKind' | 'byteLen'>>, spans: ReadonlyArray<{ from: number; to: number }>): Promise<number> {+ const joined = (i: number) => i + 1 < rows.length && rows[i]!.cutKind === 'forced' && rows[i]!.region === rows[i + 1]!.region;+ const runOf = (i: number): [number, number] => {+ let from = i, to = i;+ while (from > 0 && joined(from - 1)) from--;+ while (joined(to)) to++;+ return [from, to];+ };+ const touched = new Set<number>(), reach = new Set<number>();+ const add = (into: Set<number>, from: number, to: number) => { for (let i = from; i <= to; i++) into.add(rows[i]!.occurrenceId); };+ for (const span of spans) {+ const [from] = runOf(span.from), [, to] = runOf(span.to);+ add(touched, from, to);+ for (let at = from - 1, bytes = 0; at >= 0 && bytes < LINK_REACH_BYTES;) {+ const [a, b] = runOf(at);+ add(reach, a, b);+ for (let i = a; i <= b; i++) bytes += rows[i]!.byteLen;+ at = a - 1;+ }+ for (let at = to + 1, bytes = 0; at < rows.length && bytes < LINK_REACH_BYTES;) {+ const [a, b] = runOf(at);+ add(reach, a, b);+ for (let i = a; i <= b; i++) bytes += rows[i]!.byteLen;+ at = b + 1;+ }+ }+ if (!touched.size) return 0;+ return (await engine.executeRaw(`DELETE FROM page_segment_derivations WHERE page_id=$1+ AND (occurrence_id = ANY($2::bigint[]) OR (pipeline = 'links' AND occurrence_id = ANY($3::bigint[]))) RETURNING 1`, [pageId, [...touched], [...reach]])).length;+}++/** SHA-256 hex (its first 32 digits) of a key, recorded in an output instead of the key's text. */+export function keyDigest(key: string): string {+ return createHash('sha256').update(key).digest('hex').slice(0, 32);+}diff --git a/src/core/page-body/segment-facts.ts b/src/core/page-body/segment-facts.tsindex a504af950d..26c6506da5 100644--- a/src/core/page-body/segment-facts.ts+++ b/src/core/page-body/segment-facts.ts@@ -21,6 +21,11 @@* it and overlaid whole (read-range.ts `trustedSegments`, up to* FENCE_MAX_BYTES), then cut into blocks here as any run is.*+ * The incremental view (PR 4, `incrementalFactsFenceView`) keeps each run's+ * facts and takes scan on its `fences` row in page_segment_derivations, so a+ * reconcile reads only the runs that changed since; a fence that runs past the+ * run it begins in falls back to the view above.+ ** `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.@@ -30,11 +35,14 @@ 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,+ FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence, timelineHasGenuineFactsFenceMarker, type FactsFenceParseResult, type FactsFenceView,} from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';+import { commitRuns, derivationScope, planRuns, readRuns, SegmentDerivationRaced, type DerivationScope, type DeriveRun } from './segment-derive.ts';+import { TakesFenceScan, type TakesRunSummary } from './segment-takes.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 { BLOCK_MAX_BYTES, blockTooLargeError, bodyBlocks, readGarbageCollector, segmentedPassWork, type BodyBlock } from './segment-blocks.ts';import type { BodyRegion } from './types.ts';type FencePage = { id: number; slug: string; source_id: string };@@ -50,43 +58,78 @@ async function markerSeqs(engine: BrainEngine, pageId: number): Promise<Set<numbreturn 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;+/**+ * parseFactsFence, factsFenceSections and (timeline) timelineHasGenuineFactsFenceMarker of one region as a push scan:+ * feed the region's blocks in order (`first`: the block opens the region), then `result`.+ */+export class FactsFenceScan {+ private fence: string[] | null = null;+ private fenceChars = 0;+ private endOnly = false;+ private marker = false;+ private parsedText: string | null = null;++ constructor(private readonly page: FencePage, private readonly region: BodyRegion) {}++ /** A fence is open: the blocks after it are its text until it closes. */+ get open(): boolean {+ return this.fence !== null && this.parsedText === null;+ }++ /** The parse is decided: later blocks only feed the timeline marker scan. */+ get parsed(): boolean {+ return this.parsedText !== null;+ }++ push(text: string, first: boolean): void {+ if (this.region === 'timeline') this.marker ||= timelineHasGenuineFactsFenceMarker(text);+ if (this.parsedText !== null) return;let from = 0;let search = 0;- if (!fence) {+ if (!this.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;+ // region's first sits past that (a segment holds at least SEGMENT_MIN_BYTES).+ this.endOnly ||= indexOfOutsideCode(text, FACTS_FENCE_END, first ? FACTS_FENCE_BEGIN.length - 1 : 0) !== -1;+ return;}- fence = [];+ this.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;+ this.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('');+ if (this.fenceChars > BLOCK_MAX_BYTES) throw blockTooLargeError(this.page.slug, this.page.source_id, this.fenceChars);+ this.fence.push(piece);+ if (end !== -1) this.parsedText = this.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 };++ result(): RegionFence {+ return regionFenceOf(this.parsedText, this.fence !== null, this.endOnly, this.marker);+ }++ /** What the blocks pushed so far hold, for a run's fences row. */+ summary(): FactsRunSummary {+ return { marker: this.marker, endOnly: this.endOnly, fence: this.fence ? { text: this.fence.join(''), closed: this.parsedText !== null } : null };+ }+}++interface RegionFence { parsed: FactsFenceParseResult; holds: boolean; marker: boolean }++function regionFenceOf(parsedText: string | null, holds: boolean, endOnly: boolean, marker: boolean): RegionFence {+ const reduced = parsedText ?? (holds ? FACTS_FENCE_BEGIN : endOnly ? `${'\n'.repeat(FACTS_FENCE_BEGIN.length)}${FACTS_FENCE_END}` : '');+ return { parsed: parseFactsFence(reduced), holds, marker };+}++/** One region of the facts fence view, streamed, reading only the runs that can hold a fence marker. */+async function regionFence(engine: BrainEngine, page: FencePage, region: BodyRegion, marked: ReadonlySet<number>): Promise<RegionFence> {+ const scan = new FactsFenceScan(page, region);+ const want = ({ seqs }: { seqs: readonly number[] }) => scan.open || ((!scan.parsed || region === 'timeline') && seqs.some(seq => marked.has(seq)));+ for await (const { text, at } of bodyBlocks(engine, page, { regions: [region], want })) scan.push(text, at === 0);+ return scan.result();}/** factsFenceView of a segmented page, reading only the runs that can hold a fence marker. */@@ -98,6 +141,85 @@ export async function segmentedFactsFenceView(engine: BrainEngine, page: { id?:return { body: truth.parsed, timeline: timeline.parsed, sections: { body: truth.holds, timeline: timeline.holds }, timelineMarker: timeline.marker };}+/** One run's FactsFenceScan state (a scan started fresh at the run): the timeline marker, the end-only scan before any begin, and its first fence. */+export interface FactsRunSummary { marker: boolean; endOnly: boolean; fence: { text: string; closed: boolean } | null }++/** What a run's fences row holds (spec 8.2 facts / takes fences): the facts and takes scans of its blocks. */+export interface FenceRunOutput { facts: FactsRunSummary; takes: TakesRunSummary }++/**+ * Each run of a segmented page with its fences row output, in page order (spec 8.2 facts / takes fences): runs whose+ * rows match their text are reused, the others are read block by block and stored. Null when the page is not+ * segmented. A fence parse is a function of the text alone (fence trust moves stored regions, not markers), so the+ * context is the run's identity, the ledger and the segmenter version the driver adds.+ */+export async function segmentedFenceRuns(engine: BrainEngine, page: FencePage): Promise<Array<{ run: DeriveRun; output: FenceRunOutput }> | null> {+ const scope = await derivationScope(engine, page);+ if (!scope) return null;+ const fences = await openFenceRuns(engine, page, scope);+ return fences.finish();+}++/**+ * The fences rows of a scope, for a caller that reads some runs for another kind: `push` the blocks it reads (a due+ * run seen whole is scanned there), then `finish` reads only the due runs still unscanned and stores every scan.+ */+export async function openFenceRuns(engine: BrainEngine, page: FencePage, scope: DerivationScope) {+ const inputs = () => ({ facts: FACTS_FENCE_BEGIN, takes: TAKES_FENCE_BEGIN });+ const plan = await planRuns<FenceRunOutput>(engine, 'fences', scope, inputs);+ const scans = new Map(plan.todo.map(run => [run.index, { facts: new FactsFenceScan(page, run.region), takes: new TakesFenceScan(page), at: 0, seen: false }]));+ const push = (run: DeriveRun | null, block: BodyBlock) => {+ const scan = run && scans.get(run.index);+ if (!scan) return;+ scan.seen = true;+ scan.facts.push(block.text, run.first && scan.at === 0);+ scan.takes.push({ text: block.text, at: run.first ? scan.at : Number.MAX_SAFE_INTEGER });+ scan.at += block.text.length;+ };+ return {+ /** Feed one block a caller read whole with its run's other blocks, in order. */+ push,+ async finish(): Promise<Array<{ run: DeriveRun; output: FenceRunOutput }>> {+ await readRuns(engine, scope, new Set([...scans].filter(([, scan]) => !scan.seen).map(([index]) => index)), push);+ const outputs = new Map([...scans].map(([index, scan]) => [index, { facts: scan.facts.summary(), takes: scan.takes.summary() }]));+ await commitRuns(engine, 'fences', scope, outputs, inputs);+ return scope.runs.map(run => ({ run, output: outputs.get(run.index) ?? plan.current.get(run.index)! }));+ },+ };+}++/** A region's facts fence from its runs' summaries, in order; null when a fence does not close in the run it begins in. */+export function factsFromRuns(summaries: readonly FactsRunSummary[]): RegionFence | null {+ let endOnly = false, marker = false, parsedText: string | null = null;+ for (const summary of summaries) {+ marker ||= summary.marker;+ if (parsedText !== null) continue;+ if (summary.fence) {+ if (!summary.fence.closed) return null;+ parsedText = summary.fence.text;+ } else endOnly ||= summary.endOnly;+ }+ return regionFenceOf(parsedText, parsedText !== null, endOnly, marker);+}++/**+ * factsFenceView of a segmented page from its fences rows (segmentedFenceRuns): only runs that changed since their row+ * was written are read. Falls back to segmentedFactsFenceView when a fence runs past the run it begins in or the body+ * moves during the read.+ */+export async function incrementalFactsFenceView(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 runs = await segmentedFenceRuns(engine, p).catch(error => {+ if (error instanceof SegmentDerivationRaced) return null;+ throw error;+ });+ const region = (name: BodyRegion) => runs && factsFromRuns(runs.filter(({ run }) => run.region === name).map(({ output }) => output.facts));+ const truth = region('truth');+ const timeline = region('timeline');+ if (!truth || !timeline) return segmentedFactsFenceView(engine, page);+ 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. */diff --git a/src/core/page-body/segment-links.ts b/src/core/page-body/segment-links.tsindex 1ee6d5680a..08b7c0cda4 100644--- a/src/core/page-body/segment-links.ts+++ b/src/core/page-body/segment-links.ts@@ -1,15 +1,15 @@/**- * Segmented page storage (Wave B, spec 8.2 links, PR 2 full-pass mode): link- * extraction over a segmented page's body, one block at a time- * (segment-blocks.ts), with the result extractPageLinks gives for the joined- * body: O(page) work, O(segment) memory, not yet incremental.+ * Segmented page storage (Wave B, spec 8.2 links): link extraction over a segmented page's body, one block at a time+ * (segment-blocks.ts), with the result extractPageLinks gives for the joined body. The full pass+ * (extractSegmentedPageLinks) does O(page) work in O(segment) memory; the incremental mode (openSegmentedLinkSession,+ * PR 4) derives only the runs whose inputs changed and merges the rest from page_segment_derivations.** Each block is extracted in a window (`bodyWindows`) and only references* starting in the block are kept, at their page offsets. The candidates are* merged in extractPageLinks' order (pass, then offset) with its* first-occurrence dedup, then the frontmatter's. The page-role priors read* the role phrases a first pass over the blocks found (rolePriorPhrases), and- * one pack-regex budget serves the page.+ * one pack-regex budget serves the page (the incremental mode: one per call).** Exact for every rule that stays inside a window; a construct the segmenter* does not keep inside a segment (an HTML comment or a mid-line ``` run@@ -18,15 +18,17 @@*/import type { BrainEngine } from '../engine.ts';import {- candidateKey, dedupeCandidates, extractBodyLinks, frontmatterLinks, rolePriorPhrases, stripCodeBlocks,+ candidateKey, dedupeCandidates, extractBodyLinks, frontmatterLinks, LINK_EXTRACTOR_VERSION_TS, rolePriorPhrases, stripCodeBlocks,type BodyLinkCandidate, type ExtractPageLinksOptions, type PageLinksResult, type SlugResolver,} from '../link-extraction.ts';+import { canonicalJson } from '../belief/keys.ts';import { datedLines, narrativeRefs } from '../link-temporal-evidence.ts';import { rangedRelationLines } from '../link-effective.ts';import type { TemporalBody } from '../link-temporal-apply.ts';import { PageRegexBudget } from '../schema-pack/redos-guard.ts';import type { PageType } from '../types.ts';import { bodyBlocks, detachedValue, segmentedPassWork, type BodyBlock, type BodyBlockOptions } from './segment-blocks.ts';+import { commitRuns, derivationScope, keyDigest, planRuns, readRuns, runIdentity, SEGMENT_PIPELINE_VERSIONS, type DeriveRun } from './segment-derive.ts';/** Context a window carries after its block (an excerpt reaches 120 chars past a link) and, at least, before it. */const CONTEXT_CHARS = 4096;@@ -38,7 +40,7 @@ export interface SegmentedLinkPage { id: number; slug: string; source_id: stringexport interface BodyWindow { text: string; start: number; end: number; offset: number; block: BodyBlock }/** Track the headings still open after `text`, by level (a heading closes every deeper one). */-function openHeadings(text: string, open: string[]): void {+export function openHeadings(text: string, open: string[]): void {const masked = stripCodeBlocks(text);let at = 0;for (const line of masked.split('\n')) {@@ -52,52 +54,70 @@ function openHeadings(text: string, open: string[]): void {}/**- * Each block of a segmented body in a window: whole preceding blocks of at least CONTEXT_CHARS before it (a window- * starts where parsers start fresh), the next CONTEXT_CHARS after it and, ahead of all, the headings still open- * there, so section-scoped rules (role-prior suppression, machine sections, attendance sections) see the block's- * section. A window that does not start the body opens with a blank line, so it never starts with frontmatter.+ * Cuts a stream of blocks into windows (bodyWindows): push each block, then flush. A cutter started mid-body takes the+ * headings open where it starts; its first windows lack the text before them, so a caller keeps only windows whose+ * blocks have CONTEXT_CHARS of pushed text before them (or start the body).*/-export async function* bodyWindows(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },- opts: BodyBlockOptions = {}): AsyncIterable<BodyWindow> {- const ahead: BodyBlock[] = [];- const before: BodyBlock[] = [];- const headings: string[] = [];- let beforeChars = 0;- const windowOf = (own: BodyBlock): BodyWindow => {- const lead = before[0]?.at ?? own.at;- const head = (lead === 0 ? '' : `\n${headings.filter(Boolean).map(h => `${h}\n`).join('')}`) + before.map(b => b.text).join('');+export class WindowCutter {+ private readonly ahead: BodyBlock[] = [];+ private readonly before: BodyBlock[] = [];+ private beforeChars = 0;++ constructor(private readonly headings: string[] = []) {}++ private windowOf(own: BodyBlock): BodyWindow {+ const lead = this.before[0]?.at ?? own.at;+ const head = (lead === 0 ? '' : `\n${this.headings.filter(Boolean).map(h => `${h}\n`).join('')}`) + this.before.map(b => b.text).join('');let after = '';- for (const b of ahead) {+ for (const b of this.ahead) {if (after.length >= CONTEXT_CHARS) break;after += b.text.slice(0, CONTEXT_CHARS - after.length);}segmentedPassWork.windows += head.length + own.text.length + after.length;return { text: head + own.text + after, start: head.length, end: head.length + own.text.length, offset: own.at - head.length, block: own };- };- const done = (own: BodyBlock) => {- before.push(own);- beforeChars += own.text.length;- while (before.length > 1 && beforeChars - before[0]!.text.length >= CONTEXT_CHARS) {- const gone = before.shift()!;- beforeChars -= gone.text.length;- openHeadings(gone.text, headings);+ }++ private done(own: BodyBlock): void {+ this.before.push(own);+ this.beforeChars += own.text.length;+ while (this.before.length > 1 && this.beforeChars - this.before[0]!.text.length >= CONTEXT_CHARS) {+ const gone = this.before.shift()!;+ this.beforeChars -= gone.text.length;+ openHeadings(gone.text, this.headings);}- };- for await (const block of bodyBlocks(engine, page, opts)) {- ahead.push(block);- while (ahead.length > 1 && ahead.slice(1).reduce((n, b) => n + b.text.length, 0) >= CONTEXT_CHARS) {- const own = ahead.shift()!;- yield windowOf(own);- done(own);+ }++ *push(block: BodyBlock): Iterable<BodyWindow> {+ this.ahead.push(block);+ while (this.ahead.length > 1 && this.ahead.slice(1).reduce((n, b) => n + b.text.length, 0) >= CONTEXT_CHARS) {+ const own = this.ahead.shift()!;+ yield this.windowOf(own);+ this.done(own);}}- while (ahead.length) {- const own = ahead.shift()!;- yield windowOf(own);- done(own);++ *flush(): Iterable<BodyWindow> {+ while (this.ahead.length) {+ const own = this.ahead.shift()!;+ yield this.windowOf(own);+ this.done(own);+ }}}+/**+ * Each block of a segmented body in a window: whole preceding blocks of at least CONTEXT_CHARS before it (a window+ * starts where parsers start fresh), the next CONTEXT_CHARS after it and, ahead of all, the headings still open+ * there, so section-scoped rules (role-prior suppression, machine sections, attendance sections) see the block's+ * section. A window that does not start the body opens with a blank line, so it never starts with frontmatter.+ */+export async function* bodyWindows(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },+ opts: BodyBlockOptions = {}): AsyncIterable<BodyWindow> {+ const cutter = new WindowCutter();+ for await (const block of bodyBlocks(engine, page, opts)) yield* cutter.push(block);+ yield* cutter.flush();+}+/** The page-role phrases of a segmented body (rolePriorPhrases over every block), as ExtractPageLinksOptions.roleText. */export async function segmentedRoleText(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },opts: BodyBlockOptions = {}): Promise<string> {@@ -143,3 +163,279 @@ export async function extractSegmentedPageLinks(engine: BrainEngine, page: Segmereturn { candidates: dedupeCandidates([...body, ...fm.candidates]), unresolved: fm.unresolved,attendanceComplete: attendanceComplete && fm.attendanceComplete, ...(opts.temporal ? { temporalBody } : {}) };}++/** What one run contributes to its page's links: the links row's output (offsets and authored-ref keys run-local). */+interface LinkRunOutput {+ /** UTF-16 units of the run's text. */+ chars: number;+ /** rolePriorPhrases over the run's blocks, the first per phrase. */+ roles: Array<string | null>;+ /** The headings open before the run and after it (openHeadings over every block up to its end). */+ headsIn: Array<string | null>;+ headsOut: Array<string | null>;+ /** Digest of the run's first CONTEXT_CHARS units: what a window before it reads past its block. */+ head: string;+ /** Digest of the run's last blocks totalling CONTEXT_CHARS (or all of them), with the headings open before them: what a window after it reads. */+ tail: string;+ links: BodyLinkCandidate[];+ attendance: boolean;+ temporal: TemporalBody;+ /** The answers the extraction read, so a run is reused only while they hold: basename matches and target types. */+ basenames: Array<[string, string[]]>;+ types: Array<[string, string | null, string | null]>;+}++type RunInfo = Pick<LinkRunOutput, 'chars' | 'roles' | 'headsIn' | 'headsOut' | 'head' | 'tail'>;++const heads = (open: ReadonlyArray<string | null | undefined>): Array<string | null> => Array.from(open, h => h ?? null);+const sameJson = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);+const sameBytes = (a: Uint8Array, b: Uint8Array) => Buffer.from(a).equals(Buffer.from(b));+const REF_KEY = /^ref:(-?\d+)$/;++/** A candidate moved `by` units from its run-local offset: its index and its authored-ref key move together. */+function shifted(link: BodyLinkCandidate, by: number): BodyLinkCandidate {+ const ref = link.candidate.authoredRef;+ const m = ref ? REF_KEY.exec(ref.key) : null;+ return { ...link, index: link.index + by, candidate: m ? { ...link.candidate, authoredRef: { ...ref!, key: `ref:${Number(m[1]) + by}` } } : link.candidate };+}++/** Options the incremental mode cannot honour (it reads the default regions, keeps no explain hook): those use the full pass. */+function incrementalOptions(opts: ExtractPageLinksOptions & BodyBlockOptions): boolean {+ return !opts.explain && !opts.regions && opts.separator === undefined && !opts.want && !opts.roleText && !opts.window;+}++export interface SegmentedLinkSession {+ /**+ * Every body and frontmatter link candidate with the due runs extracted untyped (no targetType): the targets a caller+ * reads endpoints for. Only the targets are the typed result's; link types and attendance may differ from it.+ */+ targets(opts: ExtractPageLinksOptions): Promise<PageLinksResult>;+ /** The typed result (extractSegmentedPageLinks with `temporal`), deriving only the due runs and storing them. */+ finish(opts: ExtractPageLinksOptions & { targetType: NonNullable<ExtractPageLinksOptions['targetType']> }): Promise<PageLinksResult & { temporalBody: TemporalBody }>;+}++/**+ * The incremental mode of extractSegmentedPageLinks (spec 8.2 links), for the write path's typed extraction with+ * temporal inputs: each run's candidates, role phrases, headings and temporal inputs are stored on its links rows, and+ * a run is derived again only when its text, its window (the runs whose text its windows read: at least CONTEXT_CHARS+ * before and after it), the headings open where that window starts, the page's role phrases, the page inputs (slug,+ * type, pack, extractor version, resolution options) or an answer its extraction read (a basename match, a target type)+ * changed. The page result is merged from the run outputs exactly as the full pass merges windows. Null when the page+ * is not segmented or the options ask for something only the full pass does. A body that moves under it throws+ * SegmentDerivationRaced (the caller falls back to the full pass); nothing is stored then.+ */+export async function openSegmentedLinkSession(engine: BrainEngine, page: SegmentedLinkPage, resolver: SlugResolver,+ base: ExtractPageLinksOptions & BodyBlockOptions): Promise<SegmentedLinkSession | null> {+ if (!incrementalOptions(base)) return null;+ const scope = await derivationScope(engine, page);+ if (!scope) return null;+ const rows = await engine.readSegmentDerivations(scope.pageId, { kind: 'links' });+ const byOccurrence = new Map(rows.map(row => [row.occurrenceId, row]));+ const stored = new Map<number, LinkRunOutput>();+ for (const run of scope.runs) {+ const output = byOccurrence.get(run.occurrences[0]!)?.output as LinkRunOutput | null | undefined;+ const ownValid = run.occurrences.every((id, i) => {+ const row = byOccurrence.get(id);+ return row !== undefined && row.state === 'done' && row.version === SEGMENT_PIPELINE_VERSIONS.links && sameBytes(row.segmentSha256, run.shas[i]!);+ });+ if (ownValid && output && Array.isArray(output.links)) stored.set(run.index, output);+ }++ // The chain: each run's chars, role phrases, headings and context digests, read only where no stored output holds+ // for the headings open before it.+ const info = new Map<number, RunInfo>();+ let open: Array<string | null> = [];+ type Reading = { run: DeriveRun; info: RunInfo; head: string; tail: string[]; tailChars: number; tailHeads: Array<string | null>; shifted: boolean };+ let reading: Reading | null = null;+ const close = () => {+ if (!reading) return;+ const { run, info: into, head, tail, tailHeads, shifted } = reading;+ into.headsOut = heads(open);+ into.head = keyDigest(head);+ into.tail = keyDigest(JSON.stringify([heads(tailHeads), tail, !shifted && run.index === 0 && run.region === 'truth']));+ info.set(run.index, into);+ reading = null;+ };+ await readRuns(engine, scope, run => {+ close();+ const output = stored.get(run.index);+ if (output && sameJson(output.headsIn, heads(open))) {+ info.set(run.index, { chars: output.chars, roles: output.roles, headsIn: output.headsIn, headsOut: output.headsOut, head: output.head, tail: output.tail });+ open = [...output.headsOut];+ return false;+ }+ reading = { run, info: { chars: 0, roles: [null, null, null], headsIn: heads(open), headsOut: [], head: '', tail: '' },+ head: '', tail: [], tailChars: 0, tailHeads: heads(open), shifted: false };+ return true;+ }, (run, block) => {+ const r = run && reading;+ if (r) {+ r.info.chars += block.text.length;+ rolePriorPhrases(block.text).forEach((phrase, i) => { r.info.roles[i] ??= phrase === null ? null : detachedValue(phrase); });+ if (r.head.length < CONTEXT_CHARS) r.head += block.text.slice(0, CONTEXT_CHARS - r.head.length);+ r.tail.push(block.text);+ r.tailChars += block.text.length;+ while (r.tail.length > 1 && r.tailChars - r.tail[0]!.length >= CONTEXT_CHARS) {+ const gone = r.tail.shift()!;+ r.tailChars -= gone.length;+ openHeadings(gone, r.tailHeads as string[]);+ r.shifted = true;+ }+ }+ openHeadings(block.text, open as string[]);+ });+ close();++ const found: Array<string | null> = [null, null, null];+ for (const run of scope.runs) info.get(run.index)!.roles.forEach((phrase, i) => { found[i] ??= phrase; });+ const roleText = found.filter(Boolean).join('\n');+ const separator = '\n';+ const lastTruth = scope.runs.filter(run => run.region === 'truth').length - 1;+ const charsOf = (index: number) => info.get(index)!.chars;+ // The runs whose text the windows of run k read: back and forward until CONTEXT_CHARS (the separator counts as a block).+ const range = (k: number): [number, number] => {+ let from = k, to = k;+ for (let acc = 0; from > 0 && acc < CONTEXT_CHARS;) { acc += charsOf(from - 1) + (from - 1 === lastTruth ? separator.length : 0); from--; }+ for (let acc = 0; to < scope.runs.length - 1 && acc < CONTEXT_CHARS;) { acc += charsOf(to + 1) + (to === lastTruth ? separator.length : 0); to++; }+ return [from, to];+ };+ const pageInputs = { extractor: LINK_EXTRACTOR_VERSION_TS, slug: page.slug, type: page.type, pack: base.pack ? keyDigest(canonicalJson(base.pack)) : null,+ globalBasename: !!base.globalBasename, lineGrammar: base.lineGrammar ?? null, roleText, separator };+ // A run's windows read the last blocks of the first run in its range (with the headings open before them), every run+ // between, and the first units of the last one. The separator's place is marked, as it is a block of its own.+ const sepBefore = (index: number) => index === lastTruth + 1;+ const between = (a: number, b: number) => [...scope.runs.slice(a + 1, b).flatMap(r => [...(sepBefore(r.index) ? ['sep'] : []), runIdentity(r)]),+ ...(sepBefore(b) ? ['sep'] : [])];+ const inputsOf = (run: DeriveRun) => {+ const [from, to] = range(run.index);+ return { ...pageInputs, before: from < run.index ? [info.get(from)!.tail, ...between(from, run.index)] : null,+ after: to > run.index ? [...between(run.index, to), info.get(to)!.head] : null };+ };+ const plan = await planRuns<LinkRunOutput>(engine, 'links', scope, inputsOf, rows);+ for (const [index, output] of [...plan.current]) {+ for (const [name, matches] of output.basenames) {+ if (sameJson(await resolver.resolveBasenameMatches?.(name) ?? null, matches)) continue;+ plan.current.delete(index);+ plan.todo.push(scope.runs[index]!);+ break;+ }+ }++ /** Extract the runs in `todo` (their windows read with their context runs) under `opts`, recording what each read. */+ const derive = async (todo: readonly DeriveRun[], opts: ExtractPageLinksOptions): Promise<Map<number, LinkRunOutput>> => {+ const wanted = new Set<number>();+ for (const run of todo) {+ const [from, to] = range(run.index);+ for (let i = from; i <= to; i++) wanted.add(i);+ }+ const outputs = new Map<number, LinkRunOutput>();+ for (const run of todo) outputs.set(run.index, { ...info.get(run.index)!, links: [], attendance: true, temporal: { lines: [], narrative: [], ranged: [] }, basenames: [], types: [] });+ type Recording = { basenames: Map<string, string[]>; types: Map<string, [string, string | null, string | null]> };+ let recording: Recording | null = null;+ const records = new Map<number, Recording>();+ const recorded: SlugResolver = { resolve: resolver.resolve.bind(resolver),+ ...(resolver.resolveAttendance ? { resolveAttendance: resolver.resolveAttendance.bind(resolver) } : {}),+ ...(resolver.resolveBasenameMatches ? { resolveBasenameMatches: async (name: string) => {+ const matches = await resolver.resolveBasenameMatches!(name);+ recording?.basenames.set(name, [...matches]);+ return matches;+ } } : {}) };+ const typed = opts.targetType;+ const targetType = typed && ((slug: string, sourceId?: string) => {+ const type = typed(slug, sourceId);+ recording?.types.set(`${sourceId ?? ''}\u0000${slug}`, [slug, sourceId ?? null, type ?? null]);+ return type;+ });+ const regexBudget = new PageRegexBudget();+ const local = new Map<BodyBlock, { run: DeriveRun; at: number }>();+ const used = new Map<number, number>();+ let cutter = new WindowCutter();+ let last = -2;+ const position = (run: DeriveRun | null) => run === null ? lastTruth + 1 : run.index + (run.region === 'timeline' ? 1 : 0);+ const onWindow = async (w: BodyWindow) => {+ const own = local.get(w.block);+ local.delete(w.block);+ const output = own && outputs.get(own.run.index);+ if (!own || !output) return;+ const offset = own.at - w.start;+ recording = records.get(own.run.index) ?? { basenames: new Map(), types: new Map() };+ records.set(own.run.index, recording);+ const body = await extractBodyLinks(page.slug, w.text, page.type, recorded,+ { ...opts, ...(targetType ? { targetType } : {}), roleText, regexBudget, window: { start: w.start, end: w.end, offset } });+ recording = null;+ output.attendance &&= body.attendanceComplete;+ output.links.push(...detachedValue(body.links));+ output.temporal.lines.push(...detachedValue(datedLines(w.block.text)));+ if (w.block.region === 'truth') output.temporal.narrative.push(...detachedValue(narrativeRefs(w.block.text)));+ for (const line of rangedRelationLines(w.text)) if (line.start >= w.start && line.start < w.end) output.temporal.ranged.push(detachedValue({ ...line, start: line.start + offset }));+ };+ await readRuns(engine, scope, wanted, async (run, block) => {+ const at = position(run);+ if (at !== last && at !== last + 1) {+ for (const w of cutter.flush()) await onWindow(w);+ const next = run ?? scope.runs[lastTruth + 1];+ cutter = new WindowCutter([...(next ? info.get(next.index)!.headsIn : open)] as string[]);+ }+ last = at;+ if (run) {+ local.set(block, { run, at: used.get(run.index) ?? 0 });+ used.set(run.index, (used.get(run.index) ?? 0) + block.text.length);+ }+ for (const w of cutter.push(block)) await onWindow(w);+ });+ for (const w of cutter.flush()) await onWindow(w);+ for (const [index, record] of records) {+ const output = outputs.get(index)!;+ output.basenames = [...record.basenames];+ output.types = [...record.types.values()];+ }+ return outputs;+ };++ /** The page's body candidates merged from every run, as the full pass merges its windows. */+ const merge = (outputs: ReadonlyMap<number, LinkRunOutput>) => {+ const kept = new Map<string, BodyLinkCandidate & { seq: number }>();+ const temporalBody: TemporalBody = { lines: [], narrative: [], ranged: [] };+ let seq = 0, at = 0, attendance = true;+ for (const run of scope.runs) {+ if (run.index === lastTruth + 1) at += separator.length;+ const output = outputs.get(run.index) ?? plan.current.get(run.index)!;+ attendance &&= output.attendance;+ for (const raw of output.links) {+ const link = shifted(raw, at);+ const key = candidateKey(link.candidate);+ const prior = kept.get(key);+ if (!prior || link.pass < prior.pass || (link.pass === prior.pass && link.index < prior.index)) kept.set(key, { ...link, seq: seq++ });+ }+ temporalBody.lines.push(...output.temporal.lines);+ temporalBody.narrative.push(...output.temporal.narrative);+ temporalBody.ranged.push(...output.temporal.ranged.map(line => ({ ...line, start: line.start + at })));+ at += output.chars;+ }+ const body = [...kept.values()].sort((a, b) => a.pass - b.pass || a.index - b.index || a.seq - b.seq).map(link => link.candidate);+ return { body, attendance, temporalBody };+ };++ return {+ async targets(opts) {+ const fresh = await derive(plan.todo, { ...base, ...opts });+ const { body, attendance } = merge(fresh);+ const fm = await frontmatterLinks(page.slug, page.frontmatter, page.type, resolver, { ...base, ...opts });+ return { candidates: dedupeCandidates([...body, ...fm.candidates]), unresolved: fm.unresolved, attendanceComplete: attendance && fm.attendanceComplete };+ },+ async finish(opts) {+ const todo = [...plan.todo];+ for (const [index, output] of [...plan.current]) {+ if (output.types.every(([slug, sourceId, type]) => (opts.targetType(slug, sourceId ?? undefined) ?? null) === type)) continue;+ plan.current.delete(index);+ todo.push(scope.runs[index]!);+ }+ todo.sort((a, b) => a.index - b.index);+ const fresh = await derive(todo, { ...base, ...opts });+ await commitRuns(engine, 'links', scope, fresh, inputsOf);+ const { body, attendance, temporalBody } = merge(fresh);+ const fm = await frontmatterLinks(page.slug, page.frontmatter, page.type, resolver, { ...base, ...opts });+ return { candidates: dedupeCandidates([...body, ...fm.candidates]), unresolved: fm.unresolved, attendanceComplete: attendance && fm.attendanceComplete, temporalBody };+ },+ };+}diff --git a/src/core/page-body/segment-rewrite.ts b/src/core/page-body/segment-rewrite.tsindex d45783bdab..e0f3ee04ab 100644--- a/src/core/page-body/segment-rewrite.ts+++ b/src/core/page-body/segment-rewrite.ts@@ -26,6 +26,7 @@ import { ContentHashStream } from './content-hash-stream.ts';import type { StoredRegion } from './segmenter.ts';import type { BodyRegion, JsonObject, ManifestRow } from './types.ts';import { assertGenerationTiles } from './body-tiling.ts';+import { deleteRewrittenDerivations } from './segment-derive.ts';/** Rewrites one fence (the text of a stored facts or takes region, markers included), given the body region holding it; called in body order. */export type FenceTransform = (fence: string, at: { region: BodyRegion }) => Promise<string>;@@ -154,6 +155,8 @@ const rewriteTier = (page: { contextual_retrieval_mode: string | null; corpus_geexport interface LiveFenceRewrite {/** Segment shas the old generation referenced in place of the rewritten units. */replaced: Uint8Array[];+ /** page_segment_derivations rows deleted because they may hold the replaced text (deleteRewrittenDerivations). */+ derivations: number;/** False when the page was left unsealed (its projection runs after commit: `buildSegmentedProjection`). */sealed: boolean;}@@ -162,7 +165,8 @@ export interface LiveFenceRewrite {* Rewrite the fences of a segmented page's live body through `transform`, in* the caller's transaction: a new generation whose unchanged segments keep* their rows and chunks, and whose rewritten segments get new occurrences- * (their chunks staged here, the old ones retired by the flip). A fence edit+ * (their chunks staged here, the old ones retired by the flip), and the+ * derivation rows that may hold the replaced text are deleted. A fence edit* is not authorship, so the page keeps its trust tier; a soft-deleted page* stays deleted. Null when no fence changed (nothing is written).*/@@ -189,7 +193,8 @@ export async function rewriteLiveSegmentedFences(tx: BrainEngine, pageId: numberretireMaxRows: flipRetireMaxRows, meta: { title: page.title, type: page.type as never, frontmatter, page_kind: page.page_kind as never } }));if (page.deleted_at) await tx.executeRaw('UPDATE pages SET deleted_at=$2 WHERE id=$1', [pageId, page.deleted_at]);if (applied.complete) await sealSegmentedPage(tx, pageId);- return { replaced: replacedShas(rows, units), sealed: applied.complete };+ const derivations = await deleteRewrittenDerivations(tx, pageId, rows, units);+ return { replaced: replacedShas(rows, units), sealed: applied.complete, derivations };}const MANIFEST_COLUMNS = `page_id,occurrence_id,seq,region,source_id,sha256,byte_start,byte_len,line_start,line_count,cut_kind,entry_state,diff --git a/src/core/page-body/segment-takes.ts b/src/core/page-body/segment-takes.tsindex 5cc248dd99..2bc750a711 100644--- a/src/core/page-body/segment-takes.ts+++ b/src/core/page-body/segment-takes.ts@@ -68,9 +68,41 @@ export class TakesFenceScan {result(): StreamedTakes {if (this.done) return this.done;- const reduced = this.fence ? TAKES_FENCE_BEGIN : this.endOnly ? `${'\n'.repeat(TAKES_FENCE_BEGIN.length)}${TAKES_FENCE_END}` : this.nearMiss ? 'gbrain:takes:begin' : '';- return { parsed: parseTakesFence(reduced), hasBegin: this.hasBegin, hasMarker: this.hasMarker };+ return { parsed: parseTakesFence(reducedTakes(this.fence !== null, this.endOnly, this.nearMiss)), hasBegin: this.hasBegin, hasMarker: this.hasMarker };}++ /** What the blocks pushed so far hold, for a run's fences row (segment-facts.ts segmentedFenceRuns). */+ summary(): TakesRunSummary {+ return { hasBegin: this.hasBegin, hasMarker: this.hasMarker, endOnly: this.endOnly, nearMiss: this.nearMiss,+ fence: this.fence ? { text: this.fence.join(''), closed: this.done !== null } : null };+ }+}++/** The text parseTakesFence reduces an unfinished scan to: a lone begin, an end only, a near-miss marker, or nothing. */+function reducedTakes(begun: boolean, endOnly: boolean, nearMiss: boolean): string {+ return begun ? TAKES_FENCE_BEGIN : endOnly ? `${'\n'.repeat(TAKES_FENCE_BEGIN.length)}${TAKES_FENCE_END}` : nearMiss ? 'gbrain:takes:begin' : '';+}++/**+ * One run's TakesFenceScan state (a scan started fresh at the run, its blocks pushed with region offsets): the raw marker+ * flags up to the block that closed its first fence, the end-only and near-miss scans before any begin, and that fence.+ */+export interface TakesRunSummary { hasBegin: boolean; hasMarker: boolean; endOnly: boolean; nearMiss: boolean; fence: { text: string; closed: boolean } | null }++/**+ * parseTakesFenceBlocks of a region from its runs' summaries, in order; null when a fence a run begins does not close+ * in that run (the caller reads the region whole).+ */+export function takesFromRuns(summaries: readonly TakesRunSummary[]): StreamedTakes | null {+ let hasBegin = false, hasMarker = false, endOnly = false, nearMiss = false;+ for (const summary of summaries) {+ hasBegin ||= summary.hasBegin;+ hasMarker ||= summary.hasMarker;+ if (summary.fence) return summary.fence.closed ? { parsed: parseTakesFence(summary.fence.text), hasBegin, hasMarker } : null;+ endOnly ||= summary.endOnly;+ nearMiss ||= summary.nearMiss;+ }+ return { parsed: parseTakesFence(reducedTakes(false, endOnly, nearMiss)), hasBegin, hasMarker };}export async function parseTakesFenceBlocks(blocks: AsyncIterable<BodyBlock>, page: { slug: string; source_id: string }): Promise<StreamedTakes> {diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 214ed6d27b..f08df03fc4 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -7,14 +7,16 @@ import { FACTS_FENCE_BEGIN, FACTS_FENCE_END, parseFactsFence } from '../facts-feimport { TAKES_FENCE_BEGIN, TAKES_FENCE_END, parseTakesFence } from '../takes-fence.ts';import { extractFactsFromFenceText } from '../facts/extract-from-fence.ts';import { takesPreparation } from '../takes-write.ts';-import { parseTimelineEntries } from '../link-extraction.ts';+import { LINK_EXTRACTOR_VERSION_TS, parseTimelineEntries } from '../link-extraction.ts';import { eachStoredTimelineRow, extractTimelineFromContent, hasExtractorDetail, supersededCitationTimeline, TimelineKeySet,type ExtractedTimelineEntry } from '../timeline-extract.ts';import { sanitizeRemoteBody } from '../remote-body.ts';import { sanitizeForJsonb } from '../batch-rows.ts';import { bodyUnread } from '../page-body/page-shape.ts';-import { bodyBlocks, detachedValue } from '../page-body/segment-blocks.ts';-import { TakesFenceScan } from '../page-body/segment-takes.ts';+import { bodyBlocks, detachedValue, type BodyBlock } from '../page-body/segment-blocks.ts';+import { TakesFenceScan, takesFromRuns } from '../page-body/segment-takes.ts';+import { openFenceRuns } from '../page-body/segment-facts.ts';+import { derivationScope, readRuns, SegmentDerivationRaced, streamRuns, type DerivationScope, type DeriveRun } from '../page-body/segment-derive.ts';import type { BodyRegion } from '../page-body/types.ts';import { createHash } from 'node:crypto';import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';@@ -158,10 +160,10 @@ function timelineView(body: CanonicalBody, slug: string): TimelineView {* What a prior body says about the stored rows a write classifies, by the row's index in the rows read and its key:* a bullet (`entry`), a bullet a marker still matches (`marked`), a superseded citation reading (`superseded`).*/-interface PriorRows { entry(i: number, key: string): boolean; marked(i: number, key: string): boolean; superseded(i: number, key: string): boolean }+export interface PriorRows { entry(i: number, key: string): boolean; marked(i: number, key: string): boolean; superseded(i: number, key: string): boolean }/** The views a prior snapshot contributes, plus its takes rows per field and whether either field's takes fence warns. */-interface PriorView { rows: PriorRows; takeRows: Set<number>; takesWarn: boolean }+export interface PriorView { rows: PriorRows; takeRows: Set<number>; takesWarn: boolean }function viewRows(view: TimelineView): PriorRows {return { entry: (_, key) => view.entries.has(key), marked: (_, key) => view.marked.has(key), superseded: (_, key) => view.superseded.has(key) };@@ -182,7 +184,7 @@ const segmentedPriors = new WeakMap<object, { digest: string; view: PriorView }>* about are kept, one flag byte each, never the body's entries. A `###` dated entry's detail ends at its block. The* takes rows are parsed per field, as canonicalTakeRows does (page-body/segment-takes.ts), in the same pass.*/-async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string, keys: readonly string[]): Promise<PriorView> {+export async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string, keys: readonly string[]): Promise<PriorView> {const digest = createHash('sha256').update(keys.join('\0')).digest('hex');const cached = segmentedPriors.get(page);if (cached?.digest === digest) return cached.view;@@ -211,9 +213,129 @@ async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug:return view;}+/** The timeline keys one block of a segmented body yields, as segmentedPriorView and segmentedCanonicalCollector read them. */+function blockTimeline(text: string, slug: string) {+ const safe = sanitizeRemoteBody(text, { keepMaterializedMarkers: true });+ return {+ extracted: extractTimelineFromContent(safe, slug).map(t => [timelineKey(t), t] as const),+ parsed: parseTimelineEntries(safe).map(t => [timelineKey({ ...t, source: t.source ?? 'markdown' }), { ...t, source: t.source ?? 'markdown', slug }] as const),+ marked: markedTimeline(safe, slug),+ superseded: supersededCitationTimeline(safe).map(t => timelineKey(t)),+ };+}++/**+ * What one run of a segmented body holds for the timeline (spec 8.2): the timelineDigest of the timelineKey of each+ * entry its blocks yield (extracted, parsed; each in block order, repeats kept), of each materialized marker and of each+ * superseded citation. Numbers, not entries, so a row and the read that builds it stay a small fraction of the run's+ * text even when forced cuts join a whole timeline into one run.+ */+interface TimelineRunOutput { x: number[]; p: number[]; m: number[]; s: number[] }++/** The first 52 bits of a timeline key's SHA-256, as an exact JS number. */+const timelineDigest = (key: string) => Number.parseInt(createHash('sha256').update(key).digest('hex').slice(0, 13), 16);++/**+ * Each run's timeline row output, in page order, handed to `visit` (page-body/segment-derive.ts streamRuns); every block+ * a due run is read for also goes to `onBlock`. Returns the scope, or null when the page is not segmented.+ */+async function eachTimelineRun(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string,+ visit: (run: DeriveRun, output: TimelineRunOutput) => void,+ opts: { scope?: DerivationScope; onBlock?: (run: DeriveRun | null, block: BodyBlock) => void } = {}): Promise<DerivationScope | null> {+ const scope = opts.scope ?? await derivationScope(engine, { id: Number(page.id), slug: page.slug, source_id: page.source_id });+ if (!scope) return null;+ const inputs = () => ({ slug, extractor: LINK_EXTRACTOR_VERSION_TS });+ await streamRuns<TimelineRunOutput>(engine, 'timeline', scope, inputs, {+ start: () => ({ x: [], p: [], m: [], s: [] }),+ block: (out, block) => {+ const safe = sanitizeRemoteBody(block.text, { keepMaterializedMarkers: true });+ for (const t of extractTimelineFromContent(safe, slug)) out.x.push(timelineDigest(timelineKey(t)));+ for (const t of parseTimelineEntries(safe)) out.p.push(timelineDigest(timelineKey({ ...t, source: t.source ?? 'markdown' })));+ for (const key of markedTimeline(safe, slug)) out.m.push(timelineDigest(key));+ for (const t of supersededCitationTimeline(safe)) out.s.push(timelineDigest(timelineKey(t)));+ },+ }, visit, opts.onBlock);+ return scope;+}++const raced = (error: unknown): null => {+ if (error instanceof SegmentDerivationRaced) return null;+ throw error;+};++/**+ * segmentedPriorView from the page's timeline and fences rows: only runs changed since their rows were written are read.+ * Null (the caller takes the full pass) when the page is not segmented, a takes fence runs past the run it begins in,+ * or the body moves during the read.+ */+export async function incrementalPriorView(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string, keys: readonly string[]): Promise<PriorView | null> {+ const index = new Map<number, number[]>();+ keys.forEach((key, i) => { const digest = timelineDigest(key); const at = index.get(digest); if (at) at.push(i); else index.set(digest, [i]); });+ const flags = new Uint8Array(keys.length);+ const mark = (digest: number, bit: number) => { for (const i of index.get(digest) ?? []) flags[i]! |= bit; };+ // One read serves both kinds: a run due for its fences row is scanned while the timeline reads it.+ const fences = async () => {+ const scope = await derivationScope(engine, { id: Number(page.id), slug: page.slug, source_id: page.source_id });+ if (!scope) return null;+ const runs = await openFenceRuns(engine, page, scope);+ await eachTimelineRun(engine, page, slug, (_, out) => {+ for (const digest of out.x) mark(digest, PRIOR_ENTRY);+ for (const digest of out.p) mark(digest, PRIOR_ENTRY);+ for (const digest of out.m) mark(digest, PRIOR_MARKED);+ for (const digest of out.s) mark(digest, PRIOR_SUPERSEDED);+ }, { scope, onBlock: runs.push });+ return runs.finish();+ };+ const runs = await fences().catch(raced);+ if (!runs) return null;+ const fields = (['truth', 'timeline'] as const).map(region => takesFromRuns(runs.filter(({ run }) => run.region === region).map(({ output }) => output.takes)));+ if (fields.some(field => field === null)) return null;+ return {+ rows: { entry: i => (flags[i]! & PRIOR_ENTRY) !== 0, marked: i => (flags[i]! & PRIOR_MARKED) !== 0, superseded: i => (flags[i]! & PRIOR_SUPERSEDED) !== 0 },+ takeRows: new Set(fields.flatMap(field => field!.parsed.takes.map(t => t.rowNum))), takesWarn: fields.some(field => field!.parsed.warnings.length > 0),+ };+}++/**+ * segmentedCanonicalTimeline from the page's timeline rows: the entries no stored row records are found from the+ * digests, and only the runs that last yield one of them are read for its entry (plus runs changed since their row was+ * written). Null (the caller takes the full pass) when the page is not segmented or its body moves during the read.+ */+async function incrementalCanonicalTimeline(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<Map<string, ExtractedTimelineEntry> | null> {+ const recorded = new TimelineKeySet();+ await eachStoredTimelineRow(engine, Number(page.id), row => {+ canonicalTimelineWork.storedRows++;+ recorded.add(String(timelineDigest(timelineKey({ date: row.date_text, source: row.source, summary: row.summary }))));+ });+ // Each unrecorded digest's run of last occurrence, in first-occurrence order (the full pass's Map semantics).+ const extracted = new Map<number, number>(), parsed = new Map<number, number>();+ const scope = await eachTimelineRun(engine, page, slug, (run, out) => {+ for (const digest of out.x) if (!recorded.has(String(digest))) extracted.set(digest, run.index);+ for (const digest of out.p) if (!recorded.has(String(digest))) parsed.set(digest, run.index);+ });+ if (!scope) return null;+ const entries = new Map<number, { x: Map<number, readonly [string, ExtractedTimelineEntry]>; p: Map<number, readonly [string, ExtractedTimelineEntry]> }>();+ const wanted = new Set([...extracted.values(), ...parsed.values()]);+ await readRuns(engine, scope, wanted, (run, block) => {+ if (!run) return;+ const into = entries.get(run.index) ?? { x: new Map(), p: new Map() };+ entries.set(run.index, into);+ const found = blockTimeline(block.text, slug);+ for (const [key, entry] of found.extracted) if (extracted.get(timelineDigest(key)) === run.index) into.x.set(timelineDigest(key), [key, detachedValue(entry)]);+ for (const [key, entry] of found.parsed) if (parsed.get(timelineDigest(key)) === run.index) into.p.set(timelineDigest(key), [key, detachedValue(entry)]);+ });+ const kept = new Map<string, ExtractedTimelineEntry>();+ for (const [digest, at] of extracted) { const [key, entry] = entries.get(at)!.x.get(digest)!; kept.set(key, entry); }+ for (const [digest, at] of parsed) { const [key, entry] = entries.get(at)!.p.get(digest)!; kept.set(key, entry); }+ return kept;+}+/** The prior snapshot's view of `rows` (its stored timeline rows): from its strings, or streamed when its segmented body is unread. */async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug: string, rows: readonly StoredTimelineRow[]): Promise<PriorView> {- if (bodyUnread(page)) return segmentedPriorView(engine, page, slug, rows.map(row => timelineKey(row)));+ if (bodyUnread(page)) {+ const keys = rows.map(row => timelineKey(row));+ return await incrementalPriorView(engine, page, slug, keys) ?? segmentedPriorView(engine, page, slug, keys);+ }const fields = [page.compiled_truth, page.timeline ?? ''].map(field => parseTakesFence(field));return { rows: viewRows(timelineView(page, slug)),takeRows: new Set(fields.flatMap(field => field.takes.map(t => t.rowNum))), takesWarn: fields.some(field => field.warnings.length > 0) };@@ -260,6 +382,11 @@ export const canonicalTimelineWork = { storedRows: 0, kept: 0 };* (TimelineKeySet), so the read keeps what an insert-only caller may add, never every entry the body yields.*/async function segmentedCanonicalTimeline(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<Map<string, ExtractedTimelineEntry>> {+ const incremental = await incrementalCanonicalTimeline(engine, page, slug).catch(raced);+ if (incremental) {+ canonicalTimelineWork.kept += incremental.size;+ return incremental;+ }const recorded = new TimelineKeySet();await eachStoredTimelineRow(engine, Number(page.id), row => {canonicalTimelineWork.storedRows++;diff --git a/src/core/persistence/effect-journal.ts b/src/core/persistence/effect-journal.tsindex f52b7576be..368785969a 100644--- a/src/core/persistence/effect-journal.ts+++ b/src/core/persistence/effect-journal.ts@@ -54,7 +54,13 @@ export async function queuePublicationEffects(tx: BrainEngine, row: EffectRequeselse queue('facts-backstop', { visibility: await resolveDefaultVisibility(tx) });}// The links effect is inserted with the others, gated in SQL on auto_link and mcp.remote_auto_links.- if (queuesMentionLinks(row)) queued.push({ kind: 'links', data: { ...data }, gated: true });+ // Wave B (spec 8.5): on a segmented page it carries the occurrences this write added (live rows with no older row).+ if (queuesMentionLinks(row)) {+ const added = await tx.executeRaw<{ id: string }>(`SELECT m.occurrence_id::text AS id FROM page_body_manifest m JOIN pages p ON p.id=m.page_id+ WHERE m.page_id=$1 AND p.body_storage='segmented' AND m.gen_from=p.body_generation AND m.gen_to IS NULL AND m.staging_id IS NULL+ AND NOT EXISTS (SELECT 1 FROM page_body_manifest o WHERE o.page_id=m.page_id AND o.occurrence_id=m.occurrence_id AND o.gen_from<m.gen_from) ORDER BY m.seq`, [snapshot.page.id]);+ queued.push({ kind: 'links', data: { ...data, ...(added.length ? { occurrence_ids: added.map(r => Number(r.id)) } : {}) }, gated: true });+ }// #5876: the Life Chronicle decision is a ledger row, not an effect; the `chronicle` cycle phase executes it.await recordChronicleDecision(tx, row, snapshot, outcome);}diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex 83e7cbeaef..66d901007e 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -11,9 +11,16 @@ import { readFix } from '../ops/op-fix.ts';import { readLineGrammarSettings, type LineGrammarSettings } from '../line-grammar.ts';import { primeRelationSemantics } from '../link-semantics-pack.ts';import { bodyUnread, isSegmentedPage } from '../page-body/page-shape.ts';-import { extractSegmentedPageLinks, segmentedRoleText } from '../page-body/segment-links.ts';+import { extractSegmentedPageLinks, openSegmentedLinkSession, segmentedRoleText } from '../page-body/segment-links.ts';+import { SegmentDerivationRaced } from '../page-body/segment-derive.ts';import { temporalBodyOf, type TemporalBody } from '../link-temporal-apply.ts';+/** A body that moved under an incremental read: null, so the caller takes the full pass. */+const raced = (error: unknown): null => {+ if (error instanceof SegmentDerivationRaced) return null;+ throw error;+};+async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {if (!targets.length) return new Map();try {@@ -80,8 +87,9 @@ export const LINK_ENDPOINTS_SQL = `WITH own AS (/*** `primeSemantics`: install the pack relation semantics now, during preparation, so apply's* replacement does not read them again inside the publication transaction.- * A stored segmented page (its body unread) is extracted block by block (page-body/segment-links.ts),- * and its temporal inputs are collected here; publication never reads a segmented body.+ * A stored segmented page (its body unread) is extracted block by block (page-body/segment-links.ts), incrementally:+ * only the runs whose inputs changed are read, the rest come from their page_segment_derivations rows; a body that moves+ * during the read falls back to the full pass. Its temporal inputs are collected here; publication never reads a segmented body.*/export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'> & { id?: number }, sourceId: string, primeSemantics = false) {@@ -96,10 +104,17 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,if (!opts.pack || !settings) return { pageKeys: [{ sourceId, slug }], attendanceComplete: true, settings,apply: async () => ({ created: 0, removed: 0, errors: 1, unresolved_count: 1 }) };const segmented = bodyUnread(page) ? { id: Number(page.id), slug, source_id: sourceId, type: page.type, frontmatter: page.frontmatter } : null;- const roleText = segmented ? await segmentedRoleText(engine, segmented) : undefined;- const extract = (o: ExtractPageLinksOptions & { temporal?: boolean }): Promise<PageLinksResult & { temporalBody?: TemporalBody }> => segmented- ? extractSegmentedPageLinks(engine, segmented, resolver, { ...o, roleText })- : extractPageLinks(slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter, page.type, resolver, o);+ let session = segmented ? await openSegmentedLinkSession(engine, segmented, resolver, opts).catch(raced) : null;+ let roleText: string | undefined;+ const extract = async (o: ExtractPageLinksOptions & { temporal?: boolean }): Promise<PageLinksResult & { temporalBody?: TemporalBody }> => {+ if (!segmented) return extractPageLinks(slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter, page.type, resolver, o);+ const targetType = o.targetType;+ const incremental = session && await (targetType ? session.finish({ ...o, targetType }) : session.targets(o)).catch(raced);+ if (incremental) return incremental;+ session = null;+ roleText ??= await segmentedRoleText(engine, segmented);+ return extractSegmentedPageLinks(engine, segmented, resolver, { ...o, roleText });+ };const referenced = new Set([slug]);const initial = await extract({ ...opts, onResolvedFrontmatterTarget: target => referenced.add(target) });// A link written against a renamed page's old slug follows its slug alias, like get_page does.diff --git a/test/e2e/derivation-equivalence-postgres.test.ts b/test/e2e/derivation-equivalence-postgres.test.tsnew file mode 100644index 0000000000..95e7f3d5de--- /dev/null+++ b/test/e2e/derivation-equivalence-postgres.test.ts@@ -0,0 +1,12 @@+/**+ * Wave B PR 4 lane 4a (spec 8.1, 8.2), Postgres arm: the incremental links, mentions, timeline and fence derivations of+ * a segmented page equal a full recompute after every step of a seeded sequence of appends and edits, and a forget+ * deletes only the derivation rows that may hold the text it rewrote. Cases in test/helpers/derivation-equivalence-cases.ts;+ * PGLite arm: test/large-pages/derivation-equivalence.test.ts.+ */+import { describe, test } from 'bun:test';+import { registerDerivationEquivalenceCases } from '../helpers/derivation-equivalence-cases.ts';+import { hasDatabase } from './helpers.ts';++if (hasDatabase()) registerDerivationEquivalenceCases('postgres');+else describe.skip('incremental derivations equal a full recompute (postgres)', () => { test('needs DATABASE_URL', () => {}); });diff --git a/test/helpers/derivation-equivalence-cases.ts b/test/helpers/derivation-equivalence-cases.tsnew file mode 100644index 0000000000..ed8f73a564--- /dev/null+++ b/test/helpers/derivation-equivalence-cases.ts@@ -0,0 +1,361 @@+/**+ * Shared cases for the incremental-derivation equivalence tests (Wave B PR 4 lane 4a, spec 8.1/8.2): a segmented page+ * goes through a seeded sequence of appends, mid-page edits, a title change, a gazetteer change and fence row edits,+ * and after every step each incremental pipeline (links, mentions, timeline, fences) must give what its full pass gives+ * over the same generation, with page_segment_derivations rows for exactly the live occurrences and an append deriving+ * only the runs it changed (plus, for links, the run whose window reaches into them).+ *+ * test/large-pages/derivation-equivalence.test.ts runs them on PGLite; test/e2e/derivation-equivalence-postgres.test.ts+ * on PostgreSQL.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { makeResolver, type ExtractPageLinksOptions } from '../../src/core/link-extraction.ts';+import { loadActivePackForLocalEngine } from '../../src/core/schema-pack/best-effort.ts';+import { extractSegmentedPageLinks, openSegmentedLinkSession, segmentedRoleText } from '../../src/core/page-body/segment-links.ts';+import { segmentDeriveWork, SEGMENT_PIPELINE_VERSIONS, type UnpaidDerivationKind } from '../../src/core/page-body/segment-derive.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { maintenanceTransaction } from '../../src/core/persistence/attribution.ts';+import { rewriteLiveSegmentedFences } from '../../src/core/page-body/segment-rewrite.ts';+import { pageMentions } from '../../src/core/mentions/pass.ts';+import { readMentionPolicy } from '../../src/core/mentions/policy.ts';+import { buildGazetteer, findMentionedEntities, type Mention } from '../../src/core/by-mention.ts';+import { bodyBlocks } from '../../src/core/page-body/segment-blocks.ts';+import { incrementalFactsFenceView, segmentedFactsFenceView } from '../../src/core/page-body/segment-facts.ts';+import { incrementalPriorView, segmentedCanonicalCollector, segmentedPriorView, storedCanonicalTimeline, type PriorView } from '../../src/core/persistence/canonical-projections.ts';+import { eachStoredTimelineRow, TimelineKeySet } from '../../src/core/timeline-extract.ts';+import { timelineKey } from '../../src/core/timeline-marker.ts';+import { runExtractFacts } from '../../src/core/cycle/extract-facts.ts';+import { forgetFactInFence } from '../../src/core/facts/forget.ts';+import { conversationBody } from './conversation-page.ts';+import { openAppendBrain, type AppendBrain } from './append-brain.ts';++export const EQUIVALENCE_SLUG = 'notes/derivation-equivalence';+const SOURCE = 'default';++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;+ };+}++/** Prose without day headings, so a section opened above it stays open across segments. */+const prose = (bytes: number, seed: number) => conversationBody(bytes, { seed }).replace(/^## Day \d+$/gm, 'Next day.');++const FACTS = '<!--- gbrain:facts:begin -->\n'+ + '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'+ + '|---|---|---|---|---|---|---|---|---|---|\n'+ + '| 1 | ships quarterly | fact | 0.9 | world | low | 2026-01-01 | | user | |\n'+ + '| 2 | prefers email | preference | 0.8 | world | low | 2026-02-01 | | user | |\n'+ + '<!--- gbrain:facts:end -->\n';++const TAKES = `${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n`+ + `| 1 | Acme ships quarterly | fact | world | 1.0 | 2026-01 | notes |\n| 2 | Pricing will hold | bet | brain | 0.6 | 2026-02 | notes |\n${TAKES_FENCE_END}\n`;++/**+ * About 2.6 MB: an intro link, a ## Related section longer than a segment (its machine-section heading suppresses the+ * role prior segments later), sections with links, bare slug paths, entity names and unique edit markers, the facts and+ * takes fences, a page-role phrase near the end, then a timeline of dated bullets.+ */+export function equivalencePage(): string {+ const parts = ['---\ntype: person\ntitle: Equivalence Example\n---\n\nIntro: met [[companies/c1-example]] early.\n\n## Related\n\n', prose(600_000, 11),+ '\n\n- [[companies/c2-example]]\n\n'];+ for (let i = 0; i < 6; i++) {+ parts.push(`## Section ${i}\n\n${prose(240_000, 20 + i)}\n\n`);+ parts.push(`Marker ${i}: met [[people/alice-example]] and [[people/p${i}-example]] about launch ${i}; see people/bob-example for notes. `+ + `Alice Example reviewed it with Bob Example.\n\n`);+ if (i === 2) parts.push(`## Facts\n\n${FACTS}\n`);+ if (i === 4) parts.push(`${TAKES}\n`);+ }+ parts.push('Equivalence Example is a senior advisor to founders.\n\n<!-- timeline -->\n\n');+ parts.push(Array.from({ length: 30 }, (_, i) => `- **2026-0${1 + (i % 9)}-${String(10 + (i % 18)).padStart(2, '0')}** | Met [[people/alice-example]] about item ${i}\n`+ + (i % 5 === 0 ? ` detail line for item ${i}\n` : '')).join(''));+ parts.push(`\n${prose(200_000, 9)}\n`);+ return parts.join('');+}++export interface EquivalencePage { id: number; slug: string; source_id: string; type: 'person'; frontmatter: Record<string, unknown>; title: string }++export async function storedPage(engine: BrainEngine, slug = EQUIVALENCE_SLUG): Promise<EquivalencePage> {+ const [row] = await engine.executeRaw<{ id: number; type: string; title: string; frontmatter: Record<string, unknown> | string; body_storage: string }>(+ 'SELECT id, type, title, frontmatter, body_storage FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, slug]);+ expect(row!.body_storage).toBe('segmented');+ const frontmatter = typeof row!.frontmatter === 'string' ? JSON.parse(row!.frontmatter) : row!.frontmatter;+ return { id: Number(row!.id), slug, source_id: SOURCE, type: row!.type as 'person', frontmatter, title: row!.title };+}++/** The write path's link options (prepareAutomaticLinks) and a target typer from the source's page types. */+async function linkOptions(engine: BrainEngine) {+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: SOURCE }))?.manifest ?? null;+ const types = new Map((await engine.executeRaw<{ slug: string; type: string }>('SELECT slug, type FROM pages WHERE source_id=$1 AND deleted_at IS NULL', [SOURCE]))+ .map(row => [row.slug, row.type]));+ const opts: ExtractPageLinksOptions = { pack, globalBasename: false, lineGrammar: { enabled: true, allowUndeclaredTypes: false } };+ return { opts, targetType: (slug: string) => types.get(slug) };+}++export async function incrementalLinks(engine: BrainEngine, page: EquivalencePage) {+ const resolver = makeResolver(engine, { mode: 'live', sourceId: SOURCE });+ const { opts, targetType } = await linkOptions(engine);+ const session = await openSegmentedLinkSession(engine, page, resolver, opts);+ expect(session).not.toBeNull();+ await session!.targets(opts);+ return session!.finish({ ...opts, temporal: true, targetType } as never);+}++export async function fullLinks(engine: BrainEngine, page: EquivalencePage) {+ const resolver = makeResolver(engine, { mode: 'live', sourceId: SOURCE });+ const { opts, targetType } = await linkOptions(engine);+ return extractSegmentedPageLinks(engine, page, resolver, { ...opts, temporal: true, targetType, roleText: await segmentedRoleText(engine, page) });+}++const MENTION_KINDS = { fromSlug: EQUIVALENCE_SLUG, fromSourceId: SOURCE, allowCrossSource: false };++async function gazetteerOf(engine: BrainEngine) {+ return buildGazetteer(engine, { policy: await readMentionPolicy(engine), strict: true });+}++export async function incrementalMentions(engine: BrainEngine, page: EquivalencePage): Promise<Mention[]> {+ return pageMentions(engine, { id: page.id, slug: page.slug, source_id: SOURCE, title: page.title, body_storage: 'segmented' }, await gazetteerOf(engine), MENTION_KINDS);+}++/** The PR 2 full pass of pageMentions: the title, then every block with the '\n\n' separator. */+export async function fullMentions(engine: BrainEngine, page: EquivalencePage): Promise<Mention[]> {+ const gazetteer = await gazetteerOf(engine);+ const found = new Map<string, Mention>();+ const add = (mentions: Mention[], at: number) => {+ for (const m of mentions) if (!found.has(`${m.source_id}\0${m.slug}`)) found.set(`${m.source_id}\0${m.slug}`, { ...m, offset: m.offset + at });+ };+ add(findMentionedEntities(page.title, gazetteer, MENTION_KINDS), 0);+ for await (const block of bodyBlocks(engine, page, { separator: '\n\n' })) add(findMentionedEntities(block.text, gazetteer, MENTION_KINDS), page.title.length + 2 + block.at);+ return [...found.values()];+}++export async function incrementalTimeline(engine: BrainEngine, page: EquivalencePage) {+ const snapshot = (await engine.readPageSnapshot(page.slug, { sourceId: SOURCE }))!;+ return [...(await storedCanonicalTimeline(engine, snapshot.page, page.slug))];+}++/** The PR 2 full pass of the canonical timeline: every block through segmentedCanonicalCollector, less the stored rows. */+export async function fullTimeline(engine: BrainEngine, page: EquivalencePage) {+ const recorded = new TimelineKeySet();+ await eachStoredTimelineRow(engine, page.id, row => recorded.add(timelineKey({ date: row.date_text, source: row.source, summary: row.summary })));+ const collector = segmentedCanonicalCollector(page.slug, recorded);+ for await (const block of bodyBlocks(engine, page)) collector.add(block.text);+ return [...collector.result()];+}++/** The keys a prior view is asked about: the page's stored timeline rows, two entries an append writes and one no page holds. */+async function priorKeys(engine: BrainEngine, page: EquivalencePage): Promise<string[]> {+ const keys: string[] = [];+ await eachStoredTimelineRow(engine, page.id, row => { keys.push(timelineKey({ date: row.date_text, source: row.source, summary: row.summary })); });+ return [...keys, timelineKey({ date: '2026-10-01', source: 'markdown', summary: 'appended event 0' }),+ timelineKey({ date: '2026-10-03', source: 'markdown', summary: 'appended event 2' }), timelineKey({ date: '2030-01-01', source: 'markdown', summary: 'nowhere' })];+}++const viewShape = (view: PriorView, keys: readonly string[]) => ({+ rows: keys.map((key, i) => [view.rows.entry(i, key), view.rows.marked(i, key), view.rows.superseded(i, key)]),+ takeRows: [...view.takeRows].sort((a, b) => a - b), takesWarn: view.takesWarn });++export async function priorViews(engine: BrainEngine, page: EquivalencePage) {+ const keys = await priorKeys(engine, page);+ const incremental = await incrementalPriorView(engine, page, page.slug, keys);+ expect(incremental).not.toBeNull();+ return { incremental: viewShape(incremental!, keys), full: viewShape(await segmentedPriorView(engine, page, page.slug, keys), keys) };+}++/** Every incremental pipeline once (each stores its rows). */+export async function deriveAll(engine: BrainEngine, page: EquivalencePage): Promise<void> {+ await incrementalLinks(engine, page);+ await incrementalMentions(engine, page);+ await incrementalTimeline(engine, page);+ await priorViews(engine, page);+ await incrementalFactsFenceView(engine, page);+}++export const KINDS: readonly UnpaidDerivationKind[] = ['links', 'mentions', 'timeline', 'fences'];++/** The live occurrences of the page, and its derivation rows per kind. */+export async function derivationRowsMatch(engine: BrainEngine, page: EquivalencePage, kinds: readonly UnpaidDerivationKind[]): Promise<void> {+ const live = (await engine.executeRaw<{ occurrence_id: string }>(+ 'SELECT occurrence_id::text AS occurrence_id FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL ORDER BY occurrence_id', [page.id]))+ .map(row => Number(row.occurrence_id)).sort((a, b) => a - b);+ for (const kind of kinds) {+ const rows = await engine.readSegmentDerivations(page.id, { kind });+ expect({ kind, occurrences: rows.map(row => row.occurrenceId).sort((a, b) => a - b) }).toEqual({ kind, occurrences: live });+ expect(rows.every(row => row.version === SEGMENT_PIPELINE_VERSIONS[kind] && row.state === 'done')).toBe(true);+ }+}++export async function liveOccurrences(engine: BrainEngine, pageId: number): Promise<Set<number>> {+ return new Set((await engine.executeRaw<{ occurrence_id: string }>(+ 'SELECT occurrence_id::text AS occurrence_id FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL', [pageId]))+ .map(row => Number(row.occurrence_id)));+}++export function resetDeriveWork(): void {+ for (const work of Object.values(segmentDeriveWork)) Object.assign(work, { derived: 0, occurrences: 0, reused: 0 });+}++const revision = async (brain: AppendBrain) => (await brain.engine.executeRaw<{ r: string }>(+ 'SELECT knowledge_revision::text AS r FROM pages WHERE source_id=$1 AND slug=$2', [SOURCE, EQUIVALENCE_SLUG]))[0]!.r;++type Step = { name: string; run: (brain: AppendBrain, page: EquivalencePage) => Promise<void>; append?: boolean };++/** The seeded step sequence: at least 20 steps, appends most often, every other kind of change at least once. */+export function equivalenceSteps(seed = 7): Step[] {+ const next = rng(seed);+ const append = (n: number): Step => ({ name: `append ${n}`, append: true, run: async brain => {+ const text = `Appended ${n}: met [[people/p${n % 6}-example]] and Alice Example; see people/bob-example.\n\n- **2026-10-${String(1 + (n % 28)).padStart(2, '0')}** | appended event ${n}\n\n${prose(6_000 + Math.floor(next() * 20_000), 100 + n)}`;+ const res = await brain.call('append_page', { slug: EQUIVALENCE_SLUG, text, region: 'truth', request_id: randomUUID() });+ expect(res).toMatchObject({ isError: false });+ } });+ const edit = (n: number): Step => ({ name: `edit marker ${n % 6}`, run: async brain => {+ const body = (await brain.body(EQUIVALENCE_SLUG)).truth;+ const old = new RegExp(`Marker ${n % 6}(?: \\(edit \\d+\\))?: `).exec(body)![0];+ const res = await brain.call('edit_page', { slug: EQUIVALENCE_SLUG, expected_revision: await revision(brain), edits: [{ old_text: old, new_text: `Marker ${n % 6} (edit ${n}): see [[companies/c${n % 6}-example]] and ` }] });+ expect(res).toMatchObject({ isError: false });+ } });+ const steps: Step[] = [];+ for (let n = 0; n < 22; n++) {+ if (n === 5) steps.push({ name: 'title change', run: async (brain, page) => {+ await brain.engine.executeRaw('UPDATE pages SET title=$2 WHERE id=$1', [page.id, `Equivalence Example ${n}`]);+ } });+ if (n === 9) steps.push({ name: 'gazetteer change', run: async brain => {+ await brain.engine.putPage('people/carol-example', { type: 'person', title: 'Carol Example', compiled_truth: 'Carol Example fixture.', timeline: '', frontmatter: {} }, { sourceId: SOURCE });+ } });+ // A fence row changes the way forget and purge change one: the segment holding the fence is rewritten (spec 6.4).+ if (n === 13) steps.push({ name: 'fence row edit', run: async (brain, page) => {+ const done = await maintenanceTransaction(brain.engine, tx => rewriteLiveSegmentedFences(tx, page.id, async fence => fence.replace('| 2 | prefers email |', '| 2 | prefers phone |')));+ expect(done).not.toBeNull();+ } });+ steps.push(next() < 0.7 ? append(n) : edit(n));+ }+ return steps;+}++/** Seeds the page and the entities its links and mentions name. */+export async function seedEquivalenceBrain(brain: AppendBrain): Promise<void> {+ const put = (slug: string, type: string, title: string) => brain.engine.putPage(slug, { type, title, compiled_truth: `${title} fixture.`, timeline: '', frontmatter: {} }, { sourceId: SOURCE });+ await put('people/alice-example', 'person', 'Alice Example');+ await put('people/bob-example', 'person', 'Bob Example');+ for (let i = 0; i < 6; i++) {+ await put(`people/p${i}-example`, 'person', `Person ${i}`);+ await put(`companies/c${i}-example`, 'company', `Company ${i}`);+ }+ await brain.seed(EQUIVALENCE_SLUG, equivalencePage());+}++export function registerDerivationEquivalenceCases(kind: 'pglite' | 'postgres'): void {+ describe(`incremental derivations equal a full recompute (${kind})`, () => {+ let brain: AppendBrain;+ beforeAll(async () => {+ brain = await openAppendBrain(kind);+ await seedEquivalenceBrain(brain);+ }, 600_000);+ afterAll(() => brain.close(), 120_000);++ test('after every step of a seeded sequence, each pipeline equals its full pass, rows track live occurrences, and an append derives only its runs', async () => {+ const check = async (label: string) => {+ const current = await storedPage(brain.engine);+ const links = { incremental: await incrementalLinks(brain.engine, current), full: await fullLinks(brain.engine, current) };+ expect({ label, links: links.incremental.candidates }).toEqual({ label, links: links.full.candidates });+ expect({ label, temporal: links.incremental.temporalBody }).toEqual({ label, temporal: links.full.temporalBody! });+ expect({ label, attendance: links.incremental.attendanceComplete }).toEqual({ label, attendance: links.full.attendanceComplete });+ expect({ label, mentions: await incrementalMentions(brain.engine, current) }).toEqual({ label, mentions: await fullMentions(brain.engine, current) });+ expect({ label, timeline: await incrementalTimeline(brain.engine, current) }).toEqual({ label, timeline: await fullTimeline(brain.engine, current) });+ const views = await priorViews(brain.engine, current);+ expect({ label, prior: views.incremental }).toEqual({ label, prior: views.full });+ expect({ label, fences: await incrementalFactsFenceView(brain.engine, current) }).toEqual({ label, fences: await segmentedFactsFenceView(brain.engine, current) });+ await derivationRowsMatch(brain.engine, current, KINDS);+ };+ const page = await storedPage(brain.engine);+ await check('seed');+ expect((await fullLinks(brain.engine, page)).candidates.length).toBeGreaterThan(10);+ expect((await fullMentions(brain.engine, page)).length).toBeGreaterThanOrEqual(2);+ expect((await segmentedFactsFenceView(brain.engine, page)).body.facts.length).toBe(2);+ expect(views0(await priorViews(brain.engine, page))).toBe(true);+ resetDeriveWork();+ await deriveAll(brain.engine, page);+ for (const kind of KINDS) expect({ kind, derived: segmentDeriveWork[kind].derived }).toEqual({ kind, derived: 0 });+ const steps = equivalenceSteps();+ expect(steps.length).toBeGreaterThanOrEqual(20);+ const work: string[] = [];+ for (const step of steps) {+ const before = await liveOccurrences(brain.engine, page.id);+ resetDeriveWork();+ await step.run(brain, page);+ const after = await liveOccurrences(brain.engine, page.id);+ await deriveAll(brain.engine, await storedPage(brain.engine));+ if (step.append) {+ // Everything the append and the derivations after it derived: the new or rewritten tail occurrences, and for+ // links also the timeline's first run, whose window reads the truth's last blocks.+ const fresh = [...after].filter(id => !before.has(id)).length;+ work.push(`${step.name}: ${KINDS.map(kind => `${kind} ${segmentDeriveWork[kind].occurrences}/${after.size}`).join(', ')} (fresh ${fresh})`);+ for (const kind of KINDS) {+ const bound = fresh + (kind === 'links' ? 1 : 0);+ expect({ step: step.name, kind, derived: segmentDeriveWork[kind].occurrences <= bound }).toEqual({ step: step.name, kind, derived: true });+ expect({ step: step.name, kind, reused: segmentDeriveWork[kind].reused > 0 }).toEqual({ step: step.name, kind, reused: true });+ }+ }+ await check(step.name);+ }+ console.log(`derivation work per append (occurrences derived / live):\n${work.join('\n')}`);+ }, 1_800_000);++ test('a forget that rewrites the segment holding the fence deletes that run\'s derivation rows and only nearby link rows', async () => {+ const page = await storedPage(brain.engine);+ await runExtractFacts(brain.engine, { slugs: [EQUIVALENCE_SLUG] });+ const [fact] = await brain.engine.executeRaw<{ id: number }>(+ "SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND fact ILIKE '%ships quarterly%' AND expired_at IS NULL", [SOURCE, EQUIVALENCE_SLUG]);+ expect(fact).toBeDefined();+ await deriveAll(brain.engine, page);+ const seqs = new Map((await brain.engine.executeRaw<{ occurrence_id: string; seq: number }>(+ 'SELECT occurrence_id::text AS occurrence_id, seq FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL', [page.id]))+ .map(row => [Number(row.occurrence_id), Number(row.seq)]));+ const rowsBefore = await brain.engine.readSegmentDerivations(page.id);+ const before = await liveOccurrences(brain.engine, page.id);+ expect((await forgetFactInFence(brain.engine, Number(fact!.id), { sourceId: SOURCE })).ok).toBe(true);+ const after = await liveOccurrences(brain.engine, page.id);+ const rewritten = [...before].filter(id => !after.has(id));+ expect(rewritten.length).toBe(1);+ const rowsAfter = await brain.engine.readSegmentDerivations(page.id);+ // The rewritten occurrence holds no row of any kind; every other occurrence keeps its rows, except links rows of+ // the runs next to it (a candidate excerpt reaches 120 units past its block).+ expect(rowsAfter.filter(row => rewritten.includes(row.occurrenceId))).toEqual([]);+ const key = (row: { kind: string; occurrenceId: number }) => `${row.kind}:${row.occurrenceId}`;+ const kept = new Set(rowsAfter.map(key));+ const dropped = rowsBefore.filter(row => !rewritten.includes(row.occurrenceId) && !kept.has(key(row)));+ const at = seqs.get(rewritten[0]!)!;+ expect(dropped.every(row => row.kind === 'links' && Math.abs(seqs.get(row.occurrenceId)! - at) === 1)).toBe(true);+ expect(rowsAfter.filter(row => row.kind !== 'links').length).toBe(rowsBefore.filter(row => row.kind !== 'links').length - KINDS.length + 1);+ const current = await storedPage(brain.engine);+ await deriveAll(brain.engine, current);+ expect(await incrementalFactsFenceView(brain.engine, current)).toEqual(await segmentedFactsFenceView(brain.engine, current));+ expect((await incrementalLinks(brain.engine, current)).candidates).toEqual((await fullLinks(brain.engine, current)).candidates);+ await derivationRowsMatch(brain.engine, current, KINDS);+ }, 600_000);++ test('a remote edit queues a links effect carrying the occurrences the edit added (spec 8.5)', async () => {+ const page = await storedPage(brain.engine);+ const before = await liveOccurrences(brain.engine, page.id);+ const old = /Marker 3(?: \(edit \d+\))?: /.exec((await brain.body(EQUIVALENCE_SLUG)).truth)![0];+ const res = await brain.call('edit_page', { slug: EQUIVALENCE_SLUG, expected_revision: await revision(brain),+ edits: [{ old_text: old, new_text: 'Marker 3 (remote edit): see [[companies/c3-example]] and ' }] }, { remote: true });+ expect(res).toMatchObject({ isError: false });+ const added = [...await liveOccurrences(brain.engine, page.id)].filter(id => !before.has(id)).sort((a, b) => a - b);+ expect(added.length).toBeGreaterThan(0);+ const effects = await brain.engine.executeRaw<{ data: { occurrence_ids?: number[]; slug?: string } }>(+ "SELECT e.data FROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_id WHERE e.kind='links' AND r.operation='edit_page' AND e.data->>'slug'=$1",+ [EQUIVALENCE_SLUG]);+ expect(effects.length).toBe(1);+ expect([...(effects[0]!.data.occurrence_ids ?? [])].sort((a, b) => a - b)).toEqual(added);+ }, 600_000);+ });+}++const views0 = (views: { incremental: unknown; full: unknown }) => JSON.stringify(views.incremental) === JSON.stringify(views.full);diff --git a/test/large-pages/derivation-equivalence.test.ts b/test/large-pages/derivation-equivalence.test.tsnew file mode 100644index 0000000000..07c2a09a38--- /dev/null+++ b/test/large-pages/derivation-equivalence.test.ts@@ -0,0 +1,8 @@+/**+ * Wave B PR 4 lane 4a (spec 8.1, 8.2): the incremental links, mentions, timeline and fence derivations of a segmented+ * page equal a full recompute after every step of a seeded sequence of appends and edits (PGLite arm; the PostgreSQL+ * arm is test/e2e/derivation-equivalence-postgres.test.ts). Cases in test/helpers/derivation-equivalence-cases.ts.+ */+import { registerDerivationEquivalenceCases } from '../helpers/derivation-equivalence-cases.ts';++registerDerivationEquivalenceCases('pglite');