Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Fix lane C2: derived consumers on segmented pages (D1-D7)

garrytan29bcdc607375
diff --git a/scripts/page-body-readers-baseline.tsv b/scripts/page-body-readers-baseline.tsv
index 1d09ef9617..19b4b55cc8 100644
--- a/scripts/page-body-readers-baseline.tsv
+++ b/scripts/page-body-readers-baseline.tsv
@@ -85,8 +85,6 @@ src/core/company-brain/profile.ts importCompanyBrainFile field META
src/core/company-brain/verification.ts verifyCompanyBrain field STREAM
src/core/content-repair/judgment.ts judgmentParticipant field STREAM
src/core/content-sanity.ts assessContentSanity field STREAM
-src/core/context/compile-view.ts compileView field LEAD
-src/core/context/compile-view.ts renderEntry field LEAD
src/core/context/proactive-brief.ts editItem field INLINE reads the body only at or under 64 KiB, below the segmented threshold; a segmented page's NULL body skips the edit arm
src/core/context/proactive-brief.ts editItem sql INLINE reads the body only at or under 64 KiB, below the segmented threshold; a segmented page's NULL body skips the edit arm
src/core/context/retrieval-reflex.ts resolveEntitiesToPointers sql LEAD boundedBodyPrefixSql AS compiled_truth
diff --git a/src/commands/extract-conversation-facts.ts b/src/commands/extract-conversation-facts.ts
index 342864195a..d92d05b3a1 100644
--- a/src/commands/extract-conversation-facts.ts
+++ b/src/commands/extract-conversation-facts.ts
@@ -761,15 +761,15 @@ function regularPageVersionToken(page: Page): string {
return `page-${hash}-${effectiveDate}`;
}
-function snapshotVersionToken(page: Page, body: string): string {
+function snapshotVersionToken(page: Page, input: { body: string; sidecar?: true }): string {
if (!hasRawTranscriptSidecar(page)) return regularPageVersionToken(page);
- // Sidecar contents can change without touching pages.updated_at. Hash the
- // exact parser input plus parser-relevant page metadata so those edits reopen
- // the page without a schema migration.
+ // Sidecar contents can change without touching pages.updated_at. Hash the exact parser input plus parser-relevant page metadata so those
+ // edits reopen the page without a schema migration. A segmented page parsing its own body hashes content_hash, never the input the prior-fact guard empties.
+ const parserInput = page.body_storage === 'segmented' && !input.sidecar ? { page: regularPageVersionToken(page) } : { body: input.body };
return `sidecar-${createHash('sha256')
.update(
JSON.stringify({
- body,
+ ...parserInput,
title: page.title,
type: page.type,
frontmatter: page.frontmatter,
@@ -784,8 +784,8 @@ async function preparePageSnapshot(
page: Page,
): Promise<ConversationPageSnapshot> {
try {
- const { body, window } = await readConversationInput(engine, page, { priorFacts: () => countConversationFacts(engine, page.source_id, page.slug) });
- return { page, body, ...(window ? { window } : {}), versionToken: snapshotVersionToken(page, body) };
+ const input = await readConversationInput(engine, page, { priorFacts: () => countConversationFacts(engine, page.source_id, page.slug) });
+ return { page, body: input.body, ...(input.window ? { window: input.window } : {}), versionToken: snapshotVersionToken(page, input) };
} catch (error) {
if (!(error instanceof ConversationBodyTooLargeError)) throw error;
return { page, body: '', versionToken: `sidecar-oversized-${error.bytes}-${error.mtimeMs}`, oversizedSidecarBytes: error.bytes };
diff --git a/src/core/context/compile-view.ts b/src/core/context/compile-view.ts
index 2650107cef..3292cb2404 100644
--- a/src/core/context/compile-view.ts
+++ b/src/core/context/compile-view.ts
@@ -48,6 +48,9 @@ import { createHash } from 'crypto';
import { estimateTokens, packToBudget } from '../search/token-budget.ts';
import { DEFAULT_SOURCE_BOOSTS } from '../search/source-boost.ts';
import type { GetPageOpts, Page, PageFilters } from '../types.ts';
+import type { BrainEngine } from '../engine.ts';
+import { isSegmentedPage } from '../page-body/page-shape.ts';
+import { overlaidBoundedPrefix, pageLeadSource } from '../page-window/bounded-lead.ts';
import { safeSynopsis } from './retrieval-reflex.ts';
import type { SensitivityScanConfig } from './sensitivity-scan.ts';
import { scanSensitive } from './sensitivity-scan.ts';
@@ -99,6 +102,8 @@ export interface CompileViewEngine {
getPage(slug: string, opts?: GetPageOpts): Promise<Page | null>;
/** Relationship notes (temporal typed edges); absent → entries render without them. */
executeRaw?<R = Record<string, unknown>>(sql: string, params?: unknown[]): Promise<R[]>;
+ /** A segmented page's excerpt: its stored lead under the withdrawal overlay; absent → such a page renders without one. */
+ readPageSnapshotsBatch?: BrainEngine['readPageSnapshotsBatch'];
}
export interface CompileViewInput {
@@ -266,7 +271,7 @@ interface RenderedEntry {
rendered: string;
}
-function renderEntry(page: Page, relationshipNote?: string): RenderedEntry {
+function renderEntry(page: Page, lead: string | null, relationshipNote?: string): RenderedEntry {
const date = updatedDate(page);
const excerpt = safeSynopsis(
{
@@ -275,7 +280,7 @@ function renderEntry(page: Page, relationshipNote?: string): RenderedEntry {
title: page.title,
type: page.type ?? null,
frontmatter: page.frontmatter ?? null,
- compiled_truth: page.compiled_truth ?? null,
+ compiled_truth: lead,
},
{ keepVisibility: ['world'], maxLen: EXCERPT_MAX_LEN },
);
@@ -291,6 +296,19 @@ function renderEntry(page: Page, relationshipNote?: string): RenderedEntry {
return { slug: page.slug, date, block, rendered: `\n\n${block}` };
}
+/**
+ * The excerpt source of a page read whole: its (overlaid) compiled truth, or a segmented page's stored lead under the
+ * same withdrawal overlay (its body fields throw). A segmented page without the overlay readers gets no excerpt.
+ */
+async function entryLead(engine: CompileViewEngine, page: Page): Promise<string | null> {
+ const segmented = isSegmentedPage(page);
+ if (segmented && (!engine.executeRaw || !engine.readPageSnapshotsBatch)) return null;
+ const reader = { executeRaw: (sql: string, params?: unknown[]) => engine.executeRaw!(sql, params),
+ readPageSnapshotsBatch: (...args: Parameters<BrainEngine['readPageSnapshotsBatch']>) => engine.readPageSnapshotsBatch!(...args) } as Pick<BrainEngine, 'readPageSnapshotsBatch' | 'executeRaw'>;
+ const lead = await pageLeadSource(reader, page);
+ return segmented ? overlaidBoundedPrefix(reader, { slug: page.slug, source_id: page.source_id ?? 'default', compiled_truth: lead }) : lead;
+}
+
function headerLine(digestHex16: string, target: string, budget: number, core?: CompileViewInput['core']): string {
const coreAttrs = core ? ` core_revision=${core.revision} refresh="${core.command}"` : '';
return `<!-- gbrain:compiled-context digest=sha256:${digestHex16} target=${target} budget=${budget}${coreAttrs} -->`;
@@ -337,7 +355,7 @@ export async function compileView(input: CompileViewInput): Promise<CompileViewR
const raw = input.engine.executeRaw?.bind(input.engine);
const notes = !raw ? new Map<string, string>() : await loadRelationshipNotes(
{ executeRaw: raw },
- scored.map(({ c }) => ({ slug: c.page.slug, source_id: input.sourceId, summary: c.page.compiled_truth ?? '' })),
+ await Promise.all(scored.map(async ({ c }) => ({ slug: c.page.slug, source_id: input.sourceId, summary: await pageLeadSource({ executeRaw: raw }, c.page) ?? '' }))),
{ excludePrivate: true },
).catch(() => new Map<string, string>());
for (const { c } of scored) {
@@ -347,7 +365,7 @@ export async function compileView(input: CompileViewInput): Promise<CompileViewR
`compile-context: page ${c.page.slug} vanished mid-run (source ${input.sourceId}) — aborting, no partial output`,
);
}
- const entry = renderEntry(page, notes.get(relationshipNoteKey(input.sourceId, page.slug)));
+ const entry = renderEntry(page, await entryLead(input.engine, page), notes.get(relationshipNoteKey(input.sourceId, page.slug)));
const findings = scanSensitive(entry.rendered, input.scanConfig);
if (findings.length > 0) {
scanDrops.push({
diff --git a/src/core/conversation-parser/body.ts b/src/core/conversation-parser/body.ts
index cc58d29a1d..2d256ace68 100644
--- a/src/core/conversation-parser/body.ts
+++ b/src/core/conversation-parser/body.ts
@@ -134,13 +134,14 @@ export async function readConversationBodyForParsing(
* readConversationBodyForParsing with the window it read: a segmented page's summary body is read through ranged
* reads, and one over CONVERSATION_WINDOW_BYTES is its newest window (page-body/segment-conversation.ts). With
* `priorFacts`, a page over the window that has conversation facts is not read at all: its input is empty and the
- * window carries the count (the run keeps those facts and skips the page).
+ * window carries the count (the run keeps those facts and skips the page). `sidecar` marks an input read from the
+ * `raw_transcript` file rather than the page.
*/
export async function readConversationInput(
engine: BrainEngine,
page: Page,
opts: { priorFacts?: () => Promise<number> } = {},
-): Promise<SegmentedConversationInput> {
+): Promise<SegmentedConversationInput & { sidecar?: true }> {
const rawTranscript = extractRawTranscriptPath(page);
if (rawTranscript) {
const resolved = await resolveTranscriptPath(engine, page, rawTranscript);
@@ -148,7 +149,7 @@ export async function readConversationInput(
const { size, mtimeMs } = statSync(resolved);
if (size > CONVERSATION_BODY_MAX_BYTES) throw new ConversationBodyTooLargeError(size, mtimeMs);
const rawBody = readFileSync(resolved, 'utf8').trim();
- if (rawBody.length > 0) return { body: rawBody };
+ if (rawBody.length > 0) return { body: rawBody, sidecar: true };
}
if (!resolved) {
// Refusal is loud but class-only: never echo the attempted path
diff --git a/src/core/facts/forget.ts b/src/core/facts/forget.ts
index 72f308bd0a..e83010eeca 100644
--- a/src/core/facts/forget.ts
+++ b/src/core/facts/forget.ts
@@ -183,12 +183,12 @@ export async function forgetFactInFence(
// rewritten occurrences' chunks are replaced), never by loading the body. As `strikeFenceRow` on the whole string,
// only the first facts fence is a candidate: of the compiled truth for the DB body, of truth then timeline for the
// file mirror (the file holds both); a first fence without the row strikes nothing.
- const strikeSegments = async (pageId: number, regions: readonly BodyRegion[]): Promise<void> => {
+ const strikeSegments = async (pageId: number, regions: readonly BodyRegion[], strikeRow = strike): Promise<void> => {
let first = true;
await maintenanceTransaction(engine, tx => rewriteLiveSegmentedFences(tx, pageId, async (fence, at) => {
if (!first || !regions.includes(at.region) || !fence.includes(FENCE_BEGIN)) return fence;
first = false;
- return strikeFenceRow(fence, row.row_num!, strike) ?? fence;
+ return strikeFenceRow(fence, row.row_num!, strikeRow) ?? fence;
}));
};
const strikeDbBody = async (): Promise<void> => {
@@ -305,7 +305,10 @@ export async function forgetFactInFence(
try {
const reparsed = parseMarkdown(tmpBody, `${slug}.md`);
const page = await engine.getPage(slug, { sourceId: row.source_id });
- if (page && isSegmentedPage(page)) await strikeSegments(page.id, ['truth', 'timeline']);
+ // The withdrawal already struck the segmented row with the overlay's reason; it takes the file's row, as the
+ // inline body takes the file's text, so the caller's reason reaches the stored body.
+ const fileRow = parseFactsFence(tmpBody).facts.find(f => f.rowNum === targetRowNum);
+ if (page && isSegmentedPage(page)) await strikeSegments(page.id, ['truth', 'timeline'], fileRow ? () => fileRow : strike);
else if (page) {
await maintenanceTransaction(engine, tx => tx.refreshPageBody(slug, row.source_id,
sanitizeText(reparsed.compiled_truth), sanitizeText(reparsed.timeline),
diff --git a/src/core/facts/purge.ts b/src/core/facts/purge.ts
index e2a19c9d07..74edba930d 100644
--- a/src/core/facts/purge.ts
+++ b/src/core/facts/purge.ts
@@ -96,6 +96,43 @@ async function loadTarget(engine: BrainEngine, id: number, sourceId: string): Pr
return row ? { ...row, id: Number(row.id) } : null;
}
+/** @internal Work the cross-part staging scan does, for its bound test: parts visited and bytes read. Counts, not time. */
+export const purgeStagingWork = { parts: 0, bytes: 0 };
+
+const STAGING_PART_BATCH = 1000;
+
+/**
+ * Live stagings of the source whose upload parts hold `claim`'s exact bytes across a part boundary (a claim inside one
+ * part is matched in SQL). Parts are walked in order per staging carrying the stream's last (claim bytes - 1) bytes,
+ * and only each part's head and tail of that length are read, never a whole part.
+ */
+async function stagingsWithClaimAcrossParts(engine: BrainEngine, sourceId: string, claim: string): Promise<string[]> {
+ const needle = Buffer.from(claim, 'utf8');
+ const keep = needle.length - 1;
+ if (keep < 1) return [];
+ const hits = new Set<string>();
+ let carry = Buffer.alloc(0);
+ let previous: { id: string; part: number } = { id: '00000000-0000-0000-0000-000000000000', part: -1 };
+ for (;;) {
+ const parts = await engine.executeRaw<{ id: string; part_no: number; head: Uint8Array; tail: Uint8Array }>(`SELECT pt.staging_id::text AS id,pt.part_no,
+ substring(pt.body from 1 for $2) AS head,substring(pt.body from greatest(1,octet_length(pt.body)-$2+1)) AS tail
+ FROM page_body_staging_parts pt JOIN page_body_stagings s ON s.id=pt.staging_id
+ WHERE s.source_id=$1 AND s.state IN ('open','sealed','prepared') AND (pt.staging_id,pt.part_no)>($3::uuid,$4::int)
+ ORDER BY pt.staging_id,pt.part_no LIMIT ${STAGING_PART_BATCH}`, [sourceId, keep, previous.id, previous.part]);
+ for (const part of parts) {
+ const head = Buffer.from(part.head), tail = Buffer.from(part.tail);
+ purgeStagingWork.parts++;
+ purgeStagingWork.bytes += head.length + tail.length;
+ if (part.id !== previous.id || Number(part.part_no) !== previous.part + 1) carry = Buffer.alloc(0);
+ if (!hits.has(part.id) && carry.length && Buffer.concat([carry, head]).includes(needle)) hits.add(part.id);
+ carry = Buffer.concat([carry, tail]).subarray(-keep);
+ previous = { id: part.id, part: Number(part.part_no) };
+ }
+ if (parts.length < STAGING_PART_BATCH) break;
+ }
+ return [...hits];
+}
+
/** Read-only: everything a purge of `target` would touch. Inside the purge transaction it runs under the source lock. */
export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, allSubjects: boolean): Promise<PurgePlan> {
const subject = allSubjects ? '*' : target.entity_slug ?? '*';
@@ -116,11 +153,12 @@ export async function planFactPurge(engine: BrainEngine, target: PurgeTarget, al
const [versions] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_versions v JOIN pages p ON p.id=v.page_id
WHERE p.source_id=$1 AND (${carriesClaimSql('v', 2)}
OR (v.body_storage='segmented' AND ${SEGMENTED_VERSION_CARRIES}))`, [target.source_id, ...claimNeedles(target.fact)]);
- const stagings = (await engine.executeRaw<{ id: string }>(`SELECT s.id::text AS id FROM page_body_stagings s
+ const stagings = [...new Set([...(await engine.executeRaw<{ id: string }>(`SELECT s.id::text AS id FROM page_body_stagings s
WHERE s.source_id=$1 AND s.state IN ('open','sealed','prepared') AND (EXISTS (SELECT 1 FROM page_body_manifest m
JOIN page_segment_texts t ON t.source_id=m.source_id AND t.sha256=m.sha256 WHERE m.staging_id=s.id AND strpos(lower(convert_from(t.body,'UTF8')),$2)>0)
OR EXISTS (SELECT 1 FROM page_body_staging_parts pt WHERE pt.staging_id=s.id AND position(convert_to($3::text,'UTF8') in pt.body)>0))
- ORDER BY s.id`, [target.source_id, target.fact.toLowerCase(), target.fact])).map(row => row.id);
+ ORDER BY s.id`, [target.source_id, target.fact.toLowerCase(), target.fact])).map(row => row.id),
+ ...await stagingsWithClaimAcrossParts(engine, target.source_id, target.fact)])].sort();
const held = await findRequestsHoldingStagings(engine, target.source_id, stagings);
// #6511 [R5]: a statement timeout of this unindexable substring search is deterministic on a large journal, not contention: the typed code, not a retry.
const requests = await faultPoint('purge:carrying_lookup', { sourceId: target.source_id, operation: PURGE_OPERATION })
@@ -226,25 +264,33 @@ async function redactPageVersions(tx: BrainEngine, sourceId: string, claim: stri
}
if (rows.length < VERSION_REDACTION_BATCH) break;
}
- // Wave B (spec 11): a segmented version references a generation; that generation is rebuilt with the rows dropped.
- const segmented = await tx.executeRaw<{ id: number; page_id: number; generation: number; slug: string; title: string; type: string;
- frontmatter: Record<string, unknown>; tags: string[] | null }>(`SELECT v.id,v.page_id,v.body_generation AS generation,p.slug,v.title,v.type,v.frontmatter,v.tags
- FROM page_versions v JOIN pages p ON p.id=v.page_id
- WHERE p.source_id=$1 AND v.body_storage='segmented' AND (v.page_id=ANY($3::int[]) OR ${SEGMENTED_VERSION_CARRIES})
- ORDER BY v.id LIMIT 5000`, [sourceId, needle, pageIds]);
- const done = new Set<string>();
+ // Wave B (spec 11): a segmented version references a generation; that generation is rebuilt with the rows dropped,
+ // once per generation (versions sharing one share its rebuild and its prose probe), in the same keyset batches.
+ const carries = new Map<string, boolean>();
+ const segmentedPages = new Set<number>();
const replaced: Uint8Array[] = [];
- for (const v of segmented) {
- const pageId = Number(v.page_id), generation = Number(v.generation);
- if (!done.has(`${pageId}:${generation}`)) {
- done.add(`${pageId}:${generation}`);
- const shas = await rewriteSegmentedGeneration(tx, pageId, generation, fence => dropPurgedFenceRows(tx, sourceId, fence, v.slug),
- { title: v.title, type: v.type, frontmatter: v.frontmatter ?? {}, tags: v.tags ?? [] });
- if (shas) { redacted++; replaced.push(...shas); }
+ for (let after = 0; ;) {
+ const segmented = await tx.executeRaw<{ id: number; page_id: number; generation: number; slug: string; title: string; type: string;
+ frontmatter: Record<string, unknown>; tags: string[] | null }>(`SELECT v.id,v.page_id,v.body_generation AS generation,p.slug,v.title,v.type,v.frontmatter,v.tags
+ FROM page_versions v JOIN pages p ON p.id=v.page_id
+ WHERE p.source_id=$1 AND v.body_storage='segmented' AND v.id>$4 AND (v.page_id=ANY($3::int[]) OR ${SEGMENTED_VERSION_CARRIES})
+ ORDER BY v.id LIMIT ${VERSION_REDACTION_BATCH}`, [sourceId, needle, pageIds, after]);
+ if (!segmented.length) break;
+ after = Number(segmented[segmented.length - 1].id);
+ for (const v of segmented) {
+ const pageId = Number(v.page_id), generation = Number(v.generation), key = `${pageId}:${generation}`;
+ segmentedPages.add(pageId);
+ if (!carries.has(key)) {
+ const shas = await rewriteSegmentedGeneration(tx, pageId, generation, fence => dropPurgedFenceRows(tx, sourceId, fence, v.slug),
+ { title: v.title, type: v.type, frontmatter: v.frontmatter ?? {}, tags: v.tags ?? [] });
+ if (shas) { redacted++; replaced.push(...shas); }
+ carries.set(key, await segmentedBodyContains(tx, pageId, sourceId, [claim], { generation }) === true);
+ }
+ if (carries.get(key)) prose.push({ slug: v.slug, version_id: Number(v.id) });
}
- if (await segmentedBodyContains(tx, pageId, sourceId, [claim], { generation }) === true) prose.push({ slug: v.slug, version_id: Number(v.id) });
+ if (segmented.length < VERSION_REDACTION_BATCH) break;
}
- return { redacted, prose, segmentedPages: [...new Set(segmented.map(v => Number(v.page_id)))], replaced };
+ return { redacted, prose, segmentedPages: [...segmentedPages], replaced };
}
/**
@@ -264,6 +310,8 @@ async function purgeSegmentStorage(tx: BrainEngine, sourceId: string, claim: str
parts = (await tx.executeRaw('DELETE FROM page_body_staging_parts WHERE staging_id=ANY($1::uuid[]) RETURNING 1', [plan.stagings])).length;
}
for (const pageId of new Set([...pageIds, ...staged])) await tx.sweepSegments({ pageId });
+ // The cached view digests (sizes and sha256 of a read view) of the rewritten bodies describe pre-purge text.
+ if (pageIds.length) await tx.executeRaw('DELETE FROM page_view_digests WHERE page_id=ANY($1::int[])', [pageIds]);
const texts = (await tx.executeRaw(`DELETE FROM page_segment_texts d WHERE (d.source_id,d.sha256) IN (SELECT t.source_id,t.sha256 FROM page_segment_texts t
WHERE t.source_id=$1 AND NOT EXISTS (SELECT 1 FROM page_body_manifest m WHERE m.source_id=t.source_id AND m.sha256=t.sha256) OFFSET 0)
AND (d.sha256=ANY(SELECT decode(h,'hex') FROM unnest($2::text[]) AS h) OR strpos(lower(convert_from(d.body,'UTF8')),$3)>0) RETURNING 1`,
diff --git a/src/core/page-body/body-digests.ts b/src/core/page-body/body-digests.ts
index c76e0c2a16..0016a8c3e6 100644
--- a/src/core/page-body/body-digests.ts
+++ b/src/core/page-body/body-digests.ts
@@ -13,7 +13,8 @@ import type { BrainEngine } from '../engine.ts';
import type { ParseOpts } from '../markdown.ts';
import { BodyScanner, type BodyPiece, type BodyScan } from './body-scan.ts';
import { openSegmentedBody, readBodyRange, type BodyLedger } from './read-range.ts';
-import { readGarbageCollector } from './segment-blocks.ts';
+import { BLOCK_MAX_BYTES, readGarbageCollector } from './segment-blocks.ts';
+import { partialFenceRuns } from '../facts/withdrawal-overlay.ts';
import { SEGMENT_MAX_BYTES } from './limits.ts';
import type { BodyRegion } from './types.ts';
@@ -34,7 +35,7 @@ export type RegionDigests = Record<BodyRegion, string>;
export interface FileReading { prefix: Uint8Array; skip: number }
export type FileDigests =
- | { kind: 'ok'; parsed: BodyScan['parsed']; digests: RegionDigests; factsFence: boolean }
+ | { kind: 'ok'; parsed: BodyScan['parsed']; digests: RegionDigests; factsFence: boolean; regions: Record<BodyRegion, readonly BodyPiece[]> }
| { kind: 'unreadable'; reason: 'invalid_utf8' | 'frontmatter_head_unbounded' };
function count(piece: Uint8Array, field: 'fileBytes' | 'segmentBytes'): Uint8Array {
@@ -74,7 +75,51 @@ export function fileBodyDigests(bytes: Uint8Array, reading: FileReading, filePat
}
return hash.digest('hex');
};
- return { kind: 'ok', parsed: scan.parsed, digests: { truth: digest(scan.truth), timeline: digest(scan.timeline) }, factsFence };
+ return { kind: 'ok', parsed: scan.parsed, digests: { truth: digest(scan.truth), timeline: digest(scan.timeline) }, factsFence,
+ regions: { truth: scan.truth, timeline: scan.timeline } };
+}
+
+/**
+ * The digest of each file region after `overlay` (the withdrawal overlay of one complete text, overlayCanonicalBodies),
+ * applied as the stored side applies it per segment: to complete lines, each chunk ending outside every facts fence
+ * block (partialFenceRuns), so a block is always overlaid whole. Text before the first fence marker of a chunk is
+ * hashed as read. A block that stays open past BLOCK_MAX_BYTES (a fence the stored side can only hold split across
+ * forced cuts) calls `refuse`: such a body is not overlaid in pieces.
+ */
+export async function overlaidFileBodyDigests(bytes: Uint8Array, reading: FileReading, regions: Record<BodyRegion, readonly BodyPiece[]>,
+ overlay: (text: string) => Promise<string>, refuse: () => Error): Promise<RegionDigests> {
+ const digests = {} as RegionDigests;
+ for (const region of REGIONS) {
+ const hash = createHash('sha256');
+ const update = (text: string) => {
+ const buffer = Buffer.from(text, 'utf8');
+ for (let at = 0; at < buffer.length; at += SEGMENT_MAX_BYTES) hash.update(count(buffer.subarray(at, at + SEGMENT_MAX_BYTES), 'fileBytes'));
+ };
+ const emit = async (text: string) => update(text.includes('gbrain:facts:begin') ? await overlay(text) : text);
+ const decoder = new TextDecoder('utf-8');
+ let pending = '';
+ const drain = async () => {
+ const end = pending.lastIndexOf('\n') + 1;
+ if (end === 0) return;
+ const complete = pending.slice(0, end);
+ const { tail } = partialFenceRuns(complete, false);
+ const cut = tail === complete.length ? end : complete.lastIndexOf('\n', tail - 1) + 1;
+ if (cut > 0) await emit(complete.slice(0, cut));
+ pending = pending.slice(cut);
+ if (Buffer.byteLength(pending, 'utf8') > BLOCK_MAX_BYTES) throw refuse();
+ };
+ for (const piece of regions[region]) {
+ const parts = 'text' in piece ? [Buffer.from(piece.text, 'utf8')] : virtualSlice(bytes, reading, piece.start, piece.end);
+ for (const part of parts) {
+ pending += decoder.decode(count(part, 'fileBytes'), { stream: true });
+ await drain();
+ }
+ }
+ pending += decoder.decode();
+ if (pending) await emit(pending);
+ digests[region] = hash.digest('hex');
+ }
+ return digests;
}
/** The digest of each region of a segmented page's trusted stored body under `ledger` (the snapshot's withdrawals), one segment at a time. */
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 405cc6b471..cafe518ba7 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -46,7 +46,7 @@ import { pipelined } from '../page-state/transactions.ts';
import { overlayCanonicalBodies } from '../page-state/snapshot.ts';
import { segmentedRevertRefusal } from '../page-state/versions.ts';
import { bodyUnread, isSegmentedPage, pageBodySegmentedError, withoutBody } from '../page-body/page-shape.ts';
-import { fileBodyDigests, storedBodyDigests, type FileReading, type RegionDigests } from '../page-body/body-digests.ts';
+import { fileBodyDigests, overlaidFileBodyDigests, storedBodyDigests, type FileReading, type RegionDigests } from '../page-body/body-digests.ts';
import { ledgerApplies, type BodyLedger } from '../page-body/segment-ledger.ts';
import { inferredHeadPrefix } from '../page-body/streamed-import.ts';
import { FRONTMATTER_HEAD_MAX_BYTES } from '../page-body/limits.ts';
@@ -218,8 +218,14 @@ async function segmentedFileMatches(engine: BrainEngine, slug: string, bytes: Bu
const matches = async (reading: FileReading, inferred: boolean) => {
const file = fileBodyDigests(bytes, reading, slug, { activePack });
if (file.kind !== 'ok') return file.reason;
- if (file.factsFence && ledgerApplies(ledger)) throw pageBodySegmentedError(snapshot.page, 'fileMatchesSnapshot (a facts fence under withdrawals)');
- const parsed = { ...file.parsed, compiled_truth: file.digests.truth, timeline: file.digests.timeline };
+ // A facts fence under a ledger that applies is compared overlaid, one complete fence block at a time; a block too
+ // long to overlay whole (held split across forced cuts) still refuses.
+ const fileDigests = file.factsFence && ledgerApplies(ledger)
+ ? await overlaidFileBodyDigests(bytes, reading, file.regions, async text => (await overlayCanonicalBodies(engine.executeRaw.bind(engine), text, '',
+ ledger.withdrawals, { sourceId: snapshot.page.source_id, marker: ledger.globalPurges })).compiled_truth,
+ () => pageBodySegmentedError(snapshot.page, 'fileMatchesSnapshot (a facts fence block under withdrawals longer than a block)'))
+ : file.digests;
+ const parsed = { ...file.parsed, compiled_truth: fileDigests.truth, timeline: fileDigests.timeline };
const type = importedFileType(parsed, snapshot.page, inferred);
stored ??= await storedBodyDigests(engine, Number(snapshot.page.id), ledger);
return digest(canonical({ ...parsed, type }, parsed.tags))
diff --git a/src/core/think/gather.ts b/src/core/think/gather.ts
index 325dce35ad..fe6e8987c6 100644
--- a/src/core/think/gather.ts
+++ b/src/core/think/gather.ts
@@ -21,7 +21,7 @@ import { EXTERNAL_DATA_RULE, needsDataEnvelope, trustAttributes } from '../eligi
import { hybridSearch } from '../search/hybrid.ts';
import { INTERNAL_BREADTH_SEARCH_OPTS } from '../search/internal-breadth.ts';
import { boundedProjectedPrefix } from '../page-window/document.ts';
-import { overlaidBoundedRows } from '../page-window/bounded-lead.ts';
+import { overlaidBoundedRows, pageLeadSource } from '../page-window/bounded-lead.ts';
import type { Page, SearchResult } from '../types.ts';
import { DEFAULT_PAGES_BUDGET, PAGES_BLOCK_EXCERPT_FLOOR_CHARS, type PagesBudget } from './pages-budget.ts';
import { filterPagesToWindow, type TemporalWindow } from './temporal-window.ts';
@@ -138,8 +138,9 @@ export async function runGather(
const decide = { remote: opts.remote !== false, callSite: 'think', ...(opts.decideIntent ? { intent: opts.decideIntent } : {}) };
// Large pages: a page row's text is a bounded, withdrawal-overlaid prefix
// (raw for the trusted local CLI, the sanitized projection otherwise), never the whole body.
+ // A segmented page's lead source is its stored truth_lead (its body fields throw).
const visibleLeads = async (rows: Page[]): Promise<string[]> =>
- (await overlaidBoundedRows(engine, rows.map(p => ({ slug: p.slug, source_id: p.source_id ?? 'default', compiled_truth: p.compiled_truth ?? '' }))))
+ (await overlaidBoundedRows(engine, await Promise.all(rows.map(async p => ({ slug: p.slug, source_id: p.source_id ?? 'default', compiled_truth: await pageLeadSource(engine, p) ?? '' })))))
.map(r => opts.remote === false ? r.compiled_truth ?? '' : boundedProjectedPrefix(r.compiled_truth));
// Sanitize the question for any path that includes it in an LLM prompt.
diff --git a/src/core/timeline-extract.ts b/src/core/timeline-extract.ts
index e2e9cb47be..e4413db084 100644
--- a/src/core/timeline-extract.ts
+++ b/src/core/timeline-extract.ts
@@ -15,7 +15,7 @@ import { parseInlineCitationTimelineEntries, findTimelineSourceDelimiter, parseT
import { 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';
+import { BLOCK_MAX_BYTES, blockTooLargeError, bodyBlocks, detachedValue, segmentedPassWork } from './page-body/segment-blocks.ts';
export interface ExtractedTimelineEntry {
slug: string;
@@ -160,6 +160,38 @@ export async function segmentedTimelineText(engine: Pick<BrainEngine, 'executeRa
return { kept, superseded, entries };
}
+/**
+ * The stored text of a retained segmented generation (a segmented page_versions row: its body columns are NULL) as
+ * `${compiled_truth}\n${timeline}` in blocks cut as bodyBlocks cuts the live body (a run of forced cuts is one block),
+ * read from the generation's manifest rows, so a page demoted inline since still yields its segmented versions.
+ * Counts its bytes and units in segmentedPassWork.
+ */
+async function* retainedGenerationBlocks(engine: Pick<BrainEngine, 'readManifest' | 'readSegmentTexts'>,
+ page: { id: number; slug: string; sourceId: string }, generation: number): AsyncIterable<string> {
+ const rows = await engine.readManifest(page.id, { generation });
+ for (const [n, region] of (['truth', 'timeline'] as const).entries()) {
+ if (n > 0) yield '\n';
+ const own = rows.filter(row => row.region === region);
+ for (let i = 0; i < own.length;) {
+ let j = i;
+ while (j + 1 < own.length && own[j]!.cutKind === 'forced') j++;
+ const run = own.slice(i, j + 1);
+ i = j + 1;
+ const bytes = run.reduce((sum, row) => sum + row.byteLen, 0);
+ if (bytes > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, page.sourceId, bytes);
+ const texts = await engine.readSegmentTexts(page.sourceId, run.map(row => row.sha256));
+ const text = Buffer.concat(run.map(row => {
+ const bytes = texts.get(Buffer.from(row.sha256).toString('hex'));
+ if (bytes === undefined) throw new Error(`Segment text of page ${page.id} generation ${generation} is missing.`);
+ return bytes;
+ })).toString('utf8');
+ segmentedPassWork.bytes += bytes;
+ segmentedPassWork.blocks += text.length;
+ yield text;
+ }
+ }
+}
+
/** 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 };
@@ -175,7 +207,7 @@ export type StoredTimelineTuple = TimelineTuple & { id: number; detail: string |
* `current` is the page text, or its keys when the caller read a segmented body (segmentedTimelineText).
*/
export async function retractRemovedTimelineEntries(
- engine: Pick<BrainEngine, 'executeRaw'>,
+ engine: Pick<BrainEngine, 'executeRaw' | 'readManifest' | 'readSegmentTexts'>,
slug: string,
sourceId: string,
current: string | TimelineTextKeys,
@@ -188,16 +220,19 @@ export async function retractRemovedTimelineEntries(
WHERE p.source_id = $1 AND p.slug = $2 AND t.event_page_id IS NULL`, [sourceId, slug]);
const extra = rows.filter(row => !kept.has(tupleKey(row)));
if (!extra.length) return [];
- const versions = await engine.executeRaw<{ compiled_truth: string; timeline: string | null }>(
- `SELECT DISTINCT v.compiled_truth, v.timeline FROM page_versions v JOIN pages p ON p.id = v.page_id
+ const versions = await engine.executeRaw<{ compiled_truth: string | null; timeline: string | null; body_storage: string; page_id: number; generation: number | null }>(
+ `SELECT DISTINCT v.compiled_truth, v.timeline, v.body_storage, v.page_id, v.body_generation AS generation FROM page_versions v JOIN pages p ON p.id = v.page_id
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(typeof current === 'string' ? supersededCitationTimeline(current).map(tupleKey) : current.superseded);
- for (const version of versions) {
- const text = `${version.compiled_truth}\n${version.timeline ?? ''}`;
+ const addText = (text: string) => {
for (const key of markdownTimelineKeys(text, slug)) produced.add(key);
for (const entry of supersededCitationTimeline(text)) superseded.add(tupleKey(entry));
+ };
+ for (const version of versions) {
+ if (version.body_storage !== 'segmented') { addText(`${version.compiled_truth}\n${version.timeline ?? ''}`); continue; }
+ for await (const block of retainedGenerationBlocks(engine, { id: Number(version.page_id), slug, sourceId }, Number(version.generation))) addText(block);
}
const orphans = extra.filter(row => produced.has(tupleKey(row)) || (superseded.has(tupleKey(row)) && hasExtractorDetail(row)))
.map(({ detail: _detail, ...row }) => row);
diff --git a/test/large-pages/forget-reason-segmented.test.ts b/test/large-pages/forget-reason-segmented.test.ts
new file mode 100644
index 0000000000..a692c1761b
--- /dev/null
+++ b/test/large-pages/forget-reason-segmented.test.ts
@@ -0,0 +1,79 @@
+/**
+ * Wave B PR 2 fix lane C2 (D7): forget keeps the caller's reason on a
+ * segmented page, as on an inline one.
+ *
+ * 1. Protects: on the fence path (the source has a local path and the page a
+ * file) forget strikes the file's row with the caller's reason, and the
+ * stored body mirrors the file: an inline page takes the file's text, a
+ * segmented page takes the file's struck row in the segment holding the
+ * fence. Both stored rows read `forgotten: <reason>` (parity).
+ * 2. Fails when: the segmented strike re-strikes the row the withdrawal
+ * already struck with the overlay's reason (`forgotten: memory withdrawn`)
+ * and keeps it, so the caller's reason never reaches the stored body.
+ * 3. Out of scope: the legacy path (no file) gives both storages the
+ * overlay's reason; that is unchanged.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { forgetFactInFence } from '../../src/core/facts/forget.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { reconstructedPage } from '../helpers/segmented-page-checks.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const REASON = 'asked to drop it on the call';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-forget-reason-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const fence = (claim: string) => `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${claim} | preference | 1.0 | world | medium | 2026-01-01 | | chat | said at lunch |
+| 2 | Walks to work | preference | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->`;
+const filler = (sections: number) => Array.from({ length: sections }, (_, i) => `## Part ${i}\n\n${'Notes on hiring and the budget review. '.repeat(30)}\n\n`).join('');
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, 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; }
+ for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }
+}), 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+describe('forget reason on a segmented page', () => {
+ test('the fence path stores the caller\'s reason in the segmented row, as in the inline row', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const [index, engine] of engines.entries()) {
+ const root = mkdtempSync(join(home, `brain-${index}-`));
+ mkdirSync(join(root, 'notes'));
+ await engine.executeRaw('UPDATE sources SET local_path=$1 WHERE id=$2', [root, 'default']);
+ const rows: Record<string, string | undefined> = {};
+ for (const [storage, sections] of [['inline', 2], ['segmented', 1500]] as const) {
+ const slug = `notes/forget-reason-${storage}`, claim = `Prefers the ${storage} window seat`;
+ const content = `---\ntitle: Reason\ntype: note\n---\n\n# Reason\n\n## Facts\n\n${fence(claim)}\n\n${filler(sections)}`;
+ writeFileSync(join(root, `${slug}.md`), content);
+ await importFromContent(engine, slug, content, { noEmbed: true, sourceId: 'default' });
+ const [fact] = await engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)
+ VALUES ('default',$1,$2,'world','test',$2,1) RETURNING id`, [claim, slug]), TEST_WRITE_ATTRIBUTION));
+ const result = await withCoordinatedWrite(engine, ['default'], () => forgetFactInFence(engine, Number(fact!.id), { reason: REASON }), TEST_WRITE_ATTRIBUTION);
+ expect(result).toMatchObject({ ok: true, path: 'fence' });
+ const [page] = await engine.executeRaw<{ body_storage: string; compiled_truth: string | null }>('SELECT body_storage, compiled_truth FROM pages WHERE slug=$1', [slug]);
+ expect(page!.body_storage).toBe(storage);
+ const stored = storage === 'segmented' ? (await reconstructedPage(engine, slug)).body.compiled_truth : page!.compiled_truth!;
+ const row = (text: string) => text.split('\n').find(line => line.startsWith('| 1 |'))?.replace(storage, 'STORAGE');
+ expect(row(stored)).toBe(row(readFileSync(join(root, `${slug}.md`), 'utf8')));
+ rows[storage] = row(stored);
+ }
+ expect(rows.segmented).toContain(`forgotten: ${REASON} \\| said at lunch`);
+ expect(rows.segmented).toBe(rows.inline);
+ }
+ }), 300_000);
+});
diff --git a/test/large-pages/purge-segment-residue.test.ts b/test/large-pages/purge-segment-residue.test.ts
new file mode 100644
index 0000000000..09db2b9317
--- /dev/null
+++ b/test/large-pages/purge-segment-residue.test.ts
@@ -0,0 +1,134 @@
+/**
+ * Wave B PR 2 fix lane C2 (D6): purge_fact leaves no pre-purge residue in
+ * page_view_digests or in an upload staging whose parts split the claim.
+ *
+ * 1. Protects: the purge deletes the cached view digests (sizes and sha256 of
+ * a read view) of every segmented page it rewrites, in its transaction; and
+ * it finds an open upload staging whose claim straddles a part boundary
+ * (also across a part shorter than the claim), aborts it and deletes its
+ * parts. The cross-part scan reads only each part's head and tail of the
+ * claim's length minus one (a work counter, not time), never a whole part.
+ * 2. Fails when: the digests of the pre-purge revision stay until the next
+ * write, or the staging scan matches only within one part (the staging
+ * stays open with the claim's bytes in its parts).
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { operations } from '../../src/core/operations.ts';
+import { purgeStagingWork } from '../../src/core/facts/purge.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const CLAIM = 'Garage gate code is 7734';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-residue-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const fence = (claim: string) => `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+| 2 | Likes green tea | preference | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->`;
+function filler(bytes: number): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## Section ${i}\n\n${`Notes on launch planning, pricing and roadmap review for week ${i}. `.repeat(30)}\n\n`;
+ parts.push(part);
+ n += part.length;
+ }
+ return parts.join('');
+}
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const purge = operations.find(o => o.name === 'purge_fact')!;
+const run = (engine: BrainEngine, params: Record<string, unknown>) => purge.handler(ctx(engine), params) as Promise<Record<string, any>>;
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, 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; }
+ for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }
+}), 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+/** An open upload staging whose parts are `parts`, in order. */
+async function stage(engine: BrainEngine, slug: string, parts: Buffer[]): Promise<string> {
+ const [source] = await engine.executeRaw<{ incarnation: string }>(`SELECT incarnation FROM sources WHERE id='default'`);
+ const stagingId = randomUUID();
+ const total = parts.reduce((n, part) => n + part.length, 0);
+ await coordinated(engine, async tx => {
+ await tx.openBodyStaging({ id: stagingId, kind: 'upload', principalKind: 'application', principalId: 'test:fixture', clientRequestId: randomUUID(),
+ sourceId: 'default', sourceIncarnation: source!.incarnation, slug, pageId: null, mode: 'create', baseRevision: null,
+ baseGeneration: null, declaredBytes: total, declaredSha256: null, reservedBytes: 0,
+ idleExpiresAt: new Date(Date.now() + 3_600_000), hardExpiresAt: new Date(Date.now() + 7_200_000) });
+ let at = 0;
+ for (const [n, part] of parts.entries()) {
+ await tx.executeRaw(`INSERT INTO page_body_staging_parts(staging_id,part_no,byte_start,byte_len,sha256,body) VALUES ($1::uuid,$2,$3,$4,$5,$6)`,
+ [stagingId, n, at, part.length, createHash('sha256').update(part).digest(), part]);
+ at += part.length;
+ }
+ });
+ return stagingId;
+}
+
+describe('purge_fact residue in view digests and staging parts', () => {
+ test('pre-purge view digests go, and stagings splitting the claim across parts are aborted', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await importFromContent(engine, 'notes/residue', `---\ntitle: Residue\ntype: note\n---\n\n# Residue\n\n## Facts\n\n${fence(CLAIM)}\n\n${filler(1_300_000)}`,
+ { noEmbed: true, sourceId: 'default' });
+ const page = await segmentedPageRow(engine, 'notes/residue');
+ expect(page.body_storage).toBe('segmented');
+ // A digest of the page's pre-purge read view, as get_page caches it.
+ const [revision] = await engine.executeRaw<{ r: string }>('SELECT knowledge_revision::text AS r FROM pages WHERE id=$1', [page.id]);
+ await engine.executeRaw(`INSERT INTO page_view_digests (page_id, revision, view, audience, total_bytes, total_lines, sha256) VALUES ($1,$2,'markdown','trusted',1000,10,$3)`,
+ [page.id, revision!.r, 'ab'.repeat(32)]);
+
+ // Two stagings: the claim split in the middle by a 1 MiB part boundary, and split over three parts by a 4-byte middle part.
+ const text = `Uploaded notes.\n${fence(CLAIM)}\n`;
+ const cut = text.indexOf(CLAIM) + 10;
+ const pad = Buffer.alloc(1024 * 1024, 'p');
+ const split = await stage(engine, 'notes/upload-split', [Buffer.concat([pad, Buffer.from(text.slice(0, cut))]), Buffer.concat([Buffer.from(text.slice(cut)), pad])]);
+ const three = await stage(engine, 'notes/upload-three', [Buffer.from(text.slice(0, cut)), Buffer.from(text.slice(cut, cut + 4)), Buffer.from(text.slice(cut + 4))]);
+ const untouched = await stage(engine, 'notes/upload-other', [Buffer.from('Unrelated notes about the garage.\n'), Buffer.from('Nothing to purge here.\n')]);
+ for (const id of [split, three]) {
+ const [whole] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_staging_parts WHERE staging_id=$1::uuid AND position(convert_to($2::text,'UTF8') in body)>0`, [id, CLAIM]);
+ expect(Number(whole!.n)).toBe(0);
+ }
+
+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)
+ VALUES ('default',$1,NULL,'world','test','notes/residue',1) RETURNING id`, [CLAIM]));
+ Object.assign(purgeStagingWork, { parts: 0, bytes: 0 });
+ const dry = await run(engine, { id: Number(fact!.id), dry_run: true });
+ const work = { ...purgeStagingWork };
+ const done = await run(engine, { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ expect(done.state).toBe('committed');
+ const state = async (id: string) => ({
+ state: (await engine.executeRaw<{ state: string }>('SELECT state FROM page_body_stagings WHERE id=$1::uuid', [id]))[0]?.state,
+ parts: Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_body_staging_parts WHERE staging_id=$1::uuid', [id]))[0]!.n),
+ });
+ expect({
+ digests: Number((await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM page_view_digests WHERE page_id=$1', [page.id]))[0]!.n),
+ split: await state(split), three: await state(three), untouched: await state(untouched),
+ // The dry run's scan visited the 7 parts and read at most a head and a tail of the claim's length minus one from each.
+ work: { parts: work.parts, withinBound: work.bytes <= work.parts * 2 * (Buffer.byteLength(CLAIM) - 1) },
+ }).toEqual({ digests: 0, split: { state: 'aborted', parts: 0 }, three: { state: 'aborted', parts: 0 }, untouched: { state: 'open', parts: 2 },
+ work: { parts: 7, withinBound: true } });
+ for (const id of [split, three, untouched]) await engine.executeRaw('DELETE FROM page_body_stagings WHERE id=$1::uuid', [id]);
+ }
+ }), 300_000);
+});
diff --git a/test/large-pages/purge-segmented-versions-batch.test.ts b/test/large-pages/purge-segmented-versions-batch.test.ts
new file mode 100644
index 0000000000..638f8686e7
--- /dev/null
+++ b/test/large-pages/purge-segmented-versions-batch.test.ts
@@ -0,0 +1,113 @@
+/**
+ * Wave B PR 2 fix lane C2 (D4): purge_fact redacts every retained segmented
+ * generation, past the first batch of versions.
+ *
+ * 1. Protects: the segmented version redaction walks page_versions in keyset
+ * batches of VERSION_REDACTION_BATCH (5,000), as the inline redaction does,
+ * so a generation whose version sorts after the first 5,000 candidate
+ * versions is rebuilt without the claim. Versions sharing a generation share
+ * one rebuild (the receipt counts two rebuilt generations).
+ * 2. Fails when: the segmented redaction reads one LIMIT 5000 page with no
+ * continuation (the later generation keeps the purged claim).
+ * 3. Fixture: 5,000 extra version rows of the first page reference generation
+ * 0, which no manifest row covers (empty, so each costs one manifest read),
+ * and push the second page's real version past the first batch.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/ops/contract.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { operations } from '../../src/core/operations.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { withCoordinatedWrite } from '../../src/core/persistence/context.ts';
+import { segmentedBodyContains } from '../../src/core/page-body/segment-rewrite.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { segmentedPageRow } from '../helpers/segmented-page-checks.ts';
+import { TEST_WRITE_ATTRIBUTION } from '../helpers/write-attribution.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const CLAIM = 'Locker combination is 2291';
+const home = mkdtempSync(join(tmpdir(), 'gbrain-purge-versions-batch-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+const FENCE = `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+| 1 | ${CLAIM} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |
+| 2 | Likes green tea | preference | 1.0 | world | medium | 2026-01-01 | | chat | |
+<!--- gbrain:facts:end -->`;
+function filler(bytes: number): string {
+ const parts: string[] = [];
+ for (let i = 0, n = 0; n < bytes; i++) {
+ const part = `## Section ${i}\n\n${`Notes on launch planning, pricing and roadmap review for week ${i}. `.repeat(30)}\n\n`;
+ parts.push(part);
+ n += part.length;
+ }
+ return parts.join('');
+}
+const page = (title: string, tail: string) => `---\ntitle: ${title}\ntype: note\n---\n\n# ${title}\n\n## Facts\n\n${FENCE}\n\n${filler(1_300_000)}## Tail\n\n${tail}\n`;
+
+const ctx = (engine: BrainEngine): OperationContext => ({ engine, sourceId: 'default', remote: false, dryRun: false,
+ config: { engine: engine.kind }, logger: { info() {}, warn() {}, error() {} } } as OperationContext);
+const purge = operations.find(o => o.name === 'purge_fact')!;
+const run = (engine: BrainEngine, params: Record<string, unknown>) => purge.handler(ctx(engine), params) as Promise<Record<string, any>>;
+const coordinated = <T>(engine: BrainEngine, fn: (tx: BrainEngine) => Promise<T>) =>
+ engine.transaction(tx => withCoordinatedWrite(tx, ['default'], () => fn(tx), TEST_WRITE_ATTRIBUTION));
+
+beforeAll(async () => withEnv({ GBRAIN_HOME: home }, 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; }
+ for (const engine of engines) { await registerLocalWriter(engine, 'cli'); await engine.setConfig('pages.segmented_storage', 'on'); }
+}), 120_000);
+afterAll(async () => { for (const engine of engines) await engine.disconnect(); await closePostgres?.(); rmSync(home, { recursive: true, force: true }); });
+
+/** The generation a page's (only) segmented version references. */
+async function versionGeneration(engine: BrainEngine, pageId: number): Promise<number> {
+ const rows = await engine.executeRaw<{ g: number }>(`SELECT DISTINCT body_generation AS g FROM page_versions WHERE page_id=$1 AND body_storage='segmented' AND body_generation>0`, [pageId]);
+ expect(rows).toHaveLength(1);
+ return Number(rows[0]!.g);
+}
+
+describe('purge_fact over more than one batch of segmented versions', () => {
+ test('a retained generation whose version sorts after the first 5,000 candidates is rebuilt without the claim', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ await importFromContent(engine, 'notes/batch-a', page('Batch A', 'First tail.'), { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, 'notes/batch-a', page('Batch A', 'Second tail.'), { noEmbed: true, sourceId: 'default' });
+ const a = await segmentedPageRow(engine, 'notes/batch-a');
+ const aGeneration = await versionGeneration(engine, a.id);
+ const [first] = await engine.executeRaw<{ g: number }>('SELECT min(gen_from) AS g FROM page_body_manifest WHERE page_id=$1', [a.id]);
+ expect(Number(first!.g)).toBeGreaterThan(0);
+ await coordinated(engine, tx => tx.executeRaw(`INSERT INTO page_versions (page_id,body_storage,body_generation,body_bytes,content_hash,frontmatter,knowledge_revision,title,type,tags,is_deleted,source_path)
+ SELECT v.page_id,'segmented',0,v.body_bytes,v.content_hash,v.frontmatter,v.knowledge_revision,v.title,v.type,v.tags,v.is_deleted,v.source_path
+ FROM page_versions v CROSS JOIN generate_series(1,5000) WHERE v.page_id=$1 AND v.body_storage='segmented' AND v.body_generation=$2`, [a.id, aGeneration]));
+ await importFromContent(engine, 'notes/batch-b', page('Batch B', 'First tail.'), { noEmbed: true, sourceId: 'default' });
+ await importFromContent(engine, 'notes/batch-b', page('Batch B', 'Second tail.'), { noEmbed: true, sourceId: 'default' });
+ const b = await segmentedPageRow(engine, 'notes/batch-b');
+ const bGeneration = await versionGeneration(engine, b.id);
+ const [order] = await engine.executeRaw<{ before: number }>(`SELECT count(*)::int AS before FROM page_versions
+ WHERE body_storage='segmented' AND id < (SELECT max(id) FROM page_versions WHERE page_id=$1)`, [b.id]);
+ expect(Number(order!.before)).toBeGreaterThanOrEqual(5001);
+ expect(await segmentedBodyContains(engine, b.id, 'default', [CLAIM], { generation: bGeneration })).toBe(true);
+
+ const [fact] = await coordinated(engine, tx => tx.executeRaw<{ id: number }>(`INSERT INTO facts(source_id,fact,entity_slug,visibility,source,source_markdown_slug,row_num)
+ VALUES ('default',$1,NULL,'world','test','notes/batch-a',1) RETURNING id`, [CLAIM]));
+ const dry = await run(engine, { id: Number(fact!.id), dry_run: true });
+ const done = await run(engine, { id: Number(fact!.id), confirm: dry.confirm_token, expected_revision: dry.expected_revision, request_id: randomUUID() });
+ expect(done.state).toBe('committed');
+ expect({
+ a: await segmentedBodyContains(engine, a.id, 'default', [CLAIM], { generation: aGeneration }),
+ b: await segmentedBodyContains(engine, b.id, 'default', [CLAIM], { generation: bGeneration }),
+ kept: await segmentedBodyContains(engine, b.id, 'default', ['likes green tea'], { generation: bGeneration }),
+ rebuilt: done.purge.removed.page_versions,
+ }).toEqual({ a: false, b: false, kept: true, rebuilt: 2 });
+ expect(JSON.stringify(done)).not.toContain(CLAIM);
+ }
+ }), 600_000);
+});
diff --git a/test/large-pages/segmented-conversation-sidecar-token.test.ts b/test/large-pages/segmented-conversation-sidecar-token.test.ts
new file mode 100644
index 0000000000..f2586402c5
--- /dev/null
+++ b/test/large-pages/segmented-conversation-sidecar-token.test.ts
@@ -0,0 +1,101 @@
+/**
+ * Wave B PR 2 fix lane C2 (D1): conversation facts finish on a segmented page
+ * over the window cap whose `raw_transcript` sidecar does not resolve.
+ *
+ * 1. Protects: such a page parses its own body (the newest window). Once the
+ * run inserts its first fact the prior-fact admission guard would empty the
+ * parser input, so the version token must not hash that input: the
+ * end-of-page recheck finds the page unchanged, the run writes its terminal
+ * row (pages_failed 0), and the next run skips the page as completed
+ * without reading a segment.
+ * 2. Fails when: the token hashes the guarded input (the recheck reports the
+ * page as concurrently edited, pages_failed 1, and every later run skips it
+ * for its prior facts without finishing).
+ * 3. Why existing coverage misses it: segmented-conversation-facts.test.ts runs
+ * its over-the-window extraction with an extractor that returns no facts.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set. Seams: a
+ * readSegmentTexts spy counts segment reads (a work counter, not time).
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { importFromFile } from '../../src/core/import-file.ts';
+import { readPageBodyPolicy } from '../../src/core/page-body/limits.ts';
+import { runExtractConversationFactsCore } from '../../src/commands/extract-conversation-facts.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+let dir: string;
+const SLUG = 'conversations/huge-sidecar';
+
+/** A dated chat log of about `bytes`, with long turns so the extractor sees a few thousand windows, not tens of thousands. */
+function chat(bytes: number): string {
+ const sentence = 'We went over the launch budget, the pricing review and the hiring roadmap again. ';
+ const parts: string[] = [];
+ let size = 0;
+ for (let day = 0; size < bytes; day++) {
+ parts.push(`## ${new Date(Date.UTC(2025, 0, 1) + day * 86_400_000).toISOString().slice(0, 10)}\n\n`);
+ for (let turn = 0; turn < 50; turn++) {
+ const line = `**${turn % 2 ? 'Alice Example' : 'Bob Example'}** (${9 + Math.floor(turn / 6)}:${String((turn * 10) % 60).padStart(2, '0')} AM): ${sentence.repeat(36)}day ${day} turn ${turn}.\n\n`;
+ parts.push(line);
+ size += line.length;
+ }
+ }
+ return parts.join('');
+}
+
+beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'segmented-sidecar-token-'));
+ 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 file = join(dir, 'huge-sidecar.md');
+ writeFileSync(file, `---\ntype: conversation\ntitle: Huge\ndate: 2025-01-01\nraw_transcript: transcripts/missing-example.txt\n---\n\n${chat(PAGE_MAX_BYTES + 2 * 1024 * 1024)}`);
+ for (const engine of engines) {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ expect(await importFromFile(engine, file, `${SLUG}.md`, { noEmbed: true, bodyPolicy: await readPageBodyPolicy(engine) })).toMatchObject({ status: 'imported' });
+ }
+}, 900_000);
+
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ await closePostgres?.();
+ rmSync(dir, { recursive: true, force: true });
+});
+
+describe('conversation facts on a segmented page over the window with an unresolved sidecar', () => {
+ test('the run finishes after inserting facts, and the next run skips it as completed without reading a segment', async () => {
+ const outcomes: unknown[] = [];
+ const expected: unknown[] = [];
+ for (const [index, engine] of engines.entries()) {
+ const [page] = await engine.executeRaw<{ body_storage: string; body_bytes: number }>('SELECT body_storage, body_bytes FROM pages WHERE slug=$1', [SLUG]);
+ expect(page!.body_storage).toBe('segmented');
+ expect(Number(page!.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ let calls = 0;
+ const first = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG], sleepMs: 0, segmentLimit: 1_000_000,
+ extractor: async () => (++calls === 1
+ ? [{ fact: 'Alice Example owns the launch budget', kind: 'fact', entity_slug: null, source: 'cli:extract-conversation-facts' }]
+ : []) as never });
+ const original = engine.readSegmentTexts.bind(engine);
+ let segmentReads = 0;
+ engine.readSegmentTexts = (async (sourceId: string, shas: Uint8Array[]) => { segmentReads += shas.length; return original(sourceId, shas); }) as BrainEngine['readSegmentTexts'];
+ let second: Awaited<ReturnType<typeof runExtractConversationFactsCore>>;
+ let secondCalls = 0;
+ try {
+ second = await runExtractConversationFactsCore(engine, { sourceId: 'default', slugs: [SLUG], sleepMs: 0, segmentLimit: 1_000_000,
+ extractor: async () => { secondCalls++; return []; } });
+ } finally {
+ delete (engine as { readSegmentTexts?: unknown }).readSegmentTexts;
+ }
+ outcomes.push({ engine: index, firstCalledExtractor: calls > 1, first: { failed: first.pages_failed, processed: first.pages_processed, inserted: first.facts_inserted },
+ second: { failed: second.pages_failed, completed: second.pages_skipped_completed, tooLarge: second.pages_skipped_too_large, calls: secondCalls, segmentReads } });
+ expected.push({ engine: index, firstCalledExtractor: true, first: { failed: 0, processed: 1, inserted: 1 },
+ second: { failed: 0, completed: 1, tooLarge: 0, calls: 0, segmentReads: 0 } });
+ }
+ expect(outcomes).toEqual(expected);
+ }, 1_800_000);
+});
diff --git a/test/large-pages/segmented-file-drift-ledger.test.ts b/test/large-pages/segmented-file-drift-ledger.test.ts
new file mode 100644
index 0000000000..6456668a84
--- /dev/null
+++ b/test/large-pages/segmented-file-drift-ledger.test.ts
@@ -0,0 +1,190 @@
+/**
+ * Wave B PR 2 fix lane C2 (D5): the file drift check of a segmented page over
+ * the single-string ceiling when its source has withdrawals.
+ *
+ * 1. Protects: a file holding a facts fence, under a withdrawal ledger that
+ * applies (any '*' withdrawal or purge in the source applies to every
+ * page), is compared overlaid instead of refused: each complete fence block
+ * of the file is overlaid alone, as the stored side overlays each segment,
+ * so the overlaid file digests equal the stored digests of the same body
+ * (also with a fence across a 1 MiB read boundary and a withdrawn row), and
+ * a file edited on disk to add a fence is refused as drift (source_changed,
+ * the refusal an inline page gets), not as page_body_segmented. A fence
+ * block longer than BLOCK_MAX_BYTES (one the stored side holds split across
+ * forced cuts) still refuses page_body_segmented (fail closed).
+ * 2. Fails when: the check refuses every fenced file whenever the source has
+ * any withdrawal (page_body_segmented), or the file overlay differs from the
+ * stored overlay.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import type { OperationContext } from '../../src/core/operations.ts';
+import { parseMarkdown } from '../../src/core/markdown.ts';
+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';
+import { fileBodyDigests, overlaidFileBodyDigests, storedBodyDigests } from '../../src/core/page-body/body-digests.ts';
+import { readBodyLedger } from '../../src/core/page-body/segment-ledger.ts';
+import { overlayCanonicalBodies } from '../../src/core/page-state/snapshot.ts';
+import { PAGE_MAX_BYTES } from '../../src/core/page-size-policy.ts';
+import { claimWorktree } from '../../src/core/persistence/ownership.ts';
+import { registerLocalWriter } from '../../src/core/persistence/identity.ts';
+import { importManagedFile } from '../../src/core/persistence/import-mutations.ts';
+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { withEnv } from '../helpers/with-env.ts';
+import { conversationPage } from '../helpers/conversation-page.ts';
+
+const home = mkdtempSync(join(tmpdir(), 'gbrain-segmented-file-drift-ledger-'));
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const env = { GBRAIN_HOME: home, OPENAI_API_KEY: undefined, VOYAGE_API_KEY: undefined, ANTHROPIC_API_KEY: undefined };
+const logger = { info() {}, warn() {}, error() {} };
+// Over the single-string ceiling, under the 25 MiB pre-push scan cap a restored file must fit.
+const huge = conversationPage(PAGE_MAX_BYTES + 512 * 1024, { seed: 97, needles: [{ at: 0.5, word: 'midpointmarker' }] });
+
+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 () => {
+ await withEnv(env, async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.();
+ });
+ rmSync(home, { recursive: true, force: true });
+});
+
+interface Fixture { sourceId: string; root: string; ctx: OperationContext }
+
+async function managedSource(engine: BrainEngine): Promise<Fixture> {
+ await disposePersistenceConsumer(engine);
+ await engine.setConfig('pages.segmented_storage', 'on');
+ const root = join(home, `src-${randomUUID().slice(0, 8)}`);
+ mkdirSync(join(root, 'notes'), { recursive: true });
+ execFileSync('git', ['init', '-q'], { cwd: root });
+ const sourceId = `drift-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("INSERT INTO sources(id,name,local_path,config) 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');
+ const ctx = { engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true } as never, dryRun: false, logger } as OperationContext;
+ return { sourceId, root, ctx };
+}
+
+async function importHuge(engine: BrainEngine, f: Fixture, slug: string): Promise<string> {
+ const file = join(f.root, `${slug}.md`);
+ writeFileSync(file, huge);
+ expect(await importManagedFile(engine, file, `${slug}.md`, { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ const [row] = await engine.executeRaw<{ body_storage: string; body_bytes: string }>('SELECT body_storage, body_bytes::text AS body_bytes FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, slug]);
+ expect(row?.body_storage).toBe('segmented');
+ expect(Number(row?.body_bytes)).toBeGreaterThan(PAGE_MAX_BYTES);
+ return file;
+}
+
+
+const revisionOf = async (engine: BrainEngine, f: Fixture, slug: string) => (await engine.readPageSnapshot(slug, { sourceId: f.sourceId, includeDeleted: true }))!.revision;
+
+async function submit(engine: BrainEngine, f: Fixture, operation: 'delete_page' | 'restore_page', slug: string, extra: Record<string, unknown> = {}) {
+ return submitPageMutation(f.ctx, { operation, params: { slug, expected_revision: await revisionOf(engine, f, slug), request_id: randomUUID(), ...extra } }) as Promise<Record<string, any>>;
+}
+
+async function refusal(p: Promise<unknown>): Promise<{ code?: string; message: string }> {
+ try { await p; } catch (error) { return { code: (error as { code?: string }).code, message: (error as Error).message }; }
+ throw new Error('expected a refusal');
+}
+
+
+const ROW = (n: number, claim: string) => `| ${n} | ${claim} | fact | 1.0 | world | medium | 2026-01-01 | | chat | |`;
+const FENCE = (rows: string[]) => `<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${rows.join('\n')}
+<!--- gbrain:facts:end -->`;
+const withdraw = (engine: BrainEngine, sourceId: string, claim: string) => engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash)
+ VALUES ($1, 'world', '*', gbrain_fact_fingerprint($2)) ON CONFLICT DO NOTHING`, [sourceId, claim]);
+
+test('a fenced file under withdrawals is overlaid block by block to the stored digests of the same body', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await managedSource(engine);
+ const slug = 'notes/overlay-parity';
+ // A fence near the top of the truth, one straddling the timeline's 1 MiB read boundary, a withdrawn row in each.
+ const line = 'Notes on planning, pricing and the roadmap review.\n\n';
+ const lead = line.repeat(Math.floor((1024 * 1024 - 400) / line.length));
+ const content = `---\ntitle: Overlay parity\ntype: note\n---\n\n# Overlay parity\n\n${FENCE([ROW(1, 'Door code is 5512'), ROW(2, 'Likes green tea')])}\n\n${line.repeat(20_000)}\n<!-- timeline -->\n\n${lead}`
+ + `${FENCE([ROW(3, 'Vault code is 8841'), ROW(4, 'Walks to work'), ROW(5, 'Reads on the train')])}\n\n${line.repeat(20_000)}`;
+ writeFileSync(join(f.root, `${slug}.md`), content);
+ expect(await importManagedFile(engine, join(f.root, `${slug}.md`), `${slug}.md`, { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ await disposePersistenceConsumer(engine);
+ const [page] = await engine.executeRaw<{ id: number; body_storage: string }>('SELECT id, body_storage FROM pages WHERE source_id=$1 AND slug=$2', [f.sourceId, slug]);
+ expect(page!.body_storage).toBe('segmented');
+ await withdraw(engine, f.sourceId, 'Door code is 5512');
+ await withdraw(engine, f.sourceId, 'Vault code is 8841');
+ const ledger = await readBodyLedger(engine, f.sourceId, slug);
+ expect(ledger.withdrawals.length).toBeGreaterThanOrEqual(2);
+ const bytes = Buffer.from(content, 'utf8');
+ // The timeline fence straddles the file side's first 1 MiB read boundary in its region.
+ const timeline = Buffer.from(parseMarkdown(content, `${slug}.md`).timeline, 'utf8');
+ expect(timeline.indexOf('gbrain:facts:begin')).toBeLessThan(SEGMENT_MAX_BYTES);
+ expect(timeline.indexOf('gbrain:facts:end')).toBeGreaterThan(SEGMENT_MAX_BYTES);
+ const reading = { prefix: new Uint8Array(0), skip: 0 };
+ const file = fileBodyDigests(bytes, reading, `${slug}.md`, {});
+ if (file.kind !== 'ok') throw new Error(file.reason);
+ expect(file.factsFence).toBe(true);
+ const overlays: string[] = [];
+ const overlaid = await overlaidFileBodyDigests(bytes, reading, file.regions, async text => {
+ overlays.push(text);
+ return (await overlayCanonicalBodies(engine.executeRaw.bind(engine), text, '', ledger.withdrawals, { sourceId: f.sourceId, marker: ledger.globalPurges })).compiled_truth;
+ }, () => new Error('refused'));
+ // Without the ledger the file is the stored body byte for byte; with it, both sides strike the same rows.
+ expect(file.digests).toEqual(await storedBodyDigests(engine, Number(page!.id), { withdrawals: [] }));
+ const stored = await storedBodyDigests(engine, Number(page!.id), ledger);
+ const [forced] = await engine.executeRaw<{ n: number }>(`SELECT count(*)::int AS n FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND cut_kind='forced'`, [page!.id]);
+ expect(Number(forced!.n)).toBe(0);
+ expect(overlaid).toEqual(stored);
+ expect(overlaid.truth).not.toBe(file.digests.truth);
+ // Each overlay call saw complete fence blocks only, never the whole region.
+ expect(overlays.length).toBeGreaterThanOrEqual(2);
+ for (const text of overlays) expect(text.split('gbrain:facts:begin').length).toBe(text.split('gbrain:facts:end').length);
+ expect(Math.max(...overlays.map(text => Buffer.byteLength(text)))).toBeLessThan(bytes.length);
+ }
+}), 600_000);
+
+test('under a source withdrawal, a fence added on disk is drift and a fence too long to overlay whole refuses', async () => withEnv(env, async () => {
+ for (const engine of engines) {
+ const f = await managedSource(engine);
+ try {
+ await withdraw(engine, f.sourceId, 'Some unrelated withdrawn claim');
+ const small = join(f.root, 'notes/small.md');
+ writeFileSync(small, '---\ntitle: Small note\ntype: note\n---\n\nA short body.\n');
+ expect(await importManagedFile(engine, small, 'notes/small.md', { sourceId: f.sourceId, noEmbed: true })).toMatchObject({ status: 'imported' });
+ writeFileSync(small, `---\ntitle: Small note\ntype: note\n---\n\nA short body.\n\n${FENCE([ROW(1, 'Added on disk')])}\n`);
+ const inline = await refusal(submit(engine, f, 'delete_page', 'notes/small'));
+ expect(inline).toMatchObject({ code: 'source_changed', message: 'The canonical file contains an uncoordinated local edit.' });
+
+ const file = await importHuge(engine, f, 'notes/huge');
+ writeFileSync(file, huge.replace('midpointmarker', `midpointmarker\n\n${FENCE([ROW(1, 'Added on disk')])}\n`));
+ expect(await refusal(submit(engine, f, 'delete_page', 'notes/huge'))).toEqual(inline);
+ expect(await refusal(submit(engine, f, 'delete_page', 'notes/huge', { purge: true }))).toEqual(inline);
+
+ const rows = Array.from({ length: 90_000 }, (_, i) => ROW(i + 1, `Routine note number ${i + 1} about the weekly planning meeting`));
+ const long = FENCE(rows);
+ expect(Buffer.byteLength(long)).toBeGreaterThan(8 * 1024 * 1024);
+ writeFileSync(file, huge.replace('midpointmarker', `midpointmarker\n\n${long}\n`));
+ const refused = await refusal(submit(engine, f, 'delete_page', 'notes/huge'));
+ expect(refused.code).toBe('page_body_segmented');
+ expect(refused.message).toContain('longer than a block');
+ expect(readFileSync(file, 'utf8').includes('Routine note number 90000')).toBe(true);
+ } finally {
+ await disposePersistenceConsumer(engine);
+ }
+ }
+}), 900_000);
diff --git a/test/large-pages/segmented-think-compile-leads.serial.test.ts b/test/large-pages/segmented-think-compile-leads.serial.test.ts
new file mode 100644
index 0000000000..fb79e45652
--- /dev/null
+++ b/test/large-pages/segmented-think-compile-leads.serial.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Wave B PR 2 fix lane C2 (D2): think and compile-context on segmented pages.
+ *
+ * 1. Protects: think's gather reads a segmented page's lead from its stored
+ * truth_lead (overlaid with the page's withdrawal ledger), so an anchored
+ * think hydrates the anchor row and the temporal-window floor keeps the
+ * page; compile-context renders the page's excerpt and relationship-note
+ * summary from the same lead. Each matches the same body stored inline
+ * (parity: the same opening text) and shows no private, withdrawn or
+ * purged row.
+ * 2. Fails when: gather or compile-context reads Page.compiled_truth of a
+ * segmented page (the getter throws page_body_segmented: the anchored
+ * think rejects, the window floor drops every page with
+ * GATHER_WINDOW_FLOOR_FAILED, compile-context aborts).
+ * 3. Serial: the embed transport is stubbed process-wide (keyword-only gather).
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../../src/core/engine.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { importFromContent } from '../../src/core/import-file.ts';
+import { runGather } from '../../src/core/think/gather.ts';
+import { parseTemporalWindow } from '../../src/core/think/temporal-window.ts';
+import { compileView } from '../../src/core/context/compile-view.ts';
+import { loadSensitivityConfig } from '../../src/core/context/sensitivity-scan.ts';
+import { __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { testBackends } from '../helpers/test-backends.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import { PRIVATE, importSegmented, pageContent, privacyFacts, privacyText, privateTokensIn, seedLedger } from '../helpers/segmented-privacy-fixture.ts';
+
+const SLUG = 'people/think-lead-example';
+const INLINE = 'people/think-lead-inline-example';
+const OPENING = 'Think Lead Example runs research at acme-example and writes about widgets.';
+/** Leads do not apply the fence overlay's holds, inline or segmented (segmented-leads.test.ts), so a held row is not counted. */
+const leaked = (text: string) => privateTokensIn(text).filter(token => token !== PRIVATE.held);
+/**
+ * Lead parity as segmented-leads.test.ts states it: the same opening text. The two bounded prefixes are cut at
+ * different points (the segmented lead is overlaid alone), so the shorter is a prefix of the longer.
+ */
+function expectSameLead(segmented: string, inline: string): void {
+ expect(Math.min(segmented.length, inline.length)).toBeGreaterThan(4000);
+ const [shorter, longer] = segmented.length <= inline.length ? [segmented, inline] : [inline, segmented];
+ expect(longer.startsWith(shorter)).toBe(true);
+}
+const tmp = mkdtempSync(join(tmpdir(), 'segmented-think-compile-'));
+
+beforeAll(() => { __setEmbedTransportForTests(() => { throw new Error('keyword-only test'); }); });
+afterAll(() => { __setEmbedTransportForTests(null); rmSync(tmp, { recursive: true, force: true }); });
+
+for (const kind of testBackends()) {
+ describe(`think and compile-context leads of a segmented page (${kind})`, () => {
+ let engine: BrainEngine;
+ let close: () => Promise<void>;
+
+ beforeAll(async () => {
+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));
+ else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ close = () => engine.disconnect();
+ }
+ const content = pageContent(`${OPENING}\n\n${privacyFacts()}\n${privacyText(mulberry32(907), 1_500_000)}`);
+ await engine.setConfig('pages.segmented_storage', 'off');
+ await importFromContent(engine, INLINE, content, { sourceId: 'default', noEmbed: true });
+ await importSegmented(engine, SLUG, content);
+ await seedLedger(engine, SLUG);
+ await seedLedger(engine, INLINE);
+ await engine.executeRaw(`UPDATE pages SET effective_date='2026-07-17T12:00:00Z', updated_at='2026-07-17T12:00:00Z' WHERE slug = ANY($1::text[])`, [[SLUG, INLINE]]);
+ }, 240_000);
+
+ afterAll(async () => { await close(); });
+
+ test('an anchored think hydrates the segmented anchor with the inline lead', async () => {
+ const leads: Record<string, string> = {};
+ for (const slug of [SLUG, INLINE]) {
+ const gathered = await runGather(engine, { question: 'qqnomatchquestion', anchor: slug });
+ expect(gathered.warnings).toEqual([]);
+ leads[slug] = gathered.pages.find(p => p.slug === slug)!.chunk_text;
+ }
+ expect(leads[SLUG]).toContain(OPENING);
+ expect(leaked(leads[SLUG]!)).toEqual([]);
+ expectSameLead(leads[SLUG]!, leads[INLINE]!);
+ }, 120_000);
+
+ test('the temporal-window floor keeps the segmented page with the inline lead', async () => {
+ const gathered = await runGather(engine, { question: 'qqnomatchquestion', window: parseTemporalWindow('2026-07-17', '2026-07-18')! });
+ expect(gathered.warnings).toEqual([]);
+ const lead = (slug: string) => gathered.pages.find(p => p.slug === slug)?.chunk_text;
+ expect(lead(SLUG)).toContain(OPENING);
+ expect(leaked(lead(SLUG)!)).toEqual([]);
+ expectSameLead(lead(SLUG)!, lead(INLINE)!);
+ }, 120_000);
+
+ test('compile-context renders the segmented excerpt as it renders the inline one', async () => {
+ const view = await compileView({ engine, sourceId: 'default', target: 'claude-code', budget: 8000,
+ scanConfig: loadSensitivityConfig({ workspaceRoot: tmp, blocklist: '', userPatternsPath: join(tmp, 'no-such-patterns.txt') }) });
+ const entry = (slug: string) => view.text.split('\n\n## ').find(block => block.includes(`(brain://${slug})`))?.trim();
+ expect(entry(SLUG)).toContain(OPENING);
+ expect(leaked(entry(SLUG)!)).toEqual([]);
+ expect(entry(SLUG)!.replace(SLUG, 'SLUG')).toBe(entry(INLINE)!.replace(INLINE, 'SLUG'));
+ }, 120_000);
+ });
+}
diff --git a/test/large-pages/segmented-timeline-retract-versions.test.ts b/test/large-pages/segmented-timeline-retract-versions.test.ts
new file mode 100644
index 0000000000..44e2f53d42
--- /dev/null
+++ b/test/large-pages/segmented-timeline-retract-versions.test.ts
@@ -0,0 +1,73 @@
+/**
+ * Wave B PR 2 fix lane C2 (D3): timeline retraction reads a segmented page's
+ * retained versions.
+ *
+ * 1. Protects: a dated bullet an earlier segmented version held and the
+ * current body no longer holds is retracted (its row was produced by a
+ * version of the page). A segmented page_versions row has NULL body
+ * columns and references a body generation, so the reconciliation streams
+ * that generation's stored text block by block (each block once: the work
+ * counter equals the live body's bytes plus the retained generation's).
+ * 2. Fails when: the retraction reads the segmented version's NULL columns
+ * (the text `null\n`), finds no version producing the row, and keeps the
+ * removed bullet's row forever.
+ * 3. Why existing coverage misses it: segmented-derived-passes.test.ts seeds
+ * an inline version only.
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set. Seams: segmentedPassWork (a work counter, not time).
+ */
+import { afterAll, beforeAll, 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 { extractTimelineFromDB } from '../../src/commands/extract-timeline-db.ts';
+import { pruneTimelineOrphans } from '../../src/core/timeline-extract.ts';
+import { segmentedPassWork } from '../../src/core/page-body/segment-blocks.ts';
+import { conversationBody } from '../helpers/conversation-page.ts';
+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+
+const SLUG = 'notes/segmented-retract';
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+const KICKOFF = '- **2026-03-04** | Kickoff with the design team';
+const PRICING = '- **2026-04-05** | Pricing review';
+
+/** ~2.4 MiB, the dated bullets after the first ~1.2 MiB. */
+const page = (bullets: string[]) => `---\ntype: note\ntitle: Retract\n---\n\n${conversationBody(1_200_000, { seed: 41 })}\n\n`
+ + `${conversationBody(1_200_000, { seed: 42 })}\n\n## Timeline\n\n${bullets.join('\n')}\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; }
+}, 120_000);
+
+afterAll(async () => {
+ for (const engine of engines) await engine.disconnect();
+ await closePostgres?.();
+});
+
+describe('timeline retraction over segmented versions', () => {
+ test('a bullet only a retained segmented generation held is retracted, reading that generation once', async () => {
+ for (const engine of engines) {
+ await engine.setConfig('pages.segmented_storage', 'on');
+ expect(await importFromContent(engine, SLUG, page([KICKOFF, PRICING]), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ await extractTimelineFromDB(engine, { dryRun: false, jsonMode: false, quiet: true, sourceIdFilter: 'default', slugs: [SLUG] });
+ const rows = async () => (await engine.executeRaw<{ summary: string }>(`SELECT t.summary FROM timeline_entries t JOIN pages p ON p.id=t.page_id
+ WHERE p.slug=$1 AND t.event_page_id IS NULL ORDER BY t.date`, [SLUG])).map(row => row.summary);
+ expect(await rows()).toEqual(['Kickoff with the design team', 'Pricing review']);
+ expect(await importFromContent(engine, SLUG, page([KICKOFF]), { sourceId: 'default', noEmbed: true })).toMatchObject({ status: 'imported' });
+ const [live] = await engine.executeRaw<{ id: number; body_storage: string; body_bytes: number; body_generation: number }>(
+ 'SELECT id, body_storage, body_bytes, body_generation FROM pages WHERE slug=$1', [SLUG]);
+ expect(live!.body_storage).toBe('segmented');
+ const versions = await engine.executeRaw<{ body_storage: string; body_bytes: number; body_generation: number; compiled_truth: string | null }>(
+ 'SELECT body_storage, body_bytes, body_generation, compiled_truth FROM page_versions WHERE page_id=$1', [live!.id]);
+ // The rewrite versioned the page first: a reference to the older generation, its body columns NULL.
+ const retained = new Map(versions.map(v => [Number(v.body_generation), Number(v.body_bytes)]));
+ expect(versions.every(v => v.body_storage === 'segmented' && v.compiled_truth === null)).toBe(true);
+ expect([...retained.keys()].every(g => g < Number(live!.body_generation))).toBe(true);
+ const before = segmentedPassWork.bytes;
+ const pruned = await pruneTimelineOrphans(engine, { sourceId: 'default', dryRun: false });
+ expect({ removed: pruned.removed, rows: await rows(), bytes: segmentedPassWork.bytes - before })
+ .toEqual({ removed: 1, rows: ['Kickoff with the design team'], bytes: Number(live!.body_bytes) + [...retained.values()].reduce((a, b) => a + b, 0) });
+ }
+ }, 600_000);
+});
diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txt
index 75dceb8de2..3cd2598a37 100644
--- a/test/postgres-unit-arms.txt
+++ b/test/postgres-unit-arms.txt
@@ -66,6 +66,7 @@ test/lane-apply-pipelining.test.ts
test/large-pages/chunk-visibility.test.ts
test/large-pages/contextual-reembed-segmented.test.ts
test/large-pages/credential-reseal-segments.test.ts
+test/large-pages/forget-reason-segmented.test.ts
test/large-pages/forget-scope.test.ts
test/large-pages/managed-import-outside-root.test.ts
test/large-pages/managed-streamed-import.test.ts
@@ -74,6 +75,8 @@ test/large-pages/managed-sync-streamed.test.ts
test/large-pages/oversized-backfill-segmented.test.ts
test/large-pages/page-purge-segments.test.ts
test/large-pages/projection-parity.test.ts
+test/large-pages/purge-segment-residue.test.ts
+test/large-pages/purge-segmented-versions-batch.test.ts
test/large-pages/purge-segments.test.ts
test/large-pages/remote-get-page-privacy.test.ts
test/large-pages/remote-window-privacy.test.ts
@@ -82,6 +85,7 @@ test/large-pages/segment-vector-reuse.test.ts
test/large-pages/segmented-append-reembed.test.ts
test/large-pages/segmented-body-unreachable.test.ts
test/large-pages/segmented-conversation-facts.test.ts
+test/large-pages/segmented-conversation-sidecar-token.test.ts
test/large-pages/segmented-create-searchable.test.ts
test/large-pages/segmented-derived-parity.test.ts
test/large-pages/segmented-derived-passes.test.ts
@@ -91,6 +95,7 @@ test/large-pages/segmented-embedding.test.ts
test/large-pages/segmented-evidence-read-cost.test.ts
test/large-pages/segmented-evidence.test.ts
test/large-pages/segmented-facts-reconcile.test.ts
+test/large-pages/segmented-file-drift-ledger.test.ts
test/large-pages/segmented-file-drift.test.ts
test/large-pages/segmented-get-cli.test.ts
test/large-pages/segmented-get-page-parity.test.ts
@@ -103,6 +108,8 @@ test/large-pages/segmented-search-dedup.test.ts
test/large-pages/segmented-shrink-below-ceiling.test.ts
test/large-pages/segmented-storage-visibility.test.ts
test/large-pages/segmented-switch.test.ts
+test/large-pages/segmented-think-compile-leads.serial.test.ts
+test/large-pages/segmented-timeline-retract-versions.test.ts
test/large-pages/segmented-versions.test.ts
test/link-cross-source.test.ts
test/link-preparation-shared-index.test.ts