Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Wave B 1b-i: bound pass 1 memory on long lines
garrytan581bf1292d4e
diff --git a/src/core/page-body/body-scan.ts b/src/core/page-body/body-scan.tsindex 0eeaafc33f..424270cb97 100644--- a/src/core/page-body/body-scan.ts+++ b/src/core/page-body/body-scan.ts@@ -1,7 +1,9 @@/*** Pass 1 of streaming ingest (Wave B, spec 3.1): one read of a raw markdown* file that decides what parseMarkdown decides, without ever holding the- * file as one string. Memory is O(longest line) beyond a bounded head.+ * file as one string. Memory is O(SCAN_LINE_BUFFER_BYTES) beyond a bounded+ * head, whatever the line lengths, except that the line giving the title (a+ * body H1, or an embedded fence `title:`) is held whole: its text is the result.** Head. The frontmatter readers run on a prefix `P` of the file (at most* FRONTMATTER_HEAD_MAX_BYTES) through the same code parseMarkdown uses@@ -31,6 +33,13 @@* closes on a later bare `---` line), that part of the body is a `{ text }`* piece holding the rewritten text, exactly as parseMarkdown sees it.*+ * Long lines. A line longer than the line buffer is decoded in slices into a+ * `LongLine`: its compressed head (every line classifier is anchored at the+ * line start and reads a bounded structure there; see `LongLine.head`), its+ * content endpoints, one fence token per CR sub-line (fed to the region walks+ * as the slices arrive), the pre-quote rewrite test, and its text only while+ * it can still be the title line.+ ** `body_flags.fence_trust` / `timeline_fence_trust` are scanMarkdownCode's* trust of each region's text as stored: no unclosed and no mispaired fence.*@@ -40,14 +49,13 @@* surrogates cannot occur: the file must be valid UTF-8 (`invalid_utf8`).*/import { scanDataFrontmatter } from '../data-frontmatter.ts';-import { stepFenceWalk, type FenceWalk } from '../fence-scan.ts';import {- bareTimelineSectionLine, comparableFrontmatter, embeddedTitleLineValue, FENCE_TOGGLE_RE, frontmatterQuoteFence,- h1TitleLineValue, isBareTimelineHeading, isTimelineHeadingAfterDash, nullBytesError, parsedMarkdownFields,- parseMarkdownHead, quoteAmbiguousFrontmatterLine, timelineSentinelKind, validatorFrontmatterFence,+ bareTimelineSectionLine, coerceFrontmatterString, comparableFrontmatter, embeddedTitleLineValue, FENCE_TOGGLE_RE,+ frontmatterQuoteFence, h1TitleLineValue, isBareTimelineHeading, isTimelineHeadingAfterDash, nullBytesError,+ parsedMarkdownFields, parseMarkdownHead, quoteAmbiguousFrontmatterLine, timelineSentinelKind, validatorFrontmatterFence,type ParsedMarkdown, type ParsedMarkdownHead, type ParseOpts,} from '../markdown.ts';-import { FRONTMATTER_HEAD_MAX_BYTES } from './limits.ts';+import { FRONTMATTER_HEAD_MAX_BYTES, SCAN_LINE_BUFFER_BYTES } from './limits.ts';/** A file byte range `[start, end)`, or rewritten text the pre-quote pass produced inside the head. */export type BodyPiece = { start: number; end: number } | { text: string };@@ -91,6 +99,7 @@ interface Pos { byte: number; line: number }interface Line {index: number;start: number;+ /** The line, or for a long line its compressed head (`LongLine.head`). */text: string;hasNewline: boolean;/** First non-whitespace code point, or null for a blank line. */@@ -99,65 +108,415 @@ interface Line {contentEnd: Pos | null;}-/** scanMarkdownCode's fence pairing over a region's text, fed line by line with the region's trim applied. */+/**+ * A fence line as fence-scan.ts judges it: a run of at least three of one+ * fence char (code `c`) after up to three spaces, followed by text the opener+ * grammar accepts; `blank` when only spaces and tabs follow, so it can close.+ * A line whose tail the opener grammar rejects can neither open, close nor+ * mispair, so it has no token.+ */+interface FenceToken { c: number; n: number; blank: boolean }+type Token = FenceToken | null;++/** stepFenceWalk's state with the opener as its run, so a run longer than the line buffer needs no string. */+interface RunWalk { open: FenceToken | null; mispaired: boolean }++/** The token stepFenceWalk reads in `s` (a trailing CR is its line ending). */+function fenceToken(s: string): Token {+ const c0 = s.charCodeAt(0);+ if (c0 !== 32 && c0 !== 96 && c0 !== 126) return null;+ const end = s.charCodeAt(s.length - 1) === 13 ? s.length - 1 : s.length;+ let p = 0;+ while (p < end && p < 3 && s.charCodeAt(p) === 32) p++;+ const c = s.charCodeAt(p);+ if (p >= end || (c !== 96 && c !== 126)) return null;+ let q = p;+ while (q < end && s.charCodeAt(q) === c) q++;+ if (q - p < 3) return null;+ let blank = true;+ for (let k = q; k < end; k++) {+ const ch = s.charCodeAt(k);+ if ((c === 96 && ch === 96) || ch === 13 || ch === 0x2028 || ch === 0x2029) return null;+ if (ch !== 32 && ch !== 9) blank = false;+ }+ return { c, n: q - p, blank };+}++/** stepFenceWalk over a token: open, close on a blank run at least as long, or mispair on a longer opener. */+function stepToken(walk: RunWalk, token: Token): void {+ if (!token) return;+ if (!walk.open) {+ walk.open = token;+ } else if (token.c === walk.open.c && token.n >= walk.open.n) {+ if (token.blank) walk.open = null;+ else walk.mispaired = true;+ }+}++/** One nonblank CR sub-line of a long line, as each trim of the region text could leave it. */+interface SubLine { raw: Token; start: Token; end: Token; both: Token }++/**+ * scanMarkdownCode's fence pairing over a region's text, fed line by line+ * (or a long line's sub-lines) with the region's trim applied. The region's+ * last content is held unstepped, since the trailing trim may still shorten+ * it: a short line's text, or a long line's last nonblank sub-line.+ */class RegionFenceWalk {- private walk: FenceWalk = { opener: null, mispaired: false };- /** The region's last content line so far, not yet stepped: the trailing trim may still shorten it. */- private pending: string | null = null;+ private walk: RunWalk = { open: null, mispaired: false };+ private started = false;+ private text: string | null = null;+ private sub: SubLine | null = null;+ /** `sub` is the region's first content, so the leading trim applies to it. */+ private subFirst = false;push(line: Line): void {if (!line.contentStart) return;- if (this.pending === null) {- this.pending = line.text.trimStart();- return;- }- stepRegionLine(this.walk, this.pending);- this.pending = line.text;+ const text = this.started ? line.text : line.text.trimStart();+ this.stepHeld(this.walk, false);+ this.text = text;+ this.sub = null;+ this.started = true;+ }++ pushSub(sub: SubLine): void {+ this.stepHeld(this.walk, false);+ this.subFirst = !this.started;+ this.sub = sub;+ this.text = null;+ this.started = true;}clone(): RegionFenceWalk {const copy = new RegionFenceWalk();copy.walk = { ...this.walk };- copy.pending = this.pending;+ copy.started = this.started;+ copy.text = this.text;+ copy.sub = this.sub;+ copy.subFirst = this.subFirst;return copy;}trust(): FenceTrust {const walk = { ...this.walk };- if (this.pending !== null) stepRegionLine(walk, this.pending.trimEnd());- return walk.opener || walk.mispaired ? 'void' : 'trusted';+ this.stepHeld(walk, true);+ return walk.open || walk.mispaired ? 'void' : 'trusted';}-}-/** scanMarkdownCode ends lines at CR too; stepFenceWalk takes '\n' lines. */-function stepRegionLine(walk: FenceWalk, text: string): void {- for (const sub of text.split('\r')) stepFenceWalk(walk, sub);+ /** scanMarkdownCode ends lines at CR too; `last` applies the region's trailing trim. */+ private stepHeld(walk: RunWalk, last: boolean): void {+ if (this.text !== null) {+ for (const sub of (last ? this.text.trimEnd() : this.text).split('\r')) stepToken(walk, fenceToken(sub));+ } else if (this.sub) {+ const sub = this.sub;+ stepToken(walk, this.subFirst ? (last ? sub.both : sub.start) : (last ? sub.end : sub.raw));+ }+ }}-interface SentinelCandidate {- line: Line;- /** Last content before the sentinel line (truth end), null when nothing precedes it. */- truthEnd: Pos | null;- truthWalk: RegionFenceWalk;- timelineFirst: Pos | null;- timelineWalk: RegionFenceWalk;-}+/** The JS `\s` and `String.prototype.trim` whitespace units. */+const WS_UNITS = '\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';+/** 1 + the unit's index in WS_UNITS, 0 for any other unit. */+const WS_INDEX = new Uint8Array(0x10000);+for (let k = 0; k < WS_UNITS.length; k++) WS_INDEX[WS_UNITS.charCodeAt(k)] = k + 1;-interface BareCandidate {- line: Line;- bullets: number;- truthEnd: Pos | null;- truthWalk: RegionFenceWalk;- timelineWalk: RegionFenceWalk;-}+const isWs = (c: number) => WS_INDEX[c]! > 0;-interface BareSection extends BareCandidate {- /** Start of the next H2 (null when the section runs to EOF) and the last content before it. */- end: Pos | null;- timelineEnd: Pos;-}+/** Characters the regex `.` does not match inside a line. */+const isTerminator = (c: number) => c === 13 || c === 0x2028 || c === 0x2029;-interface QuoteWatch { anyBefore: boolean; prev: boolean; prevChanged: boolean }+/** Longest compressed head kept: well past every anchored structure a classifier reads (at most 72 units). */+const LONG_HEAD_CHARS = 256;++const SUB_LEAD = 0, SUB_RUN = 1, SUB_REST = 2, SUB_NONE = 3;+const QUOTE_KEY0 = 0, QUOTE_KEY = 1, QUOTE_GAP = 2, QUOTE_VALUE = 3, QUOTE_NO = 4;++/**+ * What pass 1 keeps of a line longer than the line buffer, fed one decoded+ * slice at a time (slices end on code points). All of it is bounded except+ * `value`, the text of a line that may be the title.+ */+class LongLine {+ bytes = 0;+ /** An incomplete UTF-8 sequence at the end of the last slice. */+ tail: Uint8Array = new Uint8Array(0);+ hasNul = false;+ /**+ * The line with every whitespace run longer than four units cut to its+ * first two units, each other unit once, and its last two, and every `*`+ * run cut to four, truncated to LONG_HEAD_CHARS. Each classifier gives the+ * same answer on it as on the line: they test run kinds and lengths up to+ * four, and anchored structures that end within the kept head; once+ * truncated, the head is longer than any whole-line match.+ */+ head = '';+ truncated = false;+ private runKind = 0;+ private runLength = 0;+ private wsFirst = '';+ /** Bit k: WS_UNITS[k] occurs in the run between its first two and last two units. */+ private wsMiddle = 0;+ private wsLastA = -1;+ private wsLastB = -1;+ /** Line byte offset past the last non-whitespace code point. */+ contentEnd = -1;+ /** Completed nonblank sub-lines not yet given to the region walks. */+ readonly subs: SubLine[] = [];+ targets: RegionFenceWalk[] | null = null;+ /** Token of the first sub-line (null when blank), once it ends. */+ firstRaw: Token | undefined = undefined;+ /** A CR followed by more text: stepFenceWalk then rejects the line. */+ innerCr = false;+ lastUnit = -1;+ private readonly sub = { phase: SUB_LEAD, spaces: 0, onlySpaces: true, c: 0, n: 0, restBad: false, restSpTab: true, restNonWs: false, wsBad: false, endBad: false };+ private quote: { phase: number; gap: number; colonSpace: boolean; last: number } | null;+ /** 'pending' until seven units decide whether the line may be the title. */+ private valueKind: 'pending' | 'h1' | 'embedded' | null;+ private valueParts: string[] = [];+ private valuePrefix = '';+ private valueSeen = false;+ private valueBreak = false;++ constructor(readonly line: Line, quote: boolean, private readonly h1: boolean, private readonly embedded: boolean) {+ this.quote = quote ? { phase: QUOTE_KEY0, gap: 0, colonSpace: false, last: -1 } : null;+ this.valueKind = h1 || embedded ? 'pending' : null;+ }++ consume(text: string, pieceBytes: number): void {+ const before = this.bytes;+ this.bytes += pieceBytes;+ if (text.length === 0) return;+ if (this.valueKind !== null) this.keepValue(text);+ if (!this.truncated) this.compress(text);+ let last = text.length - 1;+ while (last >= 0 && isWs(text.charCodeAt(last))) last--;+ if (last >= 0) {+ const line = this.line;+ if (!line.contentStart) {+ let first = 0;+ while (isWs(text.charCodeAt(first))) first++;+ line.contentStart = { byte: line.start + before + utf8(text.slice(0, first)), line: line.index };+ }+ this.contentEnd = this.bytes - utf8(text.slice(last + 1));+ }+ if (this.quote && this.quote.phase !== QUOTE_NO) this.stepQuote(text);+ if (this.lastUnit === 13) this.innerCr = true;+ const cr = text.indexOf('\r');+ if (cr !== -1 && cr < text.length - 1) this.innerCr = true;+ this.lastUnit = text.charCodeAt(text.length - 1);+ for (let from = 0; ;) {+ const at = text.indexOf('\r', from);+ this.subUnits(text, from, at === -1 ? text.length : at);+ if (at === -1) return;+ this.endSub();+ from = at + 1;+ }+ }++ finish(): void {+ this.endRun();+ this.endSub();+ }++ /** The line's text for the title readers, or null when this line cannot give a title. */+ value(): string | null {+ return this.valueKind === null ? null : this.valueParts.join('');+ }++ /** pre-quote rewrite test (`quoteAmbiguousFrontmatterLine` non-null), once the line has ended. */+ quoteRewrites(): boolean {+ const q = this.quote!;+ return q.phase === QUOTE_VALUE && (q.colonSpace || q.last === 58);+ }++ private emit(units: string): void {+ this.head += units;+ if (this.head.length <= LONG_HEAD_CHARS) return;+ this.head = this.head.slice(0, LONG_HEAD_CHARS);+ this.truncated = true;+ }++ private compress(text: string): void {+ for (let i = 0; i < text.length && !this.truncated; i++) {+ const c = text.charCodeAt(i);+ const kind = isWs(c) ? 1 : c === 42 ? 2 : 0;+ if (kind !== this.runKind) this.endRun();+ if (kind === 0) {+ this.emit(text[i]!);+ continue;+ }+ this.runKind = kind;+ this.runLength++;+ if (kind === 2) continue;+ if (this.runLength <= 2) {+ this.wsFirst += text[i];+ } else if (this.runLength <= 4) {+ this.wsLastA = this.wsLastB;+ this.wsLastB = c;+ } else {+ this.wsMiddle |= 1 << (WS_INDEX[this.wsLastA]! - 1);+ this.wsLastA = this.wsLastB;+ this.wsLastB = c;+ }+ }+ }++ private endRun(): void {+ if (this.runKind === 1) {+ let middle = '';+ for (let k = 0; k < WS_UNITS.length; k++) if (this.wsMiddle & (1 << k)) middle += WS_UNITS[k];+ const last = [this.wsLastA, this.wsLastB].filter(c => c !== -1);+ this.emit(this.wsFirst + middle + String.fromCharCode(...last));+ } else if (this.runKind === 2) {+ this.emit('*'.repeat(Math.min(this.runLength, 4)));+ }+ this.runKind = 0;+ this.runLength = 0;+ this.wsFirst = '';+ this.wsMiddle = 0;+ this.wsLastA = this.wsLastB = -1;+ }++ /** Tokenize one CR sub-line's units in [from, to). */+ private subUnits(text: string, from: number, to: number): void {+ const s = this.sub;+ for (let i = from; i < to; i++) {+ if (s.phase === SUB_NONE || (s.restBad && s.endBad)) return;+ const c = text.charCodeAt(i);+ if (s.phase === SUB_LEAD) {+ if (isWs(c)) {+ if (c === 32) s.spaces++;+ else s.onlySpaces = false;+ continue;+ }+ if (c === 96 || c === 126) {+ s.phase = SUB_RUN;+ s.c = c;+ s.n = 1;+ } else {+ s.phase = SUB_NONE;+ }+ continue;+ }+ if (s.phase === SUB_RUN) {+ if (c === s.c) {+ s.n++;+ continue;+ }+ s.phase = SUB_REST;+ }+ const bad = c === 0x2028 || c === 0x2029 || (s.c === 96 && c === 96);+ if (bad) s.restBad = true;+ if (c !== 32 && c !== 9) s.restSpTab = false;+ if (!isWs(c)) {+ s.restNonWs = true;+ if (s.wsBad || bad) s.endBad = true;+ } else if (bad) {+ s.wsBad = true;+ }+ }+ }++ private endSub(): void {+ const s = this.sub;+ let raw: Token = null;+ if (s.phase !== SUB_LEAD) {+ const fence = (s.phase === SUB_RUN || s.phase === SUB_REST) && s.n >= 3;+ const open = fence && !s.restBad ? { c: s.c, n: s.n, blank: s.restSpTab } : null;+ const close = !fence || s.endBad ? null : open && open.blank === !s.restNonWs ? open : { c: s.c, n: s.n, blank: !s.restNonWs };+ const indented = !s.onlySpaces || s.spaces > 3;+ raw = indented ? null : open;+ this.subs.push({ raw, start: open, end: indented ? null : close, both: close });+ }+ if (this.firstRaw === undefined) this.firstRaw = raw;+ s.phase = SUB_LEAD;+ s.spaces = s.c = s.n = 0;+ s.onlySpaces = s.restSpTab = true;+ s.restBad = s.restNonWs = s.wsBad = s.endBad = false;+ }++ private stepQuote(text: string): void {+ const q = this.quote!;+ for (let i = 0; i < text.length; i++) {+ const c = text.charCodeAt(i);+ const word = (c >= 97 && c <= 122) || (c >= 65 && c <= 90) || c === 95;+ if (q.phase === QUOTE_KEY0) {+ q.phase = word ? QUOTE_KEY : QUOTE_NO;+ } else if (q.phase === QUOTE_KEY) {+ if (c === 58) q.phase = QUOTE_GAP;+ else if (!word && !(c >= 48 && c <= 57)) q.phase = QUOTE_NO;+ } else if (q.phase === QUOTE_GAP) {+ if (c === 32 || c === 9) {+ q.gap++;+ continue;+ }+ q.phase = q.gap === 0 || `'"[{|>`.includes(text[i]!) ? QUOTE_NO : QUOTE_VALUE;+ if (q.phase === QUOTE_VALUE) this.quoteValue(text.slice(i));+ return;+ } else {+ return this.quoteValue(text);+ }+ if (q.phase === QUOTE_NO) return;+ }+ }++ private quoteValue(value: string): void {+ const q = this.quote!;+ if (/[\r\u2028\u2029]/.test(value)) {+ q.phase = QUOTE_NO;+ return;+ }+ q.colonSpace ||= value.includes(': ') || (q.last === 58 && value.charCodeAt(0) === 32);+ q.last = value.charCodeAt(value.length - 1);+ }++ /**+ * Keep the text while the line can still be the title: an H1 (`#`, then+ * whitespace) or an embedded `title:` line. Dropped once the reader's regex+ * cannot match: a line terminator inside the heading text, or inside or+ * before non-blank text of the `title:` value.+ */+ private keepValue(text: string): void {+ let from = 0;+ if (this.valueKind === 'pending') {+ from = Math.min(text.length, 7 - this.valuePrefix.length);+ this.valuePrefix += text.slice(0, from);+ this.valueParts.push(text.slice(0, from));+ if (this.valuePrefix.length < 7) return;+ const p = this.valuePrefix;+ this.valueKind = this.h1 && p[0] === '#' && isWs(p.charCodeAt(1)) ? 'h1'+ : this.embedded && p.startsWith('title:') && (p[6] === ' ' || p[6] === '\t') ? 'embedded' : null;+ if (this.valueKind === null) {+ this.valueParts = [];+ return;+ }+ this.scanValue(p, 1);+ if (this.valueKind === null) return;+ }+ if (from === text.length) return;+ const rest = from === 0 ? text : text.slice(from);+ this.valueParts.push(rest);+ this.scanValue(rest, 0);+ }++ private scanValue(text: string, from: number): void {+ for (let i = from; i < text.length && this.valueKind !== null; i++) {+ const c = text.charCodeAt(i);+ if (this.valueKind === 'h1') {+ if (isTerminator(c)) this.valueBreak ||= this.valueSeen;+ else if (!isWs(c)) {+ if (this.valueBreak) this.valueKind = null;+ this.valueSeen = true;+ }+ } else if (c === 0x2028 || c === 0x2029 || (this.valueBreak && c !== 32 && c !== 9 && c !== 13)) {+ this.valueKind = null;+ } else if (c === 13) {+ this.valueBreak = true;+ }+ }+ if (this.valueKind === null) this.valueParts = [];+ }+}const utf8 = (text: string) => Buffer.byteLength(text, 'utf8');@@ -169,6 +528,17 @@ function concatBytes(parts: Uint8Array[], total: number): Uint8Array {return out;}+/** Length of the longest prefix of `bytes` that ends on a code point (an invalid tail is kept whole). */+function codePointCut(bytes: Uint8Array): number {+ for (let back = 1; back <= 3 && back <= bytes.length; back++) {+ const b = bytes[bytes.length - back]!;+ if ((b & 0xc0) === 0x80) continue;+ const need = b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;+ return back >= need ? bytes.length : bytes.length - back;+ }+ return bytes.length;+}+/** Offset of the first byte that is not valid UTF-8 (an incomplete tail counts only when `final`), or -1. */export function firstInvalidUtf8(bytes: Uint8Array, final = true): number {for (let i = 0; i < bytes.length;) {@@ -187,9 +557,35 @@ export function firstInvalidUtf8(bytes: Uint8Array, final = true): number {return -1;}+interface SentinelCandidate {+ line: Line;+ /** Last content before the sentinel line (truth end), null when nothing precedes it. */+ truthEnd: Pos | null;+ truthWalk: RegionFenceWalk;+ timelineFirst: Pos | null;+ timelineWalk: RegionFenceWalk;+}++interface BareCandidate {+ line: Line;+ bullets: number;+ truthEnd: Pos | null;+ truthWalk: RegionFenceWalk;+ timelineWalk: RegionFenceWalk;+}++interface BareSection extends BareCandidate {+ /** Start of the next H2 (null when the section runs to EOF) and the last content before it. */+ end: Pos | null;+ timelineEnd: Pos;+}++interface QuoteWatch { anyBefore: boolean; prev: boolean; prevChanged: boolean }+/*** Push-based pass 1. `push` the raw file bytes in order (any chunking), then* `finish`. Throws FrontmatterLanguageError exactly where parseMarkdown would.+ * `lineBufferBytes` only exists so tests can send short lines down the long-line path.*/export class BodyScanner {private readonly decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });@@ -208,9 +604,12 @@ export class BodyScanner {private firstNulLine: number | null = null;private hasNul = false;private quoteWatch: QuoteWatch | null = null;+ /** A frontmatter `title:` wins, so no body line is read for a title. */+ private frontmatterTitle = false;private carry: Uint8Array[] = [];private carryBytes = 0;+ private long: LongLine | null = null;private pos = 0;private lineIndex = 0;@@ -218,7 +617,7 @@ export class BodyScanner {private lastContentEnd: Pos | null = null;private readonly allWalk = new RegionFenceWalk();- private readonly sentinelWalk: FenceWalk = { opener: null, mispaired: false };+ private readonly sentinelWalk: RunWalk = { open: null, mispaired: false };private decided: SentinelCandidate | null = null;private firstQuoted: SentinelCandidate | null = null;private firstOutside: SentinelCandidate | null = null;@@ -229,9 +628,11 @@ export class BodyScanner {private bare: BareSection | null = null;private bodyTitle: string | null = null;+ /** The current line is read for the body H1 title. */+ private titleLine = false;private readonly embedded = { state: 'start' as 'start' | 'block' | 'done', opener: -1, first: null as string | null, title: '' };- constructor(private readonly filePath?: string, private readonly opts?: ParseOpts) {}+ constructor(private readonly filePath?: string, private readonly opts?: ParseOpts, private readonly lineBufferBytes = SCAN_LINE_BUFFER_BYTES) {}push(chunk: Uint8Array): void {if (this.refusal || chunk.length === 0) return;@@ -243,7 +644,10 @@ export class BodyScanner {finish(): BodyScanResult {if (!this.refusal && !this.started) this.startBody(true);- if (!this.refusal) this.onLine(concatBytes(this.carry, this.carryBytes), false);+ if (!this.refusal) {+ if (this.long) this.endLong(false);+ else this.onLine(concatBytes(this.carry, this.carryBytes), false);+ }return this.refusal ?? this.compose();}@@ -266,6 +670,7 @@ export class BodyScanner {const head = parseMarkdownHead(prefix, this.opts);this.head = head;this.headEnd = utf8(prefix);+ this.frontmatterTitle = coerceFrontmatterString(head.frontmatter.title).trim() !== '';if (bounded) {let data: ReturnType<typeof scanDataFrontmatter> | null;try { data = scanDataFrontmatter(head.safeContent); } catch { data = null; }@@ -277,7 +682,7 @@ export class BodyScanner {if (frontmatterQuoteFence(head.lifted) === 'open') {const watch = { anyBefore: false, prev: false, prevChanged: false };const lines = head.lifted.split('\n');- for (let k = 1; k < lines.length - 1; k++) watchQuoteLine(watch, lines[k]!);+ for (let k = 1; k < lines.length - 1; k++) watchQuoteLine(watch, quoteAmbiguousFrontmatterLine(lines[k]!) !== null, lines[k]!.endsWith('\r'));this.quoteWatch = watch;}}@@ -305,22 +710,25 @@ export class BodyScanner {let from = 0;while (!this.refusal) {const nl = bytes.indexOf(10, from);- if (nl === -1) {- if (from < bytes.length) {+ const end = nl === -1 ? bytes.length : nl;+ if (this.long || this.carryBytes + end - from > this.lineBufferBytes) {+ this.feedLong(bytes.subarray(from, end));+ if (nl === -1 || this.refusal) return;+ this.endLong(true);+ } else if (nl === -1) {+ if (from < end) {this.carry.push(bytes.slice(from));- this.carryBytes += bytes.length - from;+ this.carryBytes += end - from;}return;- }- const piece = bytes.subarray(from, nl);- if (this.carryBytes > 0) {- this.carry.push(piece);- const line = concatBytes(this.carry, this.carryBytes + piece.length);+ } else if (this.carryBytes > 0) {+ this.carry.push(bytes.subarray(from, nl));+ const line = concatBytes(this.carry, this.carryBytes + nl - from);this.carry = [];this.carryBytes = 0;this.onLine(line, true);} else {- this.onLine(piece, true);+ this.onLine(bytes.subarray(from, nl), true);}from = nl + 1;}@@ -331,11 +739,36 @@ export class BodyScanner {return v - this.literalBytes + this.bodyFileStart;}+ /** Line number parseMarkdown's NULL_BYTES finding names for a NUL on body line `index`, when the line is in the file. */+ private noteNul(start: number, index: number): void {+ this.hasNul = true;+ if (start >= this.literalBytes && this.firstNulLine === null) this.firstNulLine = this.fileNewlinesBeforeBody + index - this.literalNewlines + 1;+ }++ /** The quote watch reads this line: the pre-quote fence is still open past the head. */+ private quoteWatched(start: number): boolean {+ return this.quoteWatch !== null && start >= this.literalBytes && this.fileOffset(start) >= this.headEnd;+ }++ /** The quote watch's step for one line; false when it refused. */+ private watchQuote(text: string, hasNewline: boolean, rewrites: boolean, endsCr: boolean): boolean {+ const watch = this.quoteWatch!;+ if (text === '---' || (text === '---\r' && hasNewline)) {+ if (watch.anyBefore || watch.prevChanged) {+ this.unbounded('quote_fence');+ return false;+ }+ this.quoteWatch = null;+ } else {+ watchQuoteLine(watch, rewrites, endsCr);+ }+ return true;+ }+private onLine(bytes: Uint8Array, hasNewline: boolean): void {const start = this.pos;const index = this.lineIndex++;this.pos = start + bytes.length + (hasNewline ? 1 : 0);- const inFile = start >= this.literalBytes;let text: string;try {text = this.decoder.decode(bytes);@@ -343,18 +776,8 @@ export class BodyScanner {this.refusal = { kind: 'invalid_utf8', offset: this.fileOffset(start) + firstInvalidUtf8(bytes) };return;}- if (bytes.indexOf(0) !== -1) {- this.hasNul = true;- if (inFile && this.firstNulLine === null) this.firstNulLine = this.fileNewlinesBeforeBody + index - this.literalNewlines + 1;- }- if (this.quoteWatch && inFile && this.fileOffset(start) >= this.headEnd) {- if (text === '---' || (text === '---\r' && hasNewline)) {- if (this.quoteWatch.anyBefore || this.quoteWatch.prevChanged) return this.unbounded('quote_fence');- this.quoteWatch = null;- } else {- watchQuoteLine(this.quoteWatch, text);- }- }+ if (bytes.indexOf(0) !== -1) this.noteNul(start, index);+ if (this.quoteWatched(start) && !this.watchQuote(text, hasNewline, quoteAmbiguousFrontmatterLine(text) !== null, text.endsWith('\r'))) return;const lead = text.search(/\S/);let contentStart: Pos | null = null;let contentEnd: Pos | null = null;@@ -363,7 +786,88 @@ export class BodyScanner {contentStart = { byte: start + utf8(text.slice(0, lead)), line: index };contentEnd = { byte: start + bytes.length - utf8(text.slice(text.length - trailing)), line: index };}- this.step({ index, start, text, hasNewline, contentStart, contentEnd });+ const line = { index, start, text, hasNewline, contentStart, contentEnd };+ for (const walk of this.lineHead(line)) walk.push(line);+ this.lineEnd(line, fenceToken(text), text);+ }++ /** Bytes of a line longer than the line buffer, read in slices that end on code points. */+ private feedLong(bytes: Uint8Array): void {+ let long = this.long;+ if (!long) {+ const index = this.lineIndex++;+ const line: Line = { index, start: this.pos, text: '', hasNewline: false, contentStart: null, contentEnd: null };+ const e = this.embedded;+ long = this.long = new LongLine(line, this.quoteWatched(line.start),+ !this.frontmatterTitle && this.bodyTitle === null && !this.inFence,+ !this.frontmatterTitle && e.state === 'block' && e.first === null);+ const carry = this.carry;+ this.carry = [];+ this.carryBytes = 0;+ for (const part of carry) this.sliceLong(part);+ }+ this.sliceLong(bytes);+ }++ private sliceLong(bytes: Uint8Array): void {+ const long = this.long!;+ for (let at = 0; at < bytes.length && !this.refusal;) {+ const take = Math.min(bytes.length - at, this.lineBufferBytes);+ let slice = bytes.subarray(at, at + take);+ at += take;+ if (long.tail.length > 0) slice = concatBytes([long.tail, slice], long.tail.length + slice.length);+ const cut = codePointCut(slice);+ long.tail = slice.slice(cut);+ this.decodeLong(slice.subarray(0, cut));+ }+ }++ private decodeLong(piece: Uint8Array): void {+ if (piece.length === 0) return;+ const long = this.long!;+ let text: string;+ try {+ text = this.decoder.decode(piece);+ } catch {+ this.refusal = { kind: 'invalid_utf8', offset: this.fileOffset(long.line.start + long.bytes) + firstInvalidUtf8(piece) };+ return;+ }+ if (!long.hasNul && piece.indexOf(0) !== -1) {+ long.hasNul = true;+ this.noteNul(long.line.start, long.line.index);+ }+ long.consume(text, piece.length);+ if (!long.targets && long.truncated) this.longHead(long);+ this.drainLong(long);+ }++ private longHead(long: LongLine): void {+ long.line.text = long.head;+ long.targets = this.lineHead(long.line);+ }++ private drainLong(long: LongLine): void {+ if (!long.targets) return;+ for (const sub of long.subs) for (const walk of long.targets) walk.pushSub(sub);+ long.subs.length = 0;+ }++ private endLong(hasNewline: boolean): void {+ const long = this.long!;+ if (long.tail.length > 0) {+ this.refusal = { kind: 'invalid_utf8', offset: this.fileOffset(long.line.start + long.bytes) + firstInvalidUtf8(long.tail) };+ return;+ }+ this.long = null;+ long.finish();+ const line = long.line;+ line.hasNewline = hasNewline;+ if (long.contentEnd !== -1) line.contentEnd = { byte: line.start + long.contentEnd, line: line.index };+ this.pos = line.start + long.bytes + (hasNewline ? 1 : 0);+ if (!long.targets) this.longHead(long);+ if (this.quoteWatched(line.start) && !this.watchQuote(line.text, hasNewline, long.quoteRewrites(), long.lastUnit === 13)) return;+ this.drainLong(long);+ this.lineEnd(line, long.innerCr ? null : long.firstRaw ?? null, long.value());}private newCandidate(line: Line): SentinelCandidate {@@ -385,9 +889,15 @@ export class BodyScanner {}}- private step(line: Line): void {+ /**+ * The decisions a line's head settles (sentinels, the bare section, which+ * fence state it is read in), before the line feeds any walk; returns the+ * region walks its text feeds, in order.+ */+ private lineHead(line: Line): RegionFenceWalk[] {const { text, contentStart } = line;const trimmed = contentStart ? text.trim() : '';+ const targets: RegionFenceWalk[] = [];if (this.pendingDash && contentStart) {const { candidate, opener, mispaired } = this.pendingDash;@@ -396,36 +906,41 @@ export class BodyScanner {}if (!this.decided && contentStart) {const kind = timelineSentinelKind(trimmed);- const opener = this.sentinelWalk.opener !== null;+ const opener = this.sentinelWalk.open !== null;const mispaired = this.sentinelWalk.mispaired;if (kind === 'marker') this.register(this.newCandidate(line), opener, mispaired);else if (kind === 'dash' && this.firstContent) this.pendingDash = { candidate: this.newCandidate(line), opener, mispaired };}- if (!this.decided) stepFenceWalk(this.sentinelWalk, text);for (const candidate of new Set([this.firstQuoted, this.firstOutside])) {if (!candidate || candidate.line.index >= line.index) continue;if (!candidate.timelineFirst && contentStart) candidate.timelineFirst = contentStart;- candidate.timelineWalk.push(line);+ targets.push(candidate.timelineWalk);}const toggle = FENCE_TOGGLE_RE.test(text);const inFence = this.inFence;if (toggle) this.inFence = !inFence;- this.stepBare(line, toggle || inFence);- if (this.bodyTitle === null && !toggle && !inFence) this.bodyTitle = h1TitleLineValue(text);- this.stepEmbeddedTitle(line);+ this.stepBare(line, toggle || inFence, targets);+ this.titleLine = this.bodyTitle === null && !toggle && !inFence;+ targets.push(this.allWalk);+ return targets;+ }- this.allWalk.push(line);- if (contentStart) {+ /** The rest of the line once it has ended: `fence` is its token for the sentinel walk, `value` its text for the title readers. */+ private lineEnd(line: Line, fence: Token, value: string | null): void {+ if (!this.decided) stepToken(this.sentinelWalk, fence);+ if (this.titleLine && value !== null) this.bodyTitle = h1TitleLineValue(value);+ this.stepEmbeddedTitle(line, value);+ if (line.contentStart) {this.firstContent ??= line;this.lastContentEnd = line.contentEnd;}}/** findBareTimelineSection, one line at a time; `skip` is a fence toggle or a line inside the toggled fence. */- private stepBare(line: Line, skip: boolean): void {+ private stepBare(line: Line, skip: boolean, targets: RegionFenceWalk[]): void {if (this.bare) {- this.bare.truthWalk.push(line);+ targets.push(this.bare.truthWalk);return;}const pending = this.bareCandidate;@@ -435,22 +950,22 @@ export class BodyScanner {this.bareCandidate = null;if (kind === 'end' && pending.bullets > 0) {this.bare = { ...pending, end: { byte: line.start, line: line.index }, timelineEnd: this.lastContentEnd! };- this.bare.truthWalk.push(line);+ targets.push(this.bare.truthWalk);return;}} else {if (kind === 'bullet') pending.bullets++;- pending.timelineWalk.push(line);+ targets.push(pending.timelineWalk);}}if (skip || !this.firstContent || !isBareTimelineHeading(line.text)) return;const timelineWalk = new RegionFenceWalk();- timelineWalk.push(line);+ targets.push(timelineWalk);this.bareCandidate = { line, bullets: 0, truthEnd: this.lastContentEnd, truthWalk: this.allWalk.clone(), timelineWalk };}/** inferTitleFromEmbeddedFrontmatter, one line at a time. */- private stepEmbeddedTitle(line: Line): void {+ private stepEmbeddedTitle(line: Line, value: string | null): void {const e = this.embedded;if (e.state === 'start') {if (!line.contentStart) return;@@ -461,8 +976,8 @@ export class BodyScanner {if (line.index >= e.opener + 2 && closes) {e.title = e.first ?? '';e.state = 'done';- } else if (e.first === null) {- e.first = embeddedTitleLineValue(line.text);+ } else if (e.first === null && value !== null) {+ e.first = embeddedTitleLineValue(value);}}}@@ -471,7 +986,7 @@ export class BodyScanner {const last = this.lastContentEnd;if (this.bareCandidate && this.bareCandidate.bullets > 0) this.bare = { ...this.bareCandidate, end: null, timelineEnd: last! };const sentinel = this.decided- ?? (this.sentinelWalk.opener !== null || this.sentinelWalk.mispaired ? this.firstQuoted : this.firstOutside);+ ?? (this.sentinelWalk.open !== null || this.sentinelWalk.mispaired ? this.firstQuoted : this.firstOutside);const first = this.firstContent?.contentStart ?? null;let truth: Array<[Pos, Pos]> = [];let timeline: Array<[Pos, Pos]> = [];@@ -537,12 +1052,13 @@ export class BodyScanner {* The pre-quote pass's view of fence lines when its fence did not close in the* head: whether closing it on the next line would change any line so far.* Every line keeps its CR except the one just before the closing `---`, which- * the pass rebuilds without its CR (and then may rewrite).+ * the pass rebuilds without its CR (and then may rewrite). `rewrites` is+ * `quoteAmbiguousFrontmatterLine(line) !== null`.*/-function watchQuoteLine(watch: QuoteWatch, text: string): void {+function watchQuoteLine(watch: QuoteWatch, rewrites: boolean, endsCr: boolean): void {watch.anyBefore ||= watch.prev;- watch.prev = quoteAmbiguousFrontmatterLine(text) !== null;- watch.prevChanged = text.endsWith('\r') || quoteAmbiguousFrontmatterLine(text) !== null;+ watch.prev = rewrites;+ watch.prevChanged = endsCr || rewrites;}/** Pass 1 over a streamed file. */@@ -558,10 +1074,10 @@ export function readBodyPieces(pieces: readonly BodyPiece[], file: Uint8Array):}/** String form: the scan plus both regions read back as text (tests and the in-memory `put_page` path). */-export function scanMarkdownString(content: string, filePath?: string, opts?: ParseOpts):+export function scanMarkdownString(content: string, filePath?: string, opts?: ParseOpts, lineBufferBytes?: number):(BodyScan & { text: { compiled_truth: string; timeline: string } }) | BodyScanRefusal {const bytes = Buffer.from(content, 'utf8');- const scanner = new BodyScanner(filePath, opts);+ const scanner = new BodyScanner(filePath, opts, lineBufferBytes);scanner.push(bytes);const scan = scanner.finish();if (scan.kind !== 'ok') return scan;diff --git a/src/core/page-body/limits.ts b/src/core/page-body/limits.tsindex 204b216808..6548a84880 100644--- a/src/core/page-body/limits.ts+++ b/src/core/page-body/limits.ts@@ -38,6 +38,8 @@ export const SEGMENT_MAX_BYTES = 1024 * 1024;export const BODY_LEAD_BYTES = 64 * 1024;/** Frontmatter of a streamed page must close within this many bytes of the file head. */export const FRONTMATTER_HEAD_MAX_BYTES = 256 * 1024;+/** Pass 1 holds a line whole up to this many bytes; a longer line is read in slices of this size into bounded summaries. */+export const SCAN_LINE_BUFFER_BYTES = 64 * 1024;/** Default segmented page ceiling per engine (`pages.max_bytes` when the switch is on). */export const SEGMENTED_PAGE_CEILING_BYTES: Readonly<Record<'postgres' | 'pglite', number>> = {diff --git a/test/large-pages/body-scan-memory.test.ts b/test/large-pages/body-scan-memory.test.tsnew file mode 100644index 0000000000..ca6501ae1d--- /dev/null+++ b/test/large-pages/body-scan-memory.test.ts@@ -0,0 +1,54 @@+/**+ * Wave B (spec 2.2, 3.1): pass 1 holds O(line buffer) of a newline-free file.+ *+ * Protects: while one 32 MiB line streams through BodyScanner in 64 KiB+ * chunks, the live heap (after a full GC) stays under 4 MiB above where it+ * started, for plain text, CR-only text (old Mac line ends), and CR-only text+ * whose first sub-line is an H1 or an embedded fence `title:` line (the title+ * readers' text is dropped once their regex cannot match).+ * Fails when: a long line is buffered whole (the carry before line buffering+ * retained twice the input), or a title candidate keeps text it cannot use.+ * Why existing coverage misses it: body-scan.test.ts checks results, not+ * what the scanner retains; body-scan-linear.test.ts checks CPU.+ * Seams: bun:jsc heapStats after Bun.gc(true); no mocks.+ */+import { describe, expect, test } from 'bun:test';+import { heapStats } from 'bun:jsc';+import { BodyScanner } from '../../src/core/page-body/body-scan.ts';++const CHUNK = 64 * 1024;+const LINE_BYTES = 32 * 1024 * 1024;+const RETAINED_LIMIT_MIB = 4;++function liveMiB(): number {+ Bun.gc(true);+ const stats = heapStats();+ return (stats.heapSize + stats.extraMemorySize) / 2 ** 20;+}++const SHAPES: Array<{ name: string; lead: string; unit: string }> = [+ { name: 'plain text', lead: 'start ', unit: 'word text ' },+ { name: 'CR-only text', lead: 'start\r', unit: 'word text\r' },+ { name: 'CR-only text after an H1', lead: '# Title\r', unit: 'word text\r' },+ { name: 'CR-only text after an embedded title', lead: '---\ntype: note\n---\n---\ntitle: x\r', unit: 'word text\r' },+];++describe('body scan memory on a newline-free line', () => {+ for (const shape of SHAPES) {+ test(`${shape.name}: live heap stays under ${RETAINED_LIMIT_MIB} MiB above the start`, () => {+ const chunk = Buffer.from(shape.unit.repeat(Math.ceil(CHUNK / shape.unit.length)).slice(0, CHUNK));+ const base = liveMiB();+ const scanner = new BodyScanner('notes/memory-example.md', { validate: true });+ scanner.push(Buffer.from(shape.lead));+ let peak = 0;+ for (let sent = 0, k = 1; sent < LINE_BYTES; sent += CHUNK, k++) {+ scanner.push(Buffer.from(chunk));+ if (k % 128 === 0) peak = Math.max(peak, liveMiB() - base);+ }+ const result = scanner.finish();+ expect(result.kind).toBe('ok');+ if (result.kind === 'ok') expect(result.parsed.title).toBe('Memory Example');+ expect(peak).toBeLessThan(RETAINED_LIMIT_MIB);+ }, 60_000);+ }+});diff --git a/test/large-pages/body-scan.test.ts b/test/large-pages/body-scan.test.tsindex 301aa7867d..caff87a66c 100644--- a/test/large-pages/body-scan.test.ts+++ b/test/large-pages/body-scan.test.ts@@ -77,9 +77,9 @@ function capture<T>(fn: () => T): T | { thrown: string } {try { return fn(); } catch (e) { return { thrown: String(e) }; }}-function expectAgrees(content: string, filePath: string, opts: ParseOpts): void {+function expectAgrees(content: string, filePath: string, opts: ParseOpts, lineBufferBytes?: number): void {const expected = capture(() => parseMarkdown(content, filePath, opts));- const got = capture(() => scanMarkdownString(content, filePath, opts));+ const got = capture(() => scanMarkdownString(content, filePath, opts, lineBufferBytes));if ('thrown' in expected) {expect(got).toEqual(expected);return;@@ -271,3 +271,169 @@ describe('invalid UTF-8', () => {}), { numRuns: 5000 });});});++describe('lines longer than the line buffer', () => {+ const ws = fc.array(fc.constantFrom(' ', ' ', '\t', '\u00a0', '\u2028', '\u3000', '\r'), { maxLength: 12 }).map(a => a.join(''));+ const spaces = fc.array(fc.constantFrom(' ', '\t'), { maxLength: 9 }).map(a => a.join(''));+ const run = (char: string) => fc.integer({ min: 1, max: 10 }).map(n => char.repeat(n));+ const word = fc.constantFrom('timeline', 'Timeline', 'HISTORY', 'history', 'notes', 'x', 'π', 'Re: a: b', 'a:', '2024', 'nul\u0000', '');+ const longTail = fc.constantFrom('', '', 'y'.repeat(300), ' '.repeat(300), `${'z '.repeat(150)}`, 'π'.repeat(140), '`x`');+ const template = fc.oneof(+ fc.tuple(ws, run('`'), ws, word, ws).map(p => p.join('')),+ fc.tuple(spaces, run('~'), spaces, longTail).map(p => p.join('')),+ fc.tuple(ws, fc.constant('---'), ws, word, ws, fc.constantFrom('---', '--', '')).map(p => p.join('')),+ fc.tuple(ws, fc.constantFrom('<!--', '<!-- '), ws, word, ws, fc.constant('-->')).map(p => p.join('')),+ fc.tuple(ws, fc.constantFrom('##', '#', '###'), ws, word, ws, longTail, ws).map(p => p.join('')),+ fc.tuple(ws, fc.constantFrom('-', '*', '+'), ws, run('*'), fc.constantFrom('2024', '20245', '2024-05-01: x', 'abcd'), longTail).map(p => p.join('')),+ fc.tuple(fc.constantFrom('title:', 'key:', 'Note:', '_k1:', '1k:'), spaces, fc.constantFrom('', '"q"', 'a: b', 'end:', 'plain', '|x'), longTail, ws).map(p => p.join('')),+ fc.tuple(fc.constantFrom('# ', '#\t', '#\r ', '#'), longTail, word, ws, fc.constantFrom('', ' ##', '\rmore'), ws).map(p => p.join('')),+ fc.tuple(ws, longTail, ws).map(p => p.join('')),+ );+ const longLine = fc.array(template, { minLength: 1, maxLength: 3 }).map(parts => parts.join('\r'));+ const longDoc = fc.record({+ frontmatter: fc.option(fc.record({+ opener: fc.constantFrom(...OPENERS),+ block: fc.array(fc.constantFrom(...BLOCK_LINES), { maxLength: 3 }),+ closer: fc.constantFrom(...CLOSERS),+ }), { nil: undefined }),+ body: fc.array(fc.oneof(fc.constantFrom(...BODY_LINES), longLine), { maxLength: 14 }),+ sep: fc.constantFrom(...SEPARATORS),+ trailing: fc.boolean(),+ });++ const join = (parts: string[]) => parts.join('');+ const embeddedDoc = fc.record({+ lead: fc.constantFrom('---\ntype: note\n---\n', '---\ntype: note\n---\n\n \n'),+ opener: fc.tuple(fc.constant('---'), ws).map(join),+ lines: fc.array(fc.oneof(+ fc.tuple(fc.constantFrom('title:', 'title: ', 'title:\t', ' title: '), spaces, fc.constantFrom('Alpha', '"Q"', "'s'", 'a\rb', 'x\u2028y', 'v\r', ''), longTail, ws).map(join),+ fc.constantFrom('type: x', '', '---', '--- \t'),+ ), { maxLength: 3 }),+ closer: fc.tuple(fc.constant('---'), ws).map(join),+ tail: fc.constantFrom('body', '# H1 wins', ''),+ sep: fc.constantFrom(...SEPARATORS),+ }).map(d => d.lead + [d.opener, ...d.lines, d.closer, d.tail].join(d.sep));+ const bareDoc = fc.record({+ heading: fc.tuple(ws, fc.constantFrom('##'), ws, fc.constantFrom('Timeline', 'history', 'Timeline notes'), ws).map(join),+ lines: fc.array(fc.oneof(+ fc.tuple(ws, fc.constantFrom('-', '*', '+', '**', '*-', 'x'), ws, run('*'), fc.constantFrom('2024', '20245', '2024: x', 'abcd'), longTail).map(join),+ fc.tuple(ws, fc.constantFrom('cont', '`x`', '')).map(join),+ ), { maxLength: 5 }),+ next: fc.constantFrom('', '## Next\nkept', '## \u00a0Next'),+ sep: fc.constantFrom(...SEPARATORS),+ }).map(d => ['intro', d.heading, ...d.lines, d.next].join(d.sep));+ const fenceLine = fc.tuple(fc.constantFrom('', ' ', ' ', ' ', '\t', '\u00a0'), fc.integer({ min: 2, max: 9 }), fc.constantFrom('`', '~'),+ fc.constantFrom('', ' ', ' \u00a0', '\u2028', ' \u2028x', 'ts', '`', ' \t', '\u3000', 'info ~'), ws)+ .map(([lead, n, c, tail, end]) => lead + c.repeat(n) + tail + end);+ const fenceDoc = fc.record({+ lines: fc.array(fc.oneof(fenceLine, fenceLine, fc.constantFrom('code', '', '<!-- timeline -->', '## Timeline', '- 2024: x', '---'),+ fc.array(fenceLine, { minLength: 2, maxLength: 3 }).map(l => l.join('\r'))), { maxLength: 10 }),+ sep: fc.constantFrom(...SEPARATORS),+ lead: fc.constantFrom('intro', ' \u00a0\n', ''),+ }).map(d => [d.lead, ...d.lines].join(d.sep));++ test('embedded fences, bare sections and fence lines agree on both paths', () => {+ fc.assert(fc.property(fc.oneof(embeddedDoc, bareDoc, fenceDoc), fc.constantFrom(1, 2, 5, 11, 40, undefined), fc.boolean(), (content, buffer, validate) => {+ expectAgrees(content, 'notes/x.md', { validate }, buffer);+ }), { numRuns: 4000 });+ }, 120_000);++ test('generated documents agree when every line takes the long-line path', () => {+ fc.assert(fc.property(docArb, fc.integer({ min: 1, max: 24 }), fc.boolean(), (doc, buffer, validate) => {+ expectAgrees(render(doc), 'notes/x.md', { validate }, buffer);+ }), { numRuns: 2000 });+ }, 120_000);++ test('long runs, CR sub-lines and astral text split at the buffer edge agree', () => {+ fc.assert(fc.property(longDoc, fc.integer({ min: 1, max: 40 }), fc.boolean(), fc.constantFrom(...PATHS), (doc, buffer, validate, path) => {+ expectAgrees(render(doc), path, { validate }, buffer);+ }), { numRuns: 3000 });+ }, 120_000);++ test('bounded-head documents agree through the long-line path, including the pre-quote watch', () => {+ const pad = (line: string) => `${line}\n`.repeat(Math.ceil((FRONTMATTER_HEAD_MAX_BYTES + 1000) / (line.length + 1)));+ const shapes = [+ `---\ntitle: x\n--- \n${pad('prose')}---\nend\n`,+ `---\ntitle: x\n--- \n${pad('prose')}Note: ${'z'.repeat(300)} end\n---\nend\n`,+ `---\ntitle: x\n--- \n${pad('Note: one two')}end\n`,+ `---\ntitle: x\n---\n${pad('body')}late\u0000nul ${'w'.repeat(500)}\n`,+ `---\ntitle: x\n--- \n${pad('prose')}Note: a: b\rmore ${'m'.repeat(300)}\nplain\n---\nend\n`,+ `---\ntitle: x\n--- \n${pad('prose')}Note: a: b\u2028more\nplain\n---\nend\n`,+ `---\ntitle: x\n--- \n${pad('prose')}Note: "a: b"\nplain\n---\nend\n`,+ ];+ for (const content of shapes) for (const buffer of [1, 7, 64]) expectAgrees(content, 'notes/x.md', { validate: true }, buffer);+ for (const value of [`one: ${'z'.repeat(300)}`, `${'z'.repeat(300)}:`, `${'k'.repeat(300)}: a: b`]) {+ for (const buffer of [1, 7, 64]) {+ const got = scanMarkdownString(`---\ntitle: x\n--- \n${pad('prose')}Note: ${value}\n---\nend\n`, 'notes/x.md', {}, buffer);+ expect(got.kind === 'frontmatter_head_unbounded' && got.reader).toBe('quote_fence');+ }+ }+ });++ test('embedded fence lines whose whitespace run hides a non-[ \t] unit in its middle', () => {+ const shapes = [+ '---\ntype: note\n---\n--- \u00a0 \ntitle: Alpha\n---\nbody\n',+ '---\ntype: note\n---\n---\ntitle: Alpha\n--- \u00a0 \nbody\n',+ '---\ntype: note\n---\n--- \r \ntitle: Alpha\n---\nbody\n',+ '---\ntype: note\n---\n---\ntitle: Alpha\n--- \t\u3000\t\t \nbody\n',+ '---\ntype: note\n---\n--- \t \t \t\r\ntitle: Alpha\r\n---\t \t \t \r\nbody\r\n',+ ];+ for (const content of shapes) for (const buffer of [1, 3, 8, undefined]) expectAgrees(content, 'notes/x.md', { validate: true }, buffer);+ });++ test('lines longer than the real 64 KiB buffer', () => {+ const big = 70_000;+ const shapes = [+ `# ${'t'.repeat(big)} ##\nbody\n`,+ `intro\n# Long ${'t '.repeat(big)}\t\nbody\n`,+ `# Title\r${'more\r'.repeat(big / 5)}\n# Second\n`,+ `---\ntype: note\n---\n---\ntitle: ${'v'.repeat(big)}\n---\nbody\n`,+ `intro\n---${' '.repeat(big)}timeline${'\t'.repeat(big)}---\n- 2024: t\n`,+ `intro\n${' '.repeat(big)}<!-- timeline -->${' '.repeat(big)}\nt\n`,+ `intro\n---\n${'\u3000'.repeat(big)}## Timeline${' '.repeat(big)}\n- 2024: t\n`,+ `intro\n${'`'.repeat(big)}\ncode\n${'`'.repeat(big + 1)}\n<!-- timeline -->\nt\n`,+ `intro\n${'`'.repeat(big)}\ncode\n${'`'.repeat(big - 1)}\n<!-- timeline -->\nt\n`,+ `intro\n${'~'.repeat(big)} info ${'i'.repeat(big)}\ncode\n${'~'.repeat(big)}${' \t'.repeat(big)}\nafter\n`,+ `intro\n\`\`\`ts${' x'.repeat(big)}\u2028\n<!-- timeline -->\n\`\`\`\nt\n`,+ `${'a\r```\rcode\r```\r'.repeat(big / 10)}\n<!-- timeline -->\nt\r\`\`\`\r`,+ `intro\n## Timeline\n- ${'*'.repeat(big)}2024 dated\n ${'w'.repeat(big)}\n## Next\nkept\n`,+ `intro\n## Timeline\n- ${'*'.repeat(big)}20245 not dated\n## Next\nkept\n`,+ `plain\n${' \u00a0\u2028'.repeat(big)}\n${'π'.repeat(big)}\n`,+ `plain\n${'x'.repeat(big)}\u0000${'y'.repeat(big)}\n`,+ `${'\r\n'.repeat(10)}${'q'.repeat(big)}\r\n<!-- timeline -->\r\n- 2024: t\r\n`,+ ];+ for (const content of shapes) for (const validate of [false, true]) expectAgrees(content, 'notes/alpha-example.md', { validate });+ });++ test('invalid UTF-8 inside a long line names its offset', () => {+ for (const at of [3, 65_535, 65_536, 65_537, 150_001]) {+ const bytes = Buffer.from(`plain\n${'a'.repeat(200_000)}\nend\n`);+ bytes[at + 6] = 0xff;+ for (const buffer of [undefined, 5]) {+ const scanner = new BodyScanner('notes/x.md', {}, buffer);+ for (let k = 0; k < bytes.length; k += 4093) scanner.push(bytes.subarray(k, k + 4093));+ expect(scanner.finish()).toEqual({ kind: 'invalid_utf8', offset: at + 6 });+ }+ }+ const cut = Buffer.concat([Buffer.from(`ok\n${'a'.repeat(100)}`), Buffer.from([0xf0, 0x9f, 0x98])]);+ const scanner = new BodyScanner(undefined, undefined, 8);+ scanner.push(cut);+ expect(scanner.finish()).toEqual({ kind: 'invalid_utf8', offset: cut.length - 3 });+ });++ test('any chunking gives the single-chunk result on the long-line path', () => {+ fc.assert(fc.property(longDoc, fc.integer({ min: 1, max: 40 }), fc.array(fc.integer({ min: 1, max: 97 }), { minLength: 1, maxLength: 4 }), (doc, buffer, sizes) => {+ const bytes = Buffer.from(render(doc), 'utf8');+ const scan = (chunks: number[]) => capture(() => {+ const scanner = new BodyScanner('notes/x.md', { validate: true }, buffer);+ for (let at = 0, k = 0; at < bytes.length; k++) {+ const size = chunks[k % chunks.length]!;+ scanner.push(bytes.subarray(at, at + size));+ at += size;+ }+ return scanner.finish();+ });+ expect(scan(sizes)).toEqual(scan([bytes.length || 1]));+ }), { numRuns: 500 });+ }, 120_000);+});