Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Wave B PR 1 lane 1b-ii: segmenter, streaming region scan, entry state, per-segment chunker

garrytan8c9c65f60b0a
diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.ts
index e46893a947..b7d47ac281 100644
--- a/src/core/chunkers/recursive.ts
+++ b/src/core/chunkers/recursive.ts
@@ -102,6 +102,24 @@ export interface TextChunk {
// rows go.
export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {
+ if (!text || text.trim().length === 0) return [];
+
+ // v0.28: strip fenced takes blocks BEFORE chunking. Takes are retrieval-
+ // accessible only via the takes table; their content must not appear in
+ // content_chunks where the per-token allow-list cannot reach.
+ //
+ // v0.32.2: also strip private facts (Codex R2-#1). World facts stay so
+ // search retains its public-knowledge surface; private rows are filtered
+ // out at the fence-row level via stripFactsFence({keepVisibility:['world']}).
+ return chunkProjectedText(credentialSafeProjection(sanitizeRemoteBody(text)), opts);
+}
+
+/**
+ * chunkText on text that is already the retrieval projection (sanitized and
+ * credential-safe): segmented pages build it per segment from stored regions
+ * (page-body/segment-chunks.ts). Spans index `stripped`.
+ */
+export function chunkProjectedText(stripped: string, opts?: ChunkOptions): TextChunk[] {
const chunkSize = opts?.chunkSize || 300;
const chunkOverlap = opts?.chunkOverlap || 50;
const maxChars = opts?.maxChars || 6000;
@@ -112,16 +130,6 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {
? Math.min(opts.maxTokens, DEFAULT_MAX_CHUNK_TOKENS)
: DEFAULT_MAX_CHUNK_TOKENS;
- if (!text || text.trim().length === 0) return [];
-
- // v0.28: strip fenced takes blocks BEFORE chunking. Takes are retrieval-
- // accessible only via the takes table; their content must not appear in
- // content_chunks where the per-token allow-list cannot reach.
- //
- // v0.32.2: also strip private facts (Codex R2-#1). World facts stay so
- // search retains its public-knowledge surface; private rows are filtered
- // out at the fence-row level via stripFactsFence({keepVisibility:['world']}).
- const stripped = credentialSafeProjection(sanitizeRemoteBody(text));
if (!stripped || stripped.trim().length === 0) return [];
const wordCount = countWords(stripped);
diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.ts
index e72ef28d65..9c5f00ae99 100644
--- a/src/core/conversation-parser/parse.ts
+++ b/src/core/conversation-parser/parse.ts
@@ -359,6 +359,8 @@ function monthNameToIndex(name: string): number {
// #4136 — folded-heading detection constants. The label capture is capped at
// 48 chars (privacy: labels can carry page text into stderr/JSON) and the
// list at 10 entries per parse.
+/** A markdown day heading (`## 2024-03-15`, levels 1-4): the date context for time-only patterns. */
+export const DAY_HEADER_RE = /^#{1,4}\s+(\d{4}-\d{2}-\d{2})\s*$/;
const UNRECOGNIZED_HEADING_RE = /^(#{1,6})\s+(.{1,48}?)\s*:?\s*$/;
const FENCE_RE = /^(```|~~~)/;
const MAX_UNRECOGNIZED_HEADINGS = 10;
@@ -393,7 +395,7 @@ export function applyPattern(
// of repeating a date on every message. Keep the caller's context immutable
// while advancing a local date anchor as those headings are encountered.
const runningCtx: DateContext = { ...dateCtx };
- const dateHeaderRe = /^#{1,4}\s+(\d{4}-\d{2}-\d{2})\s*$/;
+ const dateHeaderRe = DAY_HEADER_RE;
// #4136 — when the WINNING pattern anchors on headings, a heading-shaped
// line whose label is outside the pattern's closed speaker set is not
// rejected and not reported: it folds into the PREVIOUS turn's body
@@ -706,6 +708,63 @@ export function scorePatternFull(body: string, entry: PatternEntry): number {
return scoreFromLines(getNonBlankLines(body), entry);
}
+type Scored = { entry: PatternEntry; score: number; priority: number };
+
+function sortScored(arr: Scored[]): Scored[] {
+ return arr.sort((a, b) => {
+ if (b.score !== a.score) return b.score - a.score;
+ return a.priority - b.priority;
+ });
+}
+
+/**
+ * D18: score every candidate on the head; highest first. Tie-break on
+ * declared priority order (built-in declaration order; user patterns
+ * lose every tie).
+ */
+function headScores(body: string, candidates: readonly PatternEntry[]): Scored[] {
+ return sortScored(candidates.map((entry) => ({
+ entry,
+ score: scorePattern(body, entry),
+ priority: priorityOf(entry.id),
+ })));
+}
+
+/**
+ * The built-in pattern a page's head picks by parseConversation's head
+ * pass, or null when that pass would not decide alone: the best head
+ * score is below the full-body fallback threshold, or the winner needs a
+ * full-body re-score. Segmented pages choose their message-anchor cut
+ * pattern with it once, from a bounded head (page-body/segmenter.ts).
+ */
+export function pickHeadPattern(head: string): string | null {
+ if (!head) return null;
+ const top = headScores(head, BUILTIN_PATTERNS)[0];
+ if (!top || top.score < SCORING_HEAD_TRIGGER_THRESHOLD || top.entry.score_full_body) return null;
+ return top.entry.id;
+}
+
+/**
+ * Whether `line` opens a message under built-in pattern `patternId`, as
+ * applyPattern reads it (trimmed; quick_reject, then the anchor regex), and
+ * the inline date it carries when the pattern has one. Null when it does not
+ * open one (day headers never do) or the id is unknown.
+ */
+export function matchAnchorLine(patternId: string, line: string): { date: string | null } | null {
+ const entry = BUILTIN_PATTERNS.find((p) => p.id === patternId);
+ const text = line.trim();
+ if (!entry || !text) return null;
+ if (entry.quick_reject && !entry.quick_reject.test(text)) return null;
+ const m = entry.regex.exec(text);
+ if (!m) return null;
+ const group = entry.captures.date_group;
+ return { date: group === undefined ? null : m[group] ?? null };
+}
+
+export function isAnchorLine(patternId: string, line: string): boolean {
+ return matchAnchorLine(patternId, line) !== null;
+}
+
/**
* Parse a conversation body into messages. Tries built-in patterns
* (minus disabled), then user patterns (D7-validated), then optional
@@ -741,21 +800,7 @@ export function parseConversation(
return { messages: [], phase: 'no_match' };
}
- // D18: score every candidate; pick the highest. Tie-break on
- // declared priority order (built-in declaration order; user patterns
- // lose every tie).
- type Scored = { entry: PatternEntry; score: number; priority: number };
- const sortScored = (arr: Scored[]) =>
- arr.sort((a, b) => {
- if (b.score !== a.score) return b.score - a.score;
- return a.priority - b.priority;
- });
- let scored: Scored[] = candidates.map((entry) => ({
- entry,
- score: scorePattern(body, entry),
- priority: priorityOf(entry.id),
- }));
- sortScored(scored);
+ let scored = headScores(body, candidates);
// REGRESSION (closes #1533 + Codex P1 #1): meeting pages have
// ## Summary + blockquote + ## Transcript ahead of the chat. The
diff --git a/src/core/fence-scan.ts b/src/core/fence-scan.ts
index e195b72390..6ab5bdee41 100644
--- a/src/core/fence-scan.ts
+++ b/src/core/fence-scan.ts
@@ -135,6 +135,20 @@ export interface MarkdownCodeMap {
}
export function scanMarkdownCode(markdown: string): MarkdownCodeMap {
+ const { fenced, unclosedAt, mispaired, hasCR } = walkMarkdownCode(markdown);
+ return { body: markdown, fenced: mispaired || unclosedAt !== -1 ? [] : fenced, unclosedAt, hasCR, line: null };
+}
+
+/**
+ * Whether scanMarkdownCode trusts this body's fenced blocks: every opener
+ * closes and no block holds a line that could open a block as long as its own.
+ */
+export function markdownFenceTrusted(markdown: string): boolean {
+ const { unclosedAt, mispaired } = walkMarkdownCode(markdown);
+ return unclosedAt === -1 && !mispaired;
+}
+
+function walkMarkdownCode(markdown: string): { fenced: Array<[number, number]>; unclosedAt: number; mispaired: boolean; hasCR: boolean } {
const fenced: Array<[number, number]> = [];
const len = markdown.length;
const hasCR = markdown.includes('\r');
@@ -167,11 +181,11 @@ export function scanMarkdownCode(markdown: string): MarkdownCodeMap {
}
// Unclosed: this is the block every fence writer must stay above. No
// block is trusted any more, so there is nothing left to pair.
- return { body: markdown, fenced: [], unclosedAt: start, hasCR, line: null };
+ return { fenced, unclosedAt: start, mispaired, hasCR };
}
start = next;
}
- return { body: markdown, fenced: mispaired ? [] : fenced, unclosedAt: -1, hasCR, line: null };
+ return { fenced, unclosedAt: -1, mispaired, hasCR };
}
/**
@@ -300,6 +314,13 @@ function pushInlineCodeRanges(s: string, start: number, end: number, out: Array<
}
}
+/** Same-line inline code spans of one line (no line terminator), as `inlineCodeEndAt` computes them. */
+export function inlineCodeSpans(line: string): Array<[number, number]> {
+ const spans: Array<[number, number]> = [];
+ if (line.includes('`')) pushInlineCodeRanges(line, 0, line.length, spans);
+ return spans;
+}
+
function insideRange(ranges: Array<[number, number]>, at: number): number {
let lo = 0;
let hi = ranges.length - 1;
diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.ts
index eb0bb9fe0c..db219a06c5 100644
--- a/src/core/link-extraction.ts
+++ b/src/core/link-extraction.ts
@@ -2120,7 +2120,7 @@ export function findTimelineSourceDelimiter(text: string): number {
// pass skips the lines they read.
// `### YYYY-MM-DD — summary` headings, as the FS extractor (timeline-extract.ts Format 2) accepts.
-const TIMELINE_HEADING_RE = /^\s*###\s+(\d{4}-\d{2}-\d{2})\s*[\-–—]+\s*(.+?)\s*$/;
+export const TIMELINE_HEADING_RE = /^\s*###\s+(\d{4}-\d{2}-\d{2})\s*[\-–—]+\s*(.+?)\s*$/;
/**
* Parse timeline entries from content. Looks at:
diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.ts
index f0a664fb55..ca289682e7 100644
--- a/src/core/markdown-chunks.ts
+++ b/src/core/markdown-chunks.ts
@@ -59,11 +59,24 @@ export const fenceParseTimeoutMs = () => positiveEnv('GBRAIN_FENCE_PARSE_TIMEOUT
export const fenceParseBudgetMs = () => positiveEnv('GBRAIN_FENCE_PARSE_BUDGET_MS', 5_000);
/** Sanitize the complete body before scanning any fenced code. */
-async function extractFencedChunks(
- markdown: string,
- startChunkIndex: number,
-): Promise<ChunkInput[]> {
- markdown = credentialSafeProjection(sanitizeRemoteBody(markdown));
+function extractFencedChunks(markdown: string, startChunkIndex: number): Promise<ChunkInput[]> {
+ return fencedCodeChunks(credentialSafeProjection(sanitizeRemoteBody(markdown)), startChunkIndex);
+}
+
+/**
+ * The fence cap (MAX_FENCES_PER_PAGE) and parse budget one page shares. A
+ * segmented page passes one budget to every segment's fencedCodeChunks call,
+ * so the caps stay per page.
+ */
+export interface FenceChunkBudget { fences: number; spentMs: number }
+
+export function newFenceChunkBudget(): FenceChunkBudget {
+ return { fences: MAX_FENCES_PER_PAGE, spentMs: 0 };
+}
+
+/** Recognized code-fence chunks of an already projected (sanitized, credential-safe) text. */
+export async function fencedCodeChunks(markdown: string, startChunkIndex: number,
+ budget: FenceChunkBudget = newFenceChunkBudget()): Promise<ChunkInput[]> {
const out: ChunkInput[] = [];
// Fast path: most pages (prose, tables, converted docs) contain no code
// fence at all, so there is nothing for this function to extract — skip
@@ -72,7 +85,8 @@ async function extractFencedChunks(
// line splitting, so CR/CRLF-only documents don't lose a real fence.
if (!/(^|[\r\n])[ \t]{0,3}(```|~~~)/.test(markdown)) return out;
- const { fences, capped } = scanFencedBlocks(markdown);
+ const { fences, capped } = scanFencedBlocks(markdown, budget.fences);
+ budget.fences -= fences.length;
if (capped) {
console.warn(
`[gbrain] markdown fence cap hit (${MAX_FENCES_PER_PAGE} fences/page); skipping additional fences. ` +
@@ -81,7 +95,7 @@ async function extractFencedChunks(
}
let indexOffset = 0;
- const started = performance.now();
+ const started = performance.now() - budget.spentMs;
for (const fence of fences) {
const text = fence.text.trim();
if (!text) continue;
@@ -119,6 +133,7 @@ async function extractFencedChunks(
);
}
}
+ budget.spentMs = performance.now() - started;
return out;
}
diff --git a/src/core/page-body/entry-state.ts b/src/core/page-body/entry-state.ts
new file mode 100644
index 0000000000..ed5a9516a4
--- /dev/null
+++ b/src/core/page-body/entry-state.ts
@@ -0,0 +1,100 @@
+/**
+ * Segmented page storage (Wave B): the parser state carried into a segment
+ * (`page_body_manifest.entry_state`, spec 1.3). Everything a streaming parse
+ * needs to process one segment alone, and to resume segmentation at that
+ * segment, is here; page-global decisions known only at EOF (fence trust, the
+ * truncated tail) live in `pages.body_flags`.
+ *
+ * JSON-safe (stored as JSONB) and versioned. Positions appear only while
+ * something is open across the cut (a protected region's start, a truncated
+ * tail), so an unchanged segment that merely shifted keeps an equal entry
+ * state and its occurrence.
+ */
+import type { BodyRegion } from './types.ts';
+import { newRegionTrack, type LinePosition, type PemStart, type RegionTrack } from './region-scan.ts';
+
+export const ENTRY_STATE_VERSION = 1;
+
+export type TimelineEntryState = 'none' | 'entry' | 'detail';
+export type MarkerState = 'none' | 'after_marker' | 'details';
+
+export interface EntryState {
+ v: typeof ENTRY_STATE_VERSION;
+ region: BodyRegion;
+ /** The segment starts after `\n`, after a bare `\r`, or inside a line longer than a segment (forced cut). */
+ at: LinePosition;
+ /**
+ * The protected-region scan under each fence trust. Stored regions use the
+ * page's trust; the no-cut rule uses both, so a trust flip by append moves
+ * regions but never a cut.
+ */
+ trusted: RegionTrack;
+ untrusted: RegionTrack;
+ /**
+ * Projected chars since the last `PRIVATE KEY-----` under each trust (null:
+ * none within PEM_CONTEXT_CHARS), and the partial match at the cut.
+ */
+ pemMargin: { trusted: number | null; untrusted: number | null; carryTrusted: string; carryUntrusted: string };
+ /** Whether a PEM scan restarted here finds the same spans after the cut, and where it restarts. */
+ pem: { clean: boolean; start: PemStart };
+ /** Inside a withdrawal fence block (withdrawal-overlay.ts): the last facts marker seen was a begin. */
+ withdrawal: { open: boolean; carry: string };
+ /** parseTimelineEntries' detail run (link-extraction.ts): after a dated entry, with or without detail lines yet. */
+ timeline: { entry: TimelineEntryState; heading: boolean };
+ /** A materialized marker line, then its bullet and indented details (canonical-projections.ts). */
+ marker: MarkerState;
+ prevBlank: boolean;
+ /** The page's winning conversation pattern, the day-header date context, the last anchor's date, and whether a message is open. */
+ conversation: { pattern: string | null; fallbackDate: string | null; lastDate: string | null; open: boolean };
+ /** pageOutline's fence toggle over the projection, and whether the projection is mid-line at the cut. */
+ outline: { fence: boolean; midLine: boolean };
+}
+
+/** The state at the start of a region: `truth` for a page, or the timeline after the truth (see timelineEntryState). */
+export function initialEntryState(opts: { region: BodyRegion; conversationPattern?: string | null }): EntryState {
+ return {
+ v: ENTRY_STATE_VERSION,
+ region: opts.region,
+ at: 'lf',
+ trusted: newRegionTrack(),
+ untrusted: newRegionTrack(),
+ pemMargin: { trusted: null, untrusted: null, carryTrusted: '', carryUntrusted: '' },
+ pem: { clean: true, start: 'region_start' },
+ withdrawal: { open: false, carry: '' },
+ timeline: { entry: 'none', heading: false },
+ marker: 'none',
+ prevBlank: false,
+ conversation: { pattern: opts.conversationPattern ?? null, fallbackDate: null, lastDate: null, open: false },
+ outline: { fence: false, midLine: false },
+ };
+}
+
+/**
+ * The timeline's entry state after the truth's exit state. Each column is
+ * scanned alone today (fences, protected regions, private keys, timeline
+ * entries), so those restart; the conversation context and the outline's
+ * fence toggle run across the joined projection, so they carry.
+ */
+export function timelineEntryState(truthExit: EntryState): EntryState {
+ return {
+ ...initialEntryState({ region: 'timeline', conversationPattern: truthExit.conversation.pattern }),
+ conversation: { ...truthExit.conversation },
+ outline: { fence: truthExit.outline.fence, midLine: false },
+ };
+}
+
+/** A stored entry state of this version, or null (the caller resegments the page). */
+export function readEntryState(json: unknown): EntryState | null {
+ if (!json || typeof json !== 'object') return null;
+ const state = json as Partial<EntryState>;
+ return state.v === ENTRY_STATE_VERSION && (state.region === 'truth' || state.region === 'timeline') ? state as EntryState : null;
+}
+
+/** Segmentation can resume at a segment with this entry state and reproduce a full run's stored regions too (cuts always match). */
+export function isCleanResumePoint(state: EntryState): boolean {
+ return state.pem.clean;
+}
+
+export function cloneEntryState(state: EntryState): EntryState {
+ return structuredClone(state);
+}
diff --git a/src/core/page-body/region-scan.ts b/src/core/page-body/region-scan.ts
new file mode 100644
index 0000000000..6fac5e8902
--- /dev/null
+++ b/src/core/page-body/region-scan.ts
@@ -0,0 +1,638 @@
+/**
+ * Segmented page storage (Wave B): streaming forms of the two whole-body
+ * privacy scans, so a page body is scanned once, in pieces, with every piece
+ * of parser state small and JSON-safe.
+ *
+ * - `protectedRegionScan` is `protectedRegions` (fence-scan.ts) over a stream:
+ * the same marker tokens, the same pairing, the same truncated tail, the same
+ * `read` rule. `read` depends on whole-body fence trust, so trust is an input
+ * (pass 1 knows it at EOF) and the observed fence walk is part of the state:
+ * a caller that resumes with stale trust can see it flip and rescan.
+ * - `feedPemScan` is `privateKeySpans` (secret-scan.ts) over a stream, with a
+ * bounded window: a BEGIN fence waits for PEM_CONTEXT_CHARS of lookahead,
+ * an END fence walks back at most that far, never below the floor.
+ *
+ * Lines end at `\n`, `\r\n` or a bare `\r` (scanMarkdownCode's grammar). A line
+ * whose bytes with its terminator exceed SEGMENT_MAX_BYTES is the only line a
+ * segment cut can split; it is scanned in pieces, its fence line judged by a
+ * streaming probe, and its marker tokens read fail closed: inline code is not
+ * computed on such a line, so a begin there counts as reader-visible and an end
+ * there never closes a reader-visible region early (both hide more, never less).
+ *
+ * Coordinates: protected regions are UTF-8 byte offsets of the stored stream;
+ * PEM spans are UTF-16 offsets of the projection stream the caller feeds.
+ */
+import { inlineCodeSpans } from '../fence-scan.ts';
+import { PROTECTED_PAIRS } from '../remote-body.ts';
+import { PEM_BEGIN_RE, PEM_BODY_MAX_CHARS, PEM_END_RE, pemBackwardStart, pemForwardEnd } from '../secret-scan.ts';
+import { SEGMENT_MAX_BYTES } from './limits.ts';
+
+/** UTF-8 byte length of `s.slice(from, to)` without slicing. */
+export function utf8Len(s: string, from = 0, to = s.length): number {
+ if (from === 0 && to === s.length && to > 64) return Buffer.byteLength(s, 'utf8');
+ let n = 0;
+ for (let i = from; i < to; i++) {
+ const c = s.charCodeAt(i);
+ if (c < 0x80) n += 1;
+ else if (c < 0x800) n += 2;
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < to) {
+ const d = s.charCodeAt(i + 1);
+ if (d >= 0xdc00 && d <= 0xdfff) { n += 4; i++; } else n += 3;
+ } else n += 3;
+ }
+ return n;
+}
+
+// ---------------------------------------------------------------------------
+// Line splitting shared by the region scan and the segmenter.
+// ---------------------------------------------------------------------------
+
+/** Where the next input byte sits relative to lines: after a `\n`, after a bare `\r`, or inside a long line. */
+export type LinePosition = 'lf' | 'cr' | 'mid';
+
+export interface LineSplit {
+ /** Stored-stream byte offset of the next unsplit byte. */
+ pos: number;
+ /** Text of the current line so far (lines that may still fit in a segment). */
+ pending: string;
+ pendingBytes: number;
+ /** The input so far ends in a `\r` whose `\n` may follow. */
+ cr: boolean;
+ /** The current line is too long for one segment and is being emitted in pieces. */
+ long: boolean;
+ at: LinePosition;
+}
+
+export type SplitEvent =
+ /** A whole line of at most SEGMENT_MAX_BYTES bytes, terminator included. `term` is '' at end of input. */
+ | { kind: 'line'; text: string; byteStart: number; term: string; at: LinePosition }
+ /** A piece of a longer line; `term` is null until the piece that ends it. */
+ | { kind: 'piece'; text: string; byteStart: number; first: boolean; term: string | null; at: LinePosition };
+
+export function newLineSplit(pos: number, at: LinePosition): LineSplit {
+ return { pos, pending: '', pendingBytes: 0, cr: false, long: at === 'mid', at };
+}
+
+/** Split `chunk` into lines and long-line pieces, in order; `final` flushes the last line. */
+export function splitLines(split: LineSplit, chunk: string, final: boolean, emit: (e: SplitEvent) => void): void {
+ let i = 0;
+ if (split.cr) {
+ if (chunk.length === 0 && !final) return;
+ split.cr = false;
+ const term = chunk.charCodeAt(0) === 10 ? '\r\n' : '\r';
+ endLine(split, '', term, emit);
+ i = term.length - 1;
+ }
+ let nl = chunk.indexOf('\n', i);
+ let cr = chunk.indexOf('\r', i);
+ while (i < chunk.length) {
+ if (nl !== -1 && nl < i) nl = chunk.indexOf('\n', i);
+ if (cr !== -1 && cr < i) cr = chunk.indexOf('\r', i);
+ const e = nl === -1 ? cr : cr === -1 ? nl : Math.min(nl, cr);
+ if (e === -1) { addText(split, chunk.slice(i), emit); i = chunk.length; break; }
+ const content = chunk.slice(i, e);
+ if (chunk.charCodeAt(e) === 13 && e + 1 === chunk.length && !final) {
+ addText(split, content, emit);
+ split.cr = true;
+ return;
+ }
+ const term = chunk.charCodeAt(e) === 13 && chunk.charCodeAt(e + 1) !== 10 ? '\r' : chunk.charCodeAt(e) === 13 ? '\r\n' : '\n';
+ endLine(split, content, term, emit);
+ i = e + term.length;
+ }
+ if (final && (split.pending || split.long || split.cr)) endLine(split, '', split.cr ? '\r' : '', emit);
+}
+
+function addText(split: LineSplit, text: string, emit: (e: SplitEvent) => void): void {
+ if (!text) return;
+ if (split.long) {
+ emit({ kind: 'piece', text, byteStart: split.pos, first: false, term: null, at: split.at });
+ split.pos += utf8Len(text);
+ return;
+ }
+ split.pending += text;
+ split.pendingBytes += utf8Len(text);
+ if (split.pendingBytes < SEGMENT_MAX_BYTES) return;
+ emit({ kind: 'piece', text: split.pending, byteStart: split.pos, first: true, term: null, at: split.at });
+ split.pos += split.pendingBytes;
+ split.pending = '';
+ split.pendingBytes = 0;
+ split.long = true;
+}
+
+function endLine(split: LineSplit, content: string, term: string, emit: (e: SplitEvent) => void): void {
+ const termBytes = term.length;
+ if (split.long) {
+ emit({ kind: 'piece', text: content, byteStart: split.pos, first: false, term, at: split.at });
+ split.pos += utf8Len(content) + termBytes;
+ } else {
+ const text = split.pending + content;
+ const bytes = split.pendingBytes + utf8Len(content);
+ if (bytes + termBytes > SEGMENT_MAX_BYTES) emit({ kind: 'piece', text, byteStart: split.pos, first: true, term, at: split.at });
+ else emit({ kind: 'line', text, byteStart: split.pos, term, at: split.at });
+ split.pos += bytes + termBytes;
+ }
+ split.pending = '';
+ split.pendingBytes = 0;
+ split.long = false;
+ split.at = term === '\r' ? 'cr' : 'lf';
+}
+
+// ---------------------------------------------------------------------------
+// Literal tokens across piece boundaries.
+// ---------------------------------------------------------------------------
+
+/**
+ * Find `tokens` in `carry + text`, earliest first and non-overlapping (ties go
+ * to the longer token), as protectedRegions reads them. Returns the new carry:
+ * the longest tail after the last token that is a proper prefix of a token,
+ * so a token split across pieces is found exactly once. `onToken` gets offsets
+ * into `carry + text`.
+ */
+export function findTokens(carry: string, text: string, tokens: readonly string[],
+ onToken: (token: number, at: number) => boolean | void): string {
+ const s = carry + text;
+ let from = 0;
+ const next = tokens.map(t => s.indexOf(t));
+ for (;;) {
+ let at = -1;
+ let token = -1;
+ for (let i = 0; i < tokens.length; i++) {
+ if (next[i] !== -1 && next[i]! < from) next[i] = s.indexOf(tokens[i]!, from);
+ const hit = next[i]!;
+ if (hit !== -1 && (at === -1 || hit < at || (hit === at && tokens[i]!.length > tokens[token]!.length))) { at = hit; token = i; }
+ }
+ if (at === -1) break;
+ from = at + tokens[token]!.length;
+ if (onToken(token, at) === false) return '';
+ }
+ const lastChar = s.charAt(s.length - 1);
+ if (!lastChar || !tokens.some(t => t.includes(lastChar))) return '';
+ const longest = Math.max(...tokens.map(t => t.length)) - 1;
+ for (let k = Math.min(longest, s.length - from); k > 0; k--) {
+ const tail = s.slice(s.length - k);
+ if (tokens.some(t => t.startsWith(tail))) return tail;
+ }
+ return '';
+}
+
+// ---------------------------------------------------------------------------
+// Fence lines (scanMarkdownCode's grammar, judged one character at a time).
+// ---------------------------------------------------------------------------
+
+/** The open fenced code block: its fence character and run length, plus the mispairing flag. */
+export interface FenceWalk { fence: '`' | '~' | null; len: number; mispaired: boolean }
+
+/** A fence-line judgement in progress: up to 3 spaces, a run of ` or ~, then the rest of the line. */
+export interface FenceProbe {
+ phase: 'indent' | 'run' | 'rest' | 'none';
+ indent: number;
+ ch: '`' | '~' | null;
+ run: number;
+ /** The rest holds a backtick, U+2028 or U+2029, or anything but spaces and tabs. */
+ tick: boolean;
+ sep: boolean;
+ ws: boolean;
+}
+
+export function newFenceWalk(): FenceWalk { return { fence: null, len: 0, mispaired: false }; }
+
+export function newFenceProbe(): FenceProbe {
+ return { phase: 'indent', indent: 0, ch: null, run: 0, tick: false, sep: false, ws: true };
+}
+
+export function feedFenceProbe(p: FenceProbe, s: string): void {
+ for (let i = 0; i < s.length && p.phase !== 'none'; i++) {
+ const c = s.charCodeAt(i);
+ if (p.phase === 'indent') {
+ if (c === 32 && p.indent < 3) { p.indent++; continue; }
+ if (c === 96 || c === 126) { p.phase = 'run'; p.ch = c === 96 ? '`' : '~'; p.run = 1; continue; }
+ p.phase = 'none';
+ continue;
+ }
+ if (p.phase === 'run') {
+ if (c === p.ch!.charCodeAt(0)) { p.run++; continue; }
+ p.phase = 'rest';
+ }
+ if (c === 96) p.tick = true;
+ if (c === 0x2028 || c === 0x2029) p.sep = true;
+ if (c !== 32 && c !== 9) p.ws = false;
+ if (!p.ws && p.sep && (p.tick || p.ch === '~')) p.phase = 'none';
+ }
+}
+
+function probeOpens(p: FenceProbe): boolean {
+ return (p.phase === 'run' || p.phase === 'rest') && p.run >= 3 && !p.sep && !(p.ch === '`' && p.tick);
+}
+
+function probeCloses(p: FenceProbe, walk: FenceWalk): boolean {
+ return (p.phase === 'run' || p.phase === 'rest') && p.ch === walk.fence && p.run >= walk.len && p.ws;
+}
+
+/** Advance the walk past a judged line. */
+export function advanceFenceWalk(walk: FenceWalk, p: FenceProbe): void {
+ if (!walk.fence) {
+ if (probeOpens(p)) { walk.fence = p.ch; walk.len = p.run; }
+ } else if (probeCloses(p, walk)) {
+ walk.fence = null;
+ walk.len = 0;
+ } else if (!walk.mispaired && probeOpens(p) && p.ch === walk.fence && p.run >= walk.len) {
+ walk.mispaired = true;
+ }
+}
+
+/** The trust scanMarkdownCode would give the body scanned so far, were it to end here. */
+export function walkTrusted(walk: FenceWalk): boolean {
+ return !walk.fence && !walk.mispaired;
+}
+
+// ---------------------------------------------------------------------------
+// Protected regions.
+// ---------------------------------------------------------------------------
+
+const MARKERS = PROTECTED_PAIRS.flatMap((p, pair) => [{ text: p.begin, pair, begin: true }, { text: p.end, pair, begin: false }]);
+/** The protected-fence marker tokens, in PROTECTED_PAIRS order (begin, end per pair). */
+export const PROTECTED_MARKERS = MARKERS.map(m => m.text);
+const MARKER_TEXTS = PROTECTED_MARKERS;
+const MARKER_LEAD = MARKER_TEXTS.reduce((a, b) => { let k = 0; while (k < a.length && a[k] === b[k]) k++; return a.slice(0, k); });
+
+/** The region scanner's parser state at a line start (or inside a long line). JSON-safe. */
+export interface RegionTrack {
+ walk: FenceWalk;
+ /** The open protected region: its pair index, stored-stream byte start and `read`. */
+ open: { pair: number; start: number; read: boolean } | null;
+ /** Byte where an ambiguous tail starts; everything from there to the end of the region is protected. */
+ truncatedAt: number | null;
+ /** Progress through the current long line. */
+ long: { probe: FenceProbe; carry: string } | null;
+}
+
+/** A closed protected region, stored-stream bytes; same fields as fence-scan's ProtectedRegion. */
+export interface ScannedRegion { pair: number; start: number; end: number; read: boolean }
+
+/**
+ * A protected run inside the text just scanned, in UTF-16 offsets of that text
+ * (`to` may equal the text length when the run continues): the region's pair
+ * (or -1 after truncation) and its stored-stream start.
+ */
+export interface Cover { from: number; to: number; pair: number; start: number }
+
+export interface ScanOut {
+ regions: ScannedRegion[];
+ covers: Cover[];
+ /** The line terminator is protected too. */
+ coverTerm: boolean;
+}
+
+export function newRegionTrack(): RegionTrack {
+ return { walk: newFenceWalk(), open: null, truncatedAt: null, long: null };
+}
+
+/** Scan one whole line (no terminator in `text`) starting at stored byte `byteStart`. */
+export function scanRegionLine(track: RegionTrack, trusted: boolean, text: string, byteStart: number, term: string, out: ScanOut): void {
+ const probe = newFenceProbe();
+ feedFenceProbe(probe, text);
+ const inBlock = trusted && (track.walk.fence !== null || probeOpens(probe));
+ let coverFrom = track.open || track.truncatedAt !== null ? 0 : -1;
+ if (track.truncatedAt === null && text.includes(MARKER_LEAD)) {
+ let spans: Array<[number, number]> | null = null;
+ let charAt = 0;
+ let byteAt = byteStart;
+ findTokens('', text, MARKER_TEXTS, (i, at) => {
+ byteAt += utf8Len(text, charAt, at);
+ charAt = at;
+ const read = !inBlock && !insideSpan(spans ??= inlineCodeSpans(text), at);
+ const step = regionToken(track, i, byteAt, read, out);
+ if (step === 'open') coverFrom = at;
+ else if (step === 'close') { out.covers.push({ from: coverFrom, to: at + MARKERS[i]!.text.length, pair: MARKERS[i]!.pair, start: out.regions[out.regions.length - 1]!.start }); coverFrom = -1; }
+ return step !== 'truncate';
+ });
+ }
+ if (coverFrom !== -1) out.covers.push({ from: coverFrom, to: text.length, pair: track.open?.pair ?? -1, start: track.open?.start ?? track.truncatedAt! });
+ out.coverTerm = coverFrom !== -1 && term !== '';
+ advanceFenceWalk(track.walk, probe);
+}
+
+/**
+ * Scan a piece of a long line. `first` starts the line; `term` (non-null) ends
+ * it. Splitting a piece in two and scanning both gives the same result.
+ */
+export function scanRegionPiece(track: RegionTrack, trusted: boolean, text: string, byteStart: number,
+ first: boolean, term: string | null, out: ScanOut): void {
+ if (first || !track.long) track.long = { probe: newFenceProbe(), carry: '' };
+ const long = track.long;
+ feedFenceProbe(long.probe, text);
+ const known = trusted && track.walk.fence !== null;
+ let coverFrom = track.open || track.truncatedAt !== null ? 0 : -1;
+ if (track.truncatedAt === null) {
+ const lead = long.carry.length;
+ let charAt = 0;
+ let byteAt = byteStart;
+ long.carry = findTokens(long.carry, text, MARKER_TEXTS, (i, at) => {
+ const local = Math.max(0, at - lead);
+ if (at >= lead) { byteAt += utf8Len(text, charAt, local); charAt = local; }
+ const tokenByte = at >= lead ? byteAt : byteStart - (lead - at);
+ const read = known ? false : track.open === null;
+ const step = regionToken(track, i, tokenByte, read, out);
+ if (step === 'open') coverFrom = local;
+ else if (step === 'close') { out.covers.push({ from: coverFrom === -1 ? 0 : coverFrom, to: at + MARKERS[i]!.text.length - lead, pair: MARKERS[i]!.pair, start: out.regions[out.regions.length - 1]!.start }); coverFrom = -1; }
+ return step !== 'truncate';
+ });
+ if (track.truncatedAt !== null) long.carry = '';
+ }
+ if (coverFrom !== -1) out.covers.push({ from: coverFrom, to: text.length, pair: track.open?.pair ?? -1, start: track.open?.start ?? track.truncatedAt! });
+ out.coverTerm = coverFrom !== -1 && !!term;
+ if (term !== null) {
+ advanceFenceWalk(track.walk, long.probe);
+ track.long = null;
+ }
+}
+
+/** protectedRegions' decision for one marker token; a closed region goes to `out.regions`. */
+function regionToken(track: RegionTrack, i: number, byteAt: number, read: boolean, out: ScanOut): 'open' | 'close' | 'skip' | 'truncate' {
+ const m = MARKERS[i]!;
+ const open = track.open;
+ if (!open) {
+ if (!m.begin) return 'skip';
+ track.open = { pair: m.pair, start: byteAt, read };
+ return 'open';
+ }
+ const isEnd = !m.begin && m.pair === open.pair;
+ if (open.read && !read && isEnd) return 'skip';
+ if (!isEnd) {
+ track.truncatedAt = open.start;
+ track.open = null;
+ return 'truncate';
+ }
+ out.regions.push({ pair: open.pair, start: open.start, end: byteAt + m.text.length, read: open.read });
+ track.open = null;
+ return 'close';
+}
+
+function insideSpan(spans: Array<[number, number]>, at: number): boolean {
+ let lo = 0;
+ let hi = spans.length - 1;
+ while (lo <= hi) {
+ const mid = (lo + hi) >> 1;
+ const [s, e] = spans[mid]!;
+ if (at < s) hi = mid - 1;
+ else if (at >= e) lo = mid + 1;
+ else return true;
+ }
+ return false;
+}
+
+/** State of the chunk-at-a-time region scan. */
+export interface RegionScanState { trusted: boolean; track: RegionTrack; split: LineSplit }
+
+export function initialRegionScan(trusted: boolean, pos = 0): RegionScanState {
+ return { trusted, track: newRegionTrack(), split: newLineSplit(pos, 'lf') };
+}
+
+/**
+ * Scan the next chunk of one body region. Regions are reported as they close;
+ * with `final`, an unpaired begin becomes the truncated tail, as in
+ * protectedRegions. Concatenating every call's regions over any chunking gives
+ * protectedRegions(body) in stored bytes (for lines under SEGMENT_MAX_BYTES).
+ */
+export function protectedRegionScan(state: RegionScanState, chunk: string, final = false):
+ { regions: ScannedRegion[]; truncatedAt: number | null; state: RegionScanState } {
+ const out: ScanOut = { regions: [], covers: [], coverTerm: false };
+ splitLines(state.split, chunk, final, e => {
+ if (e.kind === 'line') scanRegionLine(state.track, state.trusted, e.text, e.byteStart, e.term, out);
+ else scanRegionPiece(state.track, state.trusted, e.text, e.byteStart, e.first, e.term, out);
+ out.covers.length = 0;
+ });
+ if (final && state.track.open) {
+ state.track.truncatedAt = state.track.open.start;
+ state.track.open = null;
+ }
+ return { regions: out.regions, truncatedAt: state.track.truncatedAt, state };
+}
+
+// ---------------------------------------------------------------------------
+// Private-key spans over a stream.
+// ---------------------------------------------------------------------------
+
+/** How far a PEM claim reads past a BEGIN fence or back from an END fence (with slack). */
+export const PEM_CONTEXT_CHARS = PEM_BODY_MAX_CHARS + 512;
+/** A fence candidate whose `[A-Z ]` run grows past this many chars is given up (memory bound; an accepted miss). */
+const PEM_FENCE_HOLD_MAX = 64 * 1024;
+/** Lines this long are judged without reading them whole (a PEM body line is at most ~160 chars). */
+const PEM_LINE_PROBE = 2048;
+
+const BEGIN_RE = new RegExp(PEM_BEGIN_RE.source, 'g');
+const END_RE = new RegExp(PEM_END_RE.source, 'g');
+const FENCE_REST = /[A-Z ]*-{0,4}$/y;
+
+interface PemFence { begin: boolean; start: number; end: number }
+
+/** Where a resumed PEM scan starts: at the region start, at a line start, or inside a line. */
+export type PemStart = 'region_start' | 'line_start' | 'mid_line';
+
+export interface PemScanState {
+ /** Projection offset of buf[0]; the projection before 0 is a sentinel on resume. */
+ base: number;
+ buf: string;
+ floor: number;
+ find: Record<'begin' | 'end', { from: number; safe: number }>;
+ begins: PemFence[];
+ ends: PemFence[];
+ /** Recent fences and claims, and BEGIN fences whose claim read ahead, for cut checks. */
+ fences: PemFence[];
+ claims: Array<{ start: number; end: number }>;
+ readAhead: Array<{ start: number; until: number }>;
+ cuts: Array<{ at: number; done?: { clean: boolean; start: PemStart } }>;
+ final: boolean;
+}
+
+export function initialPemScan(start: PemStart): PemScanState {
+ const buf = start === 'line_start' ? '\u0001\n' : start === 'mid_line' ? '\u0001' : '';
+ return {
+ base: -buf.length, buf, floor: -buf.length,
+ find: { begin: { from: 0, safe: 0 }, end: { from: 0, safe: 0 } },
+ begins: [], ends: [], fences: [], claims: [], readAhead: [], cuts: [], final: false,
+ };
+}
+
+/**
+ * Feed the next projection text. Spans go to `onSpan` in order, each final:
+ * the same spans privateKeySpans returns over the whole projection, except for
+ * fences whose `[A-Z ]` run exceeds 64 KiB.
+ */
+export function feedPemScan(st: PemScanState, text: string, final: boolean, onSpan: (start: number, end: number) => void): void {
+ st.buf += text;
+ st.final = final;
+ discoverPem(st, 'begin');
+ discoverPem(st, 'end');
+ processPem(st, onSpan);
+ const resolved = pemResolvedTo(st);
+ for (const cut of st.cuts) if (!cut.done && cut.at <= resolved) cut.done = pemCutCheck(st, cut.at);
+ trimPem(st);
+}
+
+/** Every claim starting before this projection offset has been reported. */
+export function pemResolvedTo(st: PemScanState): number {
+ if (st.final) return Infinity;
+ let h = Math.min(st.find.begin.safe, st.find.end.safe, st.base + st.buf.length);
+ const f = headFence(st);
+ if (f) h = Math.min(h, f.start);
+ return h - PEM_CONTEXT_CHARS;
+}
+
+/** Ask whether a cut at projection offset `at` is a clean resume point; answered once `at` is resolved. */
+export function markPemCut(st: PemScanState, at: number): void {
+ st.cuts.push({ at });
+}
+
+/** The answer for a marked cut (removing it), or null while unresolved. */
+export function takePemCut(st: PemScanState, at: number): { clean: boolean; start: PemStart } | null {
+ const i = st.cuts.findIndex(c => c.at === at && c.done);
+ if (i === -1) return null;
+ return st.cuts.splice(i, 1)[0]!.done!;
+}
+
+function discoverPem(st: PemScanState, kind: 'begin' | 'end'): void {
+ const re = kind === 'begin' ? BEGIN_RE : END_RE;
+ const prefix = kind === 'begin' ? '-----BEGIN ' : '-----END ';
+ const find = st.find[kind];
+ const queue = kind === 'begin' ? st.begins : st.ends;
+ const end = st.base + st.buf.length;
+ const held = st.final ? end : heldFrom(st.buf, prefix, find.from - st.base) + st.base;
+ re.lastIndex = find.from - st.base;
+ for (let m = re.exec(st.buf); m && m.index + st.base < held; m = re.exec(st.buf)) {
+ const fence = { begin: kind === 'begin', start: m.index + st.base, end: m.index + st.base + m[0].length };
+ queue.push(fence);
+ st.fences.push(fence);
+ find.from = fence.end;
+ }
+ find.from = Math.max(find.from, held);
+ find.safe = held;
+}
+
+/** Offset in `buf` of a fence candidate the text so far cannot decide, or buf.length. */
+function heldFrom(buf: string, prefix: string, from: number): number {
+ const len = buf.length;
+ let i = len;
+ const lim = Math.max(from, len - PEM_FENCE_HOLD_MAX);
+ while (i > lim && isFenceClass(buf.charCodeAt(i - 1))) i--;
+ for (let q = buf.indexOf(prefix, i); q !== -1; q = buf.indexOf(prefix, q + 1)) {
+ FENCE_REST.lastIndex = q + prefix.length;
+ if (FENCE_REST.test(buf)) return q;
+ }
+ for (let k = Math.min(prefix.length - 1, len - i); k > 0; k--) if (buf.endsWith(prefix.slice(0, k))) return len - k;
+ return len;
+}
+
+function isFenceClass(c: number): boolean {
+ return (c >= 65 && c <= 90) || c === 32 || c === 45;
+}
+
+function headFence(st: PemScanState, skip?: PemFence): PemFence | undefined {
+ const b = st.begins.find(f => f !== skip);
+ const e = st.ends.find(f => f !== skip);
+ return b && (!e || b.start <= e.start) ? b : e;
+}
+
+function dropFence(st: PemScanState, f: PemFence): void {
+ const q = f.begin ? st.begins : st.ends;
+ q.splice(q.indexOf(f), 1);
+}
+
+function processPem(st: PemScanState, onSpan: (start: number, end: number) => void): void {
+ const end = st.base + st.buf.length;
+ for (let f = headFence(st); f; f = headFence(st)) {
+ const limit = Math.min(st.find.begin.safe, st.find.end.safe);
+ if (f.start >= limit) return;
+ if (f.start < st.floor) { dropFence(st, f); continue; }
+ if (!f.begin) {
+ const start = pemBackwardStart(st.buf, f.start - st.base, Math.max(st.floor - st.base, 0));
+ if (start >= 0) claimPem(st, start + st.base, f.end, onSpan);
+ st.floor = f.end;
+ dropFence(st, f);
+ continue;
+ }
+ if (!st.final && (end < f.end + PEM_CONTEXT_CHARS || limit <= f.end + PEM_BODY_MAX_CHARS)) return;
+ const next = headFence(st, f);
+ dropFence(st, f);
+ if (next && !next.begin && next.start - f.end <= PEM_BODY_MAX_CHARS) {
+ claimPem(st, f.start, next.end, onSpan);
+ st.floor = next.end;
+ dropFence(st, next);
+ } else {
+ st.floor = pemForwardEnd(st.buf, f.end - st.base) + st.base;
+ claimPem(st, f.start, st.floor, onSpan);
+ }
+ st.readAhead.push({ start: f.start, until: f.end + PEM_CONTEXT_CHARS });
+ }
+}
+
+function claimPem(st: PemScanState, start: number, end: number, onSpan: (start: number, end: number) => void): void {
+ st.claims.push({ start, end });
+ onSpan(start, end);
+}
+
+/**
+ * A cut at `at` is clean when a scan restarted there (behind a sentinel) finds
+ * the same spans after it: no claim or fence spans the cut, no BEGIN before it
+ * read past it, and the line on one side of it can stop a backward walk.
+ */
+function pemCutCheck(st: PemScanState, at: number): { clean: boolean; start: PemStart } {
+ const rel = at - st.base;
+ if (rel <= 0 && st.base >= 0) return { clean: true, start: 'region_start' };
+ const lineStart = st.buf.charCodeAt(rel - 1) === 10;
+ const start: PemStart = lineStart ? 'line_start' : 'mid_line';
+ const spans = (r: { start: number; end: number }) => r.start < at && at < r.end;
+ if (st.claims.some(spans) || st.fences.some(spans) || st.readAhead.some(r => r.start < at && r.until > at)) return { clean: false, start };
+ if (!lineStart) return { clean: !isPemLineChar(st.buf.charCodeAt(rel - 1)), start };
+ return { clean: !(bodyLikeBefore(st.buf, rel - 1) && bodyLikeFrom(st.buf, rel)), start };
+}
+
+function isPemLineChar(c: number): boolean {
+ return (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || (c >= 48 && c <= 57) || c === 43 || c === 47 || c === 61 || c === 92;
+}
+
+/** Could the line could hold PEM body text (only base64, backslash escapes and blanks)? Unknown counts as yes. */
+export function pemBodyLike(line: string): boolean {
+ return bodyLikeFrom(line, 0);
+}
+
+function bodyLikeFrom(s: string, from: number): boolean {
+ let any = false;
+ for (let i = from; i < s.length; i++) {
+ const c = s.charCodeAt(i);
+ if (c === 10 || c === 13) return any;
+ if (i - from >= PEM_LINE_PROBE) return true;
+ if (isPemLineChar(c)) any = true;
+ else if (c !== 32 && c !== 9) return false;
+ }
+ return any || from >= s.length;
+}
+
+function bodyLikeBefore(s: string, nl: number): boolean {
+ let i = nl;
+ if (s.charCodeAt(i - 1) === 13) i--;
+ let any = false;
+ for (let k = i - 1; k >= 0; k--) {
+ const c = s.charCodeAt(k);
+ if (c === 10) return any;
+ if (i - k > PEM_LINE_PROBE) return true;
+ if (isPemLineChar(c)) any = true;
+ else if (c !== 32 && c !== 9 && c !== 1) return false;
+ }
+ return true;
+}
+
+function trimPem(st: PemScanState): void {
+ let keep = Math.min(st.find.begin.safe, st.find.end.safe, st.base + st.buf.length);
+ const f = headFence(st);
+ if (f) keep = Math.min(keep, f.start);
+ keep -= 2 * PEM_CONTEXT_CHARS;
+ for (const cut of st.cuts) if (!cut.done) keep = Math.min(keep, cut.at - PEM_LINE_PROBE - 2);
+ if (st.final || keep - st.base < 4 * PEM_CONTEXT_CHARS) return;
+ st.buf = st.buf.slice(keep - st.base);
+ st.base = keep;
+ st.fences = st.fences.filter(x => x.end > keep);
+ st.claims = st.claims.filter(x => x.end > keep);
+ st.readAhead = st.readAhead.filter(x => x.until > keep);
+}
diff --git a/src/core/page-body/segment-chunks.ts b/src/core/page-body/segment-chunks.ts
new file mode 100644
index 0000000000..b17ce7aced
--- /dev/null
+++ b/src/core/page-body/segment-chunks.ts
@@ -0,0 +1,138 @@
+/**
+ * Segmented page storage (Wave B): the chunker for one segment, spec 4.1.
+ *
+ * Today's pipeline (markdown-chunks.ts) on one segment's projection instead of
+ * a whole column: prose chunks, then the segment's recognized code-fence
+ * chunks (truth segments only, as inline pages chunk only the truth's
+ * fences), then its low-tier facts rows as marked chunks. Chunks never cross
+ * the segment's bounds and carry no overlap from the previous segment, so a
+ * segment's chunks depend only on its bytes, entry state and stored regions.
+ *
+ * The projection is built from the stored regions the segmenter computed
+ * under the page's fence trust: takes, truncated tail and materialized
+ * markers out, private keys as the projection token, and each facts region
+ * rendered (world rows through the fence overlay) where its slot sits. A
+ * facts region that crosses the segment's bounds is omitted, fail closed.
+ * Inline pages keep prepareMarkdownChunks; this is a separate chunker identity.
+ */
+import { chunkProjectedText, chunkText } from '../chunkers/recursive.ts';
+import { estimateEmbedTokens } from '../chunkers/token-estimate.ts';
+import { resolveMaxChunkTokens } from '../embedding-input-limit.ts';
+import { fencedCodeChunks, newFenceChunkBudget, type FenceChunkBudget } from '../markdown-chunks.ts';
+import { fenceTrustMarker, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';
+import { isQuarantined } from '../quarantine.ts';
+import { renderFactsRegion } from '../remote-body.ts';
+import type { EntryState } from './entry-state.ts';
+import type { SegmentChunkInput, BodyRegion } from './types.ts';
+import { segmentProjectionParts, type StoredRegion } from './segmenter.ts';
+
+/** Bump when the per-segment projection or chunk layout changes (stamped with the segmenter version). */
+export const SEGMENTED_CHUNKER_VERSION = 1;
+
+export type SegmentChunk = Omit<SegmentChunkInput, 'occurrence_id'>;
+
+/** The parts of a SegmentOut (or a stored manifest row and its text) the chunker reads. */
+export interface ChunkableSegment {
+ region: BodyRegion;
+ bytes: Uint8Array;
+ byteStart: number;
+ entryState: EntryState;
+ fenceTrust: 'trusted' | 'void';
+ protectedRegions: readonly StoredRegion[];
+}
+
+export interface SegmentChunkOptions {
+ /** The page's current fence trust (body_flags.fence_trust); a segment whose regions were computed under the other trust is refused. */
+ fenceTrust: 'trusted' | 'void';
+ frontmatter?: Record<string, unknown> | null;
+ maxChunkTokens?: number;
+ overlay?: FenceChunkOverlay;
+ /** One budget per page, shared by every segment's call, so the fence caps stay per page. */
+ fenceBudget?: FenceChunkBudget;
+}
+
+interface MappedPart { projStart: number; projEnd: number; rawStart: number; rawEnd: number; linear: boolean }
+
+export async function prepareSegmentChunks(segment: ChunkableSegment, opts: SegmentChunkOptions): Promise<SegmentChunk[]> {
+ if (isQuarantined(opts.frontmatter)) return [];
+ if (segment.fenceTrust !== opts.fenceTrust) {
+ throw new Error(`segment_regions_stale: regions at byte ${segment.byteStart} were computed under fence trust ${segment.fenceTrust}, the page is ${opts.fenceTrust}; rescan before chunking`);
+ }
+ const maxTokens = opts.maxChunkTokens ?? resolveMaxChunkTokens();
+ const raw = Buffer.from(segment.bytes).toString('utf8');
+ const segEnd = segment.byteStart + segment.bytes.length;
+ const pieces: string[] = [];
+ const map: MappedPart[] = [];
+ const factsTexts: string[] = [];
+ let projBytes = 0;
+ for (const part of segmentProjectionParts(raw, segment.protectedRegions, segment.byteStart)) {
+ let text = '';
+ if (part.kind === 'text' || part.kind === 'pem') text = part.text;
+ else if (part.kind === 'facts' && part.region!.open_start === undefined) {
+ factsTexts.push(part.text);
+ text = renderFactsRegion(splitFenceOverlay(part.text, opts.overlay).main);
+ }
+ if (!text) continue;
+ const bytes = Buffer.byteLength(text, 'utf8');
+ map.push({ projStart: projBytes, projEnd: projBytes + bytes, rawStart: part.start, rawEnd: part.end, linear: part.kind === 'text' });
+ pieces.push(text);
+ projBytes += bytes;
+ }
+ const projection = pieces.join('');
+ const source = segment.region === 'truth' ? 'compiled_truth' : 'timeline';
+ const chunks: SegmentChunk[] = [];
+ const push = (c: Omit<SegmentChunk, 'local_ordinal'>) => chunks.push({ ...c, local_ordinal: chunks.length });
+ const wholeSegment = { raw_byte_start: segment.byteStart, raw_byte_end: segEnd };
+
+ if (projection.trim()) {
+ for (const c of chunkProjectedText(projection, { maxTokens, spans: true })) {
+ if (c.byte_start === undefined || c.byte_end === undefined) {
+ push({ chunk_text: c.text, chunk_source: source, ...wholeSegment });
+ continue;
+ }
+ push({
+ chunk_text: c.text,
+ chunk_source: source,
+ projected_byte_start: c.byte_start,
+ projected_byte_end: c.byte_end,
+ raw_byte_start: segment.byteStart + rawAt(map, c.byte_start, false),
+ raw_byte_end: segment.byteStart + rawAt(map, c.byte_end, true),
+ });
+ }
+ if (segment.region === 'truth') {
+ const walk = segment.entryState.trusted.walk;
+ const opener = walk.fence ? `${walk.fence.repeat(walk.len)}\n` : '';
+ for (const c of await fencedCodeChunks(opener + projection, 0, opts.fenceBudget ?? newFenceChunkBudget())) {
+ const { chunk_index: _index, ...rest } = c;
+ push({ ...rest, ...wholeSegment });
+ }
+ }
+ }
+
+ if (factsTexts.length) {
+ for (const { tier, unconfirmed, body } of splitFenceOverlay(factsTexts.join('\n'), opts.overlay).lowTier) {
+ const room = Math.max(1, maxTokens - estimateEmbedTokens(fenceTrustMarker(tier, unconfirmed)) - 1);
+ for (const c of chunkText(body, { maxTokens: room })) {
+ push({ chunk_text: markFenceChunk(tier, c.text, unconfirmed), chunk_source: source, ...wholeSegment });
+ }
+ }
+ }
+ return chunks;
+}
+
+/**
+ * Segment-relative stored byte of projection byte `pos`: exact inside kept
+ * text; inside a token or a rendered facts table, the start (for a chunk
+ * start) or end (for a chunk end) of the stored region it stands for.
+ */
+function rawAt(map: readonly MappedPart[], pos: number, end: boolean): number {
+ let lo = 0;
+ let hi = map.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (end ? map[mid]!.projStart < pos : map[mid]!.projStart <= pos) lo = mid; else hi = mid - 1;
+ }
+ const part = map[lo]!;
+ if (part.linear) return part.rawStart + (pos - part.projStart);
+ return end ? part.rawEnd : part.rawStart;
+}
diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.ts
new file mode 100644
index 0000000000..db943b83e5
--- /dev/null
+++ b/src/core/page-body/segmenter.ts
@@ -0,0 +1,660 @@
+/**
+ * Segmented page storage (Wave B): cut one region of a page's stored stream
+ * (`compiled_truth`, then `timeline`, each already sanitized) into segments
+ * of at most SEGMENT_MAX_BYTES, spec section 2.
+ *
+ * A cut goes before a line and looks only backward (bytes since the last cut,
+ * the line itself, carried parser state), so segmentation is append-stable:
+ * appending text changes only the last segment, and segmenting from a
+ * segment's entry state over its bytes plus appended bytes reproduces a full
+ * run's cuts. Candidates, best first: a level 1-2 ATX heading or a day header,
+ * a message anchor of the page's conversation pattern, then a level 3+
+ * heading or the first line after a blank line. No structural cut before
+ * SEGMENT_MIN_BYTES; between min and target only a rank 1-3 candidate whose
+ * gear hash has its top GEAR_TOP_BITS bits clear; from target the first rank
+ * 1-3 candidate; from SEGMENT_RANK4_BYTES any candidate. A line that would not
+ * fit forces a cut before it, and a line longer than a segment is cut at the
+ * last code point that fits (never between `\r` and `\n`), with the open
+ * state carried in the next entry state.
+ *
+ * Never cut: inside a code fence, a protected region under either fence
+ * trust, a withdrawal fence block, a timeline entry's detail run, between a
+ * materialized marker and its bullet, or within PEM_CONTEXT_CHARS after a
+ * `PRIVATE KEY-----` in either trust's projection; and never before a line
+ * holding a marker token, a key fence, or text a key's body could continue
+ * through. Under those rules no private-key claim, protected region or fence
+ * block crosses a non-forced cut.
+ *
+ * Each segment carries what its manifest row stores: protected regions,
+ * facts slots and private-key spans in segment-relative raw bytes (full
+ * extent in stored-stream bytes as `open_start`/`open_end` when one crosses
+ * the segment's bounds), and its static projection's size, lines, outline and
+ * dates: the projection whole-body sanitization would give (takes, facts,
+ * materialized markers and a truncated tail out, private keys as a token),
+ * with facts regions as zero-length slots rendered at read time.
+ */
+import { createHash } from 'node:crypto';
+import { FACTS_FENCE_BEGIN, FACTS_FENCE_END } from '../facts-fence.ts';
+import { PRIVATE_KEY_PROJECTION_TOKEN } from '../credential-projection.ts';
+import { isMaterializedMarkerLine, materializedMarkerSpans } from '../timeline-marker.ts';
+import { TIMELINE_LINE_RE, TIMELINE_LINE_RE_CN } from '../timeline-citations.ts';
+import { TIMELINE_HEADING_RE } from '../link-extraction.ts';
+import { DAY_HEADER_RE, matchAnchorLine } from '../conversation-parser/parse.ts';
+import { clip, DATE, FENCE, HEADING, HEADING_MAX_CHARS } from '../page-window/window.ts';
+import { SEGMENT_MAX_BYTES, SEGMENT_MIN_BYTES, SEGMENT_RANK4_BYTES, SEGMENT_TARGET_BYTES } from './limits.ts';
+import type { BodyRegion, SegmentCutKind } from './types.ts';
+import { cloneEntryState, type EntryState } from './entry-state.ts';
+import {
+ feedPemScan, findTokens, initialPemScan, markPemCut, newLineSplit, pemBodyLike, pemResolvedTo, PEM_CONTEXT_CHARS,
+ PROTECTED_MARKERS, scanRegionLine, scanRegionPiece, splitLines, takePemCut, utf8Len,
+ type Cover, type LineSplit, type PemScanState, type RegionTrack, type ScanOut, type SplitEvent,
+} from './region-scan.ts';
+
+/** Bump when a cut rule, a bound or the stored per-segment metadata changes. */
+export const SEGMENTER_VERSION = 1;
+
+/** Between min and target, a candidate cuts when the top bits of its line's gear hash are zero (1 in 1024 candidates). */
+const GEAR_TOP_BITS = 10;
+const OUTLINE_MAX_HEADINGS = 64;
+/** Projection text is handed to the PEM scan in batches of this many chars (its buffer is re-read per feed). */
+const PEM_FEED_CHARS = 64 * 1024;
+const PEM_FENCE_TAIL = 'PRIVATE KEY-----';
+const ATX_TOP = /^#{1,2}\s/;
+const ATX_DEEP = /^#{3,6}\s/;
+const ATX_ANY = /^#{1,6}\s/;
+const PEM_HEADER_LINE = /^(?:Proc-Type:|DEK-Info:)/;
+const MATERIALIZED_DETAIL = /^[ \t]+\S/;
+const BULLET = /^[ \t]*[-*+] /;
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+const GEAR: Uint32Array = (() => {
+ const table = new Uint32Array(256);
+ let x = 0x9e3779b9;
+ for (let i = 0; i < 256; i++) {
+ x ^= x << 13; x >>>= 0;
+ x ^= x >>> 17;
+ x ^= x << 5; x >>>= 0;
+ table[i] = x;
+ }
+ return table;
+})();
+
+function gearHit(line: string): boolean {
+ let h = 0;
+ for (let i = 0; i < line.length; i++) {
+ const c = line.charCodeAt(i);
+ h = ((h << 1) + GEAR[(c ^ (c >>> 8)) & 255]!) >>> 0;
+ }
+ return h >>> (32 - GEAR_TOP_BITS) === 0;
+}
+
+export interface SegmentOptions {
+ /** Stored-stream byte offset and 0-based raw line of the entry point. */
+ byteStart: number;
+ lineStart: number;
+ /** This region's whole-body fence trust (pass 1, or body_flags.fence_trust). */
+ fenceTrust: 'trusted' | 'void';
+ /** How the input ends: `region_end` for the truth when a timeline follows, else `eof`. */
+ end: 'region_end' | 'eof';
+}
+
+export type StoredRegionKind = 'facts' | 'takes' | 'tail' | 'marker' | 'pem';
+
+/** A protected run of a segment: segment-relative raw bytes; `open_*` give the full extent in stored-stream bytes when it crosses the segment's bounds (`open_end` absent while unknown). */
+export interface StoredRegion { kind: StoredRegionKind; start: number; end: number; open_start?: number; open_end?: number }
+
+/** A facts region of a segment, rendered at read time where its zero-length slot sits in the static projection. */
+export interface FactsSlot { proj_byte: number; start: number; end: number; open_start?: number; open_end?: number }
+
+export interface OutlineHeading { proj_byte: number; level: number; text: string }
+
+/** One segment as its manifest row and text row need it (see ManifestRowInput, SegmentTextInput). */
+export interface SegmentOut {
+ region: BodyRegion;
+ bytes: Uint8Array;
+ sha256: Uint8Array;
+ byteStart: number;
+ /** 0-based raw line of the first line; `lineCount` counts `\n` bytes. */
+ lineStart: number;
+ lineCount: number;
+ /** Why the segment ends. */
+ cutKind: SegmentCutKind;
+ entryState: EntryState;
+ exitState: EntryState;
+ /** The fence trust `protectedRegions` were computed under (body_flags.fence_trust at segmentation). */
+ fenceTrust: 'trusted' | 'void';
+ protectedRegions: StoredRegion[];
+ factsSlots: FactsSlot[];
+ staticProjBytes: number;
+ /** `\n` bytes in the static projection. */
+ staticProjLines: number;
+ outline: OutlineHeading[];
+ dateMin: string | null;
+ dateMax: string | null;
+}
+
+/** Page flags only the region's end decides (body_flags). */
+export interface RegionFlags {
+ /** Stored byte where a truncated protected tail starts, under the page's trust. */
+ protectedTailFrom: number | null;
+ /** The trust the region's fence walk observed: differs from the trust used when an append flipped it (rescan). */
+ observedFenceTrust: 'trusted' | 'void';
+}
+
+export function regionFlags(exit: EntryState, fenceTrust: 'trusted' | 'void'): RegionFlags {
+ const track = fenceTrust === 'trusted' ? exit.trusted : exit.untrusted;
+ const walk = exit.trusted.walk;
+ return { protectedTailFrom: track.truncatedAt, observedFenceTrust: !walk.fence && !walk.mispaired ? 'trusted' : 'void' };
+}
+
+interface Removal { start: number; end: number; kind: Exclude<StoredRegionKind, 'pem'>; regionStart: number }
+
+interface OpenSegment {
+ entry: EntryState;
+ byteStart: number;
+ lineStart: number;
+ bytes: number;
+ lines: number;
+ parts: string[];
+ removals: Removal[];
+ projStart: number;
+}
+
+interface ClosedSegment extends OpenSegment { cutKind: SegmentCutKind; exit: EntryState; projEnd: number }
+
+/**
+ * Incremental segmenter for one region: push text, take the segments that are
+ * final. Memory is O(segment + PEM_CONTEXT_CHARS + one line).
+ */
+export class Segmenter {
+ private readonly st: EntryState;
+ private readonly split: LineSplit;
+ private readonly pem: PemScanState;
+ private proj = 0;
+ private projPieces: Array<{ proj: number; raw: number; text: string }> = [];
+ private pemPending = '';
+ private pemSpans: Array<{ start: number; end: number }> = [];
+ private regionEnds = new Map<number, number>();
+ private cur: OpenSegment;
+ private closed: ClosedSegment[] = [];
+ private outline: { fence: boolean; midLine: boolean };
+ private done = false;
+
+ constructor(entry: EntryState, private readonly opts: SegmentOptions) {
+ this.st = cloneEntryState(entry);
+ this.split = newLineSplit(opts.byteStart, entry.at);
+ this.pem = initialPemScan(entry.pem.start);
+ this.outline = { ...entry.outline };
+ this.cur = this.openSegment(cloneEntryState(entry), opts.byteStart, opts.lineStart);
+ }
+
+ push(text: string): SegmentOut[] {
+ splitLines(this.split, text, false, e => this.onEvent(e));
+ return this.drain();
+ }
+
+ finish(): SegmentOut[] {
+ splitLines(this.split, '', true, e => this.onEvent(e));
+ for (const track of [this.st.trusted, this.st.untrusted]) {
+ if (track.open) { track.truncatedAt = track.open.start; track.open = null; }
+ }
+ if (this.cur.bytes > 0) markPemCut(this.pem, this.proj);
+ this.feedPem(true);
+ this.done = true;
+ if (this.cur.bytes > 0) this.close(this.opts.end);
+ return this.drain();
+ }
+
+ private actual(): RegionTrack {
+ return this.opts.fenceTrust === 'trusted' ? this.st.trusted : this.st.untrusted;
+ }
+
+ private openSegment(entry: EntryState, byteStart: number, lineStart: number): OpenSegment {
+ return { entry, byteStart, lineStart, bytes: 0, lines: 0, parts: [], removals: [], projStart: this.proj };
+ }
+
+ private close(cutKind: SegmentCutKind): void {
+ const exit = cloneEntryState(this.st);
+ this.closed.push({ ...this.cur, cutKind, exit, projEnd: this.proj });
+ if (!this.done) markPemCut(this.pem, this.proj);
+ this.cur = this.openSegment(exit, this.cur.byteStart + this.cur.bytes, this.cur.lineStart + this.cur.lines);
+ }
+
+ private onEvent(e: SplitEvent): void {
+ if (e.kind === 'line') {
+ const bytes = utf8Len(e.text) + e.term.length;
+ const kind = this.candidate(e.text, e.at);
+ if (kind) this.close(kind);
+ else if (this.cur.bytes > 0 && this.cur.bytes + bytes > SEGMENT_MAX_BYTES) this.close('forced');
+ this.st.at = e.at;
+ this.line(e.text, e.term, e.byteStart);
+ return;
+ }
+ if (e.first && this.cur.bytes > 0) this.close('forced');
+ let { text, byteStart } = e;
+ for (;;) {
+ const fit = fitChars(text, SEGMENT_MAX_BYTES - this.cur.bytes);
+ if (fit.chars === text.length && this.cur.bytes + fit.bytes + (e.term ?? '').length <= SEGMENT_MAX_BYTES) {
+ this.piece(text, byteStart, e.first && byteStart === e.byteStart, e.term);
+ return;
+ }
+ if (fit.chars > 0) this.piece(text.slice(0, fit.chars), byteStart, e.first && byteStart === e.byteStart, null);
+ byteStart += fit.bytes;
+ text = text.slice(fit.chars);
+ this.st.at = 'mid';
+ this.close('forced');
+ }
+ }
+
+ /** The cut kind when a structural cut goes before this whole line. */
+ private candidate(text: string, at: SplitEvent['at']): SegmentCutKind | null {
+ const size = this.cur.bytes;
+ if (at !== 'lf' || size < SEGMENT_MIN_BYTES) return null;
+ const st = this.st;
+ let kind: SegmentCutKind | null = null;
+ let rank = 4;
+ if (DAY_HEADER_RE.test(text.trim())) { kind = 'day'; rank = 2; }
+ else if (ATX_TOP.test(text)) { kind = 'heading'; rank = 2; }
+ else if (st.conversation.pattern && matchAnchorLine(st.conversation.pattern, text)) { kind = 'message'; rank = 3; }
+ else if (ATX_DEEP.test(text)) kind = 'heading';
+ else if (st.prevBlank && text.trim() !== '') kind = 'blank';
+ if (!kind || this.blocked(text)) return null;
+ if (size < SEGMENT_TARGET_BYTES) return rank <= 3 && gearHit(text) ? kind : null;
+ return rank <= 3 || size >= SEGMENT_RANK4_BYTES ? kind : null;
+ }
+
+ private blocked(text: string): boolean {
+ const st = this.st;
+ if (st.trusted.walk.fence || st.trusted.open || st.untrusted.open || st.withdrawal.open) return true;
+ if (st.pemMargin.trusted !== null || st.pemMargin.untrusted !== null) return true;
+ if (timelineConsumes(st.timeline, text)) return true;
+ if (st.marker === 'after_marker' || (st.marker === 'details' && MATERIALIZED_DETAIL.test(text) && !BULLET.test(text))) return true;
+ return PROTECTED_MARKERS.some(m => text.includes(m)) || text.includes(PEM_FENCE_TAIL) || isMaterializedMarkerLine(text)
+ || pemBodyLike(text) || PEM_HEADER_LINE.test(text);
+ }
+
+ private line(text: string, term: string, byteStart: number): void {
+ const st = this.st;
+ const outT: ScanOut = { regions: [], covers: [], coverTerm: false };
+ const outU: ScanOut = { regions: [], covers: [], coverTerm: false };
+ scanRegionLine(st.trusted, true, text, byteStart, term, outT);
+ scanRegionLine(st.untrusted, false, text, byteStart, term, outU);
+ const whole = text + term;
+ const markers = whole.includes('gbrain:materialized') ? materializedMarkerSpans(whole) : [];
+ this.project(whole, text.length, byteStart, outT, outU, markers);
+ const b = text.lastIndexOf(FACTS_FENCE_BEGIN);
+ const e = text.lastIndexOf(FACTS_FENCE_END);
+ if (b !== -1 || e !== -1) st.withdrawal.open = b > e;
+ st.timeline = timelineNext(st.timeline, text);
+ st.marker = isMaterializedMarkerLine(text) ? 'after_marker'
+ : st.marker === 'after_marker' || (st.marker === 'details' && MATERIALIZED_DETAIL.test(text) && !BULLET.test(text)) ? 'details' : 'none';
+ st.prevBlank = text.trim() === '';
+ const day = DAY_HEADER_RE.exec(text.trim());
+ if (day) st.conversation.fallbackDate = day[1]!;
+ else if (st.conversation.pattern) {
+ const anchor = matchAnchorLine(st.conversation.pattern, text);
+ if (anchor) {
+ st.conversation.open = true;
+ st.conversation.lastDate = anchor.date && ISO_DATE.test(anchor.date) ? anchor.date : st.conversation.fallbackDate;
+ }
+ }
+ this.append(whole, term.includes('\n') ? 1 : 0);
+ }
+
+ private piece(text: string, byteStart: number, first: boolean, term: string | null): void {
+ const st = this.st;
+ const outT: ScanOut = { regions: [], covers: [], coverTerm: false };
+ const outU: ScanOut = { regions: [], covers: [], coverTerm: false };
+ scanRegionPiece(st.trusted, true, text, byteStart, first, term, outT);
+ scanRegionPiece(st.untrusted, false, text, byteStart, first, term, outU);
+ const whole = text + (term ?? '');
+ this.project(whole, text.length, byteStart, outT, outU, []);
+ let last = -1;
+ st.withdrawal.carry = findTokens(st.withdrawal.carry, text, [FACTS_FENCE_BEGIN, FACTS_FENCE_END], t => { last = t; });
+ if (last !== -1) st.withdrawal.open = last === 0;
+ if (term !== null) {
+ st.withdrawal.carry = '';
+ st.timeline = { entry: 'none', heading: false };
+ st.marker = 'none';
+ st.prevBlank = false;
+ }
+ this.append(whole, term?.includes('\n') ? 1 : 0);
+ }
+
+ private append(whole: string, lines: number): void {
+ this.cur.parts.push(whole);
+ this.cur.bytes += utf8Len(whole);
+ this.cur.lines += lines;
+ }
+
+ /**
+ * The projection of one line or piece under each trust: PEM margins for
+ * both, and for the page's trust the removals, the PEM scan feed and the
+ * offsets that map PEM spans back to stored bytes.
+ */
+ private project(whole: string, textLen: number, byteStart: number, outT: ScanOut, outU: ScanOut,
+ markers: Array<[number, number]>): void {
+ const st = this.st;
+ const trusted = this.opts.fenceTrust === 'trusted';
+ for (const [out, track, isTrusted] of [[outT, st.trusted, true], [outU, st.untrusted, false]] as const) {
+ const plain = out.covers.length === 0 && markers.length === 0;
+ const keep = plain ? (whole.length ? [[0, whole.length] as [number, number]] : []) : keptRanges(whole, textLen, out, markers);
+ const projected = plain ? whole : keep.map(([a, b]) => whole.slice(a, b)).join('');
+ const carryKey = isTrusted ? 'carryTrusted' : 'carryUntrusted';
+ const marginKey = isTrusted ? 'trusted' : 'untrusted';
+ let found = -1;
+ const lead = st.pemMargin[carryKey].length;
+ st.pemMargin[carryKey] = findTokens(st.pemMargin[carryKey], projected, [PEM_FENCE_TAIL], (_t, at) => { found = at + PEM_FENCE_TAIL.length - lead; });
+ let margin = found !== -1 ? projected.length - found : st.pemMargin[marginKey] === null ? null : st.pemMargin[marginKey]! + projected.length;
+ if (track.truncatedAt !== null || (margin !== null && margin > PEM_CONTEXT_CHARS)) margin = null;
+ st.pemMargin[marginKey] = margin;
+ if (isTrusted !== trusted) continue;
+ for (const r of out.regions) this.regionEnds.set(r.start, r.end);
+ if (!plain) this.recordRemovals(whole, textLen, byteStart, out, markers);
+ let byte = byteStart;
+ let char = 0;
+ for (const [a, b] of keep) {
+ byte += utf8Len(whole, char, a);
+ this.projPieces.push({ proj: this.proj, raw: byte, text: plain ? whole : whole.slice(a, b) });
+ this.proj += b - a;
+ if (!plain) byte += utf8Len(whole, a, b);
+ char = b;
+ }
+ this.pemPending += projected;
+ if (this.pemPending.length >= PEM_FEED_CHARS) this.feedPem(false);
+ }
+ }
+
+ private recordRemovals(whole: string, textLen: number, byteStart: number, out: ScanOut, markers: Array<[number, number]>): void {
+ const at = (i: number) => byteStart + utf8Len(whole, 0, i);
+ const add = (r: Removal) => {
+ const prev = this.cur.removals[this.cur.removals.length - 1];
+ if (prev && prev.end === r.start && prev.kind === r.kind && prev.regionStart === r.regionStart) prev.end = r.end;
+ else this.cur.removals.push(r);
+ };
+ const covers: Cover[] = out.covers.map(c => ({ ...c, to: c.to === textLen && out.coverTerm ? whole.length : c.to }));
+ for (const [a, b] of markers) if (!covers.some(c => a < c.to && c.from < b)) add({ start: at(a), end: at(b), kind: 'marker', regionStart: at(a) });
+ for (const c of covers) add({ start: at(c.from), end: at(c.to), kind: c.pair === 0 ? 'facts' : c.pair === 1 ? 'takes' : 'tail', regionStart: c.start });
+ this.cur.removals.sort((x, y) => x.start - y.start);
+ }
+
+ private feedPem(final: boolean): void {
+ const text = this.pemPending;
+ this.pemPending = '';
+ feedPemScan(this.pem, text, final, (s, e) => this.pemSpans.push({ start: this.rawAt(s, false), end: this.rawAt(e, true) }));
+ const pieces = this.projPieces;
+ const resolved = pemResolvedTo(this.pem);
+ let lo = 0;
+ let hi = pieces.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (pieces[mid]!.proj + pieces[mid]!.text.length < resolved) lo = mid + 1; else hi = mid;
+ }
+ if (lo > 0) this.projPieces = pieces.slice(lo);
+ }
+
+ /** Stored byte of projection offset `pos` (`end`: the offset just past a char). */
+ private rawAt(pos: number, end: boolean): number {
+ const pieces = this.projPieces;
+ let lo = 0;
+ let hi = pieces.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ const p = pieces[mid]!;
+ if (end ? p.proj < pos : p.proj <= pos) lo = mid; else hi = mid - 1;
+ }
+ const p = pieces[lo]!;
+ return p.raw + utf8Len(p.text, 0, pos - p.proj);
+ }
+
+ private drain(): SegmentOut[] {
+ const out: SegmentOut[] = [];
+ while (this.closed.length) {
+ const seg = this.closed[0]!;
+ let pem = takePemCut(this.pem, seg.projEnd);
+ if (!pem && this.done) pem = { clean: false, start: seg.exit.pem.start };
+ if (!pem || (!this.done && pemResolvedTo(this.pem) < seg.projEnd)) break;
+ this.closed.shift();
+ seg.exit.pem = pem;
+ out.push(this.emit(seg));
+ }
+ return out;
+ }
+
+ private emit(seg: ClosedSegment): SegmentOut {
+ const raw = seg.parts.join('');
+ const bytes = Buffer.from(raw, 'utf8');
+ const segEnd = seg.byteStart + seg.bytes;
+ const tailFrom = this.actual().truncatedAt;
+ const regions: StoredRegion[] = [];
+ for (const r of seg.removals) {
+ const kind = tailFrom !== null && r.kind !== 'marker' && r.regionStart >= tailFrom ? 'tail' : r.kind;
+ const region: StoredRegion = { kind, start: r.start - seg.byteStart, end: r.end - seg.byteStart };
+ if (kind !== 'marker') {
+ const regionEnd = kind === 'tail' ? undefined : this.regionEnds.get(r.regionStart);
+ if (r.regionStart < seg.byteStart || regionEnd === undefined || regionEnd > segEnd) {
+ region.open_start = r.regionStart;
+ if (regionEnd !== undefined) region.open_end = regionEnd;
+ else if (kind === 'tail' && seg.cutKind === this.opts.end && this.done) region.open_end = segEnd;
+ }
+ }
+ regions.push(region);
+ }
+ for (const s of this.pemSpans) {
+ if (s.end <= seg.byteStart || s.start >= segEnd) continue;
+ const region: StoredRegion = { kind: 'pem', start: Math.max(s.start, seg.byteStart) - seg.byteStart, end: Math.min(s.end, segEnd) - seg.byteStart };
+ if (s.start < seg.byteStart || s.end > segEnd) { region.open_start = s.start; region.open_end = s.end; }
+ regions.push(region);
+ }
+ this.pemSpans = this.pemSpans.filter(s => s.end > segEnd);
+ regions.sort((a, b) => a.start - b.start || b.end - a.end);
+ const parts = segmentProjectionParts(raw, regions, seg.byteStart);
+ let projected = '';
+ let projBytes = 0;
+ const factsSlots: FactsSlot[] = [];
+ for (const p of parts) {
+ if (p.kind === 'facts') factsSlots.push({ proj_byte: projBytes, start: p.region!.start, end: p.region!.end,
+ ...(p.region!.open_start !== undefined ? { open_start: p.region!.open_start } : {}),
+ ...(p.region!.open_end !== undefined ? { open_end: p.region!.open_end } : {}) });
+ if (p.kind === 'text' || p.kind === 'pem') { projected += p.text; projBytes += utf8Len(p.text); }
+ }
+ const { outline, dateMin, dateMax } = this.outlineOf(projected);
+ seg.exit.outline = { ...this.outline };
+ let projLines = 0;
+ for (let i = projected.indexOf('\n'); i !== -1; i = projected.indexOf('\n', i + 1)) projLines++;
+ return {
+ region: seg.entry.region,
+ bytes,
+ sha256: createHash('sha256').update(bytes).digest(),
+ byteStart: seg.byteStart,
+ lineStart: seg.lineStart,
+ lineCount: seg.lines,
+ cutKind: seg.cutKind,
+ entryState: seg.entry,
+ exitState: seg.exit,
+ fenceTrust: this.opts.fenceTrust,
+ protectedRegions: regions,
+ factsSlots,
+ staticProjBytes: projBytes,
+ staticProjLines: projLines,
+ outline,
+ dateMin,
+ dateMax,
+ };
+ }
+
+ /** pageOutline's heading and date reading over one segment's static projection, carrying its fence toggle. */
+ private outlineOf(text: string): { outline: OutlineHeading[]; dateMin: string | null; dateMax: string | null } {
+ const outline: OutlineHeading[] = [];
+ let at = 0;
+ let byte = 0;
+ let skip = this.outline.midLine;
+ while (at < text.length) {
+ const nl = text.indexOf('\n', at);
+ const end = nl === -1 ? text.length : nl;
+ if (!skip) {
+ const line = text.slice(at, end);
+ if (FENCE.test(line)) this.outline.fence = !this.outline.fence;
+ else if (!this.outline.fence && outline.length < OUTLINE_MAX_HEADINGS) {
+ const h = HEADING.exec(line);
+ if (h) outline.push({ proj_byte: byte, level: h[1]!.length, text: clip(h[2]!, HEADING_MAX_CHARS) });
+ }
+ }
+ skip = false;
+ const next = nl === -1 ? text.length : nl + 1;
+ byte += utf8Len(text, at, next);
+ at = next;
+ }
+ if (text.length) this.outline.midLine = !text.endsWith('\n');
+ let dateMin: string | null = null;
+ let dateMax: string | null = null;
+ for (const m of text.matchAll(DATE)) {
+ if (dateMin === null || m[0] < dateMin) dateMin = m[0];
+ if (dateMax === null || m[0] > dateMax) dateMax = m[0];
+ }
+ return { outline, dateMin, dateMax };
+ }
+}
+
+/** The longest prefix of `text` whose UTF-8 bytes fit in `room` (chars and bytes), never splitting a surrogate pair. */
+function fitChars(text: string, room: number): { chars: number; bytes: number } {
+ let bytes = 0;
+ for (let i = 0; i < text.length; i++) {
+ const c = text.charCodeAt(i);
+ const d = c >= 0xd800 && c <= 0xdbff ? text.charCodeAt(i + 1) : 0;
+ const pair = d >= 0xdc00 && d <= 0xdfff;
+ const n = c < 0x80 ? 1 : c < 0x800 ? 2 : pair ? 4 : 3;
+ if (bytes + n > room) return { chars: i, bytes };
+ bytes += n;
+ if (pair) i++;
+ }
+ return { chars: text.length, bytes };
+}
+
+/** The kept (projected) ranges of `whole` (a line or piece plus its terminator): covers and marker spans out. */
+function keptRanges(whole: string, textLen: number, out: ScanOut, markers: Array<[number, number]>): Array<[number, number]> {
+ const cut: Array<[number, number]> = out.covers.map(c => [c.from, c.to === textLen && out.coverTerm ? whole.length : c.to]);
+ for (const m of markers) cut.push(m);
+ if (cut.length === 0) return whole.length ? [[0, whole.length]] : [];
+ cut.sort((a, b) => a[0] - b[0]);
+ const keep: Array<[number, number]> = [];
+ let at = 0;
+ for (const [a, b] of cut) {
+ if (a > at) keep.push([at, a]);
+ at = Math.max(at, b);
+ }
+ if (at < whole.length) keep.push([at, whole.length]);
+ return keep;
+}
+
+/** parseTimelineEntries' rule: would it read `line` as part of the open entry (a detail, or a blank before any)? */
+function timelineConsumes(state: EntryState['timeline'], line: string): boolean {
+ if (state.entry === 'none') return false;
+ if (TIMELINE_LINE_RE.test(line) || TIMELINE_HEADING_RE.test(line)) return false;
+ if (ATX_ANY.test(line) || isMaterializedMarkerLine(line)) return false;
+ if (line.trim().length === 0) return state.entry === 'entry';
+ return state.heading || /^\s+/.test(line) || (!line.startsWith('-') && !line.startsWith('*') && !line.startsWith('#'));
+}
+
+function timelineNext(state: EntryState['timeline'], line: string): EntryState['timeline'] {
+ if (timelineConsumes(state, line)) return { entry: line.trim().length === 0 ? state.entry : 'detail', heading: state.heading };
+ if (TIMELINE_HEADING_RE.test(line)) return { entry: 'entry', heading: true };
+ if (TIMELINE_LINE_RE.test(line) || TIMELINE_LINE_RE_CN.test(line)) return { entry: 'entry', heading: false };
+ return { entry: 'none', heading: false };
+}
+
+export interface ProjectionPart {
+ kind: 'text' | 'pem' | 'facts' | 'removed';
+ /** Segment-relative raw bytes. */
+ start: number;
+ end: number;
+ /** Projected text (text and pem parts), or the raw region text (facts parts). */
+ text: string;
+ region?: StoredRegion;
+}
+
+/**
+ * A segment's static projection in parts, from its raw text and stored
+ * regions: text kept, takes / tail / marker runs removed, facts runs as
+ * slots (`text` holds the raw fence for read-time rendering), and each
+ * private-key span as the projection token (in the segment where the span
+ * starts) plus the newlines of its projected text. `byteStart` is the
+ * segment's stored-stream offset.
+ */
+export function segmentProjectionParts(raw: string, regions: readonly StoredRegion[], byteStart: number): ProjectionPart[] {
+ const sorted = [...regions].sort((a, b) => a.start - b.start || b.end - a.end);
+ const charAt = byteToChar(raw, sorted.flatMap(r => [r.start, r.end]));
+ const parts: ProjectionPart[] = [];
+ let cursor = 0;
+ const text = (to: number) => {
+ if (to > cursor) parts.push({ kind: 'text', start: cursor, end: to, text: raw.slice(charAt.get(cursor)!, charAt.get(to)!) });
+ };
+ charAt.set(0, 0);
+ for (let i = 0; i < sorted.length; i++) {
+ const r = sorted[i]!;
+ if (r.start < cursor) continue;
+ text(r.start);
+ const from = charAt.get(r.start)!;
+ const to = charAt.get(r.end)!;
+ if (r.kind === 'pem') {
+ let newlines = 0;
+ let k = from;
+ for (let j = i + 1; j < sorted.length && sorted[j]!.start < r.end; j++) {
+ const inner = sorted[j]!;
+ newlines += countNewlines(raw, k, charAt.get(inner.start)!);
+ k = Math.max(k, charAt.get(inner.end)!);
+ }
+ newlines += countNewlines(raw, k, to);
+ const token = !(r.start === 0 && r.open_start !== undefined && r.open_start < byteStart);
+ parts.push({ kind: 'pem', start: r.start, end: r.end, text: (token ? PRIVATE_KEY_PROJECTION_TOKEN : '') + '\n'.repeat(newlines), region: r });
+ } else {
+ parts.push({ kind: r.kind === 'facts' ? 'facts' : 'removed', start: r.start, end: r.end, text: r.kind === 'facts' ? raw.slice(from, to) : '', region: r });
+ }
+ cursor = r.end;
+ }
+ const rawBytes = utf8Len(raw);
+ if (!charAt.has(rawBytes)) charAt.set(rawBytes, raw.length);
+ text(rawBytes);
+ return parts;
+}
+
+function countNewlines(s: string, from: number, to: number): number {
+ let n = 0;
+ for (let i = s.indexOf('\n', from); i !== -1 && i < to; i = s.indexOf('\n', i + 1)) n++;
+ return n;
+}
+
+/** UTF-16 index of each UTF-8 byte offset of `s` (offsets fall on code points). */
+function byteToChar(s: string, offsets: readonly number[]): Map<number, number> {
+ const want = [...new Set([...offsets, utf8Len(s)])].sort((a, b) => a - b);
+ const out = new Map<number, number>();
+ let bytes = 0;
+ let i = 0;
+ for (const target of want) {
+ while (bytes < target && i < s.length) {
+ const c = s.charCodeAt(i);
+ if (c < 0x80) bytes += 1;
+ else if (c < 0x800) bytes += 2;
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < s.length) { bytes += 4; i++; }
+ else bytes += 3;
+ i++;
+ }
+ out.set(target, i);
+ }
+ return out;
+}
+
+/** Segment a stream of one region's stored bytes (valid UTF-8; invalid input throws). */
+export async function* segmentStream(input: AsyncIterable<Uint8Array>, entry: EntryState, opts: SegmentOptions): AsyncIterable<SegmentOut> {
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
+ const segmenter = new Segmenter(entry, opts);
+ for await (const chunk of input) yield* segmenter.push(decoder.decode(chunk, { stream: true }));
+ segmenter.push(decoder.decode());
+ yield* segmenter.finish();
+}
+
+/** Segment one region held as a string (tests and the in-memory put path). */
+export function segmentString(text: string, entry: EntryState, opts: SegmentOptions): SegmentOut[] {
+ const segmenter = new Segmenter(entry, opts);
+ return [...segmenter.push(text), ...segmenter.finish()];
+}
diff --git a/src/core/page-window/window.ts b/src/core/page-window/window.ts
index 458210efb6..c47ca4d0a6 100644
--- a/src/core/page-window/window.ts
+++ b/src/core/page-window/window.ts
@@ -22,7 +22,7 @@ export const DEFAULT_OUTLINE_LIMIT = 100;
export const MAX_OUTLINE_LIMIT = 500;
/** Outline block size for pages without headings (conversation logs). */
export const OUTLINE_BLOCK_BYTES = 64 * 1024;
-const HEADING_MAX_CHARS = 200;
+export const HEADING_MAX_CHARS = 200;
const FIRST_LINE_MAX_CHARS = 120;
const NL = 0x0a;
@@ -209,11 +209,12 @@ export interface PageOutline {
next_from_index?: number;
}
-const HEADING = /^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$/;
-const FENCE = /^ {0,3}(```|~~~)/;
-const DATE = /\b((?:19|20)\d{2})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b/g;
+export const HEADING = /^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$/;
+export const FENCE = /^ {0,3}(```|~~~)/;
+export const DATE = /\b((?:19|20)\d{2})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b/g;
-function clip(text: string, max: number): string {
+/** `text` cut to `max` UTF-16 units on a code point, with an ellipsis when cut. */
+export function clip(text: string, max: number): string {
if (text.length <= max) return text;
let cut = max;
const c = text.charCodeAt(cut - 1);
diff --git a/src/core/remote-body.ts b/src/core/remote-body.ts
index d572dc1227..10d54a57d7 100644
--- a/src/core/remote-body.ts
+++ b/src/core/remote-body.ts
@@ -5,7 +5,7 @@ import { stripMaterializedMarkers } from './timeline-marker.ts';
import { protectedRegions, type FencePair } from './fence-scan.ts';
// Index 0 is the facts pair: its world rows are re-rendered, never dropped.
-const PROTECTED_PAIRS: readonly FencePair[] = [
+export const PROTECTED_PAIRS: readonly FencePair[] = [
{ begin: FACTS_FENCE_BEGIN, end: FACTS_FENCE_END },
{ begin: TAKES_FENCE_BEGIN, end: TAKES_FENCE_END },
];
@@ -28,15 +28,19 @@ export function sanitizeRemoteBody(body: string, opts: { includeWithdrawn?: bool
for (const region of regions) {
output.push(body.slice(cursor, region.start));
cursor = region.end;
- if (region.pair === 0) {
- try {
- const parsed = parseFactsFence(body.slice(region.start, region.end));
- if (parsed.warnings.length === 0) output.push(renderFactsTable(parsed.facts.filter(row => row.visibility === 'world' && (opts.includeWithdrawn || !row.forgotten))));
- } catch {
- // A protected block that cannot be parsed is omitted, never echoed.
- }
- }
+ if (region.pair === 0) output.push(renderFactsRegion(body.slice(region.start, region.end), opts.includeWithdrawn));
}
output.push(truncatedAt === -1 ? body.slice(cursor) : body.slice(cursor, truncatedAt));
return output.join('');
}
+
+/** What sanitizeRemoteBody puts in place of one protected facts region: its world rows rendered, or nothing. */
+export function renderFactsRegion(region: string, includeWithdrawn = false): string {
+ try {
+ const parsed = parseFactsFence(region);
+ if (parsed.warnings.length === 0) return renderFactsTable(parsed.facts.filter(row => row.visibility === 'world' && (includeWithdrawn || !row.forgotten)));
+ } catch {
+ // A protected block that cannot be parsed is omitted, never echoed.
+ }
+ return '';
+}
diff --git a/src/core/secret-scan.ts b/src/core/secret-scan.ts
index be286edd91..6fd58c5148 100644
--- a/src/core/secret-scan.ts
+++ b/src/core/secret-scan.ts
@@ -421,8 +421,8 @@ const PEM_LINE_MAX = 128;
const PEM_LINE_MIN = 16;
const PEM_INDENT_MAX = 16;
const PEM_RFC1421_LINE_MAX = 256;
-const PEM_BEGIN_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/g;
-const PEM_END_RE = /-----END [A-Z ]*PRIVATE KEY-----/g;
+export const PEM_BEGIN_RE = /-----BEGIN [A-Z ]*PRIVATE KEY-----/g;
+export const PEM_END_RE = /-----END [A-Z ]*PRIVATE KEY-----/g;
type PemClaimKind = 'block' | 'forward' | 'backward';
@@ -488,7 +488,7 @@ function atCut(t: string, i: number): boolean {
}
/** FORWARD claim end for a BEGIN fence ending at `headerEnd` (== headerEnd when no body line follows). */
-function pemForwardEnd(t: string, headerEnd: number): number {
+export function pemForwardEnd(t: string, headerEnd: number): number {
const n = t.length;
const cap = headerEnd + PEM_BODY_MAX_CHARS;
let pos = lineEndAfter(t, headerEnd);
@@ -520,7 +520,7 @@ function pemForwardEnd(t: string, headerEnd: number): number {
}
/** BACKWARD claim start for an END fence at `endStart`, never below `floor`; -1 when no body line precedes it. */
-function pemBackwardStart(t: string, endStart: number, floor: number): number {
+export function pemBackwardStart(t: string, endStart: number, floor: number): number {
let p = endStart;
while (endStart - p < PEM_INDENT_MAX && p > floor && isIndentCode(t.charCodeAt(p - 1))) p--;
let le = lineEndBefore(t, p, floor);
diff --git a/src/core/timeline-marker.ts b/src/core/timeline-marker.ts
index 8c5fd91f55..da6dae4e49 100644
--- a/src/core/timeline-marker.ts
+++ b/src/core/timeline-marker.ts
@@ -57,3 +57,9 @@ export function firstMaterializedMarkerIndex(text: string): number {
export function stripMaterializedMarkers(text: string): string {
return text.includes('gbrain:materialized') ? text.replace(MARKER_LINES, '') : text;
}
+
+/** The `[start, end)` UTF-16 spans `stripMaterializedMarkers` removes from `text`, in order. */
+export function materializedMarkerSpans(text: string): Array<[number, number]> {
+ if (!text.includes('gbrain:materialized')) return [];
+ return [...text.matchAll(MARKER_LINES)].map(m => [m.index, m.index + m[0].length]);
+}
diff --git a/test/helpers/segment-bodies.ts b/test/helpers/segment-bodies.ts
new file mode 100644
index 0000000000..beeedb1d2f
--- /dev/null
+++ b/test/helpers/segment-bodies.ts
@@ -0,0 +1,127 @@
+/**
+ * Page bodies and helpers for the segmented-storage tests (test/large-pages/):
+ * seeded generators of marker / fence / key soup and of multi-MiB pages, a
+ * whole-page segmentation call, and the per-segment projection joined back
+ * into one text for parity with credentialSafeProjection(sanitizeRemoteBody()).
+ */
+import { renderFactsRegion } from '../../src/core/remote-body.ts';
+import { initialEntryState, type EntryState } from '../../src/core/page-body/entry-state.ts';
+import { Segmenter, segmentProjectionParts, type SegmentOptions, type SegmentOut } from '../../src/core/page-body/segmenter.ts';
+
+export const FACTS_BLOCK = '<!--- gbrain:facts:begin -->\n'
+ + '| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n'
+ + '|---|---|---|---|---|---|---|---|---|---|\n'
+ + '| 1 | likes tea | preference | 0.9 | world | low | 2024-01-01 | | user | |\n'
+ + '| 2 | private thing | fact | 0.9 | private | low | 2024-01-01 | | user | |\n'
+ + '<!--- gbrain:facts:end -->\n';
+export const KEY_BODY = 'MIIBOgIBAAJBAKj34GkxFhD90vcNLYLInFEX6Ppy1tPf9Cnzj4p4WGeKLs1Pt8Qu';
+export const PEM_BLOCK = `-----BEGIN RSA PRIVATE KEY-----\n${KEY_BODY}\n-----END RSA PRIVATE KEY-----\n`;
+export const MARKER_BULLET = '<!-- gbrain:materialized v1 0123456789ab -->\n- **2024-01-02** | src — did a thing\n detail line\n';
+
+export const SOUP_ATOMS = [
+ '<!--- gbrain:facts:begin -->', '<!--- gbrain:facts:end -->', '<!--- gbrain:takes:begin -->', '<!--- gbrain:takes:end -->',
+ '```', '~~~', '````', '```js', '`', '\n', '\n', '\n\n', '\r\n', '\r', ' ', 'text words here', 'é', '😀', '\u2028',
+ '## Heading 2024-03-05\n', '# Top\n', '### deep\n', '-----BEGIN RSA PRIVATE KEY-----\n', `${KEY_BODY}\n`,
+ '-----END RSA PRIVATE KEY-----\n', MARKER_BULLET, '- **2024-01-02** | src — entry\n', ' detail line\n', FACTS_BLOCK,
+];
+
+export function pick<T>(r: () => number, a: readonly T[]): T {
+ return a[Math.floor(r() * a.length)]!;
+}
+
+/** A short body of random atoms (one segment). */
+export function soup(r: () => number, atoms: readonly string[] = SOUP_ATOMS, max = 60): string {
+ let body = '';
+ const n = 1 + Math.floor(r() * max);
+ for (let i = 0; i < n; i++) body += pick(r, atoms);
+ return body;
+}
+
+const WORDS = ['alpha', 'beta', 'gamma', 'delta', 'é', '😀', 'acme-example', 'notes', 'meeting', 'value', '2024-06-07'];
+
+export function paragraph(r: () => number): string {
+ let s = '';
+ const n = 20 + Math.floor(r() * 300);
+ for (let i = 0; i < n; i++) s += pick(r, WORDS) + (r() < 0.08 ? '\n' : ' ');
+ return `${s}\n`;
+}
+
+/**
+ * A page of about `target` chars: paragraphs, headings, day headers, small
+ * fences, facts and takes blocks, keys, timeline entries and markers, all
+ * closed, so structural cuts happen. `crlf` writes `\r\n` line ends.
+ */
+export function bigPage(r: () => number, target: number, opts: { crlf?: boolean; keys?: boolean; facts?: boolean } = {}): string {
+ const parts: string[] = [];
+ let len = 0;
+ while (len < target) {
+ const x = r();
+ let p: string;
+ if (x < 0.5) p = `${paragraph(r)}\n`;
+ else if (x < 0.6) p = `${pick(r, ['# Top', '## Section', '### deep', '## 2024-05-06', '#### deeper'])}\n`;
+ else if (x < 0.65) p = `\`\`\`ts\nconst a${Math.floor(r() * 1000)} = 1;\nfunction f() { return a; }\n\`\`\`\n`;
+ else if (x < 0.68) p = opts.facts === false ? paragraph(r) : FACTS_BLOCK;
+ else if (x < 0.7) p = `<!--- gbrain:takes:begin -->\n${paragraph(r)}<!--- gbrain:takes:end -->\n`;
+ else if (x < 0.72) p = opts.keys === false ? paragraph(r) : PEM_BLOCK;
+ else if (x < 0.75) p = MARKER_BULLET;
+ else if (x < 0.8) p = '- **2024-02-03** | src — entry\n more detail\n';
+ else p = paragraph(r);
+ if (opts.crlf) p = p.replace(/\n/g, '\r\n');
+ parts.push(p);
+ len += p.length;
+ }
+ return parts.join('');
+}
+
+export function segmentOptions(fenceTrust: 'trusted' | 'void', over: Partial<SegmentOptions> = {}): SegmentOptions {
+ return { byteStart: 0, lineStart: 0, fenceTrust, end: 'eof', ...over };
+}
+
+/** Segment `body` fed in pieces of `piece()` chars (never splitting a surrogate pair). */
+export function segmentPieces(body: string, opts: SegmentOptions, piece: () => number = () => body.length || 1,
+ entry: EntryState = initialEntryState({ region: 'truth' })): SegmentOut[] {
+ const seg = new Segmenter(entry, opts);
+ const out: SegmentOut[] = [];
+ for (let i = 0; i < body.length;) {
+ let k = Math.max(1, piece());
+ const c = body.charCodeAt(i + k - 1);
+ if (c >= 0xd800 && c <= 0xdbff) k++;
+ out.push(...seg.push(body.slice(i, i + k)));
+ i += k;
+ }
+ out.push(...seg.finish());
+ return out;
+}
+
+/** The segments' projections joined, each facts region rendered once in the segment where it starts. */
+export function joinedProjection(body: Buffer, segs: readonly SegmentOut[], renderFacts = true): string {
+ let out = '';
+ for (const s of segs) {
+ const raw = Buffer.from(s.bytes).toString('utf8');
+ for (const p of segmentProjectionParts(raw, s.protectedRegions, s.byteStart)) {
+ if (p.kind === 'text' || p.kind === 'pem') out += p.text;
+ else if (p.kind === 'facts' && renderFacts) {
+ const r = p.region!;
+ const start = r.open_start ?? s.byteStart + r.start;
+ const end = r.open_start !== undefined ? r.open_end : s.byteStart + r.end;
+ if (start === s.byteStart + r.start && end !== undefined) out += renderFactsRegion(body.subarray(start, end).toString('utf8'));
+ }
+ }
+ }
+ return out;
+}
+
+/** Concatenated segment bytes equal the input, offsets chain, every segment is 1..max bytes of valid UTF-8. */
+export function segmentShapeErrors(body: Buffer, segs: readonly SegmentOut[], max: number, byteStart = 0): string[] {
+ const errors: string[] = [];
+ if (!Buffer.concat(segs.map(s => s.bytes)).equals(body)) errors.push('concatenation differs from input');
+ let at = byteStart;
+ const decoder = new TextDecoder('utf-8', { fatal: true });
+ for (const [i, s] of segs.entries()) {
+ if (s.byteStart !== at) errors.push(`segment ${i} starts at ${s.byteStart}, expected ${at}`);
+ if (s.bytes.length === 0 || s.bytes.length > max) errors.push(`segment ${i} has ${s.bytes.length} bytes`);
+ try { decoder.decode(s.bytes); } catch { errors.push(`segment ${i} is not valid UTF-8`); }
+ at += s.bytes.length;
+ }
+ return errors;
+}
diff --git a/test/large-pages/region-scan.test.ts b/test/large-pages/region-scan.test.ts
new file mode 100644
index 0000000000..281be809fd
--- /dev/null
+++ b/test/large-pages/region-scan.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Streaming forms of the two whole-body privacy scans (page-body/region-scan.ts).
+ *
+ * 1. Protects: segmented pages find exactly the protected regions and
+ * private-key spans whole-body sanitization finds, scanning the body once
+ * in pieces, so a per-segment projection never shows more than
+ * sanitizeRemoteBody + credentialSafeProjection would.
+ * 2. Fails when: protectedRegionScan differs from protectedRegions (pairs,
+ * offsets, `read`, truncated tail) or feedPemScan differs from
+ * privateKeySpans for any chunking, or a fence trust flip by append goes
+ * unnoticed by the observed fence walk.
+ * 3. Existing coverage: test/fence-scan*.test.ts and
+ * test/secret-scan-private-key-spans.test.ts pin the whole-body functions.
+ * 4. No production seam: differential against the whole-body functions.
+ */
+import { describe, expect, test } from 'bun:test';
+import { markdownFenceTrusted, protectedRegions } from '../../src/core/fence-scan.ts';
+import { PROTECTED_PAIRS } from '../../src/core/remote-body.ts';
+import { privateKeySpans } from '../../src/core/secret-scan.ts';
+import { feedPemScan, initialPemScan, initialRegionScan, protectedRegionScan, walkTrusted, type ScannedRegion } from '../../src/core/page-body/region-scan.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import { KEY_BODY, pick } from '../helpers/segment-bodies.ts';
+
+const ATOMS = ['<!--- gbrain:facts:begin -->', '<!--- gbrain:facts:end -->', '<!--- gbrain:takes:begin -->', '<!--- gbrain:takes:end -->',
+ '```', '~~~', '````', '```js', '`', '\n', '\r\n', '\r', ' ', 'text', 'é', '😀', ' ```', ' ```', '\\`', '\u2028'];
+const PEM_ATOMS = ['-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----', '-----BEGIN PRIVATE KEY-----', KEY_BODY, 'AAAA',
+ '\n', '\r\n', ' ', 'prose words', '\\n', 'Proc-Type: 4,ENCRYPTED', '-----', 'BEGIN', ' PRIVATE KEY-----', 'x'.repeat(3000)];
+
+const byteAt = (s: string, i: number) => Buffer.byteLength(s.slice(0, i));
+
+function expectedRegions(body: string) {
+ const { regions, truncatedAt } = protectedRegions(body, PROTECTED_PAIRS);
+ return {
+ regions: regions.map(r => ({ pair: r.pair, start: byteAt(body, r.start), end: byteAt(body, r.end), read: r.read })),
+ truncatedAt: truncatedAt === -1 ? null : byteAt(body, truncatedAt),
+ };
+}
+
+function scanInPieces(body: string, trusted: boolean, piece: () => number) {
+ const state = initialRegionScan(trusted);
+ const regions: ScannedRegion[] = [];
+ for (let i = 0; i < body.length;) {
+ let k = piece();
+ const c = body.charCodeAt(i + k - 1);
+ if (c >= 0xd800 && c <= 0xdbff) k++;
+ regions.push(...protectedRegionScan(state, body.slice(i, i + k)).regions);
+ i += k;
+ }
+ const last = protectedRegionScan(state, '', true);
+ return { regions: [...regions, ...last.regions], truncatedAt: last.truncatedAt, state };
+}
+
+describe('protectedRegionScan', () => {
+ test('equals protectedRegions on marker and fence soup in random chunkings', () => {
+ const r = mulberry32(101);
+ for (let t = 0; t < 8000; t++) {
+ let body = '';
+ const n = 1 + Math.floor(r() * 40);
+ for (let i = 0; i < n; i++) body += pick(r, ATOMS);
+ const { regions, truncatedAt } = scanInPieces(body, markdownFenceTrusted(body), () => 1 + Math.floor(r() * 8));
+ expect({ regions, truncatedAt }).toEqual(expectedRegions(body));
+ }
+ });
+
+ test('a fence trust flip by append: the observed walk reports it, and a rescan under the new trust matches', () => {
+ const before = 'intro\n```\n<!--- gbrain:takes:begin -->\n```\nsecret <!--- gbrain:takes:end -->\n';
+ const appended = '```\nnever closed <!--- gbrain:takes:end -->\n';
+ expect(markdownFenceTrusted(before)).toBe(true);
+ expect(markdownFenceTrusted(before + appended)).toBe(false);
+ const first = scanInPieces(before, true, () => 7);
+ expect(walkTrusted(first.state.track.walk)).toBe(true);
+ const stale = initialRegionScan(true);
+ protectedRegionScan(stale, before);
+ protectedRegionScan(stale, appended, true);
+ expect(walkTrusted(stale.track.walk)).toBe(false);
+ const rescan = scanInPieces(before + appended, false, () => 5);
+ expect({ regions: rescan.regions, truncatedAt: rescan.truncatedAt }).toEqual(expectedRegions(before + appended));
+ expect(rescan.regions).not.toEqual(scanInPieces(before + appended, true, () => 5).regions);
+ });
+});
+
+describe('feedPemScan', () => {
+ test('equals privateKeySpans on key soup in random chunkings', () => {
+ const r = mulberry32(103);
+ let spans = 0;
+ for (let t = 0; t < 1500; t++) {
+ let body = '';
+ const n = 1 + Math.floor(r() * 60);
+ for (let i = 0; i < n; i++) body += pick(r, PEM_ATOMS);
+ if (r() < 0.2) body = body.repeat(1 + Math.floor(r() * 8));
+ const want = privateKeySpans(body);
+ const st = initialPemScan('region_start');
+ const got: Array<{ start: number; end: number }> = [];
+ for (let i = 0; i < body.length;) {
+ const k = 1 + Math.floor(r() * (r() < 0.5 ? 10 : 5000));
+ feedPemScan(st, body.slice(i, i + k), false, (start, end) => got.push({ start, end }));
+ i += k;
+ }
+ feedPemScan(st, '', true, (start, end) => got.push({ start, end }));
+ expect(got).toEqual(want.map(s => ({ start: s.start, end: s.end })));
+ spans += want.length;
+ }
+ expect(spans).toBeGreaterThan(500);
+ });
+});
diff --git a/test/large-pages/segment-chunks.test.ts b/test/large-pages/segment-chunks.test.ts
new file mode 100644
index 0000000000..3b614de4e8
--- /dev/null
+++ b/test/large-pages/segment-chunks.test.ts
@@ -0,0 +1,141 @@
+/**
+ * The per-segment chunker (page-body/segment-chunks.ts), spec 4.1.
+ *
+ * 1. Protects: chunks of a segmented page stay inside their segment, address
+ * their text in stored and projected coordinates, keep today's privacy
+ * projection and order within the segment (prose, fenced code, low-tier
+ * facts rows), and a quarantined page has none.
+ * 2. Fails when: a chunk's span leaves its segment or does not hold its
+ * text, fenced code or low-tier rows leave their segment's tail, a
+ * segment starting inside a giant fence misreads its closer, chunks are
+ * made from regions computed under the wrong fence trust, or a
+ * one-segment page chunks differently from prepareMarkdownChunks.
+ * 3. Existing coverage: test/fence-chunk-overlay.test.ts and the chunker
+ * suites pin the inline pipeline this reuses.
+ * 4. No production seam: pure functions; the fence overlay is passed in.
+ */
+import { describe, expect, test } from 'bun:test';
+import { markdownFenceTrusted } from '../../src/core/fence-scan.ts';
+import { stripMaterializedMarkers } from '../../src/core/timeline-marker.ts';
+import { prepareMarkdownChunks, newFenceChunkBudget } from '../../src/core/markdown-chunks.ts';
+import { QUARANTINE_KEY } from '../../src/core/quarantine.ts';
+import { chunkFenceMarker, type FenceChunkOverlay } from '../../src/core/eligibility/fence-overlay.ts';
+import { initialEntryState } from '../../src/core/page-body/entry-state.ts';
+import { segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';
+import { prepareSegmentChunks, type SegmentChunk } from '../../src/core/page-body/segment-chunks.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import { bigPage, FACTS_BLOCK, joinedProjection, PEM_BLOCK, segmentOptions } from '../helpers/segment-bodies.ts';
+
+const trustOf = (body: string) => markdownFenceTrusted(stripMaterializedMarkers(body)) ? 'trusted' as const : 'void' as const;
+const squash = (s: string) => s.replace(/\s+/g, '');
+const segment = (body: string, region: 'truth' | 'timeline' = 'truth') =>
+ segmentString(body, initialEntryState({ region }), segmentOptions(trustOf(body)));
+const kindOf = (c: SegmentChunk) => chunkFenceMarker(c.chunk_text) ? 'low' : c.chunk_source === 'fenced_code' ? 'code' : 'prose';
+const DEMOTE: FenceChunkOverlay = { omit: new Set(), demote: new Map([[1, 'external_untrusted' as const]]) };
+
+function overlaps(seg: SegmentOut, start: number, end: number): boolean {
+ return seg.protectedRegions.some(r => seg.byteStart + r.start < end && start < seg.byteStart + r.end);
+}
+
+describe('prepareSegmentChunks', () => {
+ test('a one-segment page chunks like prepareMarkdownChunks', async () => {
+ const body = '# Notes\n\nIntro paragraph about acme-example.\n\n' + FACTS_BLOCK + '\nMiddle text.\n\n'
+ + '<!--- gbrain:takes:begin -->\nsecret take\n<!--- gbrain:takes:end -->\n\n```ts\nexport function f(a: number) { return a + 1; }\n```\n\n'
+ + 'More prose 2024-04-05.\n\n' + 'filler words here. '.repeat(400) + '\n';
+ const [seg, ...rest] = segment(body);
+ expect(rest).toEqual([]);
+ const got = await prepareSegmentChunks(seg!, { fenceTrust: 'trusted' });
+ const want = await prepareMarkdownChunks({ compiled_truth: body });
+ expect(got.map(c => [c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end, c.symbol_name]))
+ .toEqual(want.map(c => [c.chunk_text, c.chunk_source, c.projected_byte_start, c.projected_byte_end, c.symbol_name]));
+ expect(got.some(c => c.chunk_source === 'fenced_code')).toBe(true);
+ expect(got.map(c => c.chunk_text).join('\n')).not.toContain('secret take');
+ expect(got.map(c => c.chunk_text).join('\n')).not.toContain('private thing');
+ });
+
+ test('chunks stay inside their segment and their spans hold their text', async () => {
+ const body = bigPage(mulberry32(3), 2_500_000);
+ const bytes = Buffer.from(body, 'utf8');
+ const segs = segment(body);
+ expect(segs.length).toBeGreaterThan(4);
+ const budget = newFenceChunkBudget();
+ let checkedRaw = 0;
+ for (const seg of segs) {
+ const chunks = await prepareSegmentChunks(seg, { fenceTrust: trustOf(body), fenceBudget: budget });
+ const projection = Buffer.from(joinedProjection(bytes, [seg]), 'utf8');
+ const segEnd = seg.byteStart + seg.bytes.length;
+ expect(chunks.map(c => c.local_ordinal)).toEqual(chunks.map((_, i) => i));
+ const order = chunks.map(kindOf).join(',');
+ expect(order).toMatch(/^(prose,)*prose(,code)*(,low)*$/);
+ for (const c of chunks) {
+ expect(c.raw_byte_start).toBeGreaterThanOrEqual(seg.byteStart);
+ expect(c.raw_byte_end).toBeLessThanOrEqual(segEnd);
+ expect(c.raw_byte_end).toBeGreaterThan(c.raw_byte_start);
+ if (kindOf(c) !== 'prose') continue;
+ expect(c.projected_byte_end!).toBeLessThanOrEqual(projection.length);
+ expect(squash(projection.subarray(c.projected_byte_start!, c.projected_byte_end!).toString('utf8'))).toBe(squash(c.chunk_text));
+ if (!overlaps(seg, c.raw_byte_start, c.raw_byte_end)) {
+ expect(squash(bytes.subarray(c.raw_byte_start, c.raw_byte_end).toString('utf8'))).toBe(squash(c.chunk_text));
+ checkedRaw++;
+ }
+ }
+ const text = chunks.map(c => c.chunk_text).join('\n');
+ expect(text).not.toContain('private thing');
+ expect(text).not.toContain('MIIBOgIB');
+ }
+ expect(checkedRaw).toBeGreaterThan(100);
+ expect(budget.fences).toBeLessThan(newFenceChunkBudget().fences);
+ });
+
+ test('low-tier facts rows are marked chunks at the end of their own segment', async () => {
+ const section = (i: number) => `## Section ${i}\n\n` + 'filler words for the section. '.repeat(10_000) + '\n\n' + FACTS_BLOCK
+ + `\n\`\`\`ts\nexport const v${i} = ${i};\n\`\`\`\n\n`;
+ const body = [0, 1, 2, 3].map(section).join('');
+ const segs = segment(body);
+ expect(segs.length).toBe(4);
+ for (const seg of segs) {
+ expect(seg.factsSlots.length).toBe(1);
+ const chunks = await prepareSegmentChunks(seg, { fenceTrust: 'trusted', overlay: DEMOTE });
+ expect(chunks.map(kindOf).join(',')).toMatch(/^(prose,)+code,low$/);
+ expect(chunks[chunks.length - 1]!.chunk_text).toContain('likes tea');
+ expect(chunks.filter(c => kindOf(c) === 'prose').map(c => c.chunk_text).join('\n')).not.toContain('likes tea');
+ }
+ });
+
+ test('raw spans of chunks around a key or a facts table cover the stored region', async () => {
+ const body = 'Lead text before the key.\n\n' + PEM_BLOCK + '\nText after the key.\n\n' + FACTS_BLOCK + '\nClosing text.\n';
+ const [seg] = segment(body);
+ const chunks = await prepareSegmentChunks(seg!, { fenceTrust: 'trusted' });
+ expect(chunks.length).toBe(1);
+ expect(chunks[0]!.chunk_text).toContain('<REDACTED:private_key_pem>');
+ expect(chunks[0]!.chunk_text).toContain('likes tea');
+ expect([chunks[0]!.raw_byte_start, chunks[0]!.raw_byte_end]).toEqual([0, Buffer.byteLength(body) - 1]);
+ });
+
+ test('a segment starting inside a giant fence still finds the fences after it closes', async () => {
+ const body = 'intro\n~~~\n' + 'plain fenced line\n'.repeat(70_000) + '~~~\n\n```ts\nexport function g(x: number) { return x * 2; }\n```\n\nafter\n';
+ const segs = segment(body);
+ expect(segs.length).toBe(2);
+ expect(segs[1]!.entryState.trusted.walk.fence).toBe('~');
+ const chunks = await prepareSegmentChunks(segs[1]!, { fenceTrust: 'trusted' });
+ expect(chunks.some(c => c.chunk_source === 'fenced_code' && c.chunk_text.includes('function g'))).toBe(true);
+ });
+
+ test('timeline segments are timeline chunks and carry no fenced-code chunks', async () => {
+ const body = '- **2024-01-02** | src — entry\n\n```ts\nexport const a = 1;\n```\n';
+ const [seg] = segment(body, 'timeline');
+ const chunks = await prepareSegmentChunks(seg!, { fenceTrust: 'trusted' });
+ expect(chunks.length).toBeGreaterThan(0);
+ expect(chunks.every(c => c.chunk_source === 'timeline')).toBe(true);
+ });
+
+ test('a quarantined page has no chunks', async () => {
+ const [seg] = segment('# Title\n\nSome text.\n');
+ expect(await prepareSegmentChunks(seg!, { fenceTrust: 'trusted', frontmatter: { [QUARANTINE_KEY]: { reason: 'test' } } })).toEqual([]);
+ });
+
+ test('regions computed under the other fence trust are refused', async () => {
+ const [seg] = segment('# Title\n\nSome text.\n');
+ await expect(prepareSegmentChunks(seg!, { fenceTrust: 'void' })).rejects.toThrow(/segment_regions_stale/);
+ });
+});
diff --git a/test/large-pages/segmenter-linear.test.ts b/test/large-pages/segmenter-linear.test.ts
new file mode 100644
index 0000000000..ec0740eb89
--- /dev/null
+++ b/test/large-pages/segmenter-linear.test.ts
@@ -0,0 +1,106 @@
+/**
+ * The segmenter is linear in the input, and appending through a stored entry
+ * state is linear in the appended text (plus one segment).
+ *
+ * 1. Protects: ingest of a 256 MB page and repeated appends to a large page
+ * stay O(bytes); a cut decision that rescans the open segment, or an
+ * append that resegments the page, would make both quadratic.
+ * 2. Fails when: doubling the input more than 2.5x the CPU time (linear is
+ * 2x, quadratic 4x), for prose, short lines, one newline-free line, a
+ * giant fence, an unterminated protected region and key-dense text.
+ * 3. Forced probe: the same ratio check run on an append path that
+ * resegments the whole prefix on each append (the quadratic variant)
+ * exceeds the bound, so the check can tell the two apart.
+ * 4. Each size takes its best of three runs in thread CPU time (cpuMs).
+ */
+import { describe, expect, test } from 'bun:test';
+import { initialEntryState } from '../../src/core/page-body/entry-state.ts';
+import { segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';
+import { cpuMs } from '../helpers/cpu-time.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import { bigPage, PEM_BLOCK, segmentOptions } from '../helpers/segment-bodies.ts';
+
+const MB = 1024 * 1024;
+const BOUND = 2.5;
+const entry = () => initialEntryState({ region: 'truth' });
+
+function bestMs(fn: () => unknown): number {
+ let best = Infinity;
+ for (let k = 0; k < 3; k++) best = Math.min(best, cpuMs(fn));
+ return best;
+}
+
+function ratio(make: (bytes: number) => string, small: number, run: (body: string) => unknown): number {
+ const a = make(small);
+ const b = make(2 * small);
+ return bestMs(() => run(b)) / bestMs(() => run(a));
+}
+
+const page = bigPage(mulberry32(7), 4.5 * MB);
+const prefix = (bytes: number) => page.slice(0, page.indexOf('\n', bytes) + 1);
+const segmentAll = (body: string) => segmentString(body, entry(), segmentOptions('trusted'));
+
+describe('segmentString scales linearly', () => {
+ const shapes: Array<[string, (bytes: number) => string, number]> = [
+ ['mixed page', prefix, 2 * MB],
+ ['short lines', bytes => 'a\n'.repeat(bytes / 2), MB / 2],
+ ['one newline-free line', bytes => 'x'.repeat(bytes), 8 * MB],
+ ['giant fence', bytes => '```\n' + '## not a heading\n\ncode line\n'.repeat(bytes / 28), 1 * MB],
+ ['unterminated protected region', bytes => '<!--- gbrain:takes:begin -->\n' + '## secret\n\nwords here\n'.repeat(bytes / 23), 1 * MB],
+ ['key-dense text', bytes => PEM_BLOCK.repeat(bytes / PEM_BLOCK.length), 2 * MB],
+ ];
+ for (const [name, make, small] of shapes) {
+ test(`${name}: twice the input takes under ${BOUND}x the time`, () => {
+ const r = ratio(make, small, segmentAll);
+ console.log(`[segmenter-linear] ${name}: ${r.toFixed(2)}x`);
+ expect(r).toBeLessThan(BOUND);
+ }, 120_000);
+ }
+});
+
+const STEP = 64 * 1024;
+
+/** Append `body` in STEP-char writes, each resegmenting only the last segment from its stored entry state. */
+function appendResuming(body: string): SegmentOut[] {
+ let segs: SegmentOut[] = [];
+ let stored = Buffer.alloc(0);
+ for (let at = 0; at < body.length; at += STEP) {
+ const added = Buffer.from(body.slice(at, at + STEP), 'utf8');
+ const last = segs.pop();
+ const start = last ? last.byteStart : 0;
+ const tail = Buffer.concat([stored.subarray(start), added]).toString('utf8');
+ segs = segs.concat(segmentString(tail, last ? last.entryState : entry(), segmentOptions('trusted', {
+ byteStart: start, lineStart: last ? last.lineStart : 0,
+ })));
+ stored = Buffer.concat([stored, added]);
+ }
+ return segs;
+}
+
+/** The quadratic variant: every append resegments the whole page. */
+function appendResegmenting(body: string): SegmentOut[] {
+ let segs: SegmentOut[] = [];
+ for (let at = 0; at < body.length; at += STEP) segs = segmentAll(body.slice(0, Math.min(body.length, at + STEP)));
+ return segs;
+}
+
+describe('appends through a stored entry state', () => {
+ const ascii = (bytes: number) => prefix(bytes).replace(/[^\n -~]/g, 'u');
+
+ test('reproduce a full run\'s cuts', () => {
+ const body = ascii(1.5 * MB);
+ expect(appendResuming(body).map(s => [s.byteStart, s.bytes.length, s.cutKind])).toEqual(segmentAll(body).map(s => [s.byteStart, s.bytes.length, s.cutKind]));
+ });
+
+ test(`twice the appended text takes under ${BOUND}x the time`, () => {
+ const r = ratio(ascii, 1 * MB, appendResuming);
+ console.log(`[segmenter-linear] appends resuming: ${r.toFixed(2)}x`);
+ expect(r).toBeLessThan(BOUND);
+ }, 120_000);
+
+ test('forced probe: resegmenting the whole page per append exceeds the bound', () => {
+ const r = ratio(ascii, 1 * MB, appendResegmenting);
+ console.log(`[segmenter-linear] appends resegmenting (quadratic probe): ${r.toFixed(2)}x`);
+ expect(r).toBeGreaterThan(BOUND);
+ }, 120_000);
+});
diff --git a/test/large-pages/segmenter.test.ts b/test/large-pages/segmenter.test.ts
new file mode 100644
index 0000000000..d647fc9f03
--- /dev/null
+++ b/test/large-pages/segmenter.test.ts
@@ -0,0 +1,348 @@
+/**
+ * The Wave B segmenter cuts one region of a page's stored stream into
+ * segments of at most SEGMENT_MAX_BYTES, spec section 2.
+ *
+ * 1. Protects: lossless storage (segments concatenate to the input, valid
+ * UTF-8, never over 1 MiB, CRLF kept whole), append-stability and resume
+ * (what makes an append O(last segment)), the never-cut zones (what makes
+ * per-segment privacy and parsing exact), and the per-segment projection
+ * metadata a windowed read is built from.
+ * 2. Fails when: a cut looks forward, lands inside a fence, protected region,
+ * key margin, timeline detail run, marker bullet or withdrawal block, a
+ * forced cut splits a code point or a CRLF, resumed state diverges from a
+ * full run, or the joined per-segment projection differs from
+ * credentialSafeProjection(sanitizeRemoteBody(body)).
+ * 3. Existing coverage: none; the segmenter is new in Wave B.
+ * 4. No production seam: pure functions over strings and bytes.
+ */
+import { describe, expect, test } from 'bun:test';
+import { markdownFenceTrusted } from '../../src/core/fence-scan.ts';
+import { sanitizeRemoteBody } from '../../src/core/remote-body.ts';
+import { credentialSafeProjection } from '../../src/core/credential-projection.ts';
+import { stripMaterializedMarkers } from '../../src/core/timeline-marker.ts';
+import { pageOutline } from '../../src/core/page-window/window.ts';
+import { pickHeadPattern } from '../../src/core/conversation-parser/parse.ts';
+import { initialEntryState, isCleanResumePoint, readEntryState, timelineEntryState } from '../../src/core/page-body/entry-state.ts';
+import { PEM_CONTEXT_CHARS } from '../../src/core/page-body/region-scan.ts';
+import { SEGMENT_MAX_BYTES, SEGMENT_MIN_BYTES } from '../../src/core/page-body/limits.ts';
+import { regionFlags, segmentStream, segmentString, type SegmentOut } from '../../src/core/page-body/segmenter.ts';
+import { mulberry32 } from '../helpers/seeded-random.ts';
+import {
+ bigPage, FACTS_BLOCK, joinedProjection, KEY_BODY, MARKER_BULLET, PEM_BLOCK, segmentOptions, segmentPieces, segmentShapeErrors, soup,
+} from '../helpers/segment-bodies.ts';
+
+const MAX = SEGMENT_MAX_BYTES;
+const truthEntry = () => initialEntryState({ region: 'truth' });
+const trustOf = (body: string) => markdownFenceTrusted(stripMaterializedMarkers(body)) ? 'trusted' as const : 'void' as const;
+const cuts = (segs: readonly SegmentOut[]) => segs.map(s => s.byteStart);
+const fingerprint = (s: SegmentOut) => JSON.stringify({
+ byteStart: s.byteStart, len: s.bytes.length, lineStart: s.lineStart, lineCount: s.lineCount, cutKind: s.cutKind,
+ sha: Buffer.from(s.sha256).toString('hex'), entry: s.entryState, exit: s.exitState, regions: s.protectedRegions,
+ facts: s.factsSlots, proj: [s.staticProjBytes, s.staticProjLines], outline: s.outline, dates: [s.dateMin, s.dateMax],
+});
+const KEY_COUNT = (s: string) => s.split(KEY_BODY).length - 1;
+
+function filler(bytes: number): string {
+ const line = 'plain words without structure '.repeat(3) + '\n';
+ return line.repeat(Math.ceil(bytes / line.length));
+}
+
+describe('lossless segments', () => {
+ test('multi-MiB pages: concatenation, bounds, UTF-8, offsets, line counts, any feed chunking', () => {
+ const r = mulberry32(11);
+ for (const crlf of [false, true]) {
+ const body = bigPage(r, 3_000_000, { crlf });
+ const bytes = Buffer.from(body, 'utf8');
+ const segs = segmentPieces(body, segmentOptions(trustOf(body)), () => 1 + Math.floor(r() * 300_000));
+ expect(segmentShapeErrors(bytes, segs, MAX)).toEqual([]);
+ expect(segs.length).toBeGreaterThan(5);
+ expect(segs.slice(0, -1).every(s => s.bytes.length >= SEGMENT_MIN_BYTES)).toBe(true);
+ expect(segs.reduce((n, s) => n + s.lineCount, 0)).toBe(body.split('\n').length - 1);
+ segs.forEach((s, i) => { if (i > 0) expect(s.lineStart).toBe(segs[i - 1]!.lineStart + segs[i - 1]!.lineCount); });
+ expect(segs.slice(0, -1).every(s => s.cutKind !== 'forced')).toBe(true);
+ expect(segs[segs.length - 1]!.cutKind).toBe('eof');
+ expect(segs.map(fingerprint)).toEqual(segmentString(body, truthEntry(), segmentOptions(trustOf(body))).map(fingerprint));
+ }
+ });
+
+ test('newline-free input is cut at 1 MiB, the open line carried as mid-line', () => {
+ const body = 'x'.repeat(3 * MAX + 12_345);
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ expect(segs.map(s => s.bytes.length)).toEqual([MAX, MAX, MAX, 12_345]);
+ expect(segs.map(s => s.cutKind)).toEqual(['forced', 'forced', 'forced', 'eof']);
+ expect(segs.slice(1).every(s => s.entryState.at === 'mid')).toBe(true);
+ expect(segmentShapeErrors(Buffer.from(body), segs, MAX)).toEqual([]);
+ });
+
+ test('4-byte code points at a forced cut stay whole', () => {
+ for (const lead of ['', 'a', 'ab', 'abc']) {
+ const body = lead + '😀'.repeat(MAX / 2) + '\n' + 'é'.repeat(MAX);
+ const bytes = Buffer.from(body, 'utf8');
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ expect(segmentShapeErrors(bytes, segs, MAX)).toEqual([]);
+ expect(segs.some(s => s.bytes.length < MAX && s.cutKind === 'forced')).toBe(true);
+ }
+ });
+
+ test('a cut never falls between \\r and \\n, and bare \\r ends a line', () => {
+ for (const eol of ['\r\n', '\r', '\n']) {
+ for (const pad of [0, 1, 2]) {
+ const body = 'y'.repeat(MAX - pad) + eol + 'z' + eol + 'y'.repeat(MAX + 7) + eol + 'tail';
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ expect(segmentShapeErrors(Buffer.from(body), segs, MAX)).toEqual([]);
+ for (let i = 1; i < segs.length; i++) {
+ const prev = segs[i - 1]!.bytes;
+ expect(prev[prev.length - 1] === 13 && segs[i]!.bytes[0] === 10).toBe(false);
+ }
+ }
+ }
+ });
+
+ test('segmentStream over byte chunks split inside code points equals segmentString', async () => {
+ const r = mulberry32(5);
+ const body = bigPage(r, 1_500_000);
+ const bytes = Buffer.from(body, 'utf8');
+ async function* feed() {
+ for (let i = 0; i < bytes.length;) {
+ const k = 1 + Math.floor(r() * 70_000);
+ yield bytes.subarray(i, i + k);
+ i += k;
+ }
+ }
+ const got: SegmentOut[] = [];
+ for await (const s of segmentStream(feed(), truthEntry(), segmentOptions(trustOf(body)))) got.push(s);
+ expect(got.map(fingerprint)).toEqual(segmentString(body, truthEntry(), segmentOptions(trustOf(body))).map(fingerprint));
+ });
+
+ test('invalid UTF-8 is refused', async () => {
+ async function* feed() { yield new Uint8Array([0x61, 0xff, 0x62]); }
+ await expect((async () => { for await (const _ of segmentStream(feed(), truthEntry(), segmentOptions('trusted'))) { /* drain */ } })()).rejects.toThrow();
+ });
+});
+
+describe('append-stability and resume', () => {
+ test('cuts of segment(A) except the last are a prefix of the cuts of segment(A+B)', () => {
+ const r = mulberry32(21);
+ for (let t = 0; t < 4; t++) {
+ const body = bigPage(r, 2_500_000, { crlf: t % 2 === 1 });
+ const full = segmentString(body, truthEntry(), segmentOptions(trustOf(body)));
+ for (let k = 0; k < 4; k++) {
+ let at = Math.floor(body.length * (0.2 + r() * 0.7));
+ const c = body.charCodeAt(at - 1);
+ if (c >= 0xd800 && c <= 0xdbff) at++;
+ const prefix = segmentString(body.slice(0, at), truthEntry(), segmentOptions(trustOf(body)));
+ const stable = prefix.slice(0, -1);
+ expect(stable.map(s => [s.byteStart, s.bytes.length, s.cutKind])).toEqual(full.slice(0, stable.length).map(s => [s.byteStart, s.bytes.length, s.cutKind]));
+ expect(stable.map(s => JSON.stringify(s.entryState))).toEqual(full.slice(0, stable.length).map(s => JSON.stringify(s.entryState)));
+ }
+ }
+ });
+
+ test('segmenting from a stored entry state reproduces the full run', () => {
+ const r = mulberry32(31);
+ for (const crlf of [false, true]) {
+ const body = bigPage(r, 3_000_000, { crlf });
+ const bytes = Buffer.from(body, 'utf8');
+ const trust = trustOf(body);
+ const full = segmentString(body, truthEntry(), segmentOptions(trust));
+ for (let k = 1; k < full.length; k++) {
+ const s = full[k]!;
+ const entry = readEntryState(JSON.parse(JSON.stringify(s.entryState)));
+ expect(entry).not.toBeNull();
+ const resumed = segmentString(bytes.subarray(s.byteStart).toString('utf8'), entry!, segmentOptions(trust, { byteStart: s.byteStart, lineStart: s.lineStart }));
+ if (isCleanResumePoint(s.entryState)) expect(resumed.map(fingerprint)).toEqual(full.slice(k).map(fingerprint));
+ else expect(cuts(resumed)).toEqual(cuts(full.slice(k)));
+ }
+ }
+ });
+
+ test('resume after forced cuts (giant line, giant fence) reproduces the full run', () => {
+ const body = 'head\n' + 'x'.repeat(2 * MAX + 999) + '\n```\n' + 'code line\n'.repeat(250_000) + '```\n## after\n' + filler(300_000);
+ const full = segmentString(body, truthEntry(), segmentOptions(trustOf(body)));
+ const bytes = Buffer.from(body, 'utf8');
+ for (let k = 1; k < full.length; k++) {
+ const s = full[k]!;
+ const resumed = segmentString(bytes.subarray(s.byteStart).toString('utf8'), s.entryState, segmentOptions(trustOf(body), { byteStart: s.byteStart, lineStart: s.lineStart }));
+ expect(resumed.map(fingerprint)).toEqual(full.slice(k).map(fingerprint));
+ }
+ });
+
+ test('cuts are the same under either fence trust (a trust flip moves regions, never a cut)', () => {
+ const r = mulberry32(41);
+ const body = bigPage(r, 2_000_000) + '```\nunclosed\n' + bigPage(r, 1_000_000);
+ expect(cuts(segmentString(body, truthEntry(), segmentOptions('trusted')))).toEqual(cuts(segmentString(body, truthEntry(), segmentOptions('void'))));
+ });
+});
+
+describe('never-cut zones', () => {
+ const after = '\n## after the zone\n';
+ const zones: Array<[string, string]> = [
+ ['open code fence', '```\n' + ('## heading inside the fence\n\n' + filler(2_000)).repeat(40) + '```\n'],
+ ['takes region', '<!--- gbrain:takes:begin -->\n' + ('## heading inside takes\n\n' + filler(2_000)).repeat(40) + '<!--- gbrain:takes:end -->\n'],
+ ['facts / withdrawal fence block', FACTS_BLOCK.replace('|---|', '\n## heading in facts\n\n|---|') + FACTS_BLOCK],
+ ['private key plus margin', PEM_BLOCK + ('\n## heading after a key\n\n' + 'tail words\n').repeat(Math.floor((PEM_CONTEXT_CHARS - 100) / 36))],
+ ['timeline entry detail run', '- **2024-01-02** | src — entry\n\nplain detail text that continues the entry\n'],
+ ['marker and its bullet', MARKER_BULLET],
+ ];
+ for (const [name, zone] of zones) {
+ test(name, () => {
+ const lead = filler(420_000);
+ const body = lead + zone + after + filler(200_000);
+ const segs = segmentString(body, truthEntry(), segmentOptions(trustOf(body)));
+ const start = Buffer.byteLength(lead);
+ const end = start + Buffer.byteLength(zone);
+ const inside = cuts(segs).filter(c => c > start && c < end);
+ expect(inside).toEqual([]);
+ if (name !== 'private key plus margin') expect(cuts(segs)).toContain(end + 1);
+ });
+ }
+
+ test('a private key keeps the next cut PEM_CONTEXT_CHARS away in the projection', () => {
+ const lead = filler(420_000);
+ const body = lead + PEM_BLOCK + ('## heading\n\nwords\n').repeat(3_000);
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ const keyEnd = Buffer.byteLength(lead + PEM_BLOCK) - 1;
+ const next = cuts(segs).find(c => c > Buffer.byteLength(lead));
+ expect(next! - keyEnd).toBeGreaterThanOrEqual(PEM_CONTEXT_CHARS - 1);
+ });
+});
+
+describe('forced cuts with open state', () => {
+ test('a giant fence: forced cuts at line starts, the fence carried, a structural cut after it closes', () => {
+ const body = filler(100_000) + '```\n' + ('## not a heading\n' + 'code line here\n'.repeat(20)).repeat(9_000) + '```\n' + '## real heading\n' + filler(400_000) + '## next\n' + filler(10_000);
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ expect(segmentShapeErrors(Buffer.from(body), segs, MAX)).toEqual([]);
+ const inFence = segs.filter(s => s.entryState.trusted.walk.fence === '`');
+ expect(inFence.length).toBeGreaterThan(1);
+ expect(inFence.every(s => s.entryState.at === 'lf')).toBe(true);
+ expect(segs.slice(0, -1).filter(s => s.exitState.trusted.walk.fence === '`').every(s => s.cutKind === 'forced')).toBe(true);
+ expect(segs.some(s => s.cutKind === 'heading')).toBe(true);
+ expect(segs.every(s => s.outline.every(h => h.text !== 'not a heading'))).toBe(true);
+ });
+
+ test('an unterminated fence: only forced cuts after it, every segment bounded', () => {
+ const body = filler(100_000) + '~~~\n' + '## inside\n\nline\n'.repeat(200_000);
+ const segs = segmentString(body, truthEntry(), segmentOptions(trustOf(body)));
+ expect(trustOf(body)).toBe('void');
+ expect(segmentShapeErrors(Buffer.from(body), segs, MAX)).toEqual([]);
+ expect(segs.slice(0, -1).every(s => s.cutKind === 'forced')).toBe(true);
+ });
+
+ test('an unterminated protected region becomes the truncated tail; later segments project nothing', () => {
+ const lead = filler(200_000);
+ const body = lead + '<!--- gbrain:takes:begin -->\n' + ('## secret heading\n\n' + filler(1_000)).repeat(3_000);
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ const flags = regionFlags(segs[segs.length - 1]!.exitState, 'trusted');
+ expect(flags.protectedTailFrom).toBe(Buffer.byteLength(lead));
+ expect(segs.length).toBeGreaterThan(2);
+ for (const s of segs.slice(1)) {
+ expect(s.staticProjBytes).toBe(0);
+ expect(s.protectedRegions).toEqual([expect.objectContaining({ kind: 'tail', start: 0, end: s.bytes.length, open_start: Buffer.byteLength(lead) })]);
+ }
+ expect(joinedProjection(Buffer.from(body), segs)).toBe(credentialSafeProjection(sanitizeRemoteBody(body)));
+ });
+
+ test('a protected region crossing a forced cut keeps its full extent on both sides', () => {
+ const lead = filler(900_000);
+ const region = '<!--- gbrain:takes:begin -->\n' + filler(400_000) + '<!--- gbrain:takes:end -->\n';
+ const body = lead + region + filler(10_000);
+ const segs = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ const start = Buffer.byteLength(lead);
+ const end = start + Buffer.byteLength(region) - 1;
+ const parts = segs.flatMap(s => s.protectedRegions.filter(r => r.kind === 'takes').map(r => ({ ...r, segStart: s.byteStart })));
+ expect(parts.length).toBe(2);
+ for (const p of parts) expect([p.open_start, p.open_end]).toEqual([start, end]);
+ });
+});
+
+describe('per-segment projection', () => {
+ test('joined segment projections equal the whole-body projection (fuzz soup)', () => {
+ const r = mulberry32(51);
+ let mixed = 0;
+ for (let t = 0; t < 1500; t++) {
+ const body = soup(r);
+ const segs = segmentPieces(body, segmentOptions(trustOf(body)), () => 1 + Math.floor(r() * 12));
+ const bytes = Buffer.from(body, 'utf8');
+ expect(segmentShapeErrors(bytes, segs, MAX)).toEqual([]);
+ const want = credentialSafeProjection(sanitizeRemoteBody(body));
+ const got = joinedProjection(bytes, segs);
+ if (body.includes('gbrain:facts:begin') && body.includes('PRIVATE KEY-----')) {
+ mixed++;
+ expect(KEY_COUNT(got)).toBeLessThanOrEqual(KEY_COUNT(want));
+ } else {
+ expect(got).toBe(want);
+ }
+ }
+ expect(mixed).toBeGreaterThan(0);
+ });
+
+ test('joined projections equal the whole-body projection across many segments', () => {
+ const r = mulberry32(61);
+ for (let t = 0; t < 3; t++) {
+ const body = bigPage(r, 2_500_000, { crlf: t === 1, keys: t !== 2 });
+ const segs = segmentString(body, truthEntry(), segmentOptions(trustOf(body)));
+ expect(segs.length).toBeGreaterThan(4);
+ expect(joinedProjection(Buffer.from(body), segs)).toBe(credentialSafeProjection(sanitizeRemoteBody(body)));
+ }
+ });
+
+ test('static projection sizes, lines, outline and dates match the joined static projection', () => {
+ const r = mulberry32(71);
+ const body = bigPage(r, 2_500_000, { facts: false });
+ const segs = segmentString(body, truthEntry(), segmentOptions(trustOf(body)));
+ const stat = joinedProjection(Buffer.from(body), segs, false);
+ expect(segs.reduce((n, s) => n + s.staticProjBytes, 0)).toBe(Buffer.byteLength(stat));
+ expect(segs.reduce((n, s) => n + s.staticProjLines, 0)).toBe(stat.split('\n').length - 1);
+ let base = 0;
+ const outline: Array<{ byte: number; level: number; text: string }> = [];
+ for (const s of segs) {
+ expect(s.outline.length).toBeLessThanOrEqual(64);
+ for (const h of s.outline) outline.push({ byte: base + h.proj_byte, level: h.level, text: h.text });
+ base += s.staticProjBytes;
+ }
+ const want = pageOutline(Buffer.from(stat), 0, 100_000).entries.filter(e => e.heading !== null)
+ .map(e => ({ byte: e.byte_start, level: e.level!, text: e.heading! }));
+ expect(outline).toEqual(want);
+ const dates = [...stat.matchAll(/\b\d{4}-\d{2}-\d{2}\b/g)].map(m => m[0]).sort();
+ expect(segs.map(s => s.dateMin).filter(Boolean).sort()[0]).toBe(dates[0]);
+ expect(segs.map(s => s.dateMax).filter(Boolean).sort().pop()).toBe(dates[dates.length - 1]);
+ });
+
+ test('facts regions are slots: zero static bytes, the raw fence kept for read-time rendering', () => {
+ const body = 'intro\n' + FACTS_BLOCK + 'outro\n';
+ const [seg] = segmentString(body, truthEntry(), segmentOptions('trusted'));
+ expect(seg!.factsSlots).toEqual([{ proj_byte: Buffer.byteLength('intro\n'), start: 6, end: 6 + Buffer.byteLength(FACTS_BLOCK) - 1 }]);
+ expect(seg!.staticProjBytes).toBe(Buffer.byteLength('intro\n\noutro\n'));
+ });
+});
+
+describe('regions of a page', () => {
+ test('truth then timeline: the region boundary cuts, offsets and lines continue', () => {
+ const r = mulberry32(81);
+ const truth = bigPage(r, 1_500_000);
+ const timeline = bigPage(r, 900_000);
+ const t = segmentString(truth, truthEntry(), segmentOptions(trustOf(truth), { end: 'region_end' }));
+ const last = t[t.length - 1]!;
+ expect(last.cutKind).toBe('region_end');
+ const tl = segmentString(timeline, timelineEntryState(last.exitState), segmentOptions(trustOf(timeline), {
+ byteStart: last.byteStart + last.bytes.length, lineStart: last.lineStart + last.lineCount,
+ }));
+ expect(tl[0]!.byteStart).toBe(Buffer.byteLength(truth));
+ expect(tl.every(s => s.region === 'timeline')).toBe(true);
+ expect(tl[tl.length - 1]!.cutKind).toBe('eof');
+ expect(segmentShapeErrors(Buffer.from(timeline), tl, MAX, Buffer.byteLength(truth))).toEqual([]);
+ });
+
+ test('conversation pages cut at the winning pattern\'s message anchors', () => {
+ const lines: string[] = [];
+ for (let i = 0; lines.join('').length < 1_200_000; i++) {
+ lines.push(`**alice-example** (2024-03-${String(1 + (i % 28)).padStart(2, '0')} 10:${String(i % 60).padStart(2, '0')} AM): ${'message words '.repeat(30)}\n`);
+ }
+ const body = lines.join('');
+ const entry = initialEntryState({ region: 'truth', conversationPattern: pickHeadPattern(body.slice(0, 64 * 1024)) });
+ expect(entry.conversation.pattern).toBe('imessage-slack');
+ const segs = segmentString(body, entry, segmentOptions('trusted'));
+ expect(segs.length).toBeGreaterThan(1);
+ expect(segs.slice(0, -1).every(s => s.cutKind === 'message')).toBe(true);
+ });
+});