Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
large pages PR 2 lane 2e: derived passes stream segmented bodies (full-pass mode)
garrytanc954832d9ebe
diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex d113f2cfcc..0beda0ba78 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -19,10 +19,11 @@import type { BrainEngine, TimelineBatchInput } from '../core/engine.ts';import type { Page, PageType } from '../core/types.ts';import { parseTimelineEntries, deriveTimelineAnchor } from '../core/link-extraction.ts';-import { retractRemovedTimelineEntries } from '../core/timeline-extract.ts';+import { retractRemovedTimelineEntries, segmentedTimelineText } from '../core/timeline-extract.ts';import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';import { maintenanceTransaction } from '../core/persistence/attribution.ts';-import { unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';+import { storedCanonicalTimeline, unrecordedCanonicalTimeline } from '../core/persistence/canonical-projections.ts';+import { isSegmentedPage } from '../core/page-body/page-shape.ts';import { maintenancePreflight, submitDatabaseMaintenanceIntent, type MaintenanceAuthority } from '../core/persistence/prepared-maintenance.ts';import { authorizeWrite } from '../core/persistence/authority.ts';import { getWriteRequest } from '../core/persistence/journal.ts';@@ -178,9 +179,11 @@ export async function extractTimelineFromDB(engine: BrainEngine, opts: TimelineDconst page = snapshot?.page ?? null;if (!page || isQuarantined(page.frontmatter)) continue;if (opts.typeFilter && page.type !== opts.typeFilter) continue;- const fullContent = page.compiled_truth + '\n' + page.timeline;+ // A segmented body is read block by block (segmentedTimelineText), never as one string.+ const segmented = isSegmentedPage(page) ? await segmentedTimelineText(engine, page) : null;+ const fullContent = segmented ?? page.compiled_truth + '\n' + page.timeline;if (!opts.dryRun) await retractRemovedTimelineEntries(engine, slug, source_id, fullContent);- let entries = parseTimelineEntries(fullContent);+ let entries = segmented ? segmented.entries : parseTimelineEntries(page.compiled_truth + '\n' + page.timeline);// --infer-dates: pages with no in-body timeline line but a trustworthy// content date (frontmatter / filename) get one anchor entry at that date.if (entries.length === 0 && opts.inferDates) {@@ -268,12 +271,15 @@ async function readTimelineBatch(engine: BrainEngine, refs: ReadonlyArray<{ slug* the page's rows; without it the checks read them.*/async function plannedTimeline(engine: BrainEngine, page: Page, slug: string, sourceId: string, inferDates: boolean, stored?: StoredTimelineRows[]) {- const fullContent = page.compiled_truth + '\n' + page.timeline;+ // A segmented body is read block by block, through the engine given (inside the coordinator's transaction too).+ const segmented = isSegmentedPage(page) ? await segmentedTimelineText(engine, page) : null;+ const fullContent = segmented ?? page.compiled_truth + '\n' + page.timeline;const removed = await retractRemovedTimelineEntries(engine, slug, sourceId, fullContent, { dryRun: true,...(stored ? { storedRows: stored.map(({ date_text: _text, ...row }) => row) } : {}) });- let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(engine, page.id, page, slug,- stored?.map(row => ({ date: row.date_text, source: row.source, summary: row.summary })));- if (entries.length === 0 && inferDates && parseTimelineEntries(fullContent).length === 0) {+ let entries: Array<{ date: string; source?: string; summary: string; detail?: string }> = await unrecordedCanonicalTimeline(engine, page.id,+ segmented ? await storedCanonicalTimeline(engine, page, slug) : page, slug, stored?.map(row => ({ date: row.date_text, source: row.source, summary: row.summary })));+ const parsed = segmented ? segmented.entries.length : parseTimelineEntries(page.compiled_truth + '\n' + page.timeline).length;+ if (entries.length === 0 && inferDates && parsed === 0) {const anchor = anchorFor(page, slug);const [count] = !anchor ? [{ n: 1 }] : stored ? [{ n: stored.length }] : await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL', [page.id]);diff --git a/src/commands/extract.ts b/src/commands/extract.tsindex 039f394151..a566d3ce03 100644--- a/src/commands/extract.ts+++ b/src/commands/extract.ts@@ -86,7 +86,7 @@ import { withRetry, isRetryableConnError } from '../core/retry.ts';export { withRetry };export type { WithRetryOpts } from '../core/retry.ts';import { buildGazetteer, findMentionedEntities, hashGazetteer } from '../core/by-mention.ts';-import { runMentionPass, type MentionPassResult } from '../core/mentions/pass.ts';+import { pageMentions, runMentionPass, type MentionPassResult } from '../core/mentions/pass.ts';import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../core/mentions/stale.ts';// #4611: the cross-source link fallback follows the configured// `sources.default` (validated shape) instead of the literal 'default'.@@ -101,6 +101,8 @@ import { isAborted } from '../core/abort-check.ts';import { parseWorkers, resolveWorkersWithClamp } from '../core/sync-concurrency.ts';import { loadAllSources } from '../core/sources-load.ts';import { plannerStatsForLinkDrain } from '../core/planner-stats.ts';+import { isSegmentedPage, withoutBody } from '../core/page-body/page-shape.ts';+import { extractSegmentedPageLinks } from '../core/page-body/segment-links.ts';// Batch size for addLinksBatch / addTimelineEntriesBatch.// Postgres bind-parameter limit is 65535. Links use 4 cols/row → 16K hard ceiling;@@ -1957,20 +1959,21 @@ async function extractLinksFromDB(if (!resolvers.has(source_id)) resolvers.set(source_id, makeResolver(engine, { mode: 'batch', sourceId: source_id }));const resolver = resolvers.get(source_id)!;- const fullContent = page.compiled_truth + '\n' + page.timeline;// --include-frontmatter default OFF in v0.13 (codex tension 5, back-compat).// Migration orchestrator explicitly enables it for the one-time backfill;// user-invoked `gbrain extract links` stays outgoing-only.// Issue #972: globalBasename routes bare `[[name]]` wikilinks through// basename lookup; off by default for back-compat.- const extracted = await extractPageLinks(- slug, fullContent, page.frontmatter, page.type, resolver,- { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {- const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,- source_id, allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId });- return !resolved.ok ? undefined : targetSlug === slug && resolved.toSourceId === source_id ? page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;- } },- );+ const linkOpts = { skipFrontmatter: !includeFrontmatter, globalBasename, pack, lineGrammar, targetType: (targetSlug: string, targetSourceId?: string) => {+ const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,+ source_id, allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId });+ return !resolved.ok ? undefined : targetSlug === slug && resolved.toSourceId === source_id ? page.type : targetMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type;+ } };+ // A segmented body is read block by block, with its temporal inputs for the publication (page-body/segment-links.ts).+ const extracted: Awaited<ReturnType<typeof extractSegmentedPageLinks>> = isSegmentedPage(page)+ ? await extractSegmentedPageLinks(engine, { id: Number(page.id), slug, source_id, type: page.type, frontmatter: page.frontmatter }, resolver,+ { ...linkOpts, temporal: true })+ : await extractPageLinks(slug, page.compiled_truth + '\n' + page.timeline, page.frontmatter, page.type, resolver, linkOpts);unresolved.push(...extracted.unresolved);if (!extracted.attendanceComplete) { skippedAttendanceIncomplete++; continue; }@@ -2019,6 +2022,7 @@ async function extractLinksFromDB(allSlugs, slugToSources, federatedSourceIds.has(source_id), { crossSource, defaultSourceId: linkDefaultSourceId }) }) : [];pendingWrites.push({ slug, source_id, item: { origin: { slug, sourceId: source_id, expectedRevision: snapshot.revision,sourceIncarnation: snapshot.sourceIncarnation }, links: batch, opts: { includeFrontmatter, lineGrammar: grammar,+ ...(extracted.temporalBody ? { temporalBody: extracted.temporalBody } : {}),wanted: { producers: includeFrontmatter ? ['body', 'frontmatter'] : ['body'], rows: wanted },expectedEndpoints: capturedLinkEndpoints(batch, targetMetadata, { slug, sourceId: source_id }) } } });} catch (error) {@@ -2506,14 +2510,11 @@ async function extractMentionsFromDb(// D3: scan both columns joined with a paragraph separator so an// end-of-compiled token doesn't accidentally merge with a// start-of-timeline token into a false phrase match.- const body = (page.title ?? '') + '\n\n' + page.compiled_truth + '\n\n' + (page.timeline ?? '');- const mentions = body.trim()- ? findMentionedEntities(body, gazetteer, {- fromSlug: slug,- fromSourceId: source_id,- allowCrossSource,- })- : [];+ // A segmented body is scanned block by block (mentions/pass.ts pageMentions).+ const body = isSegmentedPage(page) ? null : (page.title ?? '') + '\n\n' + page.compiled_truth + '\n\n' + (page.timeline ?? '');+ const mentionOpts = { fromSlug: slug, fromSourceId: source_id, allowCrossSource };+ const mentions = body === null ? await pageMentions(engine, { ...withoutBody(page), id: Number(page.id), source_id }, gazetteer, mentionOpts)+ : body.trim() ? findMentionedEntities(body, gazetteer, mentionOpts) : [];// #3674 --rebuild: per-page delete-then-insert in ONE transaction. The// delete sweeps the page's link_source='mentions' rows — INCLUDING pagesdiff --git a/src/core/chronicle/execute.ts b/src/core/chronicle/execute.tsindex abe4024ea5..3d9dd6587b 100644--- a/src/core/chronicle/execute.ts+++ b/src/core/chronicle/execute.ts@@ -10,7 +10,9 @@* reconciliation → ledger outcome. An ended calendar invite takes the judge's* place with its deterministic projection (invite-projection.ts): no* reservation, no model call. A failed or superseded run never retires- * the previous generation.+ * the previous generation. A segmented page is never materialized: the judge+ * reads its compiled truth's first JUDGE_BODY_CHARS and its last message time+ * comes from a block-by-block parse (segmentedJudgePage).*/import type { BrainEngine } from '../engine.ts';import { BudgetTracker, type PricingOverrides } from '../budget/budget-tracker.ts';@@ -18,13 +20,16 @@ import { recordOnTracker } from '../ai/budget-record.ts';import { getCurrentBudgetTracker, withBudgetTracker } from '../ai/gateway.ts';import type { ExtractAtomsCostGate } from '../cycle/extract-atoms-cost-gate.ts';import type { MaintenanceAuthority } from '../persistence/prepared-maintenance.ts';-import { materializedPage, segmentedOverCeiling } from '../persistence/segmented-apply.ts';+import type { Page } from '../types.ts';+import { isSegmentedPage, withoutBody } from '../page-body/page-shape.ts';+import { bodyBlocks, truthLead } from '../page-body/segment-blocks.ts';+import { DAY_HEADER_RE } from '../conversation-parser/parse.ts';import { CHRONICLE_DEFAULTS, CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow } from './contract.ts';import type { ChronicleReasonCode } from './reasons.ts';import type { ChronicleSettings } from './config.ts';-import { isChronicleEligible } from './eligibility.ts';+import { chroniclePageDate, isChronicleEligible } from './eligibility.ts';import {- allDroppedReason, buildChronicleEvents, chronicleJudgeContext, isValidProposal,+ allDroppedReason, buildChronicleEvents, chronicleJudgeContext, isValidProposal, JUDGE_BODY_CHARS, lastMessageAt,type ChronicleDropCounts, type ChronicleJudge, type ChronicleJudgeResult,} from './extract-events.ts';import { endedInviteProposal, markInviteEvents } from './invite-projection.ts';@@ -176,11 +181,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroniawait finish(engine, row, row.attempts, { state: 'skipped', reason: 'no_extract', nextAttemptAt: null });return done('skipped', 'no_extract');}- if (segmentedOverCeiling(snapshot.page)) {- await finish(engine, row, row.attempts, { state: 'skipped', reason: 'page_body_segmented', nextAttemptAt: null });- return done('skipped', 'page_body_segmented');- }- const page = await materializedPage(engine, snapshot.page);+ const { page, lastMessage } = isSegmentedPage(snapshot.page) ? await segmentedJudgePage(engine, snapshot.page) : { page: snapshot.page, lastMessage: undefined };const auto = row.trigger === 'auto';const eligible = isChronicleEligible({type: page.type, slug: page.slug, body: page.compiled_truth ?? '',@@ -199,7 +200,7 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chronireturn done('skipped', reason);}- const judgeCtx = chronicleJudgeContext(page);+ const judgeCtx = chronicleJudgeContext(page, lastMessage);const invite = endedInviteProposal(page, judgeCtx.attendees, now);if (auto && !invite && !(await reserveChronicleSlot(engine, settings.dailyLimit, { sourceId: row.source_id, pageId: Number(row.page_id), contentHash: row.content_hash }))) {await setNextAttempt(engine, row, null);@@ -267,3 +268,21 @@ export async function executeChronicleRow(ctx: ChronicleExecContext, row: Chroni}export type { ChronicleDepthPin };++/**+ * A segmented page as the judge reads it, without materializing its body: `compiled_truth` is the truth's first+ * JUDGE_BODY_CHARS (all the judge and the length rule read), and `lastMessage` the latest message time over the truth,+ * parsed block by block; a block starting under a day header from an earlier block parses with that header's date.+ */+async function segmentedJudgePage(engine: BrainEngine, stored: Page): Promise<{ page: Page; lastMessage: Date | null }> {+ const page = { ...withoutBody(stored), compiled_truth: await truthLead(engine, Number(stored.id), JUDGE_BODY_CHARS), timeline: '' } as Page;+ let day = chroniclePageDate({ effectiveDate: stored.effective_date ?? null, effectiveDateSource: stored.effective_date_source ?? null,+ frontmatter: stored.frontmatter ?? null })?.toISOString().slice(0, 10);+ let lastMessage: Date | null = null;+ for await (const block of bodyBlocks(engine, stored, { regions: ['truth'] })) {+ const last = lastMessageAt(block.text, day);+ if (last && (!lastMessage || last > lastMessage)) lastMessage = last;+ for (const line of block.text.split('\n')) day = DAY_HEADER_RE.exec(line.trim())?.[1] ?? day;+ }+ return { page, lastMessage };+}diff --git a/src/core/chronicle/extract-events.ts b/src/core/chronicle/extract-events.tsindex fe8c1f0ade..3cf66c09cd 100644--- a/src/core/chronicle/extract-events.ts+++ b/src/core/chronicle/extract-events.ts@@ -176,7 +176,7 @@ export function allDroppedReason(dropped: ChronicleDropCounts): ChronicleDropRea}/** The latest message timestamp of a chat-shaped body (multi-day conversations end on their last message). */-function lastMessageAt(body: string, fallbackDate: string | undefined): Date | null {+export function lastMessageAt(body: string, fallbackDate: string | undefined): Date | null {const { messages } = parseConversation(body, { fallbackDate, noPolish: true, noFallback: true });let last: Date | null = null;for (const m of messages) {@@ -193,9 +193,14 @@ function asDate(value: unknown): Date | null {return Number.isNaN(d.getTime()) ? null : d;}-/** The judge input for one immutable depth snapshot (E5: the judge never re-reads the page). */+/**+ * The judge input for one immutable depth snapshot (E5: the judge never re-reads the page). `lastMessage` is the+ * body's last message time when the caller read the body itself (a segmented page, block by block); `compiled_truth`+ * is then its lead.+ */export function chronicleJudgeContext(page: { slug: string; type: string; title: string; compiled_truth?: string | null;- effective_date?: unknown; effective_date_source?: string | null; frontmatter?: Record<string, unknown> | null }): ChronicleJudgeContext {+ effective_date?: unknown; effective_date_source?: string | null; frontmatter?: Record<string, unknown> | null },+ lastMessage?: Date | null): ChronicleJudgeContext {const fm = (page.frontmatter ?? {}) as Record<string, unknown>;const edRaw = page.effective_date as unknown;const effectiveDate: string | null =@@ -207,7 +212,8 @@ export function chronicleJudgeContext(page: { slug: string; type: string; title:const body = page.compiled_truth ?? '';const own = chroniclePageDate({ effectiveDate: page.effective_date as Date | string | null | undefined,effectiveDateSource: page.effective_date_source ?? null, frontmatter: fm });- const pageDates = [own, asDate(fm.end), lastMessageAt(body, own?.toISOString().slice(0, 10))].filter((d): d is Date => d !== null);+ const last = lastMessage !== undefined ? lastMessage : lastMessageAt(body, own?.toISOString().slice(0, 10));+ const pageDates = [own, asDate(fm.end), last].filter((d): d is Date => d !== null);return {effectiveDate, attendees, pageDates,input: { slug: page.slug, type: page.type, title: page.title, body, effectiveDate, attendees },diff --git a/src/core/chronicle/ledger.ts b/src/core/chronicle/ledger.tsindex 5e8b564800..f45a1215dd 100644--- a/src/core/chronicle/ledger.ts+++ b/src/core/chronicle/ledger.ts@@ -8,7 +8,6 @@ import type { PageSnapshot } from '../page-state/types.ts';import type { WriteAuthority, WriteRequest } from '../persistence/model.ts';import { derivedExtractionSkip } from '../persistence/derived-extraction-gate.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';-import { segmentedOverCeiling } from '../persistence/segmented-apply.ts';import type { BodyStorage } from '../page-body/types.ts';import { CHRONICLE_ACTIVATED_AT_KEY, autoChronicleSetting, chronicleSettings, type ChronicleSettings } from './config.ts';import { CHRONICLE_EXTRACTOR_VERSION, type ChronicleLedgerRow, type ChronicleTrigger } from './contract.ts';@@ -68,7 +67,6 @@ export function decideChronicle(input: {}return skip(eligible.reason.startsWith('kind:') ? 'not_chronicle_shaped' : eligible.reason);}- if (segmentedOverCeiling(page)) return skip('page_body_segmented');return { state: 'pending', reason: null, nextAttemptAt: new Date(input.now.getTime() + input.settings.settleSeconds * 1000) };}diff --git a/src/core/chronicle/reasons.ts b/src/core/chronicle/reasons.tsindex 1cb5928ec5..0969b0dba2 100644--- a/src/core/chronicle/reasons.ts+++ b/src/core/chronicle/reasons.ts@@ -76,7 +76,7 @@ export const CHRONICLE_REASONS = {dream_generated: { stage: 'decision',meaning: () => 'Dream-generated pages are never mined for events.' },page_body_segmented: { stage: 'decision',- meaning: () => 'The page body is over the 24 MiB single-string ceiling and is stored in segments; extraction reads the whole body as one string, so it skips this page.' },+ meaning: () => 'An earlier release skipped this page: its body is over the 24 MiB single-string ceiling and is stored in segments. This release reads segmented pages, so the next revision or a backfill extracts it.' },no_write_decision: { stage: 'discovery',meaning: () => 'This revision has no recorded write decision (written by an older binary or before this release activated), so only a trusted backfill extracts it.',fix: backfill('agent', FIX_BY_BACKFILL) },diff --git a/src/core/cycle/extract-takes.ts b/src/core/cycle/extract-takes.tsindex 5d4380e4ec..15c2460c01 100644--- a/src/core/cycle/extract-takes.ts+++ b/src/core/cycle/extract-takes.ts@@ -30,6 +30,10 @@ import { readFileSync } from 'node:fs';import { join, relative, sep } from 'node:path';import type { BrainEngine, TakeBatchInput } from '../engine.ts';import { parseTakesFence, TAKES_FENCE_BEGIN, type ParsedTake } from '../takes-fence.ts';+import { isSegmentedPage } from '../page-body/page-shape.ts';+import { bodyBlocks } from '../page-body/segment-blocks.ts';+import { parseTakesFenceBlocks, type StreamedTakes } from '../page-body/segment-takes.ts';+import type { BodyStorage } from '../page-body/types.ts';import { walkMarkdownFiles } from '../../commands/extract.ts';import { takesPreparation } from '../takes-write.ts';import { withWriteTrust } from '../persistence/context.ts';@@ -112,12 +116,12 @@ async function getPageIdForSlug(engine: BrainEngine, slug: string, sourceId: strasync function pruneRemovedTakes(engine: BrainEngine,pageId: number,- body: string,+ hasBegin: boolean,takes: ParsedTake[],warnings: string[],dryRun: boolean,): Promise<void> {- if (dryRun || warnings.length > 0 || !body.includes(TAKES_FENCE_BEGIN)) return;+ if (dryRun || warnings.length > 0 || !hasBegin) return;await engine.executeRaw('DELETE FROM takes WHERE page_id = $1 AND NOT (row_num = ANY($2::integer[]))',[pageId, takes.map(t => t.rowNum)],@@ -255,7 +259,7 @@ export async function extractTakesFromFs(}// #6259: the stored page decides (the gate stamps quarantine on it); a quarantined page projects no takes.if ((await engine.executeRaw('SELECT 1 FROM pages WHERE id=$1 AND frontmatter ? $2', [pageId, QUARANTINE_KEY])).length) continue;- await pruneRemovedTakes(engine, pageId, body, takes, warnings, dryRun);+ await pruneRemovedTakes(engine, pageId, body.includes(TAKES_FENCE_BEGIN), takes, warnings, dryRun);if (takes.length === 0) continue;if (opts.rebuild && !dryRun) await deleteDivergedTakes(engine, pageId, takes);@@ -308,15 +312,14 @@ export async function extractTakesFromDb(if (!page) continue;// #6259: a quarantined page projects no takes (its existing rows are left as they are).if (isQuarantined(page.frontmatter as Record<string, unknown> | null)) continue;+ const read = await readPageTakes(engine, page);if (coordinated) {// A page with no takes marker at all yields no prune, no upsert and no// warning; near-miss and unbalanced markers still reach the parser.- if (`${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`.includes('gbrain:takes:')) {- await reextractCoordinated(engine, authorityFor, slug, source_id, rebuild, result);- }+ if (read.hasMarker) await reextractCoordinated(engine, authorityFor, slug, source_id, rebuild, result);continue;}- const takes = await reconcilePageTakes(engine, page, slug, rebuild, dryRun, result);+ const takes = await reconcilePageTakes(engine, page.id, read, slug, rebuild, dryRun, result);for (const t of takes) {buffer.push(parsedTakeToBatchInput(page.id, t));if (buffer.length >= BATCH_SIZE) await flushBatch(engine, buffer, result, dryRun);@@ -326,21 +329,30 @@ export async function extractTakesFromDb(return result;}+type TakesPage = { id: number; slug: string; source_id: string; body_storage?: BodyStorage | null; compiled_truth: string | null; timeline: string | null };+const TAKES_PAGE_COLUMNS = 'id, slug, source_id, body_storage, compiled_truth, timeline';++/** parseTakesFence over the page's `${compiled_truth}\n${timeline}`; a segmented body is read block by block (page-body/segment-takes.ts). */+async function readPageTakes(engine: BrainEngine, page: TakesPage): Promise<StreamedTakes> {+ if (isSegmentedPage(page)) return parseTakesFenceBlocks(bodyBlocks(engine, page), page);+ const body = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;+ return { parsed: parseTakesFence(body), hasBegin: body.includes(TAKES_FENCE_BEGIN), hasMarker: body.includes('gbrain:takes:') };+}+/**- * Parse one page's body and record its warnings, then prune rows that left a- * cleanly parsed fence (and, under rebuild, clear the page). Returns the takes- * the caller upserts.+ * Record one page's takes warnings, then prune rows that left a cleanly parsed+ * fence (and, under rebuild, clear the page). Returns the takes the caller upserts.*/async function reconcilePageTakes(db: BrainEngine,- page: { id: number; compiled_truth: string | null; timeline: string | null },+ pageId: number,+ read: StreamedTakes,slug: string,rebuild: boolean,dryRun: boolean,result: ExtractTakesResult,): Promise<ParsedTake[]> {- const body = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;- const { takes, warnings } = parseTakesFence(body);+ const { takes, warnings } = read.parsed;for (const w of warnings) {result.warnings.push(`${slug}: ${w}`);if (w.startsWith('TAKES_HOLDER_INVALID')) {@@ -350,9 +362,9 @@ async function reconcilePageTakes(result.failedFiles.push({ path: slug, error: w });}}- await pruneRemovedTakes(db, page.id, body, takes, warnings, dryRun);+ await pruneRemovedTakes(db, pageId, read.hasBegin, takes, warnings, dryRun);if (takes.length === 0) return [];- if (rebuild && !dryRun) await deleteDivergedTakes(db, page.id, takes);+ if (rebuild && !dryRun) await deleteDivergedTakes(db, pageId, takes);result.pagesWithTakes++;return takes;}@@ -360,15 +372,14 @@ async function reconcilePageTakes(export const TAKES_REEXTRACT_INTENT = 'managed_maintenance_takes_reextract';/** The page's takes reconcile as it stands: what a write would prune, rebuild and upsert. */-async function plannedTakes(db: BrainEngine, page: { id: number; compiled_truth: string | null; timeline: string | null }, rebuild: boolean) {- const body = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;- const { takes, warnings } = parseTakesFence(body);+async function plannedTakes(db: BrainEngine, page: { id: number }, read: StreamedTakes, rebuild: boolean) {+ const { takes, warnings } = read.parsed;const { rows } = buildTakeRows(takes.map(t => takesPreparation.toCanonicalBatchInput(page.id, t)));const stored = await db.executeRaw<{ row_num: number; claim: string; kind: string; holder: string; weight: number | string; since_date: string | null;until_date: string | null; source: string | null; superseded_by: number | null; active: boolean }>('SELECT row_num, claim, kind, holder, weight, since_date, until_date, source, superseded_by, active FROM takes WHERE page_id = $1', [page.id]);const byRow = new Map(stored.map(r => [Number(r.row_num), r]));- const prunes = warnings.length === 0 && body.includes(TAKES_FENCE_BEGIN) && stored.some(r => !takes.some(t => t.rowNum === Number(r.row_num)));+ const prunes = warnings.length === 0 && read.hasBegin && stored.some(r => !takes.some(t => t.rowNum === Number(r.row_num)));const diverged = rebuild && stored.some(r => !takes.some(t => t.rowNum === Number(r.row_num) && t.claim === r.claim));const upserts = rows.some(row => {const s = byRow.get(row.row_num);@@ -399,13 +410,13 @@ async function reextractCoordinated(result: ExtractTakesResult,): Promise<void> {const snapshot = await engine.readPageSnapshot(slug, { sourceId });- const [page] = await engine.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(- 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [sourceId, slug]);+ const [page] = await engine.executeRaw<TakesPage>(+ `SELECT ${TAKES_PAGE_COLUMNS} FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL`, [sourceId, slug]);if (!snapshot || !page || Number(page.id) !== snapshot.page.id) return;- const plan = await plannedTakes(engine, page, rebuild);+ const read = await readPageTakes(engine, page);+ const plan = await plannedTakes(engine, page, read, rebuild);if (!plan.changed) {- const { warnings } = parseTakesFence(`${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`);- recordTakesWarnings(slug, warnings, result);+ recordTakesWarnings(slug, read.parsed.warnings, result);if (plan.takes.length) result.pagesWithTakes++;return;}@@ -450,13 +461,16 @@ export async function prepareTakesReextract(engine: BrainEngine, row: WriteReque}await authorizeWrite(engine, row.authority, 'submit_job', row.slug);const rebuild = (row.intent as { rebuild?: unknown } | null)?.rebuild === true;+ // A segmented body is read here, at the observed revision, never inside the publication.+ const segmented = isSegmentedPage(snapshot.page) ? await readPageTakes(engine, snapshot.page as TakesPage) : null;return { observedRevision: snapshot.revision, noop: true,validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },apply: async tx => {- const [page] = await tx.executeRaw<{ id: number; compiled_truth: string | null; timeline: string | null }>(- 'SELECT id, compiled_truth, timeline FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [row.source_id, row.slug]);+ const [page] = await tx.executeRaw<TakesPage>(+ `SELECT ${TAKES_PAGE_COLUMNS} FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL`, [row.source_id, row.slug]);const local: ExtractTakesResult = { pagesScanned: 0, pagesWithTakes: 0, takesUpserted: 0, warnings: [], failedFiles: [] };- const takes = page ? await reconcilePageTakes(tx, page, row.slug, rebuild, false, local) : [];+ const read = page && (isSegmentedPage(page) ? segmented : await readPageTakes(tx, page));+ const takes = page && read ? await reconcilePageTakes(tx, page.id, read, row.slug, rebuild, false, local) : [];const upserted = takes.length ? await upsertProjectedTakes(tx, takes.map(t => takesPreparation.toCanonicalBatchInput(page!.id, t)), local, tx) : 0;return { status: 'completed', takes_upserted: upserted, with_takes: local.pagesWithTakes > 0, ...(local.writeGate ? { write_gate: local.writeGate } : {}),warnings: local.warnings.map(w => w.slice(row.slug.length + 2)) };diff --git a/src/core/derived-links.ts b/src/core/derived-links.tsindex bf1107ff27..23edfd069a 100644--- a/src/core/derived-links.ts+++ b/src/core/derived-links.ts@@ -5,7 +5,7 @@ import { executeRawJsonb } from './sql-query.ts';import { pageSnapshotKey } from './page-snapshot-batch.ts';import { sanitizeForJsonb } from './batch-rows.ts';import { replaceWantedLinks, type WantedLinksReplacement } from './wanted-links-store.ts';-import { applyTemporalEvidence, relationshipKeysForOrigin } from './link-temporal-apply.ts';+import { applyTemporalEvidence, relationshipKeysForOrigin, type TemporalBody } from './link-temporal-apply.ts';import { primeRelationSemantics } from './link-semantics-pack.ts';import { effectiveRangesEnabled, LINK_EXTRACTION_GENERATION_KEY, type LineGrammarSettings } from './line-grammar.ts';@@ -38,6 +38,8 @@ export interface DerivedLinkReplacementOptions {* so a page is never published from one setting and ranged from another.*/lineGrammar?: LineGrammarSettings;+ /** The origin body's temporal inputs, read at preparation; a segmented origin's body is never read inside the publication. */+ temporalBody?: TemporalBody;}export class DerivedLinkRepairRequiredError extends Error {@@ -258,7 +260,7 @@ async function publishDerivedLinks(tx: BrainEngine, origin: DerivedLinkOrigin, p() => opts.lineGrammar ? Promise.resolve(opts.lineGrammar.effectiveRanges) : effectiveRangesEnabled(tx),]) as [unknown, Awaited<ReturnType<typeof relationshipKeysForOrigin>>, unknown[], unknown[], unknown[], Existing[], boolean];const withTemporal = async (result: { created: number; removed: number }) => {- await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges });+ await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges, body: opts.temporalBody });return result;};if (ambiguous.length) throw new DerivedLinkRepairRequiredError();diff --git a/src/core/extraction-watermark.ts b/src/core/extraction-watermark.tsindex 4f4edc47b4..626b002803 100644--- a/src/core/extraction-watermark.ts+++ b/src/core/extraction-watermark.ts@@ -13,10 +13,17 @@* in `page_extraction_state`, which doctor's `extraction_input_truncated`* check reports. A full read clears the receipt; a tail read keeps it, since* the text skipped earlier is still unread.+ *+ * A segmented page's compiled truth is planned the same way without holding it+ * (planSegmentedExtraction): one pass over its segments (readBodyRange) hashes+ * the body and the watermark prefix and keeps only the head and the newest+ * window of the appended tail.*/import { createHash } from 'node:crypto';import type { BrainEngine } from './engine.ts';import { truncateUtf8 } from './text-safe.ts';+import { openSegmentedBody, readBodyRange } from './page-body/read-range.ts';+import { readGarbageCollector } from './page-body/segment-blocks.ts';export type ExtractionPipeline = 'facts_backstop' | 'extract_atoms' | 'conversation_facts';@@ -93,6 +100,55 @@ export function planExtraction(body: string, stored: StoredWatermark | null,truncated: { kind: 'tail_window', pipeline, processed_chars: window.length, total_chars: tail.length } };}+/**+ * planExtraction over a segmented page's compiled truth (the trusted stored text readPageSnapshot gives an inline+ * page), read segment by segment: the same plan, holding at most the head, the newest 2 x `cap` characters of the+ * tail and one segment. O(page) work, O(segment) memory.+ */+export async function planSegmentedExtraction(engine: BrainEngine, pageId: number, stored: StoredWatermark | null,+ opts: { cap: number; pipeline: ExtractionPipeline; emptyTail: 'skip' | 'head' }): Promise<ExtractionPlan> {+ const { cap, pipeline } = opts;+ const body = await openSegmentedBody(engine, { pageId });+ const offset = stored && stored.pipelineVersion === EXTRACTION_PIPELINE_VERSION[pipeline] ? stored.bytes : null;+ const whole = createHash('sha256');+ const prefix = createHash('sha256');+ const decoder = new TextDecoder();+ const tailDecoder = new TextDecoder();+ let bytes = 0, chars = 0, tailChars = 0, head = '', tail = '', tailText = false;+ let boundary: number | undefined;+ const collect = readGarbageCollector();+ for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: Infinity, audience: 'trusted', region: 'truth', body })) {+ const buf = piece.bytes;+ collect(buf.length);+ whole.update(buf);+ const text = decoder.decode(buf, { stream: true });+ chars += text.length;+ if (head.length <= cap) head += text.slice(0, cap + 1 - head.length);+ if (offset !== null) {+ const split = Math.max(0, Math.min(buf.length, offset - bytes));+ if (split > 0) prefix.update(buf.subarray(0, split));+ if (offset >= bytes && offset < bytes + buf.length) boundary = buf[offset - bytes];+ const after = tailDecoder.decode(buf.subarray(split), { stream: true });+ tailChars += after.length;+ tailText ||= after.trim().length > 0;+ tail = (tail + after).slice(-2 * cap);+ }+ bytes += buf.length;+ }+ const next = { bytes, sha256: whole.digest('hex') };+ if (chars <= cap) return { pipeline, mode: 'full', text: head, truncated: null, next };+ const headPlan = (reason: HeadFallbackReason): ExtractionPlan => ({ pipeline, mode: 'head', text: truncateUtf8(head, cap), next,+ truncated: { kind: 'head', pipeline, processed_chars: cap, total_chars: chars, reason } });+ if (!stored) return headPlan('no_watermark');+ if (offset === null) return headPlan('version_changed');+ const onBoundary = offset === bytes || (offset < bytes && boundary !== undefined && (boundary & 0xc0) !== 0x80);+ if (offset > bytes || !onBoundary || prefix.digest('hex') !== stored.sha256) return headPlan('prefix_changed');+ if (!tailText) return opts.emptyTail === 'skip' ? { pipeline, mode: 'tail', text: '', truncated: null, next } : headPlan('no_new_text');+ if (tailChars <= cap) return { pipeline, mode: 'tail', text: tail, truncated: null, next };+ const window = newestWindow(tail, cap);+ return { pipeline, mode: 'tail', text: window, next, truncated: { kind: 'tail_window', pipeline, processed_chars: window.length, total_chars: tailChars } };+}+let warnedStorage = false;function warnStorageOnce(action: string, error: unknown): void {if (warnedStorage) return;diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 359c5ec74e..f2d0c4b70a 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -61,7 +61,7 @@ import { intentContentOrigin } from '../trust/channel.ts';import { readTaintInputs, derivedWriteTrust, recordTaintEdges } from '../trust/taint.ts';import { applyGateDecision, derivedGateConfig, derivedGateInput, emptyGateTally, type GateTally } from '../trust/derived-gate.ts';import { decideFactWrite } from '../write-gate-store.ts';-import { commitExtractionPlan, planExtraction, readPageWatermark, type InputTruncated } from '../extraction-watermark.ts';+import { commitExtractionPlan, planExtraction, planSegmentedExtraction, readPageWatermark, type InputTruncated } from '../extraction-watermark.ts';// The notability-filter vocabulary lives in notability-filter.ts; re-exported for existing importers.export { NOTABILITY_FILTERS, coerceNotabilityFilter, type FactNotabilityFilter } from './notability-filter.ts';@@ -199,8 +199,10 @@ interface PipelineResult { inserted: number; duplicate: number; superseded: numbinterface ParsedPageInput {slug: string;type: PageType;+ /** A segmented page's (`segmentedPageId`) lead: what eligibility reads; the extraction plan reads its segments. */compiled_truth: string;frontmatter: Record<string, unknown>;+ segmentedPageId?: number;}/** k for findCandidateDuplicates — ceiling on candidates considered. */@@ -578,11 +580,15 @@ async function runPipeline(// tail; without a usable one it reads the head and the receipt says so.const { MAX_TURN_TEXT_CHARS } = await import('./extract.ts');const { pageId, stored } = await readPageWatermark(ctx.engine, ctx.sourceId, parsedPage.slug, 'facts_backstop');- const plan = planExtraction(parsedPage.compiled_truth, stored, { cap: MAX_TURN_TEXT_CHARS, pipeline: 'facts_backstop', emptyTail: 'skip' });+ // A segmented page is planned over its segments; its whole body is never one string, so the turn text is the plan's.+ const planOpts = { cap: MAX_TURN_TEXT_CHARS, pipeline: 'facts_backstop', emptyTail: 'skip' } as const;+ const plan = parsedPage.segmentedPageId !== undefined+ ? await planSegmentedExtraction(ctx.engine, parsedPage.segmentedPageId, stored, planOpts)+ : planExtraction(parsedPage.compiled_truth, stored, planOpts);if (!plan.text) return { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [] };const result = await runPipelineWithBody({- turnText: parsedPage.compiled_truth,+ turnText: parsedPage.segmentedPageId !== undefined ? plan.text : parsedPage.compiled_truth,...(plan.mode === 'full' ? {} : { extractText: plan.text }),isDreamGenerated: false, // eligibility check already rejected dream pagesref: parsedPage.slug,diff --git a/src/core/link-effective.ts b/src/core/link-effective.tsindex 499d839eba..b506735fd1 100644--- a/src/core/link-effective.ts+++ b/src/core/link-effective.ts@@ -11,7 +11,7 @@* are already exact days (line-grammar.ts resolves `[ ]` / `( )`), so the* precision is 'day'. Grammar: docs/guides/line-grammar.md.*/-import { parseLineGrammar } from './line-grammar.ts';+import { parseLineGrammar, type GrammarRelation } from './line-grammar.ts';import { lineHash, normalizeLinkTarget, refersTo, type DerivedTransition, type OwnedRow, type TemporalEvidence } from './link-temporal-evidence.ts';import { relationSemantics } from './link-validity.ts';@@ -19,14 +19,27 @@ export type InlineTransition = Omit<DerivedTransition, 'producer'> & { producer:const LINK_RE = /\[\[([^\]|\n]+)(?:\|[^\]\n]*)?\]\]|\[[^\]\n]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/;+/** A typed relation line with a validity range: its type, range, trimmed text and offset in the body. */+export interface RangedRelationLine { type: string; effective: NonNullable<GrammarRelation['effective']>; line: string; start: number }++export function rangedRelationLines(content: string): RangedRelationLine[] {+ return parseLineGrammar(content).relations.flatMap(relation => relation.effective+ ? [{ type: relation.type, effective: relation.effective, line: content.slice(relation.start, relation.end).trim(), start: relation.start }] : []);+}+export function inlineTransitions(slug: string, content: string, rows: readonly OwnedRow[]): {transitions: InlineTransition[]; unmatched: TemporalEvidence['unmatched'];+} {+ return inlineTransitionsFrom(slug, rangedRelationLines(content), rows);+}++export function inlineTransitionsFrom(slug: string, relations: readonly RangedRelationLine[], rows: readonly OwnedRow[]): {+ transitions: InlineTransition[]; unmatched: TemporalEvidence['unmatched'];} {const transitions: InlineTransition[] = [];const unmatched: TemporalEvidence['unmatched'] = [];- for (const relation of parseLineGrammar(content).relations) {- if (!relation.effective) continue;- const line = content.slice(relation.start, relation.end).trim();+ for (const relation of relations) {+ const line = relation.line;const semantics = relationSemantics(relation.type);if (semantics === 'reference') { unmatched.push({ line, reason: 'not_temporal' }); continue; }const link = LINK_RE.exec(line);diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex c223b1a701..3ee367b6a4 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -405,8 +405,14 @@ export function extractCodeRefs(content: string): CodeRef[] {* are excluded — those are typically code samples, not real entity references.*/export function extractEntityRefs(content: string): EntityRef[] {+ return entityRefPasses(content).flat();+}++/** extractEntityRefs' refs per pass (markdown, same-dir markdown, qualified, unqualified and generic wikilinks), each pass in text order. */+export function entityRefPasses(content: string): EntityRef[][] {const stripped = stripCodeBlocks(content);- const refs: EntityRef[] = [];+ const passes: EntityRef[][] = [[], [], [], [], []];+ let refs = passes[0];let match: RegExpExecArray | null;// 1. Markdown links: [Name](path)@@ -451,6 +457,7 @@ export function extractEntityRefs(content: string): EntityRef[] {// the page's dir. A `../dir/x.md` span pass 1 already claimed is skipped// so the two passes never double-emit.const sameDirPattern = new RegExp(SAME_DIR_MD_RE.source, SAME_DIR_MD_RE.flags);+ refs = passes[1];while ((match = sameDirPattern.exec(stripped)) !== null) {const at = match.index;if (markdownRanges.some(([s, e]) => at >= s && at < e)) continue;@@ -472,6 +479,7 @@ export function extractEntityRefs(content: string): EntityRef[] {// mask out the matched spans so pass 2b can't grab them.const qualifiedRanges: Array<[number, number]> = [];const qualPattern = new RegExp(QUALIFIED_WIKILINK_RE.source, QUALIFIED_WIKILINK_RE.flags);+ refs = passes[2];while ((match = qualPattern.exec(stripped)) !== null) {const sourceId = match[1];let slug = stripEscapedPipeTail(match[2].trim());@@ -489,6 +497,7 @@ export function extractEntityRefs(content: string): EntityRef[] {const unqualifiedRanges: Array<[number, number]> = [];const unmasked = maskRanges(stripped, qualifiedRanges);const wikiPattern = new RegExp(WIKILINK_RE.source, WIKILINK_RE.flags);+ refs = passes[3];while ((match = wikiPattern.exec(unmasked)) !== null) {let slug = stripEscapedPipeTail(match[1].trim());if (!slug) continue;@@ -520,6 +529,7 @@ export function extractEntityRefs(content: string): EntityRef[] {[...markdownRanges, ...qualifiedRanges, ...unqualifiedRanges, ...labelWikilinkRanges],);const genericPattern = new RegExp(WIKILINK_GENERIC_RE.source, WIKILINK_GENERIC_RE.flags);+ refs = passes[4];while ((match = genericPattern.exec(genericMasked)) !== null) {let slug = stripEscapedPipeTail(match[1].trim());if (!slug) continue;@@ -531,7 +541,7 @@ export function extractEntityRefs(content: string): EntityRef[] {refs.push({ name: displayName, slug, dir, needsResolution: true, index: match.index });}- return refs;+ return passes;}/**@@ -668,6 +678,12 @@ export interface ExtractPageLinksOptions {onResolvedFrontmatterTarget?: (slug: string) => void;/** Receives every body-link typing decision with its reasons (explainLinkType, development reports). */explain?: (e: LinkTypeExplanation) => void;+ /** The text the page-role priors read (default: the content); a streamed page passes its role phrases (rolePriorPhrases). */+ roleText?: string;+ /** The page's pack-regex budget, shared by the windows of a streamed page. */+ regexBudget?: PageRegexBudget;+ /** extractBodyLinks: extract only references starting in content[start, end), shifting offsets by `offset`. */+ window?: { start: number; end: number; offset: number };}/** The authored reference of a wikilink at `idx`: a slug path, or a bare name keyed by its basename. */@@ -713,7 +729,7 @@ function makeTypeFor(content: string, pageType: PageType, opts: ExtractPageLinks// `link_types[].inference.regex` (e.g. parent_of) was silently ignored// here and every such edge landed as 'mentions'.const pack = opts.pack ?? null;- const packBudget = pack ? new PageRegexBudget() : undefined;+ const packBudget = pack ? opts.regexBudget ?? new PageRegexBudget() : undefined;const packOwnsAttendance = ownsAttendanceInference(pack);// Timeline / See-also links never receive the page-role prior — see// rolePriorSuppressedRanges (matched on the code-stripped content, so a@@ -754,8 +770,9 @@ function makeTypeFor(content: string, pageType: PageType, opts: ExtractPageLinksreturn decide('mentions', { rule: 'page.meeting' });}const suppressPrior = idx !== undefined && idx >= 0 && inSuppressedRange(suppressedRanges, idx);- const trace = traceLinkType(pageType, ctx, suppressPrior ? undefined : content, targetSlug,- opts.targetType ? targetType ?? null : undefined, bodyReference && idx !== undefined && idx >= 0 ? excerptAnchor(content, idx, 240) : undefined, content, !!explain);+ const roleText = opts.roleText ?? content;+ const trace = traceLinkType(pageType, ctx, suppressPrior ? undefined : roleText, targetSlug,+ opts.targetType ? targetType ?? null : undefined, bodyReference && idx !== undefined && idx >= 0 ? excerptAnchor(content, idx, 240) : undefined, roleText, !!explain);const { type, ...why } = trace;if (pack?.link_types.some(lt => lt.name === type && (lt.inference?.page_type || lt.inference?.target_type))) return decide('mentions', { ...why, packRule: type });return decide(type, why);@@ -800,16 +817,37 @@ export async function extractPageLinks(resolver: SlugResolver,opts: ExtractPageLinksOptions = {},): Promise<PageLinksResult> {- const candidates: LinkCandidate[] = [];+ const body = await extractBodyLinks(slug, content, pageType, resolver, opts);+ const fm = await frontmatterLinks(slug, frontmatter, pageType, resolver, opts);+ return { candidates: dedupeCandidates([...body.links.map(link => link.candidate), ...fm.candidates]), unresolved: fm.unresolved,+ attendanceComplete: body.attendanceComplete && fm.attendanceComplete };+}++/** A body reference's candidate, with its extraction pass (entityRefPasses' five, then 5 for bare paths) and its offset in the page. */+export interface BodyLinkCandidate { pass: number; index: number; candidate: LinkCandidate }++/**+ * extractPageLinks' body candidates (markdown refs, wikilinks, bare slug paths) in extraction order, undeduplicated.+ * With `opts.window`, only references starting inside `content[start, end)` are extracted, and their offsets+ * (`index`, authored-ref keys) are shifted by `offset` into the page's coordinates.+ */+export async function extractBodyLinks(slug: string, content: string, pageType: PageType, resolver: SlugResolver,+ opts: ExtractPageLinksOptions = {}): Promise<{ links: BodyLinkCandidate[]; attendanceComplete: boolean }> {+ const links: BodyLinkCandidate[] = [];+ const shift = opts.window?.offset ?? 0;+ const inWindow = (idx: number) => !opts.window || (idx >= opts.window.start && idx < opts.window.end);+ let pass = 0;+ const candidates = { push: (candidate: LinkCandidate, idx: number) => links.push({ pass, index: idx + shift, candidate }) };- const pack = opts.pack ?? null;const attendancePending = new Set<number>();const attendanceResolved = new Set<number>();const attendanceAmbiguous = new Set<number>();const typeFor = makeTypeFor(content, pageType, opts, attendancePending, attendanceResolved);// 1. Markdown entity refs.- for (const ref of extractEntityRefs(content)) {+ for (const [refPass, refs] of entityRefPasses(content).entries()) for (const ref of refs) {+ pass = refPass;+ if (!inWindow(ref.index!)) continue;// #3190: same-directory markdown link — resolve against THIS page's// directory (the FS path's resolveSlug does exactly this via// join(fileDir, target)). Slugified through the sync grammar so@@ -825,8 +863,8 @@ export async function extractPageLinks(...typeFor(context, target, idx),context,linkSource: 'markdown',- authoredRef: { key: `ref:${idx}`, kind: 'slug', target },- });+ authoredRef: { key: `ref:${idx + shift}`, kind: 'slug', target },+ }, idx);}continue;}@@ -856,8 +894,8 @@ export async function extractPageLinks(...typeFor(litContext, ref.slug, litIdx),context: litContext,linkSource: 'markdown',- authoredRef: { key: `ref:${litIdx}`, kind: 'slug', target: ref.slug },- });+ authoredRef: { key: `ref:${litIdx + shift}`, kind: 'slug', target: ref.slug },+ }, litIdx);}// #4062: a bare `[[name]]` (no slash) gets a direct verb-typed// candidate for its root-exact slugified form, emitted regardless of@@ -915,12 +953,12 @@ export async function extractPageLinks(const uniquePerson = personTargets.length === 1;if (pageType === 'meeting' && opts.targetType && !uniquePerson&& targets.filter(target => opts.targetType!(target) !== undefined).length > 1) attendanceAmbiguous.add(idx);- const authoredRef = wikilinkAuthoredRef(ref.slug, idx);+ const authoredRef = wikilinkAuthoredRef(ref.slug, idx + shift);for (const target of bareDirect) {const inferred = typeFor(context, target, idx);candidates.push({ targetSlug: target,...(inferred.canonicalAttendance && !uniquePerson ? { linkType: 'mentions' } : inferred),- context, linkSource: 'markdown', ...(authoredRef ? { authoredRef } : {}) });+ context, linkSource: 'markdown', ...(authoredRef ? { authoredRef } : {}) }, idx);}for (const matched of matches) {const inferred = typeFor(context, matched, idx);@@ -930,7 +968,7 @@ export async function extractPageLinks(context,linkSource: 'wikilink-resolved',...(authoredRef ? { authoredRef } : {}),- });+ }, idx);}continue;}@@ -956,8 +994,8 @@ export async function extractPageLinks(...typeFor(context, targetSlug, idx, ref.sourceId ?? undefined),context,linkSource: 'markdown',- authoredRef: { key: `ref:${idx}`, kind: 'slug', target: targetSlug, ...(ref.sourceId ? { targetSourceId: ref.sourceId } : {}) },- });+ authoredRef: { key: `ref:${idx + shift}`, kind: 'slug', target: targetSlug, ...(ref.sourceId ? { targetSourceId: ref.sourceId } : {}) },+ }, idx);}// 2. Bare slug references (e.g. "see people/alice-chen for context").@@ -979,7 +1017,9 @@ export async function extractPageLinks('g',);let m: RegExpExecArray | null;+ pass = 5;while ((m = bareRe.exec(strippedContent)) !== null) {+ if (!inWindow(m.index)) continue;// Skip matches that are part of a markdown link (already handled above).const charBefore = m.index > 0 ? strippedContent[m.index - 1] : '';if (charBefore === '/' || charBefore === '(') continue;@@ -992,9 +1032,14 @@ export async function extractPageLinks(...(inferred.canonicalAttendance ? { linkType: 'mentions' } : inferred),context,linkSource: 'markdown',- });+ }, m.index);}+ return { links, attendanceComplete: [...attendancePending].every(index => attendanceResolved.has(index) && !attendanceAmbiguous.has(index)) };+}+/** extractPageLinks' frontmatter-derived candidates; none with `skipFrontmatter`. */+export async function frontmatterLinks(slug: string, frontmatter: Record<string, unknown>, pageType: PageType, resolver: SlugResolver,+ opts: ExtractPageLinksOptions = {}): Promise<Pick<PageLinksResult, 'candidates' | 'unresolved' | 'attendanceComplete'>> {// 3. Frontmatter-derived edges (v0.13). Includes the legacy `source:`// field along with the full field map. Caller can suppress via// `opts.skipFrontmatter` — used by `extractLinksFromDB` to keep@@ -1003,23 +1048,18 @@ export async function extractPageLinks(// mode). Pre-issue-#972 this gating lived in the caller via a// synthetic `nullResolver`; that pattern broke once the bare-wikilink// path needed `resolveBasenameMatches` on the real resolver.- let fmUnresolved: UnresolvedFrontmatterRef[] = [];- let frontmatterAttendanceComplete = true;- if (!opts.skipFrontmatter) {- const fm = await extractFrontmatterLinks(slug, pageType, frontmatter, resolver, opts.globalBasename, pack, opts.targetType,- opts.onResolvedFrontmatterTarget);- candidates.push(...fm.candidates);- fmUnresolved = fm.unresolved;- frontmatterAttendanceComplete = fm.attendanceComplete;- }+ if (opts.skipFrontmatter) return { candidates: [], unresolved: [], attendanceComplete: true };+ const fm = await extractFrontmatterLinks(slug, pageType, frontmatter, resolver, opts.globalBasename, opts.pack ?? null, opts.targetType,+ opts.onResolvedFrontmatterTarget);+ return { candidates: fm.candidates, unresolved: fm.unresolved, attendanceComplete: fm.attendanceComplete };+}- const result = dedupeCandidates(candidates);- return { candidates: result, unresolved: fmUnresolved,- attendanceComplete: [...attendancePending].every(index => attendanceResolved.has(index) && !attendanceAmbiguous.has(index))- && frontmatterAttendanceComplete };+/** The within-page dedup key: candidates sharing it collapse to the first. */+export function candidateKey(c: LinkCandidate): string {+ return `${c.fromSlug ?? ''}\u0000${c.targetSourceId ?? ''}\u0000${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? ''}\u0000${c.canonicalAttendance ?? false}`;}-function dedupeCandidates(candidates: LinkCandidate[]): LinkCandidate[] {+export function dedupeCandidates(candidates: LinkCandidate[]): LinkCandidate[] {// Within-page dedup: same (fromSlug, targetSlug, linkType, linkSource)// collapses to one entry. First occurrence wins.// Issue #972 (codex P2d, decided): a qualified `[[companies/acme]]` (typed@@ -1031,7 +1071,7 @@ function dedupeCandidates(candidates: LinkCandidate[]): LinkCandidate[] {const seen = new Set<string>();const result: LinkCandidate[] = [];for (const c of candidates) {- const key = `${c.fromSlug ?? ''}\u0000${c.targetSourceId ?? ''}\u0000${c.targetSlug}\u0000${c.linkType}\u0000${c.linkSource ?? ''}\u0000${c.canonicalAttendance ?? false}`;+ const key = candidateKey(c);if (seen.has(key)) continue;seen.add(key);result.push(c);@@ -1296,6 +1336,11 @@ const ADVISOR_ROLE_RE = /\b(?:full-time advisor|professional advisor|advises (?://// Scope: only fires for person-page → company-page links. Companies' own// pages mentioning their employees use the page-role layer differently.+/** The first match of each page-role prior in `text`: joined with newlines, they decide every prior exactly as the whole text does (no prior crosses a line). */+export function rolePriorPhrases(text: string): Array<string | null> {+ return [PARTNER_ROLE_RE, ADVISOR_ROLE_RE, EMPLOYEE_ROLE_RE].map(re => re.exec(text)?.[0] ?? null);+}+const EMPLOYEE_ROLE_RE = /\b(?:is an? (?:senior|staff|principal|lead|backend|frontend|full-?stack|ML|data|security|DevOps|platform)? ?engineer at|is an? (?:senior|staff|principal|lead)? ?(?:developer|designer|product manager|engineering manager|director|VP) (?:at|of)|holds? the (?:CTO|CEO|CFO|COO|CMO|CRO|VP) (?:role|position|seat|title) at|is the (?:CTO|CEO|CFO|COO|CMO|CRO) of|employee at|on the team at|works on .{0,30} at)\b/i;diff --git a/src/core/link-reconciliation.ts b/src/core/link-reconciliation.tsindex 623eeaffe8..968ad105f5 100644--- a/src/core/link-reconciliation.ts+++ b/src/core/link-reconciliation.ts@@ -1,6 +1,6 @@import type { BrainEngine, LinkBatchInput } from './engine.ts';import { extractPageLinks, unwrapWikilink, resolvedLinkCandidate,- isCrossSourceLinksEnabled, type LinkCandidate, type LinkExtractionPack, type SlugResolver } from './link-extraction.ts';+ isCrossSourceLinksEnabled, type LinkCandidate, type LinkExtractionPack, type PageLinksResult, type SlugResolver } from './link-extraction.ts';import { fetchSource, isSourceFederated } from './sources-load.ts';import { parseMarkdown } from './markdown.ts';import { isValidSourceId } from './source-id.ts';@@ -9,6 +9,8 @@ import { collectWantedLinks, isWantedPagesEnabled } from './wanted-links.ts';import { readLineGrammarSettings } from './line-grammar.ts';import { DerivedLinkSettingsChangedError } from './derived-links.ts';import { isSegmentedPage } from './page-body/page-shape.ts';+import { extractSegmentedPageLinks } from './page-body/segment-links.ts';+import type { TemporalBody } from './link-temporal-apply.ts';export interface LinkPageMetadata {slug: string;@@ -93,18 +95,17 @@ export async function reconcileSourceLinks(return result;}const page = snapshot.page;- if (isSegmentedPage(page)) {- result.failures.push({ originSlug, code: 'page_body_segmented' });- result.nextAfterSlug = page.slug;- continue;- }const sourcesOf = makeLinkSourceResolver(page.slug, sourceId, endpoints, policy);- const extracted = await extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,- page.type, resolver, { pack: opts.pack, globalBasename: opts.globalBasename, lineGrammar,- targetType: (slug, source) => {- const resolved = sourcesOf.resolve({ targetSlug: slug, targetSourceId: source, linkType: '', context: '' });- return resolved.ok ? metadata.get(`${resolved.toSourceId}\0${slug}`)?.type : undefined;- } });+ const linkOpts = { pack: opts.pack, globalBasename: opts.globalBasename, lineGrammar,+ targetType: (slug: string, source?: string) => {+ const resolved = sourcesOf.resolve({ targetSlug: slug, targetSourceId: source, linkType: '', context: '' });+ return resolved.ok ? metadata.get(`${resolved.toSourceId}\0${slug}`)?.type : undefined;+ } };+ // A segmented body is read block by block, and its temporal inputs with it (the publication never reads it).+ const extracted: PageLinksResult & { temporalBody?: TemporalBody } = isSegmentedPage(page)+ ? await extractSegmentedPageLinks(engine, { id: Number(page.id), slug: page.slug, source_id: sourceId, type: page.type, frontmatter: page.frontmatter },+ resolver, { ...linkOpts, temporal: true })+ : await extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter, page.type, resolver, linkOpts);for (const ref of extracted.unresolved) {const target = unwrapWikilink(ref.name);const qualifier = target.split(':')[0];@@ -130,7 +131,8 @@ export async function reconcileSourceLinks(try {written = await engine.replaceDerivedLinks({ slug: page.slug, sourceId,expectedRevision: snapshot.revision, sourceIncarnation }, rows, { lineGrammar: grammar,- wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints: capturedLinkEndpoints(rows, metadata) });+ wanted: { producers: ['body', 'frontmatter'], rows: wanted }, expectedEndpoints: capturedLinkEndpoints(rows, metadata),+ ...(extracted.temporalBody ? { temporalBody: extracted.temporalBody } : {}) });} catch (error) {if (!(error instanceof DerivedLinkSettingsChangedError)) throw error;result.failures.push({ originSlug, code: 'revision_conflict' });diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.tsindex b2a1b18465..90a05351e7 100644--- a/src/core/link-temporal-apply.ts+++ b/src/core/link-temporal-apply.ts@@ -16,16 +16,25 @@import type { BrainEngine, LinkBatchInput } from './engine.ts';import type { Page } from './types.ts';import { executeRawJsonb } from './sql-query.ts';-import { deriveTemporalEvidence, rowKey, type TemporalEvidence } from './link-temporal-evidence.ts';+import { datedLines, deriveTemporalEvidence, narrativeRefs, rowKey, temporalEvidenceFrom, type TemporalEvidence, type TemporalInputs } from './link-temporal-evidence.ts';import { refreshRelationships, type RelationshipKey } from './link-relationships.ts';import { temporalLinkTypes } from './link-validity.ts';-import { inlineTransitions } from './link-effective.ts';+import { inlineTransitions, inlineTransitionsFrom, rangedRelationLines, type RangedRelationLine } from './link-effective.ts';import { pipelined } from './page-state/transactions.ts';type Tx = Pick<BrainEngine, 'executeRaw'>;const DERIVED_PRODUCERS = ['timeline', 'explicit', 'frontmatter', 'dream', 'inline'];+/** What the evidence reads from the page body, collected outside the transaction (a segmented page's body is not read here). */+export interface TemporalBody extends TemporalInputs { ranged: RangedRelationLine[] }++/** The TemporalBody of a body held as strings. */+export function temporalBodyOf(page: { compiled_truth: string; timeline?: string | null }): TemporalBody {+ const content = `${page.compiled_truth}\n${page.timeline ?? ''}`;+ return { lines: datedLines(content), narrative: narrativeRefs(page.compiled_truth), ranged: rangedRelationLines(content) };+}+export interface TemporalApplyResult {transitions: number;refreshed: number;@@ -50,17 +59,18 @@ export async function applyTemporalEvidence(page: Pick<Page, 'id' | 'slug' | 'source_id' | 'compiled_truth' | 'timeline' | 'frontmatter'>,rows: readonly LinkBatchInput[],keysBefore: readonly RelationshipKey[],- opts: { inlineRanges?: boolean } = {},+ opts: { inlineRanges?: boolean; body?: TemporalBody } = {},): Promise<TemporalApplyResult> {const pageId = Number(page.id);const sourceId = page.source_id ?? 'default';- const evidence = deriveTemporalEvidence({- slug: page.slug, compiled_truth: page.compiled_truth ?? '', timeline: page.timeline ?? '',- frontmatter: (page.frontmatter ?? {}) as Record<string, unknown>,- }, rows.map(r => ({ from_slug: r.from_slug, to_slug: r.to_slug, link_type: r.link_type, link_source: r.link_source ?? 'markdown', origin_field: r.origin_field ?? null })));- const inline = opts.inlineRanges- ? inlineTransitions(page.slug, `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`, rows.filter(r => (r.link_source ?? 'markdown') !== 'frontmatter'))- : { transitions: [], unmatched: [] };+ const owned = rows.map(r => ({ from_slug: r.from_slug, to_slug: r.to_slug, link_type: r.link_type, link_source: r.link_source ?? 'markdown', origin_field: r.origin_field ?? null }));+ const frontmatter = (page.frontmatter ?? {}) as Record<string, unknown>;+ const evidence = opts.body ? temporalEvidenceFrom({ slug: page.slug, frontmatter }, opts.body, owned)+ : deriveTemporalEvidence({ slug: page.slug, compiled_truth: page.compiled_truth ?? '', timeline: page.timeline ?? '', frontmatter }, owned);+ const bodyRows = rows.filter(r => (r.link_source ?? 'markdown') !== 'frontmatter');+ const inline = !opts.inlineRanges ? { transitions: [], unmatched: [] }+ : opts.body ? inlineTransitionsFrom(page.slug, opts.body.ranged, bodyRows)+ : inlineTransitions(page.slug, `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`, bodyRows);const transitions = [...evidence.transitions, ...inline.transitions];const tenseRows = rows.filter(r => evidence.tense.has(rowKey(r))).map(r => ({diff --git a/src/core/link-temporal-evidence.ts b/src/core/link-temporal-evidence.tsindex c8d1c2b4b6..3f3e189c65 100644--- a/src/core/link-temporal-evidence.ts+++ b/src/core/link-temporal-evidence.ts@@ -172,9 +172,10 @@ const EXPLICIT_RE = /\b(Started|Ended)\s+([a-z][a-z0-9_]*)\s+(?:\[\[([^\]|\n]+)(const isRelationToken = (token: string) => token.includes('_') || KNOWN_LINK_TYPES.has(token) || relationSemantics(token) !== 'reference';const hasExplicit = (text: string) => [...text.matchAll(EXPLICIT_RE)].some(m => isRelationToken(m[2]));-interface DatedLine { date: string; text: string; dream: boolean }+export interface DatedLine { date: string; text: string; dream: boolean }-function datedLines(content: string): DatedLine[] {+/** The dated timeline lines of `content` outside code fences. */+export function datedLines(content: string): DatedLine[] {const out: DatedLine[] = [];let fence = false;for (const line of content.split('\n')) {@@ -201,12 +202,35 @@ export interface PageForEvidence {/** Receives each derived transition with the stable id of the cue that produced it (`cue.*`, `unit.*`). */export type TransitionExplainer = (t: DerivedTransition, rule: string) => void;+/**+ * What temporal evidence reads from a page body: the dated lines of the joined body and every reference in the+ * compiled truth outside dated lines, with the clause before it. A segmented page collects them block by block.+ */+export interface TemporalInputs { lines: DatedLine[]; narrative: NarrativeRef[] }+export interface NarrativeRef { target: string; window: string }++/** The references of a compiled-truth text outside dated lines, each with the clause before it (windowBefore). */+export function narrativeRefs(truth: string): NarrativeRef[] {+ const narrative = stripDatedLines(truth);+ let prevEnd = 0;+ return referencesIn(narrative).map(ref => {+ const window = windowBefore(narrative, ref.index, prevEnd);+ prevEnd = ref.index + 2;+ return { target: ref.target, window };+ });+}+export function deriveTemporalEvidence(page: PageForEvidence, rows: readonly OwnedRow[], explain?: TransitionExplainer): TemporalEvidence {+ return temporalEvidenceFrom(page, { lines: datedLines(`${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`), narrative: narrativeRefs(page.compiled_truth ?? '') },+ rows, explain);+}++export function temporalEvidenceFrom(page: Pick<PageForEvidence, 'slug' | 'frontmatter'>, inputs: TemporalInputs, rows: readonly OwnedRow[],+ explain?: TransitionExplainer): TemporalEvidence {const tense = new Map<string, AssertionTense>();const transitions: DerivedTransition[] = [];const unmatched: TemporalEvidence['unmatched'] = [];- const content = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;- const lines = datedLines(content);+ const { lines } = inputs;const temporalRows = rows.filter(r => relationSemantics(r.link_type) !== 'reference');const other = (r: OwnedRow) => (r.from_slug === page.slug ? r.to_slug : r.from_slug);const seen = new Set<string>();@@ -301,16 +325,12 @@ export function deriveTemporalEvidence(page: PageForEvidence, rows: readonly Own}// 4. Tense of each owned assertion row, from compiled-truth mentions only.- const narrative = stripDatedLines(page.compiled_truth ?? '');- const narrativeRefs = referencesIn(narrative);for (const r of temporalRows) {const cues = relationSemantics(r.link_type) === 'state' ? cuesFor(r.link_type!) : null;if (!cues) { if (relationSemantics(r.link_type) === 'state') tense.set(rowKey(r), 'present'); continue; }- let past = 0, present = 0, prevEnd = 0;- for (const ref of narrativeRefs) {- const window = windowBefore(narrative, ref.index, prevEnd);- prevEnd = ref.index + 2;- if (!refersTo(ref.target, other(r))) continue;+ let past = 0, present = 0;+ for (const { target, window } of inputs.narrative) {+ if (!refersTo(target, other(r))) continue;if (cues.past.test(window) || cues.end.test(window)) past++; else present++;}tense.set(rowKey(r), past > 0 && present === 0 && r.link_source !== 'frontmatter' ? 'past' : 'present');diff --git a/src/core/mentions/pass.ts b/src/core/mentions/pass.tsindex 233ab49829..3c619d3ade 100644--- a/src/core/mentions/pass.ts+++ b/src/core/mentions/pass.ts@@ -39,9 +39,12 @@* MENTION_EXTRACTOR_VERSION is separate from LINK_EXTRACTOR_VERSION_TS, so a* gazetteer change never reruns link or timeline extraction.*- * A segmented page (body in segments, NULL body columns) is never scanned:- * mentions derived from its title alone would delete the ones its body holds.- * It stays due, and counted as pending, until the per-segment pass.+ * 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+ * marks every segmented page in scope due (no SQL prefilter reads its body).+ * Derived aliases are still refreshed for inline entity pages only.*/import { createHash } from 'node:crypto';@@ -50,8 +53,9 @@ import { pipelined } from '../page-state/transactions.ts';import { isCrossSourceLinksEnabled } from '../link-extraction.ts';import {buildGazetteer, findMentionedEntities, gazetteerEntryKeys, tokenizeTitle,- type Gazetteer, type GazetteerEntry, type GazetteerEntryKey,+ type FindMentionsOpts, type Gazetteer, type GazetteerEntry, type GazetteerEntryKey, type Mention,} from '../by-mention.ts';+import { bodyBlocks } from '../page-body/segment-blocks.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';@@ -232,7 +236,24 @@ async function disableSource(engine: BrainEngine, managed: boolean, sourceId: st}interface 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 }+ 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. */+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[]> {+ if (p.body_storage !== 'segmented') {+ return (p.title || p.compiled_truth || p.timeline) ? findMentionedEntities(`${p.title ?? ''}\n\n${p.compiled_truth ?? ''}\n\n${p.timeline ?? ''}`, gazetteer, opts) : [];+ }+ 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(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);+ return [...found.values()];+}/** Alias derivation options from the mention policy (`mentions.alias_deny`, `mentions.multiword_aliases`). */export function aliasOptsOf(policy: Pick<MentionPolicy, 'aliasDeny' | 'multiwordAliases'>): { deny: string[]; multiword: boolean } {@@ -324,16 +345,17 @@ async function pagesMatchingNames(engine: BrainEngine, sourceIds: string[], addeconst out: number[] = [];let after = 0;for (;;) {- const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string; body: string; mention_ignore: unknown }>(- `SELECT id, slug, source_id, COALESCE(title, '') || E'\\n\\n' || COALESCE(compiled_truth, '') || E'\\n\\n' || COALESCE(timeline, '') AS body,+ const rows = await engine.executeRaw<{ id: number; slug: string; source_id: string; body_storage: string; body: string; mention_ignore: unknown }>(+ `SELECT id, slug, source_id, body_storage, COALESCE(title, '') || E'\\n\\n' || COALESCE(compiled_truth, '') || E'\\n\\n' || COALESCE(timeline, '') AS body,frontmatter->'mention_ignore' AS mention_ignore- FROM pages WHERE deleted_at IS NULL AND body_storage = 'inline' AND source_id = ANY($1::text[]) AND id > $2- ${ascii ? `AND lower(COALESCE(title, '') || ' ' || COALESCE(compiled_truth, '') || ' ' || COALESCE(timeline, '')) LIKE ANY($4::text[])` : ''}+ FROM pages WHERE deleted_at IS NULL AND source_id = ANY($1::text[]) AND id > $2+ ${ascii ? `AND (body_storage = 'segmented' OR lower(COALESCE(title, '') || ' ' || COALESCE(compiled_truth, '') || ' ' || COALESCE(timeline, '')) LIKE ANY($4::text[]))` : ''}ORDER BY id LIMIT $3`,ascii ? [sourceIds, after, PREFILTER_BATCH, patterns] : [sourceIds, after, PREFILTER_BATCH]);if (!rows.length) break;after = rows[rows.length - 1]!.id;for (const r of rows) {+ if (r.body_storage === 'segmented') { out.push(Number(r.id)); continue; }const hits = findMentionedEntities(r.body, added, { fromSlug: r.slug, fromSourceId: r.source_id, allowCrossSource });if (hits.length) out.push(Number(r.id));}@@ -432,17 +454,15 @@ async function reconcileSource(engine: BrainEngine, sourceId: string, gazetteer:if (Date.now() > deadline) return;const pages = await engine.executeRaw<DuePage>(`SELECT p.id, p.slug, p.source_id, p.knowledge_revision::text AS revision, p.title, p.type, p.compiled_truth, p.timeline,- p.frontmatter->'mention_ignore' AS mention_ignore+ p.frontmatter->'mention_ignore' AS mention_ignore, p.body_storageFROM pages p LEFT JOIN page_mention_state s ON s.page_id = p.id- WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.body_storage = 'inline' AND p.id > $3 AND ${DUE_PREDICATE}+ WHERE p.source_id = $1 AND p.deleted_at IS NULL AND p.id > $3 AND ${DUE_PREDICATE}ORDER BY p.id LIMIT $4`, [sourceId, MENTION_EXTRACTOR_VERSION, after, RECONCILE_BATCH]);if (!pages.length) return;after = pages[pages.length - 1]!.id;- const found = new Map(pages.map(p => [Number(p.id), (p.title || p.compiled_truth || p.timeline)- ? findMentionedEntities(`${p.title ?? ''}\n\n${p.compiled_truth ?? ''}\n\n${p.timeline ?? ''}`, gazetteer, {- fromSlug: p.slug, fromSourceId: p.source_id, allowCrossSource, ignoreNames: parseNameList(p.mention_ignore),- })- : []]));+ const found = new Map<number, Mention[]>();+ for (const p of pages) found.set(Number(p.id), await pageMentions(engine, p, gazetteer,+ { fromSlug: p.slug, fromSourceId: p.source_id, allowCrossSource, ignoreNames: parseNameList(p.mention_ignore) }));await opts.beforePublish?.(pages.map(p => Number(p.id)));const outcome = await engine.transaction(async tx => {if (!sameGenerations(generations, await readGenerations(tx, genSources, true))) return null;diff --git a/src/core/minions/handlers/facts-absorb.ts b/src/core/minions/handlers/facts-absorb.tsindex f601476aec..cf53db548e 100644--- a/src/core/minions/handlers/facts-absorb.ts+++ b/src/core/minions/handlers/facts-absorb.ts@@ -45,6 +45,8 @@ export function factsAbsorbShouldRetry(*//** How long a keyless job waits before the next look for a key (no attempt is counted). */export const FACTS_ABSORB_KEYLESS_RETRY_MS = 30 * 60_000;+/** The lead of a segmented page that the backstop's eligibility reads. */+const FACTS_ABSORB_LEAD_CHARS = 8_000;export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {const handle: MinionHandler = async (job) => {@@ -80,12 +82,17 @@ export function makeFactsAbsorbHandler(engine: BrainEngine): MinionHandler {const source = (KNOWN_SOURCES as readonly string[]).includes(job.data.source as string)? (job.data.source as typeof KNOWN_SOURCES[number]): 'mcp:put_page';+ // A segmented page is never materialized: eligibility reads its lead, the extraction plan its segments.+ const { isSegmentedPage } = await import('../../page-body/page-shape.ts');+ const segmented = isSegmentedPage(page);+ const { truthLead } = await import('../../page-body/segment-blocks.ts');const result = await runFactsBackstop({slug: page.slug,type: page.type,- compiled_truth: page.compiled_truth,+ compiled_truth: segmented ? await truthLead(engine, Number(page.id), FACTS_ABSORB_LEAD_CHARS) : page.compiled_truth,frontmatter: (page.frontmatter ?? {}) as Record<string, unknown>,+ ...(segmented ? { segmentedPageId: Number(page.id) } : {}),},{engine, config: await loadConfigWithEngine(engine, loadConfig() ?? { engine: engine.kind }) ?? { engine: engine.kind },diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex c5055cda8e..c01a4febba 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -389,11 +389,12 @@ async function runAutoLink(opts?: { sourceId?: string },) {const sourceId = opts?.sourceId ?? 'default';- const { materializedSnapshot, segmentedOverCeiling } = await import('../persistence/segmented-apply.ts');- const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(slug, { sourceId }));- if (!snapshot || segmentedOverCeiling(snapshot.page)) return;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot) return;const { prepareAutomaticLinks } = await import('../persistence/links-preparation.ts');- const prepared = await prepareAutomaticLinks(engine, slug, { ...snapshot.page, frontmatter: snapshot.page.frontmatter ?? {} }, sourceId);+ // A segmented page keeps its body unread: link preparation streams it.+ snapshot.page.frontmatter ??= {};+ const prepared = await prepareAutomaticLinks(engine, slug, snapshot.page, sourceId);return engine.transaction(async tx => {await tx.lockPageKeys([{sourceId,slug}, ...prepared.pageKeys]);const current = await tx.readPageSnapshot(slug, {sourceId});diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsnew file mode 100644index 0000000000..ac450aefeb--- /dev/null+++ b/src/core/page-body/segment-blocks.ts@@ -0,0 +1,116 @@+/**+ * Segmented page storage (Wave B, spec 8, PR 2 full-pass mode): a segmented+ * page's trusted body for the derived passes (links, timeline, mentions,+ * takes), one block at a time, never the whole body as one string.+ *+ * The text is the joined body `${compiled_truth}\n${timeline}` (or the regions+ * and separator a pass names) after the withdrawal overlay, read with+ * `readBodyRange` (stored space, trusted audience): what readPageSnapshot gives+ * a trusted reader of an inline page. A block is one segment, or a run of+ * segments joined across forced cuts, so every block starts where the+ * segmenter's parsers start fresh: outside code fences, protected regions,+ * fence blocks, timeline detail runs and conversation messages. A run of+ * forced cuts longer than BLOCK_MAX_BYTES (a line or fence many segments long)+ * refuses with `page_body_segmented`; a facts fence crossing a forced cut while+ * the source has withdrawals refuses with `page_projection_stale` (read-range.ts).+ */+import type { BrainEngine } from '../engine.ts';+import { opError } from '../ops/contract.ts';+import { SEGMENT_MAX_BYTES } from './limits.ts';+import { openSegmentedBody, readBodyRange } from './read-range.ts';+import type { BodyRegion } from './types.ts';++/** Bytes a pass reads between two full collections (ingest.ts collectBatchGarbage: one per 4 MiB staging batch). */+const COLLECT_EVERY_BYTES = 4 * 1024 * 1024;++/**+ * A full collection every COLLECT_EVERY_BYTES read. Each segment read leaves garbage several times its size (driver+ * buffers, decoded texts), and JSC sizes its threshold to a heap PGLite's WASM memory makes large, so a pass over a+ * 40 MiB page peaked ~0.8 GB above its live heap without this. Feed it the bytes of each piece read.+ */+export function readGarbageCollector(): (bytes: number) => void {+ let since = 0;+ return bytes => {+ since += bytes;+ if (since < COLLECT_EVERY_BYTES) return;+ since = 0;+ Bun.gc(true);+ };+}++/** The longest run of segments joined across forced cuts that a pass holds as one string. */+export const BLOCK_MAX_BYTES = 8 * SEGMENT_MAX_BYTES;++export interface BodyBlock {+ /** The block's region; null for the separator between two regions. */+ region: BodyRegion | null;+ text: string;+ /** UTF-16 offset of `text` in the joined text. */+ at: number;+}++export interface BodyBlockOptions {+ /** Regions in order (default: truth, then timeline). */+ regions?: readonly BodyRegion[];+ /** Text between two regions (default '\n', as in `${compiled_truth}\n${timeline}`). */+ separator?: string;+}++/** `page_body_segmented`: a run a derived pass must read whole is over BLOCK_MAX_BYTES. */+export function blockTooLargeError(slug: string, sourceId: string, bytes: number) {+ return opError('page_body_segmented',+ `Page ${slug} (source ${sourceId}) has a ${bytes}-byte run a derived pass must read whole (a line or fence longer than a segment), over its ${BLOCK_MAX_BYTES}-byte bound. Nothing was derived from it.`,+ 'Break the long line or fence into shorter lines and write the page again.');+}++export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },+ opts: BodyBlockOptions = {}): AsyncIterable<BodyBlock> {+ const body = await openSegmentedBody(engine, { pageId: Number(page.id) });+ const forced = new Set((await engine.executeRaw<{ seq: number }>(`SELECT seq 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) AND cut_kind='forced'`, [body.pageId, body.generation])).map(row => Number(row.seq)));+ const collect = readGarbageCollector();+ let at = 0;+ for (const [n, region] of (opts.regions ?? ['truth', 'timeline'] as const).entries()) {+ if (n > 0) {+ const separator = opts.separator ?? '\n';+ yield { region: null, text: separator, at };+ at += separator.length;+ }+ const rows = body.rows.filter(row => row.region === region);+ for (let i = 0; i < rows.length;) {+ let j = i;+ while (j + 1 < rows.length && forced.has(rows[j]!.seq)) j++;+ const start = rows[i]!.byteStart;+ const end = rows[j]!.byteStart + rows[j]!.byteLen;+ if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, body.sourceId, end - start);+ const parts: Buffer[] = [];+ for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start, end, audience: 'trusted', region, body })) parts.push(piece.bytes);+ const text = Buffer.concat(parts).toString('utf8');+ collect(end - start);+ yield { region, text, at };+ at += text.length;+ i = j + 1;+ }+ }+}++/** The first `chars` UTF-16 units of a segmented page's trusted compiled truth, reading at most 4 x `chars` + 4 bytes. */+export async function truthLead(engine: BrainEngine, pageId: number, chars: number): Promise<string> {+ const parts: Buffer[] = [];+ for await (const piece of readBodyRange(engine, { pageId, space: 'stored', start: 0, end: 4 * chars + 4, audience: 'trusted', region: 'truth' })) parts.push(piece.bytes);+ return new TextDecoder().decode(Buffer.concat(parts)).slice(0, chars);+}++/**+ * A copy of `value` whose strings share nothing with a block's text: a substring (slice, regex match) keeps its whole+ * parent alive (segmenter.ts `detached`), so a result a pass keeps past its block (a link candidate's context, a+ * timeline entry) would pin that block, and a page's results would pin the page. Plain objects and arrays are copied.+ */+export function detachedValue<T>(value: T): T {+ if (typeof value === 'string') return Buffer.from(value, 'utf8').toString('utf8') as T;+ if (Array.isArray(value)) return value.map(detachedValue) as T;+ if (value === null || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype) return value;+ const copy: Record<string, unknown> = {};+ for (const [key, field] of Object.entries(value)) copy[key] = detachedValue(field);+ return copy as T;+}diff --git a/src/core/page-body/segment-links.ts b/src/core/page-body/segment-links.tsnew file mode 100644index 0000000000..ba093ff2f7--- /dev/null+++ b/src/core/page-body/segment-links.ts@@ -0,0 +1,138 @@+/**+ * 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.+ *+ * 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.+ *+ * 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+ * crossing a cut, an attendees section longer than a window) is read within+ * its window.+ */+import type { BrainEngine } from '../engine.ts';+import {+ candidateKey, dedupeCandidates, extractBodyLinks, frontmatterLinks, rolePriorPhrases, stripCodeBlocks,+ type BodyLinkCandidate, type ExtractPageLinksOptions, type PageLinksResult, type SlugResolver,+} from '../link-extraction.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, type BodyBlock, type BodyBlockOptions } from './segment-blocks.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;+const HEADING = /^(#{1,6})[ \t]/;++export interface SegmentedLinkPage { id: number; slug: string; source_id: string; type: PageType; frontmatter: Record<string, unknown> }++/** A block in its window: `text[start, end)` is the block, at page offset `start + offset`. */+export 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 {+ const masked = stripCodeBlocks(text);+ let at = 0;+ for (const line of masked.split('\n')) {+ const m = HEADING.exec(line);+ if (m) {+ open.length = m[1]!.length;+ open[m[1]!.length - 1] = text.slice(at, at + line.length);+ }+ at += line.length + 1;+ }+}++/**+ * 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 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('');+ const after = ahead.map(b => b.text).join('').slice(0, CONTEXT_CHARS);+ 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);+ }+ };+ 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);+ }+ }+ while (ahead.length) {+ const own = ahead.shift()!;+ yield windowOf(own);+ done(own);+ }+}++/** 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> {+ const found: Array<string | null> = [null, null, null];+ for await (const block of bodyBlocks(engine, page, opts)) {+ rolePriorPhrases(block.text).forEach((phrase, i) => { found[i] ??= phrase; });+ if (found.every(Boolean)) break;+ }+ return found.filter(Boolean).join('\n');+}++/**+ * extractPageLinks(slug, `${compiled_truth}\n${timeline}`, ...) of a segmented page, streamed; `regions` narrows the+ * body (the remote mention effect reads the compiled truth only). With `temporal`, also collects the body's temporal+ * inputs (dated lines, narrative references, ranged relation lines) for publication.+ */+export async function extractSegmentedPageLinks(engine: BrainEngine, page: SegmentedLinkPage, resolver: SlugResolver,+ opts: ExtractPageLinksOptions & BodyBlockOptions & { temporal?: boolean } = {}): Promise<PageLinksResult & { temporalBody?: TemporalBody }> {+ const roleText = opts.roleText ?? await segmentedRoleText(engine, page, opts);+ const regexBudget = opts.regexBudget ?? new PageRegexBudget();+ const kept = new Map<string, BodyLinkCandidate & { seq: number }>();+ const temporalBody: TemporalBody = { lines: [], narrative: [], ranged: [] };+ let seq = 0;+ let attendanceComplete = true;+ for await (const w of bodyWindows(engine, page, opts)) {+ const body = await extractBodyLinks(page.slug, w.text, page.type, resolver,+ { ...opts, roleText, regexBudget, window: { start: w.start, end: w.end, offset: w.offset } });+ attendanceComplete &&= body.attendanceComplete;+ for (const link of body.links) {+ 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, { ...detachedValue(link), seq: seq++ });+ }+ if (!opts.temporal) continue;+ temporalBody.lines.push(...detachedValue(datedLines(w.block.text)));+ if (w.block.region === 'truth') temporalBody.narrative.push(...detachedValue(narrativeRefs(w.block.text)));+ for (const line of rangedRelationLines(w.text)) if (line.start >= w.start && line.start < w.end) temporalBody.ranged.push(detachedValue({ ...line, start: line.start + w.offset }));+ }+ const fm = await frontmatterLinks(page.slug, page.frontmatter, page.type, resolver, opts);+ const body = [...kept.values()].sort((a, b) => a.pass - b.pass || a.index - b.index || a.seq - b.seq).map(link => link.candidate);+ return { candidates: dedupeCandidates([...body, ...fm.candidates]), unresolved: fm.unresolved,+ attendanceComplete: attendanceComplete && fm.attendanceComplete, ...(opts.temporal ? { temporalBody } : {}) };+}diff --git a/src/core/page-body/segment-takes.ts b/src/core/page-body/segment-takes.tsnew file mode 100644index 0000000000..62d7d05d33--- /dev/null+++ b/src/core/page-body/segment-takes.ts@@ -0,0 +1,58 @@+/**+ * Segmented page storage (Wave B, spec 8.2 fences, PR 2 full-pass mode):+ * parseTakesFence over a body read block by block (segment-blocks.ts).+ *+ * parseTakesFence reads only the first begin marker outside code, the first+ * end marker outside code after it, and the text between them (or, with no+ * begin, whether an end or a near-miss marker exists). A block starts outside+ * code, so each marker is located in its block; only the fence itself is+ * kept, joined across blocks up to BLOCK_MAX_BYTES, and parsed. The raw+ * marker scans the callers gate on (`includes`) are reported alongside.+ */+import { indexOfOutsideCode } from '../fence-scan.ts';+import { parseTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END, type ParseResult } from '../takes-fence.ts';+import { BLOCK_MAX_BYTES, blockTooLargeError, type BodyBlock } from './segment-blocks.ts';++export interface StreamedTakes {+ parsed: ParseResult;+ /** The body contains TAKES_FENCE_BEGIN anywhere (in code too). */+ hasBegin: boolean;+ /** The body contains `gbrain:takes:` anywhere. */+ hasMarker: boolean;+}++export async function parseTakesFenceBlocks(blocks: AsyncIterable<BodyBlock>, page: { slug: string; source_id: string }): Promise<StreamedTakes> {+ let fence: string[] | null = null;+ let fenceChars = 0;+ let endOnly = false;+ let nearMiss = false;+ let hasBegin = false;+ let hasMarker = false;+ for await (const { text, at } of blocks) {+ hasBegin ||= text.includes(TAKES_FENCE_BEGIN);+ hasMarker ||= text.includes('gbrain:takes:');+ if (!hasMarker) continue;+ let from = 0;+ let search = 0;+ if (!fence) {+ const begin = indexOfOutsideCode(text, TAKES_FENCE_BEGIN);+ if (begin === -1) {+ // parseTakesFence's end search with no begin starts at TAKES_FENCE_BEGIN.length - 1.+ endOnly ||= indexOfOutsideCode(text, TAKES_FENCE_END, Math.max(0, TAKES_FENCE_BEGIN.length - 1 - at)) !== -1;+ nearMiss ||= indexOfOutsideCode(text, 'gbrain:takes:begin') !== -1;+ continue;+ }+ fence = [];+ from = begin;+ search = begin + TAKES_FENCE_BEGIN.length;+ }+ const end = indexOfOutsideCode(text, TAKES_FENCE_END, search);+ const piece = text.slice(from, end === -1 ? text.length : end + TAKES_FENCE_END.length);+ fenceChars += piece.length;+ if (fenceChars > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.source_id, fenceChars);+ fence.push(piece);+ if (end !== -1) return { parsed: parseTakesFence(fence.join('')), hasBegin, hasMarker };+ }+ const reduced = fence ? TAKES_FENCE_BEGIN : endOnly ? `${'\n'.repeat(TAKES_FENCE_BEGIN.length)}${TAKES_FENCE_END}` : nearMiss ? 'gbrain:takes:begin' : '';+ return { parsed: parseTakesFence(reduced), hasBegin, hasMarker };+}diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex 287e2a034a..231c017c2f 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -12,6 +12,8 @@ import { extractTimelineFromContent, hasExtractorDetail, supersededCitationTimelimport { 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 { parseTakesFenceBlocks } from '../page-body/segment-takes.ts';import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';import type { OperationError } from '../ops/contract.ts';import { protectedRegions } from '../fence-scan.ts';@@ -129,10 +131,9 @@ function canonicalTimeline(body: CanonicalBody, slug: string): Map<string, Extrareturn extractTimeline(safeBody(body), slug);}-/** Tuples whose bullet is introduced by a marker that still matches it. */-function markedTimeline(body: CanonicalBody, slug: string): Set<string> {- const lines = safeBody(body).split('\n');- const marked = new Set<string>();+/** Tuples of a sanitized text whose bullet is introduced by a marker that still matches it. */+function markedTimeline(safe: string, slug: string, marked = new Set<string>()): Set<string> {+ const lines = safe.split('\n');lines.forEach((line, i) => {const hash = materializedMarkerHash(line);if (!hash || i + 1 >= lines.length) return;@@ -141,6 +142,58 @@ function markedTimeline(body: CanonicalBody, slug: string): Set<string> {return marked;}+/** What a body says about timeline rows: its canonical timeline, the tuples a marker still matches, the superseded citation readings. */+interface TimelineView { timeline: Map<string, ExtractedTimelineEntry>; marked: Set<string>; superseded: Set<string> }++function timelineView(body: CanonicalBody, slug: string): TimelineView {+ const safe = safeBody(body);+ return { timeline: extractTimeline(safe, slug), marked: markedTimeline(safe, slug), superseded: new Set(supersededCitationTimeline(safe).map(t => timelineKey(t))) };+}++/** The views a prior snapshot contributes, plus its takes rows per field and whether either field's takes fence warns. */+interface PriorView extends TimelineView { takeRows: Set<number>; takesWarn: boolean }++/**+ * timelineView of a stored segmented page whose body is unread, block by block (page-body/segment-blocks.ts): each+ * block is sanitized alone, as the segmenter scans it, and extractTimeline's two passes are merged in its order+ * (every bullet and heading entry, then parseTimelineEntries' readings over them). A `###` dated entry's detail ends+ * at its block. The takes rows are parsed per field, as canonicalTakeRows does (page-body/segment-takes.ts).+ */+async function segmentedPriorView(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, slug: string): Promise<PriorView> {+ const extracted = new Map<string, ExtractedTimelineEntry>();+ const parsed = new Map<string, ExtractedTimelineEntry>();+ const marked = new Set<string>();+ const superseded = new Set<string>();+ for await (const block of bodyBlocks(engine, page)) {+ const safe = sanitizeRemoteBody(block.text, { keepMaterializedMarkers: true });+ for (const t of extractTimelineFromContent(safe, slug)) extracted.set(timelineKey(t), detachedValue(t));+ for (const t of parseTimelineEntries(safe)) parsed.set(timelineKey({ ...t, source: t.source ?? 'markdown' }), detachedValue({ ...t, source: t.source ?? 'markdown', slug }));+ markedTimeline(safe, slug, marked);+ for (const t of supersededCitationTimeline(safe)) superseded.add(timelineKey(t));+ }+ const timeline = new Map(extracted);+ for (const [key, entry] of parsed) timeline.set(key, entry);+ const fields = await Promise.all((['truth', 'timeline'] as const).map(region => parseTakesFenceBlocks(bodyBlocks(engine, page, { regions: [region] }), page)));+ return { timeline, marked, superseded, takeRows: new Set(fields.flatMap(field => field.parsed.takes.map(t => t.rowNum))),+ takesWarn: fields.some(field => field.parsed.warnings.length > 0) };+}++/** The prior snapshot's view: from its strings, or streamed when its segmented body is unread. */+async function priorView(engine: BrainEngine, page: PageSnapshot['page'], slug: string): Promise<PriorView> {+ if (bodyUnread(page)) return segmentedPriorView(engine, page, slug);+ const fields = [page.compiled_truth, page.timeline ?? ''].map(field => parseTakesFence(field));+ return { ...timelineView(page, slug), takeRows: new Set(fields.flatMap(field => field.takes.map(t => t.rowNum))),+ takesWarn: fields.some(field => field.warnings.length > 0) };+}++/**+ * The canonical timeline of a stored page (a snapshot's page): a segmented body is read block by block. Read it+ * before a transaction; unrecordedCanonicalTimeline filters it inside one.+ */+export async function storedCanonicalTimeline(engine: BrainEngine, page: PageSnapshot['page'], slug: string): Promise<Map<string, ExtractedTimelineEntry>> {+ return bodyUnread(page) ? (await segmentedPriorView(engine, page, slug)).timeline : canonicalTimeline(page, slug);+}+/*** Character ranges of materialized timeline history in a raw body: each marker* line whose hash matches the bullet after it, that bullet, and its indented@@ -178,20 +231,21 @@ function storedTimeline(engine: BrainEngine, pageId: number): Promise<StoredTime* differs only by whitespace is not duplicated. `storedRows` is the caller's* own read of the page's non-event rows (a batched walk).*/-export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: number, body: CanonicalBody, slug: string,- storedRows?: ReadonlyArray<Pick<StoredTimelineRow, 'date' | 'source' | 'summary'>>): Promise<ExtractedTimelineEntry[]> {+export async function unrecordedCanonicalTimeline(engine: BrainEngine, pageId: number, body: CanonicalBody | ReadonlyMap<string, ExtractedTimelineEntry>,+ slug: string, storedRows?: ReadonlyArray<Pick<StoredTimelineRow, 'date' | 'source' | 'summary'>>): Promise<ExtractedTimelineEntry[]> {const stored = new Set((storedRows ?? await storedTimeline(engine, pageId)).map(row => timelineKey(row)));- return [...canonicalTimeline(body, slug)].filter(([key]) => !stored.has(key)).map(([, entry]) => entry);+ return [...(body instanceof Map ? body : canonicalTimeline(body as CanonicalBody, slug))].filter(([key]) => !stored.has(key)).map(([, entry]) => entry);}-/** Classify stored rows against a new body and the writer's prior snapshot. */-function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: CanonicalBody | null, slug: string, writer: ProjectionWriter,+/** Classify stored rows against a new body and the writer's prior snapshot's view. */+function classifyTimeline(rows: StoredTimelineRow[], body: CanonicalBody, prior: TimelineView | null, slug: string, writer: ProjectionWriter,policy?: TimelineWritePolicy) {- const timeline = canonicalTimeline(body, slug);+ const incoming = timelineView(body, slug);+ const timeline = incoming.timeline;const exactIncoming = new Map([...timeline.values()].map(t => [exactTimelineKey(t), sanitizeForJsonb(t.detail ?? '')]));- const priorTimeline = prior ? new Set(canonicalTimeline(prior, slug).keys()) : new Set<string>();- const priorMarked = prior ? markedTimeline(prior, slug) : new Set<string>();- const superseded = new Set([body, ...(prior ? [prior] : [])].flatMap(b => supersededCitationTimeline(safeBody(b)).map(t => timelineKey(t))));+ const priorTimeline = new Set(prior?.timeline.keys() ?? []);+ const priorMarked = prior?.marked ?? new Set<string>();+ const superseded = new Set([...incoming.superseded, ...(prior?.superseded ?? [])]);const pinned = rows.map(row => {const key = timelineKey(row);const state: TimelineRowState = exactIncoming.has(exactTimelineKey(row)) ? 'in_body' : timeline.has(key) ? 'drifted'@@ -219,7 +273,7 @@ function removedSummary(dates: string[]): TimelineRowsRemoved | null {/** The stored rows this writer would delete because the new body dropped their bullets, judged now. */export async function timelineRowsToRemove(engine: BrainEngine, body: CanonicalBody, prior: PageSnapshot, slug: string,writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<TimelineRowsRemoved | null> {- const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, prior.page, slug, writer, policy);+ const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, await priorView(engine, prior.page, slug), slug, writer, policy);return removedSummary(pinned.filter(row => row.action === 'delete' && (row.state === 'removed' || row.state === 'removed_marked')).map(row => row.date));}@@ -245,7 +299,7 @@ export function renderMaterializedBullet(row: { date: string; source: string; suif (extracted.length !== 1) return null;const [entry] = extracted;const same = entry.date === tuple.date && entry.source === tuple.source && entry.summary === tuple.summary && (entry.detail ?? '') === detail;- return same && markedTimeline({ compiled_truth: block, timeline: '' }, slug).size === 1 ? block : null;+ return same && markedTimeline(safeBody({ compiled_truth: block, timeline: '' }), slug).size === 1 ? block : null;}export interface TimelineMaterialization { timeline: string; materialized: number; unrenderable: number }@@ -260,7 +314,7 @@ export async function materializeTimeline(engine: BrainEngine, body: CanonicalBoprior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<TimelineMaterialization> {const timelineText = body.timeline ?? '';if (!prior) return { timeline: timelineText, materialized: 0, unrenderable: 0 };- const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, prior.page, slug, writer, policy);+ const { pinned } = classifyTimeline(await storedTimeline(engine, prior.page.id), body, await priorView(engine, prior.page, slug), slug, writer, policy);const blocks: string[] = [];const seen = new Set<string>();let unrenderable = 0;@@ -278,7 +332,7 @@ export async function materializeTimeline(engine: BrainEngine, body: CanonicalBo/** Database-only timeline rows on one page, split by whether they can be materialized. */export async function pendingTimelineRows(engine: BrainEngine, page: { id: number; slug: string } & CanonicalBody, exclude: ReadonlySet<number> = new Set()) {- const { pinned } = classifyTimeline(await storedTimeline(engine, page.id), page, page, page.slug, 'editing');+ const { pinned } = classifyTimeline(await storedTimeline(engine, page.id), page, timelineView(page, page.slug), page.slug, 'editing');const renderable = new Set<string>();let unrenderable = 0;for (const row of pinned) {@@ -289,10 +343,6 @@ export async function pendingTimelineRows(engine: BrainEngine, page: { id: numbereturn { materializable: renderable.size, unrenderable };}-function canonicalTakeRows(body: CanonicalBody): Set<number> {- return new Set([body.compiled_truth, body.timeline ?? ''].flatMap(field => parseTakesFence(field).takes.map(t => t.rowNum)));-}-/*** Validate a canonical body and compile its provider-free projections. A fence* the shared scan refuses throws typed `invalid_fence` (wire `invalid_params`)@@ -366,8 +416,7 @@ function takeCollision(rows: number[], sections: Map<number, FenceSection>, slug* caller's snapshot at its observed revision; stored timeline rows and take* row numbers are pinned here so the publication transaction only removes* what this writer actually edited. A prior body left unread (a segmented page- * over the single-string ceiling, which holds no fences) contributes no rows of- * its own: stored timeline rows and takes stay unless the new body changes them.+ * over the single-string ceiling) is read block by block (segmentedPriorView).*/export async function prepareCanonicalProjections(engine: BrainEngine, page: ParsedPage, slug: string, sourceId: string,prior: PageSnapshot | null, writer: ProjectionWriter, policy?: TimelineWritePolicy): Promise<(tx: BrainEngine, pageId?: number) => Promise<CanonicalProjectionResult>> {@@ -375,19 +424,19 @@ export async function prepareCanonicalProjections(engine: BrainEngine, page: Par// #6259: a page the content-quality gate hid as junk projects no facts or takes. Rows projected before it// was quarantined are left as they are (hiding them would need a new row state); only new projection stops.const projectFences = !isQuarantined(page.frontmatter);- const priorBody = prior && !bodyUnread(prior.page) ? prior.page : null;+ const prior_ = prior ? await priorView(engine, prior.page, slug) : null;const { timeline, exactIncoming, pinned } = classifyTimeline(prior ? await storedTimeline(engine, prior.page.id) : [],- page, priorBody, slug, writer, policy);+ page, prior_, slug, writer, policy);const deletions = JSON.stringify(pinned.filter(row => row.action === 'delete').map(({ id, date, source, summary, detail, state }) => ({ id, date, source, summary, detail, removed: state === 'removed' || state === 'removed_marked' })));const refreshes = JSON.stringify(pinned.filter(row => row.action === 'refresh_detail').map(row => ({ id: row.id, detail: row.detail, next: exactIncoming.get(exactTimelineKey(row)) })).filter(row => row.next !== row.detail));- const priorTakes = priorBody ? canonicalTakeRows(priorBody) : new Set<number>();+ const priorTakes = prior_?.takeRows ?? new Set<number>();// TE1 (#6188): when the prior takes fence does not parse, its stored rows count as prior canonical rows, so a// row Tier 1 normalized (same number, holder `system` -> `brain`) updates its stored take instead of colliding.- const priorCanonical = priorBody && [priorBody.compiled_truth, priorBody.timeline ?? ''].some(field => parseTakesFence(field).warnings.length)- ? new Set([...priorTakes, ...(await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM takes WHERE page_id=$1', [priorBody.id])).map(r => Number(r.row_num))])+ const priorCanonical = prior && prior_?.takesWarn+ ? new Set([...priorTakes, ...(await engine.executeRaw<{ row_num: number }>('SELECT row_num FROM takes WHERE page_id=$1', [prior.page.id])).map(r => Number(r.row_num))]): priorTakes;const newTakes = JSON.stringify(takes.filter(t => !priorCanonical.has(t.rowNum)).map(t => ({ row_num: t.rowNum, claim: t.claim, kind: t.kind, holder: t.holder })));const takeRowsGone = [...priorTakes].filter(n => !takes.some(t => t.rowNum === n));diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex 2d1d1adc0a..6646ed1aa0 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -13,8 +13,7 @@ import { authorizeStoredRequest, authorizeWrite } from './authority.ts';import { completeEffect } from './effect-journal.ts';import { guardEffectSource } from './effect-recovery.ts';import { derivedExtractionSkip } from './derived-extraction-gate.ts';-import { bodyStorageOf, stringWriteStorage } from './segmented-apply.ts';-import { isSegmentedPage, pageBodyBytes } from '../page-body/page-shape.ts';+import { bodyUnread, isSegmentedPage } from '../page-body/page-shape.ts';import type { PersistenceEffect } from './effect-model.ts';import type { WriteRequest } from './model.ts';@@ -80,7 +79,8 @@ async function extractionCompletedForPage(engine: BrainEngine, pageId: number):*/async function bodyAlreadyOffered(engine: BrainEngine, slug: string, page: ParsedPage, before: PageSnapshot | null): Promise<boolean> {const live = before && !before.page.deleted_at ? before.page : null;- if (!live || live.compiled_truth !== page.compiled_truth) return false;+ // A segmented prior body is not compared; the extraction's watermark finds nothing appended and calls no model.+ if (!live || isSegmentedPage(live) || bodyUnread(page) || live.compiled_truth !== page.compiled_truth) return false;if (!isFactsBackstopEligible(slug, live).ok) return false;if (!(await extractionCompletedForPage(engine, live.id))) return false;return !(await extractionPendingForPage(engine, live.id));@@ -96,7 +96,6 @@ export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequesif (!(await isFactsExtractionEnabled(engine))) return { skipped: 'extraction_disabled' };const eligible = isFactsBackstopEligible(row.slug, page);if (!eligible.ok) return { skipped: eligible.reason };- if ((await stringWriteStorage(engine, pageBodyBytes(page), bodyStorageOf(before?.page))).storage === 'segmented') return { skipped: 'page_body_segmented' };if (await bodyAlreadyOffered(engine, row.slug, page, before)) return { skipped: 'body_unchanged' };return { queued: true };}@@ -120,7 +119,6 @@ export async function readFactsBackstopJobPage(engine: BrainEngine, data: Recordthrow error;}}- if (isSegmentedPage(snapshot.page)) return { skipped: 'page_body_segmented' } as const;return { page: snapshot.page };}diff --git a/src/core/persistence/effect-links.ts b/src/core/persistence/effect-links.tsindex d5584b0c7e..f6ca8b0cf3 100644--- a/src/core/persistence/effect-links.ts+++ b/src/core/persistence/effect-links.ts@@ -11,6 +11,7 @@ import { guardEffectSource } from './effect-recovery.ts';import type { SqlEngine, WriteAuthority, WriteRequest } from './model.ts';import { excludesPrivateWrites } from './page-visibility.ts';import { isSegmentedPage } from '../page-body/page-shape.ts';+import { extractSegmentedPageLinks } from '../page-body/segment-links.ts';import { isRemoteWantedPagesEnabled, replaceWantedLinks } from '../wanted-links.ts';/** `mcp.remote_auto_links`: unset is on; false/0/no/off (any case) turns the remote `links` effect off. */@@ -27,11 +28,16 @@ const SKIPPED_TARGET_LIMIT = 50;* Plain mention targets of a page body: markdown links, [[wikilinks]] and* page-path mentions in compiled_truth only. No frontmatter, no timeline* section, no schema-pack verbs; every edge is stored as an untyped `mentions`.+ * A segmented page's compiled truth is read block by block (page-body/segment-links.ts).*/async function mentionTargets(engine: BrainEngine, snapshot: PageSnapshot, sourceId: string) {const { page } = snapshot;- const { candidates } = await extractPageLinks(page.slug, page.compiled_truth, {}, page.type,- makeResolver(engine, { mode: 'live', sourceId }), { skipFrontmatter: true, pack: null, globalBasename: await isGlobalBasenameEnabled(engine) });+ const resolver = makeResolver(engine, { mode: 'live', sourceId });+ const opts = { skipFrontmatter: true, pack: null, globalBasename: await isGlobalBasenameEnabled(engine) };+ const { candidates } = isSegmentedPage(page)+ ? await extractSegmentedPageLinks(engine, { id: Number(page.id), slug: page.slug, source_id: sourceId, type: page.type, frontmatter: {} }, resolver,+ { ...opts, regions: ['truth'] })+ : await extractPageLinks(page.slug, page.compiled_truth, {}, page.type, resolver, opts);const targets = new Map<string, string>();const skipped: SkippedLinkTarget[] = [];for (const candidate of candidates) {@@ -68,9 +74,8 @@ async function targetGrant(tx: SqlEngine, a: WriteAuthority): Promise<(slug: str* mention edges (link_source `mcp-remote-mention`, origin = the page) against* the targets that exist at execution time, in the page's source, visible to* the writer and inside its slug grant. Only this producer's edges are added- * or removed. A changed or deleted page, a revoked grant, a disabled config or- * a segmented page (its body is not read; its edges are kept) finishes the- * effect as skipped with its reason. The links table carries no+ * or removed. A changed or deleted page, a revoked grant or a disabled config+ * finishes the effect as skipped with its reason. The links table carries no* writer guard or row attribution, so the source guard and the page keys of* the page and its targets are what serialize this with publications.*/@@ -82,7 +87,6 @@ export async function runLinksEffect(engine: BrainEngine, effect: PersistenceEffconst snapshot = await engine.readPageSnapshot(effect.data.slug, { sourceId });if (!snapshot || snapshot.page.id !== effect.data.page_id || snapshot.revision !== effect.revision) return skip(engine, 'superseded');if (!await isAutoLinkEnabled(engine) || !await isRemoteAutoLinksEnabled(engine)) return skip(engine, 'disabled');- if (isSegmentedPage(snapshot.page)) return skip(engine, 'page_body_segmented');const { targets, skipped } = await mentionTargets(engine, snapshot, sourceId);await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");diff --git a/src/core/persistence/links-maintenance.ts b/src/core/persistence/links-maintenance.tsindex b4c0a38045..71a283ce54 100644--- a/src/core/persistence/links-maintenance.ts+++ b/src/core/persistence/links-maintenance.ts@@ -2,18 +2,15 @@ import type { BrainEngine } from '../engine.ts';import { effectiveLinkExtractorWatermark } from '../link-extraction-watermark.ts';import { isQuarantined } from '../quarantine.ts';import { prepareAutomaticLinks } from './links-preparation.ts';-import { materializedSnapshot, segmentedOverCeiling } from './segmented-apply.ts';import { preparationConfigView } from './config-snapshot.ts';import { withCoordinatedWrite } from './context.ts';import { maintenanceAttribution } from './attribution.ts';-import { unrecordedCanonicalTimeline } from './canonical-projections.ts';+import { storedCanonicalTimeline, unrecordedCanonicalTimeline } from './canonical-projections.ts';import { runMentionPass, type MentionPassResult } from '../mentions/pass.ts';import { formatMentionSummary, linkPhaseDeadline, mentionJsonFields, previewMentionPass } from '../mentions/stale.ts';import { plannerStatsForLinkDrain } from '../planner-stats.ts';export interface ManagedLinkExtraction { pages: number; created: number; removed: number; timeline: number; skipped: number; remaining: number;- /** Pages skipped for a named reason (`page_body_segmented`: a segmented body over the 24 MiB single-string ceiling; it stays stale). */- skipped_reasons?: Record<string, number>;/** The mention pass (absent when the caller ran links only, as sync does). */mentions?: MentionPassResult; mention_due?: number; mention_last_pass_at?: string | null; }@@ -86,14 +83,11 @@ export async function extractManagedStaleLinks(engine: BrainEngine,const derive = async (slug: string, sourceId: string, stamp?: string) => {opts.signal?.throwIfAborted();done.add(`${sourceId}\0${slug}`);- const snapshot = await materializedSnapshot(engine, await engine.readPageSnapshot(slug, { sourceId }));+ // A segmented body stays unread: links and the canonical timeline read it block by block, before the transaction.+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });if (!snapshot || isQuarantined(snapshot.page.frontmatter)) return;- if (segmentedOverCeiling(snapshot.page)) {- result.skipped++;- result.skipped_reasons = { ...result.skipped_reasons, page_body_segmented: (result.skipped_reasons?.page_body_segmented ?? 0) + 1 };- return;- }const prepared = await prepareAutomaticLinks(settings, slug, snapshot.page, sourceId);+ const canonical = await storedCanonicalTimeline(engine, snapshot.page, slug);const outcome = await engine.transaction(async tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.lockPageKeys(prepared.pageKeys);const current = await tx.readPageSnapshot(slug, { sourceId });@@ -104,7 +98,7 @@ export async function extractManagedStaleLinks(engine: BrainEngine,}const written = await prepared.apply(tx);if (written.errors) return null;- const timeline = (await unrecordedCanonicalTimeline(tx, current.page.id, snapshot.page, slug)).map(entry => ({ slug, date: entry.date,+ const timeline = (await unrecordedCanonicalTimeline(tx, current.page.id, canonical, slug)).map(entry => ({ slug, date: entry.date,source: entry.source, summary: entry.summary, detail: entry.detail || '', source_id: sourceId }));const added = timeline.length ? await tx.addTimelineEntriesBatch(timeline, { auditSite: 'extract.stale' }) : 0;const at = stamp ?? new Date().toISOString();diff --git a/src/core/persistence/links-preparation.ts b/src/core/persistence/links-preparation.tsindex ce0635fadd..f6e0e5501e 100644--- a/src/core/persistence/links-preparation.ts+++ b/src/core/persistence/links-preparation.ts@@ -1,7 +1,8 @@import type { BrainEngine } from '../engine.ts';import { isUndefinedTableError } from '../utils.ts';import type { ParsedPage } from '../import-file.ts';-import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResolver } from '../link-extraction.ts';+import { buildBasenameIndex, extractPageLinks, isGlobalBasenameEnabled, makeResolver, type ExtractPageLinksOptions,+ type PageLinksResult } from '../link-extraction.ts';import { loadActivePackForLocalEngine } from '../schema-pack/best-effort.ts';import { DerivedLinkEndpointChangedError } from '../derived-links.ts';import { capturedLinkEndpoints, indexLinkSources, loadLinkSourcePolicy, makeLinkSourceResolver } from '../link-reconciliation.ts';@@ -9,7 +10,9 @@ import { collectWantedLinks, isWantedPagesEnabled, possibleWantedRows } from '..import { readFix } from '../ops/op-fix.ts';import { readLineGrammarSettings, type LineGrammarSettings } from '../line-grammar.ts';import { primeRelationSemantics } from '../link-semantics-pack.ts';-import { materializedSnapshot } from './segmented-apply.ts';+import { bodyUnread, isSegmentedPage } from '../page-body/page-shape.ts';+import { extractSegmentedPageLinks, segmentedRoleText } from '../page-body/segment-links.ts';+import { temporalBodyOf, type TemporalBody } from '../link-temporal-apply.ts';async function liveSlugAliases(engine: BrainEngine, sourceId: string, targets: string[]): Promise<Map<string, string>> {if (!targets.length) return new Map();@@ -77,9 +80,11 @@ 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.*/export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,- page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'>, sourceId: string, primeSemantics = false) {+ page: Pick<ParsedPage, 'type' | 'compiled_truth' | 'timeline' | 'frontmatter'> & { id?: number }, sourceId: string, primeSemantics = false) {if (primeSemantics) await primeRelationSemantics(engine);const resolver = makeResolver(engine, { mode: 'live', sourceId, basenameIndex: () => sourceBasenameIndex(engine, sourceId) });// One settings snapshot for the whole extraction; publication validates it (derived-links.ts). An unreadable@@ -90,10 +95,13 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,pack: (await loadActivePackForLocalEngine(engine, { sourceId }))?.manifest ?? null };if (!opts.pack || !settings) return { pageKeys: [{ sourceId, slug }], attendanceComplete: true, settings,apply: async () => ({ created: 0, removed: 0, errors: 1, unresolved_count: 1 }) };- const content = `${page.compiled_truth}\n${page.timeline}`;+ 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);const referenced = new Set([slug]);- const initial = await extractPageLinks(slug, content, page.frontmatter, page.type, resolver,- { ...opts, onResolvedFrontmatterTarget: target => referenced.add(target) });+ 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.const aliases = await liveSlugAliases(engine, sourceId, initial.candidates.map(c => c.targetSlug));const retarget = <T extends { targetSlug: string; targetSourceId?: string }>(c: T): T =>@@ -109,8 +117,8 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,endpoints.slugToSources.set(slug, [...new Set([sourceId, ...(endpoints.slugToSources.get(slug) ?? [])])]);// #4680: the source policy decides the target's source (shared with the reconciliation sweep).const sources = makeLinkSourceResolver(slug, sourceId, endpoints, policy);- const { candidates, unresolved, attendanceComplete } = await extractPageLinks(slug, content, page.frontmatter, page.type, resolver,- { ...opts, targetType: (targetSlug, targetSourceId) => {+ const { candidates, unresolved, attendanceComplete, temporalBody } = await extract(+ { ...opts, temporal: true, targetType: (targetSlug, targetSourceId) => {const resolved = sources.resolve({ targetSlug, targetSourceId, linkType: '', context: '' });return resolved.ok ? (targetSlug === slug && resolved.toSourceId === sourceId ? page.type: metadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type) : undefined;@@ -131,12 +139,14 @@ export async function prepareAutomaticLinks(engine: BrainEngine, slug: string,{ sourceId: row.from_source_id!, slug: row.from_slug }, { sourceId: row.to_source_id!, slug: row.to_slug },])], apply: async (tx: BrainEngine) => {if (!attendanceComplete) return { created: 0, removed: 0, errors: 1, unresolved_count: Math.max(1, unresolved.length) };- const snapshot = await materializedSnapshot(tx, await tx.readPageSnapshot(slug, { sourceId }));+ const snapshot = await tx.readPageSnapshot(slug, { sourceId });if (!snapshot) throw new Error('Automatic link origin disappeared');+ // A page stored in segments is never read here: its temporal inputs come from preparation.+ const stored = isSegmentedPage(snapshot.page) ? { temporalBody: temporalBody ?? temporalBodyOf(page) } : {};try {const result = await tx.replaceDerivedLinks({ slug, sourceId, expectedRevision: snapshot.revision,sourceIncarnation: snapshot.sourceIncarnation, snapshot }, rows, { preserveExisting: true, semanticsPrimed: primeSemantics, lineGrammar: settings, wanted: { ...wanted, producers: [...wanted.producers] },- expectedEndpoints: capturedLinkEndpoints(rows, metadata, { slug, sourceId }) });+ expectedEndpoints: capturedLinkEndpoints(rows, metadata, { slug, sourceId }), ...stored });return { ...result, errors: 0, unresolved_count: unresolved.length, skipped_cross_source: skippedCrossSource, wanted_count: wanted.rows.length,...(wanted.rows.length ? { wanted: wanted.rows.slice(0, 10).map(row => ({ slug: row.target_ref, source_id: row.target_source_id })),wanted_message: 'These link targets have no page yet; each edge is created when its page is. Create the page if it is real, or fix the link if it is a typo.',diff --git a/src/core/sweep.ts b/src/core/sweep.tsindex 3946b1eef2..b9efdeacb8 100644--- a/src/core/sweep.ts+++ b/src/core/sweep.ts@@ -370,11 +370,22 @@ async function runLinksTimelinePass(if (linksEnabled && !pack) throw new Error('Cannot extract links: active schema pack is unavailable.');type Extracted = Awaited<ReturnType<typeof extractPageLinks>>;+ type Snapshot = NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>;+ // A segmented body is read block by block (page-body/segment-links.ts), never as one string.+ const { extractSegmentedPageLinks } = await import('./page-body/segment-links.ts');+ const { bodyBlocks } = await import('./page-body/segment-blocks.ts');+ const linksOf = (snapshot: Snapshot, opts: Parameters<typeof extractPageLinks>[5] & { temporal?: boolean }): ReturnType<typeof extractSegmentedPageLinks> => {+ const { page } = snapshot;+ return isSegmentedPage(page)+ ? extractSegmentedPageLinks(engine, { id: Number(page.id), slug: page.slug, source_id: sourceId, type: page.type, frontmatter: page.frontmatter }, resolver, opts)+ : extractPageLinks(page.slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter, page.type, resolver, opts);+ };+ const temporalBodies = new Map<string, NonNullable<Awaited<ReturnType<typeof extractSegmentedPageLinks>>['temporalBody']>>();const tlBatch: TimelineBatchInput[] = [];const processedRefs: Array<{ slug: string; source_id: string; extractedAt: string }> = [];const pageCandidates: Array<{ slug: string; candidates: Extracted['candidates'] }> = [];- const snapshots = new Map<string, NonNullable<Awaited<ReturnType<BrainEngine['readPageSnapshot']>>>>();+ const snapshots = new Map<string, Snapshot>();// Phase 1: per-page extraction. The per-slug getPage loop stays a loop —// BrainEngine has no batch read-by-slug-list primitive (resolveSlugsByPaths@@ -387,31 +398,27 @@ async function runLinksTimelinePass(const slug = recent[i].slug;const page = await engine.getPage(slug, { sourceId });if (!page) continue;- if (isSegmentedPage(page)) {- skip('page_body_segmented:links_timeline');- continue;- }const snapshot = await engine.readPageSnapshot(slug, { sourceId });- if (!snapshot || snapshot.page.compiled_truth !== page.compiled_truth || snapshot.page.timeline !== page.timeline+ const segmented = isSegmentedPage(page);+ if (!snapshot || segmented !== isSegmentedPage(snapshot.page)+ || (!segmented && (snapshot.page.compiled_truth !== page.compiled_truth || snapshot.page.timeline !== page.timeline))|| snapshot.page.type !== page.type || JSON.stringify(snapshot.page.frontmatter) !== JSON.stringify(page.frontmatter)) continue;snapshots.set(slug, snapshot);- const fullContent = page.compiled_truth + '\n' + page.timeline;-if (linksEnabled) {// skipFrontmatter matches user-invoked `gbrain extract links`// (frontmatter backfill stays a migration-orchestrator concern).- const extracted = await extractPageLinks(- slug, fullContent, page.frontmatter, page.type, resolver,- { skipFrontmatter: true, globalBasename, pack },- );+ const extracted = await linksOf(snapshot, { skipFrontmatter: true, globalBasename, pack, temporal: segmented });+ if (extracted.temporalBody) temporalBodies.set(slug, extracted.temporalBody);if (extracted.candidates.length > 0) {pageCandidates.push({ slug, candidates: extracted.candidates });}}if (timelineEnabled) {- for (const entry of parseTimelineEntries(fullContent)) {+ const entries = segmented ? [] : parseTimelineEntries(page.compiled_truth + '\n' + page.timeline);+ if (segmented) for await (const block of bodyBlocks(engine, snapshot.page)) entries.push(...parseTimelineEntries(block.text));+ for (const entry of entries) {// Same row shape as extractTimelineFromDB's batch push (extract.ts):// #3957 — parsed source label threaded so FS- and DB-extracted rows// share one dedup shape; detail '' when empty.@@ -472,9 +479,8 @@ async function runLinksTimelinePass(]);let crossSourceDrops = 0;for (const { slug } of pageCandidates) {- const page = snapshots.get(slug)!.page;- const { candidates, attendanceComplete } = await extractPageLinks(slug, `${page.compiled_truth}\n${page.timeline}`, page.frontmatter,- page.type, resolver, { skipFrontmatter: true, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {+ const { candidates, attendanceComplete } = await linksOf(snapshots.get(slug)!,+ { skipFrontmatter: true, globalBasename, pack, lineGrammar, targetType: (targetSlug, targetSourceId) => {const resolved = resolveCandidateSources({ targetSlug, targetSourceId, linkType: '', context: '' }, slug,sourceId, allSlugs, slugToSources, allowCrossSource, { crossSource, defaultSourceId: linkDefaultSourceId });return resolved.ok ? endpointMetadata.get(`${resolved.toSourceId}\0${targetSlug}`)?.type : undefined;@@ -557,7 +563,7 @@ async function runLinksTimelinePass(const result = await engine.replaceDerivedLinks({ slug: ref.slug, sourceId,expectedRevision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation }, desired,{ includeFrontmatter: false, preserveExisting: true, lineGrammar: grammar,- wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, expectedEndpoints: [...new Set(desired.flatMap(row =>+ wanted: { producers: ['body'], rows: wantedBySlug.get(ref.slug) ?? [] }, temporalBody: temporalBodies.get(ref.slug), expectedEndpoints: [...new Set(desired.flatMap(row =>[`${row.from_source_id}\0${row.from_slug}`, `${row.to_source_id}\0${row.to_slug}`]))].map(key => {const endpoint = endpointMetadata.get(key)!;return { slug: endpoint.slug, sourceId: endpoint.source_id, revision: endpoint.knowledge_revision };diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.tsindex 4720f84631..e2e9cb47be 100644--- a/src/core/timeline-extract.ts+++ b/src/core/timeline-extract.ts@@ -15,6 +15,7 @@ import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter, parseTimport { isDatedTimelineLine, supersededInlineCitationEntries } from './timeline-citations.ts';import type { BrainEngine } from './engine.ts';import { firstMaterializedMarkerIndex } from './timeline-marker.ts';+import { bodyBlocks, detachedValue } from './page-body/segment-blocks.ts';export interface ExtractedTimelineEntry {slug: string;@@ -138,6 +139,27 @@ function markdownTimelineKeys(text: string, slug: string): Set<string> {return keys;}+/** What a page text says about its timeline rows: the tuples either parser yields, and the older citation readings it supersedes. */+export interface TimelineTextKeys { kept: Set<string>; superseded: Set<string> }++/**+ * TimelineTextKeys of a segmented page's `${compiled_truth}\n${timeline}`, block by block (page-body/segment-blocks.ts),+ * with the entries parseTimelineEntries reads there, in body order. Blocks start outside timeline detail runs, so+ * each entry is read whole.+ */+export async function segmentedTimelineText(engine: Pick<BrainEngine, 'executeRaw' | 'readSegmentTexts'>, page: { id: number; slug: string; source_id?: string }):+ Promise<TimelineTextKeys & { entries: ReturnType<typeof parseTimelineEntries> }> {+ const kept = new Set<string>();+ const superseded = new Set<string>();+ const entries: ReturnType<typeof parseTimelineEntries> = [];+ for await (const block of bodyBlocks(engine as BrainEngine, page)) {+ for (const key of markdownTimelineKeys(block.text, page.slug)) kept.add(key);+ for (const entry of supersededCitationTimeline(block.text)) superseded.add(tupleKey(entry));+ entries.push(...detachedValue(parseTimelineEntries(block.text)));+ }+ return { kept, superseded, entries };+}+/** A page's stored non-event timeline row as reconciliation reads it (`date` is `YYYY-MM-DD`). */export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string | null };@@ -150,15 +172,16 @@ export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string |* scan only runs when the page holds a row the current text does not produce.* Returns the orphaned rows; they are deleted unless `dryRun`. `storedRows`* is the caller's own read of those rows (a batched walk), used instead of reading them here.+ * `current` is the page text, or its keys when the caller read a segmented body (segmentedTimelineText).*/export async function retractRemovedTimelineEntries(engine: Pick<BrainEngine, 'executeRaw'>,slug: string,sourceId: string,- currentText: string,+ current: string | TimelineTextKeys,opts: { dryRun?: boolean; storedRows?: ReadonlyArray<StoredTimelineTuple> } = {},): Promise<Array<TimelineTuple & { id: number }>> {- const kept = markdownTimelineKeys(currentText, slug);+ const kept = typeof current === 'string' ? markdownTimelineKeys(current, slug) : current.kept;const rows = opts.storedRows ?? await engine.executeRaw<StoredTimelineTuple>(`SELECT t.id, to_char(t.date, 'YYYY-MM-DD') AS date, t.source, t.summary, t.detail FROM timeline_entries tJOIN pages p ON p.id = t.page_id@@ -170,7 +193,7 @@ export async function retractRemovedTimelineEntries(WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);const produced = new Set<string>();// #6226: rows the older citation reading filed for this text or a stored version.- const superseded = new Set(supersededCitationTimeline(currentText).map(tupleKey));+ const superseded = new Set(typeof current === 'string' ? supersededCitationTimeline(current).map(tupleKey) : current.superseded);for (const version of versions) {const text = `${version.compiled_truth}\n${version.timeline ?? ''}`;for (const key of markdownTimelineKeys(text, slug)) produced.add(key);@@ -202,9 +225,11 @@ async function retractCoordinated(engine: BrainEngine, pageId: number, slug: strconst attribution = await maintenanceAttribution(engine);return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {await tx.lockPageKeys([{ sourceId, slug }]);- const [page] = await tx.executeRaw<{ compiled_truth: string; timeline: string | null }>(- 'SELECT compiled_truth, timeline FROM pages WHERE id = $1 AND deleted_at IS NULL', [pageId]);- return page ? retractRemovedTimelineEntries(tx, slug, sourceId, `${page.compiled_truth}\n${page.timeline ?? ''}`) : [];+ const [page] = await tx.executeRaw<{ compiled_truth: string; timeline: string | null; body_storage: string }>(+ 'SELECT compiled_truth, timeline, body_storage FROM pages WHERE id = $1 AND deleted_at IS NULL', [pageId]);+ if (!page) return [];+ return retractRemovedTimelineEntries(tx, slug, sourceId, page.body_storage === 'segmented'+ ? await segmentedTimelineText(tx, { id: pageId, slug, source_id: sourceId }) : `${page.compiled_truth}\n${page.timeline ?? ''}`);}, attribution));}@@ -225,8 +250,8 @@ export async function pruneTimelineOrphans(if (pageSize <= 0) break;const params: unknown[] = [afterId, pageSize];if (opts.sourceId) params.push(opts.sourceId);- const pages = await engine.executeRaw<{ id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null }>(- `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline FROM pages p+ const pages = await engine.executeRaw<{ id: number; slug: string; source_id: string; compiled_truth: string; timeline: string | null; body_storage: string }>(+ `SELECT p.id, p.slug, p.source_id, p.compiled_truth, p.timeline, p.body_storage FROM pages pWHERE p.id > $1 AND p.deleted_at IS NULL${opts.sourceId ? ' AND p.source_id = $3' : ''}AND EXISTS (SELECT 1 FROM timeline_entries t WHERE t.page_id = p.id AND t.event_page_id IS NULL)ORDER BY p.id LIMIT $2`, params);@@ -234,7 +259,8 @@ export async function pruneTimelineOrphans(for (const page of pages) {const orphans = opts.coordinated && !opts.dryRun? await retractCoordinated(engine, page.id, page.slug, page.source_id)- : await retractRemovedTimelineEntries(engine, page.slug, page.source_id, `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: opts.dryRun });+ : await retractRemovedTimelineEntries(engine, page.slug, page.source_id, page.body_storage === 'segmented'+ ? await segmentedTimelineText(engine, page) : `${page.compiled_truth}\n${page.timeline ?? ''}`, { dryRun: opts.dryRun });result.orphans += orphans.length;if (!opts.dryRun) result.removed += orphans.length;for (const row of orphans.slice(0, Math.max(0, 5 - result.examples.length))) {diff --git a/test/large-pages/segmented-derived-memory.slow.test.ts b/test/large-pages/segmented-derived-memory.slow.test.tsnew file mode 100644index 0000000000..a3e88a2d47--- /dev/null+++ b/test/large-pages/segmented-derived-memory.slow.test.ts@@ -0,0 +1,133 @@+/**+ * Wave B PR 2 lane 2e (spec 8, full-pass mode): the derived passes' memory+ * does not follow the page.+ *+ * Protects: on PGLite, in a fresh child process per page, running every+ * streamed derived pass (links with temporal inputs, the canonical timeline,+ * the timeline keys, the takes fence, mentions, the facts-backstop extraction+ * plan) over a 40 MiB segmented page (streamed import, over the 24 MiB+ * single-string ceiling)+ * - keeps under RETAINED_LIMIT_MIB of live heap above the start (taken after+ * one warm-up read of every segment, so PGLite's WASM memory has grown to its+ * high water), sampled after a full collection every 16th segment read (one+ * segment at a time: ~8 MiB measured; ~111 MiB when kept link candidates and+ * timeline entries pinned the windows they were cut from; a pass holding the+ * body would retain 40 MiB or more), and+ * - peaks (VmHWM, reset after the import) under PEAK_DELTA_LIMIT_MIB above the+ * same passes over a 4 MiB page (~60 MiB measured; ~700 MiB without the+ * block reader's collection every 4 MiB);+ * and every pass finds what it should on both pages.+ * Fails when: a pass reads the body as one string (materializedPage, a joined+ * block list), keeps every block's text alive until the pass ends, or the+ * reader stops collecting the garbage each segment read leaves.+ * Why existing coverage misses it: segmented-derived-parity.test.ts checks+ * results on a 3.5 MiB page, not memory.+ * Seams: a child process per page (VmHWM is per process); no mocks.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { spawnSync } from 'node:child_process';+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { conversationBody } from '../helpers/conversation-page.ts';++const REPO = resolve(import.meta.dir, '../..');+const PEAK_DELTA_LIMIT_MIB = 160;+const RETAINED_LIMIT_MIB = 24;+const dir = mkdtempSync(join(tmpdir(), 'segmented-derived-memory-'));+afterAll(() => rmSync(dir, { recursive: true, force: true }));++const NAMES = ['Amber', 'Birch', 'Cedar', 'Dune', 'Ember', 'Fjord', 'Grove', 'Harbor']+ .flatMap(first => ['Vale', 'Ridge', 'Brook', 'Field', 'Stone', 'Marsh', 'Glen', 'Crest'].map(last => `${first} ${last}`));+const src = (path: string) => JSON.stringify(join(REPO, 'src', path));+const CHILD = `+import { readFileSync, writeFileSync } from 'node:fs';+import { heapStats } from 'bun:jsc';+import { createEngine } from ${src('core/engine-factory.ts')};+import { importFromFile } from ${src('core/import-file.ts')};+import { readPageBodyPolicy } from ${src('core/page-body/limits.ts')};+import { makeResolver } from ${src('core/link-extraction.ts')};+import { loadActivePackForLocalEngine } from ${src('core/schema-pack/best-effort.ts')};+import { extractSegmentedPageLinks } from ${src('core/page-body/segment-links.ts')};+import { bodyBlocks } from ${src('core/page-body/segment-blocks.ts')};+import { parseTakesFenceBlocks } from ${src('core/page-body/segment-takes.ts')};+import { segmentedTimelineText } from ${src('core/timeline-extract.ts')};+import { storedCanonicalTimeline } from ${src('core/persistence/canonical-projections.ts')};+import { pageMentions } from ${src('core/mentions/pass.ts')};+import { buildGazetteer } from ${src('core/by-mention.ts')};+import { readMentionPolicy } from ${src('core/mentions/policy.ts')};+import { planSegmentedExtraction } from ${src('core/extraction-watermark.ts')};+const [file, brain] = process.argv.slice(-2);+const engine = await createEngine({ engine: 'pglite', database_path: brain });+await engine.connect({ engine: 'pglite', database_path: brain });+await engine.initSchema();+await engine.setConfig('pages.segmented_storage', 'on');+const NAMES = ${JSON.stringify(NAMES)};+for (let i = 0; i < 64; i++) await engine.putPage('people/p' + i + '-example', { type: 'person', title: NAMES[i], compiled_truth: 'Fixture.', timeline: '', frontmatter: {} });+const imported = await importFromFile(engine, file, 'notes/memory-example.md', { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) });+const snapshot = await engine.readPageSnapshot('notes/memory-example');+const page = snapshot.page;+const pack = (await loadActivePackForLocalEngine(engine, { sourceId: 'default' }))?.manifest ?? null;+const resolver = makeResolver(engine, { mode: 'live', sourceId: 'default' });+const gazetteer = await buildGazetteer(engine, { policy: await readMentionPolicy(engine), strict: true });+const live = () => { Bun.gc(true); const s = heapStats(); return (s.heapSize + s.extraMemorySize) / 2 ** 20; };+// One read of every segment first: PGLite's WASM memory (counted as extra memory, never returned) reaches its own high water.+for await (const block of bodyBlocks(engine, page)) void block;+const start = live();+let retained = 0, reads = 0;+const read = engine.readSegmentTexts.bind(engine);+engine.readSegmentTexts = async (...args) => {+ const texts = await read(...args);+ if (++reads % 16 === 0) retained = Math.max(retained, live() - start);+ return texts;+};+writeFileSync('/proc/self/clear_refs', '5');+const links = await extractSegmentedPageLinks(engine, { id: Number(page.id), slug: page.slug, source_id: 'default', type: page.type, frontmatter: page.frontmatter },+ resolver, { pack, globalBasename: false, temporal: true });+const canonical = await storedCanonicalTimeline(engine, page, page.slug);+const keys = await segmentedTimelineText(engine, page);+const takes = await parseTakesFenceBlocks(bodyBlocks(engine, page), page);+const mentions = await pageMentions(engine, { id: Number(page.id), slug: page.slug, source_id: 'default', title: page.title, body_storage: 'segmented' }, gazetteer,+ { fromSlug: page.slug, fromSourceId: 'default', allowCrossSource: false });+const plan = await planSegmentedExtraction(engine, Number(page.id), null, { cap: 8000, pipeline: 'facts_backstop', emptyTail: 'skip' });+const peak = Number(/^VmHWM:\\s+(\\d+) kB$/m.exec(readFileSync('/proc/self/status', 'utf8'))[1]) / 1024;+await engine.disconnect();+console.log(JSON.stringify({ status: imported.status, storage: page.body_storage, bytes: Number(page.body_bytes), peak, retained, reads, links: links.candidates.length,+ timeline: canonical.size, entries: keys.entries.length, takes: takes.parsed.takes.length, mentions: mentions.length, plan: plan.mode }));+`;++/** A conversation page of about `mib` MiB with a paragraph linking a distinct person every `mib` MiB / 64, and one dated bullet per paragraph. */+function derivedPage(mib: number): string {+ const parts: string[] = [];+ const step = Math.floor(mib * 2 ** 20 / 64);+ for (let i = 0; i < 64; i++) parts.push(`${conversationBody(step, { seed: 500 + i })}\n\nMet [[people/p${i}-example]] about item ${i}; ${NAMES[i]} agreed.\n\n`);+ const bullets = Array.from({ length: 64 }, (_, i) => `- **2026-0${1 + (i % 9)}-${String(10 + (i % 18)).padStart(2, '0')}** | Item ${i}`).join('\n');+ return `---\ntype: note\ntitle: Memory\n---\n\n${parts.join('')}\n## Timeline\n\n${bullets}\n`;+}++function passesInChild(mib: number) {+ const file = join(dir, `page-${mib}.md`);+ writeFileSync(file, derivedPage(mib));+ const run = spawnSync(process.execPath, ['--no-env-file', '-e', CHILD, file, join(dir, `brain-${mib}`)],+ { cwd: REPO, encoding: 'utf8', timeout: 600_000, maxBuffer: 1 << 22 });+ rmSync(file, { force: true });+ const line = run.stdout.trim().split('\n').pop() ?? '';+ if (run.status !== 0 || !line.startsWith('{')) throw new Error(`child passes over ${mib} MiB failed (${run.status}):\n${run.stderr.slice(-3000)}`);+ return JSON.parse(line) as { status: string; storage: string; bytes: number; peak: number; retained: number; reads: number; links: number; timeline: number; entries: number; takes: number; mentions: number; plan: string };+}++describe.skipIf(!existsSync('/proc/self/status'))('segmented derived passes memory', () => {+ test(`every streamed pass over a 40 MiB page peaks under ${PEAK_DELTA_LIMIT_MIB} MiB above the same passes over a 4 MiB page`, () => {+ const small = passesInChild(4);+ const large = passesInChild(40);+ for (const run of [small, large]) {+ expect(run).toMatchObject({ status: 'imported', storage: 'segmented', links: 64, timeline: 64, entries: 64, takes: 0, mentions: 64, plan: 'head' });+ }+ expect(large.bytes).toBeGreaterThan(40 * 2 ** 20 - 2 ** 20);+ console.log(`[segmented-derived-memory] peak 4 MiB ${small.peak.toFixed(0)} MiB, 40 MiB ${large.peak.toFixed(0)} MiB, delta ${(large.peak - small.peak).toFixed(0)} MiB;`+ + ` retained 4 MiB ${small.retained.toFixed(1)} MiB, 40 MiB ${large.retained.toFixed(1)} MiB over ${large.reads} segment reads`);+ expect(large.reads).toBeGreaterThan(small.reads * 5);+ expect(large.retained).toBeLessThan(RETAINED_LIMIT_MIB);+ expect(large.peak - small.peak).toBeLessThan(PEAK_DELTA_LIMIT_MIB);+ }, 1_200_000);+});diff --git a/test/large-pages/segmented-derived-parity.test.ts b/test/large-pages/segmented-derived-parity.test.tsnew file mode 100644index 0000000000..3eddb1ca76--- /dev/null+++ b/test/large-pages/segmented-derived-parity.test.ts@@ -0,0 +1,267 @@+/**+ * Wave B PR 2 lane 2e (spec 8, full-pass mode): the derived passes read a+ * segmented page one block at a time and give what they give the same body+ * held as strings.+ *+ * 1. Protects: on a multi-segment page holding links, role phrases, dated+ * timeline bullets, a takes fence and entity mentions,+ * - extractSegmentedPageLinks == extractPageLinks over the materialized+ * body (candidates in order, unresolved refs, attendance) and its+ * temporal inputs == temporalBodyOf;+ * - parseTakesFenceBlocks == parseTakesFence (rows, warnings, marker scans);+ * - segmentedTimelineText == parseTimelineEntries, and+ * storedCanonicalTimeline is the same map for the unread and the+ * materialized page;+ * - pageMentions of the segmented row == findMentionedEntities of the+ * joined strings;+ * - planSegmentedExtraction == planExtraction for no watermark, a version+ * change, a changed prefix, a matching prefix with a short and a long+ * tail, a split code point and nothing appended;+ * and every pass reads one segment text per readSegmentTexts call, never a+ * block over one segment on a page without forced cuts.+ * 2. Fails when: a pass drops or reorders a candidate at a segment boundary,+ * loses the context a window needs (headings, role priors, the text after+ * a link), parses a fence or a timeline entry per segment where it spans+ * them, or a planner reads the body as one string.+ * 3. Why existing coverage misses it: segmented-derived-work.test.ts checks+ * outcomes on bodies whose links sit in the first segment.+ * Seams: none; the readSegmentTexts spy wraps the engine method.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { materializedPage } from '../../src/core/persistence/segmented-apply.ts';+import { extractPageLinks, makeResolver, parseTimelineEntries } from '../../src/core/link-extraction.ts';+import { loadActivePackForLocalEngine } from '../../src/core/schema-pack/best-effort.ts';+import { extractSegmentedPageLinks } from '../../src/core/page-body/segment-links.ts';+import { bodyBlocks } from '../../src/core/page-body/segment-blocks.ts';+import { parseTakesFenceBlocks } from '../../src/core/page-body/segment-takes.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { parseTakesFence, TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { temporalBodyOf } from '../../src/core/link-temporal-apply.ts';+import { segmentedTimelineText } from '../../src/core/timeline-extract.ts';+import { storedCanonicalTimeline } from '../../src/core/persistence/canonical-projections.ts';+import { pageMentions } from '../../src/core/mentions/pass.ts';+import { buildGazetteer, findMentionedEntities } from '../../src/core/by-mention.ts';+import { readMentionPolicy } from '../../src/core/mentions/policy.ts';+import { EXTRACTION_PIPELINE_VERSION, planExtraction, planSegmentedExtraction, type StoredWatermark } from '../../src/core/extraction-watermark.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const SLUG = 'meetings/segmented-parity';+const ROLE_SLUG = 'people/role-example';+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++/** About 3.5 MiB: conversation runs between paragraphs that link, name roles and mention entities; a takes fence mid-page; dated bullets in the timeline. */+function parityPage(): string {+ const parts: string[] = [];+ for (let i = 0; i < 12; i++) {+ parts.push(`## Section ${i}\n\n${conversationBody(260_000, { seed: 100 + i })}\n\n`);+ parts.push(`Met [[people/alice-example]] and [[people/p${i}-example]] about launch ${i}; she works at [Acme Example](../companies/acme-example.md), `+ + `[[people/p${i}-example]] advises [C${i}](../companies/c${i}-example.md) and invested in [[companies/missing-${i}-example]]. `+ + `Bob Example joined, see people/bob-example for notes, and Alice Example reviewed it.\n\n`);+ if (i === 6) parts.push(`${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\n`);+ }+ const timeline = Array.from({ length: 40 }, (_, 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('');+ return `---\ntype: meeting\ntitle: Parity\n---\n\n${parts.join('')}\n<!-- timeline -->\n\n${conversationBody(300_000, { seed: 7 })}\n\n${timeline}`;+}++/** Conversation without its `## 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.');++/**+ * A person page whose page-role phrase comes last: links outside a machine section take the advisor prior, the one+ * under `## Related` (a later segment of that section, past any window's context) does not.+ */+function rolePage(): string {+ return `---\ntype: person\ntitle: Role Example\n---\n\nIntro: met [[companies/c1-example]] early.\n\n## Related\n\n${prose(1_600_000, 41)}\n\n`+ + `- [[companies/c2-example]]\n\n## Notes\n\n${prose(700_000, 42)}\n\nMet [[companies/c3-example]] again.\n\nRole Example is a senior advisor to founders.\n`;+}++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+ const content = parityPage();+ for (const engine of engines) {+ await engine.setConfig('pages.segmented_storage', 'on');+ for (const [slug, type, title] of [['people/alice-example', 'person', 'Alice Example'], ['people/bob-example', 'person', 'Bob Example'],+ ['companies/acme-example', 'company', 'Acme Example']] as const) {+ await engine.putPage(slug, { type, title, compiled_truth: `${title} fixture.`, timeline: '', frontmatter: {} }, { sourceId: 'default' });+ }+ for (let i = 0; i < 12; i++) {+ await engine.putPage(`people/p${i}-example`, { type: 'person', title: `Person ${i}`, compiled_truth: 'Fixture person.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ await engine.putPage(`companies/c${i}-example`, { type: 'company', title: `Company ${i}`, compiled_truth: 'Fixture company.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ }+ expect(await importFromContent(engine, SLUG, content, { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });+ expect(await importFromContent(engine, ROLE_SLUG, rolePage(), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });+ }+}, 300_000);++afterAll(async () => {+ for (const engine of engines) await engine.disconnect();+ await closePostgres?.();+});++/** The stored page (segmented, body unread) and the same page with its body read back as strings. */+async function pages(engine: BrainEngine, slug = SLUG) {+ const snapshot = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ expect(snapshot.page.body_storage).toBe('segmented');+ const inline = await materializedPage(engine, snapshot.page);+ return { snapshot, page: snapshot.page, inline, content: `${inline.compiled_truth}\n${inline.timeline}` };+}++/** Every segment text read while `run` runs: bytes per call and shas per call. */+async function readsDuring<T>(engine: BrainEngine, run: () => Promise<T>): Promise<{ result: T; calls: Array<{ shas: number; bytes: number }> }> {+ const original = engine.readSegmentTexts.bind(engine);+ const calls: Array<{ shas: number; bytes: number }> = [];+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => {+ const texts = await original(sourceId, shas);+ calls.push({ shas: shas.length, bytes: [...texts.values()].reduce((n, t) => n + t.length, 0) });+ return texts;+ }) as BrainEngine['readSegmentTexts'];+ try { return { result: await run(), calls }; } finally { engine.readSegmentTexts = original; }+}++describe('derived passes over a segmented page (full-pass mode)', () => {+ test('the page spans several segments with no forced cut, and each block is one segment', async () => {+ for (const engine of engines) {+ const { page } = await pages(engine);+ const rows = await engine.executeRaw<{ n: number; forced: number }>(+ "SELECT count(*)::int AS n, count(*) FILTER (WHERE cut_kind='forced')::int AS forced FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL", [page.id]);+ expect(rows[0]!.n).toBeGreaterThan(8);+ expect(rows[0]!.forced).toBe(0);+ const { result: sizes, calls } = await readsDuring(engine, async () => {+ const out: number[] = [];+ for await (const block of bodyBlocks(engine, page)) out.push(Buffer.byteLength(block.text, 'utf8'));+ return out;+ });+ expect(Math.max(...sizes)).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ expect(calls.every(call => call.shas === 1 && call.bytes <= SEGMENT_MAX_BYTES)).toBe(true);+ expect(calls.length).toBe(rows[0]!.n);+ }+ }, 300_000);++ test('links: extractSegmentedPageLinks gives extractPageLinks over the materialized body, with the same temporal inputs', async () => {+ for (const engine of engines) {+ const { page, inline, content } = await pages(engine);+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: 'default' }))?.manifest ?? null;+ expect(pack).not.toBeNull();+ const resolver = makeResolver(engine, { mode: 'live', sourceId: 'default' });+ const opts = { pack, globalBasename: false, lineGrammar: { enabled: true, allowUndeclaredTypes: false } };+ const expected = await extractPageLinks(SLUG, content, inline.frontmatter, inline.type, resolver, opts);+ const { result: streamed, calls } = await readsDuring(engine, () => extractSegmentedPageLinks(engine,+ { id: Number(page.id), slug: SLUG, source_id: 'default', type: page.type, frontmatter: page.frontmatter }, resolver, { ...opts, temporal: true }));+ expect(expected.candidates.length).toBeGreaterThan(20);+ expect(streamed.candidates).toEqual(expected.candidates);+ expect(streamed.unresolved).toEqual(expected.unresolved);+ expect(streamed.attendanceComplete).toBe(expected.attendanceComplete);+ expect(streamed.temporalBody).toEqual(temporalBodyOf(inline));+ expect(calls.every(call => call.shas === 1)).toBe(true);+ }+ }, 300_000);++ test('links: a page-role prior from the last segment types links in the first, and a machine section opened segments earlier still suppresses it', async () => {+ for (const engine of engines) {+ const { page, inline, content } = await pages(engine, ROLE_SLUG);+ const [range] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL', [page.id]);+ expect(range!.n).toBeGreaterThan(3);+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: 'default' }))?.manifest ?? null;+ const resolver = makeResolver(engine, { mode: 'live', sourceId: 'default' });+ const opts = { pack, globalBasename: false };+ const expected = await extractPageLinks(ROLE_SLUG, content, inline.frontmatter, inline.type, resolver, opts);+ const streamed = await extractSegmentedPageLinks(engine, { id: Number(page.id), slug: ROLE_SLUG, source_id: 'default', type: page.type, frontmatter: page.frontmatter },+ resolver, opts);+ expect(Object.fromEntries(expected.candidates.map(c => [c.targetSlug, c.linkType])))+ .toEqual({ 'companies/c1-example': 'advises', 'companies/c2-example': 'mentions', 'companies/c3-example': 'advises' });+ expect(streamed.candidates).toEqual(expected.candidates);+ }+ }, 300_000);++ test('takes: parseTakesFenceBlocks gives parseTakesFence of the joined body', async () => {+ for (const engine of engines) {+ const { page, content } = await pages(engine);+ const streamed = await parseTakesFenceBlocks(bodyBlocks(engine, page), { slug: SLUG, source_id: 'default' });+ expect(streamed.parsed).toEqual(parseTakesFence(content));+ expect(streamed.parsed.takes.map(t => t.rowNum)).toEqual([1, 2]);+ expect({ begin: streamed.hasBegin, marker: streamed.hasMarker }).toEqual({ begin: true, marker: true });+ }+ }, 300_000);++ test('takes: a fence split across blocks at any line, a quoted marker in code, an end-only or a near-miss body all parse as the joined body', async () => {+ const table = '| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n'+ + '| 1 | Acme ships quarterly | fact | world | 1.0 | 2026-01 | notes |\n\n| 2 | Pricing will hold | bet | brain | 0.6 | 2026-02 | notes |\n';+ const bodies = [+ `Intro.\n\n\`\`\`md\n${TAKES_FENCE_BEGIN}\n\`\`\`\n\nMore.\n\n${TAKES_FENCE_BEGIN}\n${table}${TAKES_FENCE_END}\n\nTail.\n`,+ `Intro.\n\n${TAKES_FENCE_BEGIN}\n${table}\nNo end here.\n`,+ `Intro, long enough that the end marker sits past the begin marker's length.\n\nStray end:\n\n${TAKES_FENCE_END}\n`,+ `Intro.\n\n<!--- gbrain:takes:begin -->\n${table}`,+ ];+ for (const body of bodies) {+ const lines = body.split(/(?<=\n)/);+ for (let a = 1; a < lines.length; a++) {+ for (let b = a; b < lines.length; b++) {+ const cuts = [0, a, b, lines.length];+ const texts = cuts.slice(1).map((end, k) => lines.slice(cuts[k], end).join('')).filter(Boolean);+ if ([a, b].some(cut => lines.slice(0, cut).filter(line => line.startsWith('```')).length % 2 === 1)) continue;+ const blocks = async function* () { let at = 0; for (const text of texts) { yield { region: 'truth' as const, text, at }; at += text.length; } };+ const streamed = await parseTakesFenceBlocks(blocks(), { slug: SLUG, source_id: 'default' });+ expect(streamed.parsed).toEqual(parseTakesFence(body));+ }+ }+ }+ });++ test('timeline: segmentedTimelineText and storedCanonicalTimeline match the string readers', async () => {+ for (const engine of engines) {+ const { page, inline, content } = await pages(engine);+ const streamed = await segmentedTimelineText(engine, page);+ expect(streamed.entries).toEqual(parseTimelineEntries(content));+ expect(streamed.entries.length).toBeGreaterThanOrEqual(40);+ const unread = await storedCanonicalTimeline(engine, page, SLUG);+ const strings = await storedCanonicalTimeline(engine, inline, SLUG);+ expect([...unread]).toEqual([...strings]);+ expect(unread.size).toBeGreaterThanOrEqual(40);+ }+ }, 300_000);++ test('mentions: pageMentions of the segmented row matches findMentionedEntities of the joined strings', async () => {+ for (const engine of engines) {+ const { page, inline } = await pages(engine);+ const gazetteer = await buildGazetteer(engine, { policy: await readMentionPolicy(engine), strict: true });+ const opts = { fromSlug: SLUG, fromSourceId: 'default', allowCrossSource: false };+ const expected = findMentionedEntities(`${inline.title}\n\n${inline.compiled_truth}\n\n${inline.timeline}`, gazetteer, opts);+ const streamed = await pageMentions(engine, { id: Number(page.id), slug: SLUG, source_id: 'default', title: page.title, body_storage: 'segmented' }, gazetteer, opts);+ expect(expected.map(m => m.slug).sort()).toEqual(['companies/acme-example', 'people/alice-example', 'people/bob-example']);+ expect(streamed).toEqual(expected);+ }+ }, 300_000);++ test('extraction watermark: planSegmentedExtraction gives planExtraction for every watermark case', async () => {+ for (const engine of engines) {+ const { page, inline } = await pages(engine);+ const truth = Buffer.from(inline.compiled_truth, 'utf8');+ const mark = (bytes: number, sha = createHash('sha256').update(truth.subarray(0, bytes)).digest('hex'), version = EXTRACTION_PIPELINE_VERSION.facts_backstop): StoredWatermark =>+ ({ pipelineVersion: version, bytes, sha256: sha });+ const nearEnd = truth.lastIndexOf('\n', truth.length - 2000) + 1;+ const midChar = truth.indexOf(Buffer.from('—'));+ const cases: Array<[string, StoredWatermark | null]> = [+ ['none', null], ['version', mark(nearEnd, undefined, 0)], ['prefix', mark(nearEnd, 'f'.repeat(64))],+ ['short tail', mark(nearEnd)], ['long tail', mark(1000)], ['nothing appended', mark(truth.length)], ['past the end', mark(truth.length + 1)],+ ...(midChar > 0 ? [['split code point', mark(midChar + 1)] as [string, StoredWatermark]] : []),+ ];+ for (const [label, stored] of cases) {+ for (const emptyTail of ['skip', 'head'] as const) {+ const opts = { cap: 8_000, pipeline: 'facts_backstop' as const, emptyTail };+ const { result: plan, calls } = await readsDuring(engine, () => planSegmentedExtraction(engine, Number(page.id), stored, opts));+ expect({ label, plan }).toEqual({ label, plan: planExtraction(inline.compiled_truth, stored, opts) });+ expect(calls.every(call => call.shas === 1)).toBe(true);+ }+ }+ }+ }, 300_000);+});diff --git a/test/large-pages/segmented-derived-passes.test.ts b/test/large-pages/segmented-derived-passes.test.tsnew file mode 100644index 0000000000..54172dbfc6--- /dev/null+++ b/test/large-pages/segmented-derived-passes.test.ts@@ -0,0 +1,150 @@+/**+ * Wave B PR 2 lane 2e (spec 8, full-pass mode): the unmanaged derived passes+ * read a segmented page block by block instead of skipping it or reading its+ * NULL body columns.+ *+ * 1. Protects: on a segmented page whose links, dated bullets, takes fence and+ * entity mentions sit past its first segment,+ * - the mention pass links it and records it scanned (it used to stay due);+ * - extract takes (db) indexes its fence rows;+ * - extract timeline (db) inserts its dated rows;+ * - the maintenance sweep extracts its links and timeline (it used to skip+ * `page_body_segmented:links_timeline`);+ * - source link reconciliation publishes its links (it used to fail the page+ * `page_body_segmented`);+ * - the timeline orphan prune keeps a row the segmented body still holds+ * (it read the NULL columns as the text `null` and retracted rows an+ * earlier inline version produced).+ * 2. Fails when: a pass skips segmented pages again, reads `compiled_truth`+ * of a segmented row, or a block reader loses a bullet or a fence.+ * 3. Why existing coverage misses it: segmented-derived-work.test.ts covers the+ * managed paths; these unmanaged walkers had no segmented page.+ * Seams: none.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import type { BrainEngine } from '../../src/core/engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { runMentionPass } from '../../src/core/mentions/pass.ts';+import { extractTakesFromDb } from '../../src/core/cycle/extract-takes.ts';+import { extractTimelineFromDB } from '../../src/commands/extract-timeline-db.ts';+import { runMaintenanceSweep } from '../../src/core/sweep.ts';+import { reconcileSourceLinks } from '../../src/core/link-reconciliation.ts';+import { pruneTimelineOrphans } from '../../src/core/timeline-extract.ts';+import { loadActivePackForLocalEngine } from '../../src/core/schema-pack/best-effort.ts';+import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../../src/core/takes-fence.ts';+import { conversationBody } from '../helpers/conversation-page.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';++const SLUG = 'notes/segmented-passes';+const engines: BrainEngine[] = [];+let closePostgres: (() => Promise<void>) | undefined;++/** ~2.6 MiB: every derived input sits after the first ~1.2 MiB of conversation. */+function page(opts: { bullets?: string[] } = {}): string {+ const bullets = opts.bullets ?? ['- **2026-03-04** | Kickoff with [[people/alice-example]]', '- **2026-04-05** | Pricing review'];+ return `---\ntype: note\ntitle: Passes\n---\n\n${conversationBody(1_200_000, { seed: 31 })}\n\n## Notes\n\n`+ + `Met [[people/alice-example]]; Alice Example works at [Acme Example](../companies/acme-example.md).\n\n`+ + `${TAKES_FENCE_BEGIN}\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n`+ + `| 1 | Acme ships quarterly | fact | world | 1.0 | 2026-01 | notes |\n${TAKES_FENCE_END}\n\n`+ + `${conversationBody(1_200_000, { seed: 32 })}\n\n## Timeline\n\n${bullets.join('\n')}\n`;+}++const pageId = async (engine: BrainEngine) => Number((await engine.executeRaw<{ id: number }>(+ "SELECT id FROM pages WHERE source_id='default' AND slug=$1", [SLUG]))[0]!.id);+const linkTargets = async (engine: BrainEngine) => (await engine.executeRaw<{ slug: string; link_source: string }>(+ `SELECT DISTINCT t.slug, l.link_source FROM links l JOIN pages t ON t.id=l.to_page_id WHERE l.from_page_id=$1 ORDER BY t.slug, l.link_source`,+ [await pageId(engine)]));+const timelineRows = async (engine: BrainEngine) => (await engine.executeRaw<{ date: string; summary: string }>(+ `SELECT to_char(date,'YYYY-MM-DD') AS date, summary FROM timeline_entries WHERE page_id=$1 AND event_page_id IS NULL ORDER BY date`, [await pageId(engine)]));++beforeAll(async () => {+ const lite = new PGLiteEngine(); await lite.connect({}); await lite.initSchema(); engines.push(lite);+ if (process.env.DATABASE_URL) { const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL); engines.push(pg.engine); closePostgres = pg.close; }+}, 120_000);++afterAll(async () => {+ for (const engine of engines) await engine.disconnect();+ await closePostgres?.();+});++beforeEach(async () => {+ for (const engine of engines) {+ await engine.executeRaw('DELETE FROM pages');+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('auto_link', 'false');+ for (const [slug, type, title] of [['people/alice-example', 'person', 'Alice Example'], ['companies/acme-example', 'company', 'Acme Example']] as const) {+ await engine.putPage(slug, { type, title, compiled_truth: `${title} fixture.`, timeline: '', frontmatter: {} }, { sourceId: 'default' });+ }+ expect(await importFromContent(engine, SLUG, page(), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });+ expect((await engine.executeRaw<{ body_storage: string }>("SELECT body_storage FROM pages WHERE slug=$1", [SLUG]))[0]!.body_storage).toBe('segmented');+ await engine.executeRaw('DELETE FROM links WHERE from_page_id=$1', [await pageId(engine)]);+ await engine.executeRaw('DELETE FROM timeline_entries WHERE page_id=$1', [await pageId(engine)]);+ await engine.executeRaw('DELETE FROM takes WHERE page_id=$1', [await pageId(engine)]);+ }+}, 300_000);++describe('unmanaged derived passes on a segmented page', () => {+ test('the mention pass links the segmented page and records it scanned', async () => {+ for (const engine of engines) {+ await engine.setConfig('auto_link', 'true');+ const result = await runMentionPass(engine, { sourceId: 'default' });+ expect(result.state).toBe('complete');+ expect((await linkTargets(engine)).filter(link => link.link_source === 'mentions').map(link => link.slug))+ .toEqual(['companies/acme-example', 'people/alice-example']);+ const [state] = await engine.executeRaw<{ scanned: boolean }>('SELECT mention_revision IS NOT NULL AS scanned FROM page_mention_state WHERE page_id=$1', [await pageId(engine)]);+ expect(state?.scanned).toBe(true);+ }+ }, 300_000);++ test('extract takes (db) indexes the fence rows of the segmented page', async () => {+ for (const engine of engines) {+ const result = await extractTakesFromDb(engine, { slugs: [SLUG] });+ expect(result).toMatchObject({ pagesWithTakes: 1, takesUpserted: 1, warnings: [] });+ expect(await engine.executeRaw('SELECT row_num, claim FROM takes WHERE page_id=$1', [await pageId(engine)]))+ .toEqual([{ row_num: 1, claim: 'Acme ships quarterly' }]);+ }+ }, 300_000);++ test('extract timeline (db) inserts the dated rows of the segmented page', async () => {+ for (const engine of engines) {+ const result = await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: 'default', slugs: [SLUG] });+ expect(result.refused).toBe(0);+ expect(await timelineRows(engine)).toEqual([{ date: '2026-03-04', summary: 'Kickoff with [[people/alice-example]]' }, { date: '2026-04-05', summary: 'Pricing review' }]);+ }+ }, 300_000);++ test('the maintenance sweep extracts the links and timeline of the segmented page', async () => {+ for (const engine of engines) {+ await engine.setConfig('auto_link', 'true');+ const report = await runMaintenanceSweep(engine, { sourceId: 'default', budgetMs: 120_000 });+ expect(report.skipped.map(skip => skip.reason)).not.toContain('page_body_segmented:links_timeline');+ expect(report.timelineExtracted).toBe(2);+ expect((await linkTargets(engine)).map(link => link.slug)).toContain('people/alice-example');+ expect((await linkTargets(engine)).map(link => link.slug)).toContain('companies/acme-example');+ }+ }, 300_000);++ test('source link reconciliation publishes the links of the segmented page', async () => {+ for (const engine of engines) {+ const pack = (await loadActivePackForLocalEngine(engine, { sourceId: 'default' }))!.manifest;+ const result = await reconcileSourceLinks(engine, 'default', { pack });+ expect(result.failures).toEqual([]);+ expect(result.ok).toBe(true);+ expect((await linkTargets(engine)).map(link => link.slug)).toEqual(expect.arrayContaining(['companies/acme-example', 'people/alice-example']));+ }+ }, 300_000);++ test('the timeline orphan prune keeps a row the segmented body still holds', async () => {+ for (const engine of engines) {+ // An earlier inline version produced both rows; the segmented page still holds both bullets.+ await engine.executeRaw(`INSERT INTO page_versions (page_id, compiled_truth, timeline, frontmatter)+ VALUES ($1, '## Timeline\n\n- **2026-03-04** | Kickoff with [[people/alice-example]]\n- **2026-04-05** | Pricing review', '', '{}'::jsonb)`, [await pageId(engine)]);+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: 'default', slugs: [SLUG] });+ expect(await timelineRows(engine)).toHaveLength(2);+ const pruned = await pruneTimelineOrphans(engine, { sourceId: 'default', dryRun: false });+ expect(pruned.removed).toBe(0);+ expect(await timelineRows(engine)).toHaveLength(2);+ }+ }, 300_000);+});diff --git a/test/large-pages/segmented-derived-work.test.ts b/test/large-pages/segmented-derived-work.test.tsindex f2ca2c288e..776023f217 100644--- a/test/large-pages/segmented-derived-work.test.ts+++ b/test/large-pages/segmented-derived-work.test.ts@@ -6,20 +6,21 @@* 1. Protects: a coordinated publication of a chronicle-shaped segmented page* commits with a pending chronicle decision; the unmanaged discovery never* reads a segmented page as `too_short` (which would retire its events);- * execution judges a segmented page within the single-string ceiling and- * skips one above it as `page_body_segmented`; backfill counts segmented- * pages as eligible; a remote write's `links` effect on a segmented page- * finishes skipped instead of retrying forever; the facts backstop neither- * queues for a segmented page nor lets a facts-absorb job throw on one; a+ * execution judges a segmented page within the single-string ceiling and,+ * since PR 2 (lane 2e, full-pass mode), one above it too, from its lead;+ * backfill counts segmented pages as eligible; a remote write's `links`+ * effect on a segmented page commits its mention edges, read block by+ * block; the facts backstop queues for a segmented page and a facts-absorb+ * job extracts it from its segments (the head, then the appended tail); a* trusted put_page (auto_link on) publishes a segmented page with its derived* links and temporal evidence, edit_page edits one, and a put_page that* shrinks one to inline versions the segmented body before demoting it;* re-linking one later (autoLinkWrittenPage, `extract --slugs`) reads its- * materialized body; the managed stale-links pass after a managed import- * links a segmented page within the ceiling and skips one over it as- * `page_body_segmented`.+ * body; the managed stale-links pass after a managed import links a+ * segmented page within the ceiling and one over it.* 2. Fails when: any of these paths reads `compiled_truth` of a segmented page- * object, or sees its NULL column as an empty body.+ * object, sees its NULL column as an empty body, or skips a page over the+ * single-string ceiling instead of reading its segments.*/import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';import { randomUUID } from 'node:crypto';@@ -43,6 +44,7 @@ import { upsertChronicleRow } from '../../src/core/chronicle/ledger.ts';import { runChronicleBackfill } from '../../src/core/chronicle/backfill.ts';import { runPhaseChronicle } from '../../src/core/cycle/chronicle.ts';import { makeFactsAbsorbHandler } from '../../src/core/minions/handlers/facts-absorb.ts';+import { __setChatTransportForTests, resetGateway, type ChatOpts, type ChatResult } from '../../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';import { withEnv } from '../helpers/with-env.ts';import { conversationBody } from '../helpers/conversation-page.ts';@@ -155,12 +157,13 @@ describe('Life Chronicle on segmented pages', () => {}}, 300_000);- test('the write decision skips a segmented page over the single-string ceiling as page_body_segmented, never too_short', () => {+ test('the write decision keeps a segmented page over the single-string ceiling pending, never page_body_segmented or too_short', () => {const settings = { recentDays: 30, settleSeconds: 0 };const page = { type: 'meeting', slug: 'meetings/huge', frontmatter: { date: today }, body_storage: 'segmented' as const };+ const now = new Date();const over = decideChronicle({ page: { ...page, body_bytes: PAGE_MAX_BYTES + 1, compiled_truth: 'x'.repeat(200) }, authority: null,- noExtract: false, enabled: true, settings, now: new Date() });- expect(over).toEqual({ state: 'skipped', reason: 'page_body_segmented', nextAttemptAt: null });+ noExtract: false, enabled: true, settings, now });+ expect(over).toEqual({ state: 'pending', reason: null, nextAttemptAt: now });});test('unmanaged discovery decides a segmented page from its truth lead and the phase judges its materialized body', async () => {@@ -184,17 +187,18 @@ describe('Life Chronicle on segmented pages', () => {}}, 300_000);- test('execution skips a segmented page over the single-string ceiling as page_body_segmented without throwing', async () => {+ test('execution judges a segmented page over the single-string ceiling from its lead, without materializing it', async () => {for (const engine of engines) {await importFromContent(engine, 'meetings/segmented-offsite', meeting('Offsite'), { sourceId: 'default', noEmbed: true });const page = await storage(engine, 'meetings/segmented-offsite');await upsertChronicleRow(engine, { sourceId: 'default', pageId: page.id, contentHash: page.content_hash, slug: 'meetings/segmented-offsite',state: 'pending', reason: null, trigger: 'auto', nextAttemptAt: null });await engine.executeRaw('UPDATE pages SET body_bytes=$2 WHERE id=$1', [page.id, PAGE_MAX_BYTES + 1]);- let calls = 0;- await runPhaseChronicle(engine, { judge: async () => { calls++; return { events: [] }; } });- expect(calls).toBe(0);- expect(await ledger(engine)).toEqual([{ slug: 'meetings/segmented-offsite', state: 'skipped', reason: 'page_body_segmented', scheduled: false }]);+ const judged: string[] = [];+ await runPhaseChronicle(engine, { judge: async (input) => { judged.push(input.body); return { events: [] }; } });+ expect(judged).toHaveLength(1);+ expect(judged[0]!.slice(0, 200)).toBe(body.slice(0, 200));+ expect(await ledger(engine)).toEqual([{ slug: 'meetings/segmented-offsite', state: 'extracted', reason: 'no_events', scheduled: false }]);}}, 300_000);@@ -209,36 +213,59 @@ describe('Life Chronicle on segmented pages', () => {});describe('page-write effects on segmented pages', () => {- test('a remote write of a segmented page finishes its links effect as skipped instead of retrying', async () => {+ test('a remote write of a segmented page commits its links effect from the segmented body', async () => {for (const engine of engines) {+ await linkTargets(engine);const committed = await coordinatedPut(engine, 'notes/segmented-remote', note('Remote'), true);expect(committed.state).toBe('committed');expect((await storage(engine, 'notes/segmented-remote')).body_storage).toBe('segmented');- await withEnv({ GBRAIN_HOME: home }, () => runPersistenceEffects(engine, config, { hostId: localHostId() }));+ // The write queues embedding, facts-backstop and links effects; one pass runs them all.+ await withEnv({ GBRAIN_HOME: home }, () => runPersistenceEffects(engine, config, { hostId: localHostId(), limit: 10 }));const effects = await engine.executeRaw<{ state: string; error_code: string | null; outcome: Record<string, unknown> | null }>("SELECT state, error_code, outcome FROM persistence_effects WHERE request_id=$1::uuid AND kind='links'", [committed.id]);- expect(effects).toEqual([{ state: 'committed', error_code: null, outcome: { links: 'skipped', reason: 'page_body_segmented' } }]);+ expect(effects).toEqual([{ state: 'committed', error_code: null, outcome: { links: 'committed', added: 1, removed: 0, skipped_targets: [] } }]);}}, 300_000);- test('a write of a segmented page reports the facts backstop skipped and queues no facts-backstop effect', async () => {+ test('a write of a segmented page queues the facts backstop as a facts-backstop effect', async () => {for (const engine of engines) {await engine.setConfig('facts.extraction_enabled', 'true');const committed = await coordinatedPut(engine, 'notes/segmented-facts', note('Facts'), true);expect(committed.state).toBe('committed');- expect(committed.outcome?.facts_backstop).toEqual({ skipped: 'page_body_segmented' });- expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE request_id=$1::uuid AND kind='facts-backstop'", [committed.id])).toEqual([]);+ expect(committed.outcome?.facts_backstop).toEqual({ queued: true });+ expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE request_id=$1::uuid AND kind='facts-backstop'", [committed.id]))+ .toEqual([{ kind: 'facts-backstop' }]);}}, 300_000);- test('a facts-absorb job for a segmented page returns skipped instead of throwing', async () => {- for (const engine of engines) {- await importFromContent(engine, 'notes/segmented-absorb', note('Absorb'), { sourceId: 'default', noEmbed: true });- expect((await storage(engine, 'notes/segmented-absorb')).body_storage).toBe('segmented');- const handler = makeFactsAbsorbHandler(engine);- const result = await withEnv({ GBRAIN_HOME: home }, () => handler({ id: 1, name: 'facts-absorb', signal: new AbortController().signal,- data: { slug: 'notes/segmented-absorb', sourceId: 'default', source: 'sync:import' } } as never));- expect(result).toEqual({ skipped: 'page_body_segmented', slug: 'notes/segmented-absorb', sourceId: 'default' });+ test('a facts-absorb job extracts a segmented page from its head, then from the text appended since', async () => {+ const prompts: string[] = [];+ __setChatTransportForTests(async (opts: ChatOpts): Promise<ChatResult> => {+ prompts.push(JSON.stringify(opts.messages));+ return { text: '{"facts":[]}', blocks: [], stopReason: 'end', model: 'test:stub', providerId: 'test',+ usage: { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_creation_tokens: 0 } };+ });+ try {+ for (const engine of engines) {+ prompts.length = 0;+ await engine.setConfig('facts.extraction_enabled', 'true');+ await importFromContent(engine, 'notes/segmented-absorb', note('Absorb'), { sourceId: 'default', noEmbed: true });+ expect((await storage(engine, 'notes/segmented-absorb')).body_storage).toBe('segmented');+ const run = () => withEnv({ GBRAIN_HOME: home }, () => makeFactsAbsorbHandler(engine)({ id: 1, name: 'facts-absorb', signal: new AbortController().signal,+ data: { slug: 'notes/segmented-absorb', sourceId: 'default', source: 'sync:import' } } as never));+ const first = await run();+ expect(first).not.toHaveProperty('skipped');+ expect(prompts.some(p => p.includes('See [[people/alice-example]]'))).toBe(true);+ prompts.length = 0;+ await importFromContent(engine, 'notes/segmented-absorb', `${note('Absorb')}\nAppended note: zebra-appended-marker reviewed the launch.\n`, { sourceId: 'default', noEmbed: true });+ expect((await storage(engine, 'notes/segmented-absorb')).body_storage).toBe('segmented');+ await run();+ expect(prompts.some(p => p.includes('zebra-appended-marker'))).toBe(true);+ expect(prompts.some(p => p.includes('See [[people/alice-example]]'))).toBe(false);+ }+ } finally {+ __setChatTransportForTests(null);+ resetGateway();}}, 300_000);});@@ -285,7 +312,7 @@ describe('trusted coordinated writes of segmented pages', () => {}}, 300_000);- test('re-linking a segmented page later (autoLinkWrittenPage, extract --slugs) reads its materialized body', async () => {+ test('re-linking a segmented page later (autoLinkWrittenPage, extract --slugs) reads its body', async () => {for (const engine of engines) {await linkTargets(engine);await engine.setConfig('auto_link', 'false');@@ -304,7 +331,7 @@ describe('trusted coordinated writes of segmented pages', () => {}}, 300_000);- test('the managed stale-links pass links a segmented page within the ceiling and skips one over it as page_body_segmented', async () => {+ test('the managed stale-links pass links a segmented page within the ceiling and one over it', async () => {for (const engine of engines) {await linkTargets(engine);const sourceId = `segmented-${randomUUID().slice(0, 8)}`;@@ -324,10 +351,47 @@ describe('trusted coordinated writes of segmented pages', () => {}// The cycle's extract phase passes the slugs a sync changed (cycle.ts → runExtractCore → extractManagedStaleLinks).const result = await extractManagedStaleLinks(engine, { sourceId, slugs: ['notes/within', 'notes/over'], mentions: false });- expect(result.skipped_reasons).toEqual({ page_body_segmented: 1 });+ expect(result.skipped).toBe(0);const links = await engine.executeRaw<{ slug: string }>(`SELECT f.slug FROM links l JOIN pages f ON f.id=l.from_page_id JOIN pages t ON t.id=l.to_page_idWHERE f.source_id=$1 AND t.slug='people/alice-example' ORDER BY f.slug`, [sourceId]);- expect(links).toEqual([{ slug: 'notes/within' }]);+ expect(links).toEqual([{ slug: 'notes/over' }, { slug: 'notes/within' }]);+ } finally {+ await disposePersistenceConsumer(engine);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');+ }+ });+ }+ }, 600_000);++ test('the stale pass projects the dated rows of a page over the ceiling, and a smaller re-import without one bullet retracts its row', async () => {+ for (const engine of engines) {+ const sourceId = `segmented-${randomUUID().slice(0, 8)}`;+ const root = join(home, sourceId);+ mkdirSync(join(root, 'notes'), { recursive: true });+ const dated = (bytes: number, bullets: string[]) =>+ `---\ntype: note\ntitle: Dated\n---\n\n${conversationBody(bytes, { seed: 63 })}\n\n## Timeline\n\n${bullets.join('\n')}\n`;+ await withEnv({ GBRAIN_HOME: home }, async () => {+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await registerLocalWriter(engine, 'cli');+ await claimWorktree(engine, sourceId, root);+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try {+ const file = join(root, 'notes/dated.md');+ const rows = () => engine.executeRaw<{ date: string; summary: string }>(`SELECT to_char(t.date,'YYYY-MM-DD') AS date, t.summary FROM timeline_entries t+ JOIN pages p ON p.id=t.page_id WHERE p.source_id=$1 AND p.slug='notes/dated' AND t.event_page_id IS NULL ORDER BY t.date`, [sourceId]);+ writeFileSync(file, dated(PAGE_MAX_BYTES + 1024 * 1024, ['- **2026-03-04** | Kickoff', '- **2026-04-05** | Pricing review']));+ expect(await importManagedFile(engine, file, 'notes/dated.md', { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ // The streamed import projects no timeline; the stale pass adds the canonical rows it reads from the segments.+ expect((await extractManagedStaleLinks(engine, { sourceId, slugs: ['notes/dated'], mentions: false })).timeline).toBe(2);+ expect(await rows()).toEqual([{ date: '2026-03-04', summary: 'Kickoff' }, { date: '2026-04-05', summary: 'Pricing review' }]);+ const [stored] = await engine.executeRaw<{ body_storage: string; body_bytes: number }>(+ "SELECT body_storage, body_bytes FROM pages WHERE source_id=$1 AND slug='notes/dated'", [sourceId]);+ expect(stored!.body_storage).toBe('segmented');+ expect(Number(stored!.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);+ // The prior body (over the ceiling, left unread) is read block by block to find the bullet this write removed.+ writeFileSync(file, dated(2_000_000, ['- **2026-03-04** | Kickoff']));+ expect(await importManagedFile(engine, file, 'notes/dated.md', { sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });+ expect(await rows()).toEqual([{ date: '2026-03-04', summary: 'Kickoff' }]);} finally {await disposePersistenceConsumer(engine);await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');