Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Walk the manifest once per block pass and split forced cuts at clean line boundaries (fix C2, C3)
garrytanfc4f07cd7b33
diff --git a/src/core/page-body/read-range.ts b/src/core/page-body/read-range.tsindex 8f0a21a3fa..c354575f3f 100644--- a/src/core/page-body/read-range.ts+++ b/src/core/page-body/read-range.ts@@ -126,6 +126,13 @@ export interface BodyRangePiece {const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });const HEAVY_BATCH = 64;++/**+ * @internal Manifest rows a read visits (`visits`): each row a range read, a block walk or a layout pass looks at, for+ * the linearity test. A pass that filters the whole manifest per block visits rows x blocks; one walk visits each row+ * a bounded number of times. Counts, not time.+ */+export const bodyRowWork = { visits: 0 };const toJson = (v: unknown) => typeof v === 'string' ? JSON.parse(v) as unknown : v;const bytesOf = (v: unknown): Uint8Array => { const b = v as Uint8Array; return new Uint8Array(b.buffer, b.byteOffset, b.byteLength); };const newlines = (s: string) => { let n = 0; for (let i = s.indexOf('\n'); i !== -1; i = s.indexOf('\n', i + 1)) n++; return n; };@@ -312,6 +319,22 @@ export function projectedUnits(body: SegmentedBody, layout: ProjectedLayout): Unconst unitBytes = (u: Unit, layout: ProjectedLayout) => u.kind === 'row' ? layout.rowBytes[u.index]! : Buffer.byteLength(u.text, 'utf8');+/** One segment of the trusted body: its row, its stored bytes and entry state, and its text after the withdrawal overlay in pieces. */+export interface TrustedSegment {+ row: BodyRow;+ raw: Uint8Array;+ entryState: unknown;+ pieces: ProjectedPiece[];+}++/** The trusted body of `rows` (rows of `body`, in order), one segment at a time: what readBodyRange's trusted stored read cuts. */+export async function* trustedSegments(engine: BrainEngine, body: SegmentedBody, rows: readonly BodyRow[]): AsyncIterable<TrustedSegment> {+ for await (const seg of loadSegments(engine, body, rows)) {+ const raw = utf8.decode(seg.bytes);+ yield { row: seg.row, raw: seg.bytes, entryState: seg.entryState, pieces: overlaidPieces(raw, await overlaidText(engine, body, seg, raw, 'trusted')) };+ }+}+export async function* readBodyRange(engine: BrainEngine, req: BodyRangeRequest): AsyncIterable<BodyRangePiece> {if (!(req.start >= 0) || !(req.end >= req.start) || !Number.isInteger(req.start) || (!Number.isInteger(req.end) && req.end !== Infinity)) {throw new Error(`readBodyRange: [${req.start}, ${req.end}) is not a byte range.`);@@ -319,11 +342,12 @@ export async function* readBodyRange(engine: BrainEngine, req: BodyRangeRequest)if (req.end === req.start) return;const body = req.body ?? await openSegmentedBody(engine, req);if (req.space === 'projected') return yield* projectedRange(engine, body, req);- const rows = body.rows.filter(r => (!req.region || r.region === req.region) && r.byteStart < req.end && r.byteStart + r.byteLen > req.start);+ bodyRowWork.visits += body.rows.length;+ const indices = body.rows.flatMap((r, i) => (!req.region || r.region === req.region) && r.byteStart < req.end && r.byteStart + r.byteLen > req.start ? [i] : []);+ const rows = indices.map(i => body.rows[i]!);if (req.audience === 'trusted') {- for await (const seg of loadSegments(engine, body, rows)) {- const raw = utf8.decode(seg.bytes);- for (const piece of overlaidPieces(raw, await overlaidText(engine, body, seg, raw, 'trusted'))) {+ for await (const seg of trustedSegments(engine, body, rows)) {+ for (const piece of seg.pieces) {const cut = cutStored(piece, seg.row.byteStart, req.start, req.end);if (cut) yield { bytes: cut.bytes, storedStart: cut.storedStart, projectedStart: cut.storedStart };}@@ -331,8 +355,9 @@ export async function* readBodyRange(engine: BrainEngine, req: BodyRangeRequest)return;}const layout = await projectedLayout(engine, body);+ let k = 0;for await (const seg of loadSegments(engine, body, rows)) {- let doc = layout.rowStart[body.rows.indexOf(seg.row)]!;+ let doc = layout.rowStart[indices[k++]!]!;if (doc < 0) continue;for (const piece of (await projectLoaded(engine, body, seg, layout.overlay)).pieces) {const cut = cutStored(piece, seg.row.byteStart, req.start, req.end);@@ -355,7 +380,9 @@ function cutStored(piece: ProjectedPiece, base: number, start: number, end: numbasync function* projectedRange(engine: BrainEngine, body: SegmentedBody, req: BodyRangeRequest): AsyncIterable<BodyRangePiece> {const layout = await projectedLayout(engine, body);- const wanted = projectedUnits(body, layout).filter(u => {+ const units = projectedUnits(body, layout);+ bodyRowWork.visits += units.length;+ const wanted = units.filter(u => {const region = u.kind === 'row' ? body.rows[u.index]!.region : u.region;return (!req.region || region === req.region) && u.start < req.end && u.start + unitBytes(u, layout) > req.start;});diff --git a/src/core/page-body/segment-blocks.ts b/src/core/page-body/segment-blocks.tsindex 40810fd8e8..f49f7fb194 100644--- a/src/core/page-body/segment-blocks.ts+++ b/src/core/page-body/segment-blocks.ts@@ -5,19 +5,26 @@** The text is the joined body `${compiled_truth}\n${timeline}` (or the regions* and separator a pass names) after the withdrawal overlay, read with- * `readBodyRange` (stored space, trusted audience): what readPageSnapshot gives- * a trusted reader of an inline page. A block is one segment, or a run of- * segments joined across forced cuts, so every block starts where the- * segmenter's parsers start fresh: outside code fences, protected regions,- * fence blocks, timeline detail runs and conversation messages. A run of- * forced cuts longer than BLOCK_MAX_BYTES (a line or fence many segments long)- * refuses with `page_body_segmented`; a facts fence crossing a forced cut while- * the source has withdrawals refuses with `page_projection_stale` (read-range.ts).+ * `trustedSegments` (read-range.ts, the trusted stored read): what readPageSnapshot+ * gives a trusted reader of an inline page. The manifest is walked once per+ * region. A block is one segment, or a run of segments joined across forced+ * cuts that fell where the segmenter's parsers do not start fresh, so every+ * block starts outside code fences, protected regions, fence blocks, timeline+ * detail runs and long lines. A forced cut after a `\n` before a line the+ * segmenter's no-cut rules allow (`cutBlocked` on the next segment's entry+ * state and first line, as a structural cut is judged) is a block boundary:+ * ordinary short lines or dated bullets with no structural candidate are cut+ * only by force. A joined run longer than BLOCK_MAX_BYTES (a line or fence many+ * segments long) refuses with `page_body_segmented`; a facts fence crossing a+ * forced cut while the source has withdrawals refuses with+ * `page_projection_stale` (read-range.ts).*/import type { BrainEngine } from '../engine.ts';import { opError } from '../ops/contract.ts';import { SEGMENT_MAX_BYTES } from './limits.ts';-import { openSegmentedBody, readBodyRange } from './read-range.ts';+import { bodyRowWork, openSegmentedBody, readBodyRange, trustedSegments, type TrustedSegment } from './read-range.ts';+import { cutBlocked } from './segmenter.ts';+import { readEntryState } from './entry-state.ts';import type { BodyRegion } from './types.ts';/** Bytes a pass reads between two full collections (ingest.ts collectBatchGarbage: one per 4 MiB staging batch). */@@ -41,10 +48,12 @@ export function readGarbageCollector(): (bytes: number) => void {/*** @internal Work the derived passes do over a segmented body, for the linearity test: bytes read (`bytes`), UTF-16* units of the blocks yielded (`blocks`) and of the link-extraction windows built around them (`windows`), and units a- * pass copies past its block (`carry`: a takes fence joined across blocks, the watermark planner's tail window).- * Counts, not time, so a busy machine cannot move them.+ * pass copies past its block (`carry`: a takes fence joined across blocks, the watermark planner's tail window),+ * and bytes scanned for the first line after a forced cut (`lines`). Counts, not time, so a busy machine cannot move them.*/-export const segmentedPassWork = { bytes: 0, blocks: 0, windows: 0, carry: 0 };+export const segmentedPassWork = { bytes: 0, blocks: 0, windows: 0, carry: 0, lines: 0 };++const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });/** The longest run of segments joined across forced cuts that a pass holds as one string. */export const BLOCK_MAX_BYTES = 8 * SEGMENT_MAX_BYTES;@@ -63,8 +72,9 @@ export interface BodyBlockOptions {/** Text between two regions (default '\n', as in `${compiled_truth}\n${timeline}`). */separator?: string;/**- * Read only the runs this accepts (the manifest seqs of a block, and whether it is its region's first); it is asked- * as each run is reached, so it may depend on the blocks already read. A block after a skipped run has `at` NaN.+ * Read only the runs this accepts (the manifest seqs of a run of segments joined by forced cuts, one block or more,+ * and whether it is its region's first); it is asked as each run is reached, so it may depend on the blocks already+ * read. A block after a skipped run has `at` NaN.*/want?: (run: { seqs: readonly number[]; first: boolean }) => boolean;}@@ -76,6 +86,21 @@ export function blockTooLargeError(slug: string, sourceId: string, bytes: number'Break the long line or fence into shorter lines and write the page again.');}+/**+ * Whether the segment after a forced cut starts a block: the cut fell after a `\n` (not inside a line longer than a+ * segment, not after a bare `\r`) and a structural cut before the segment's first line would have been allowed+ * (`cutBlocked` on its stored entry state, the parser state at the cut). Pages of another segmenter version never do.+ */+function freshAfterForcedCut(previous: Uint8Array, seg: TrustedSegment, stale: boolean): boolean {+ if (stale || previous[previous.length - 1] !== 0x0a) return false;+ const entry = readEntryState(seg.entryState);+ if (!entry) return false;+ let end = 0;+ while (end < seg.raw.length && seg.raw[end] !== 0x0a && seg.raw[end] !== 0x0d) end++;+ segmentedPassWork.lines += end;+ return !cutBlocked(entry, utf8.decode(seg.raw.subarray(0, end)));+}+export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug: string; source_id?: string },opts: BodyBlockOptions = {}): AsyncIterable<BodyBlock> {const body = await openSegmentedBody(engine, { pageId: Number(page.id) });@@ -89,26 +114,40 @@ export async function* bodyBlocks(engine: BrainEngine, page: { id: number; slug:yield { region: null, text: separator, at };at += separator.length;}+ bodyRowWork.visits += body.rows.length;const rows = body.rows.filter(row => row.region === region);for (let i = 0; i < rows.length;) {let j = i;while (j + 1 < rows.length && forced.has(rows[j]!.seq)) j++;- const start = rows[i]!.byteStart;- const end = rows[j]!.byteStart + rows[j]!.byteLen;+ bodyRowWork.visits += j - i + 1;if (opts.want && !opts.want({ seqs: rows.slice(i, j + 1).map(row => row.seq), first: i === 0 })) {at = NaN;i = j + 1;continue;}- if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, body.sourceId, end - start);- const parts: Buffer[] = [];- for await (const piece of readBodyRange(engine, { pageId: body.pageId, space: 'stored', start, end, audience: 'trusted', region, body })) parts.push(piece.bytes);- const text = Buffer.concat(parts).toString('utf8');- collect(end - start);- segmentedPassWork.bytes += end - start;- segmentedPassWork.blocks += text.length;- yield { region, text, at };- at += text.length;+ let parts: Buffer[] = [];+ let start = rows[i]!.byteStart;+ let previous: Uint8Array | null = null;+ const flush = (end: number): BodyBlock => {+ const text = Buffer.concat(parts).toString('utf8');+ collect(end - start);+ segmentedPassWork.bytes += end - start;+ segmentedPassWork.blocks += text.length;+ const block = { region, text, at };+ at += text.length;+ parts = [];+ start = end;+ return block;+ };+ for await (const seg of trustedSegments(engine, body, rows.slice(i, j + 1))) {+ bodyRowWork.visits++;+ if (previous && freshAfterForcedCut(previous, seg, body.stale)) yield flush(seg.row.byteStart);+ const end = seg.row.byteStart + seg.row.byteLen;+ if (end - start > BLOCK_MAX_BYTES) throw blockTooLargeError(page.slug, body.sourceId, end - start);+ for (const piece of seg.pieces) parts.push(Buffer.from(piece.text, 'utf8'));+ previous = seg.raw;+ }+ yield flush(rows[j]!.byteStart + rows[j]!.byteLen);i = j + 1;}}diff --git a/src/core/page-body/segmenter.ts b/src/core/page-body/segmenter.tsindex 82fa4aec08..98697915c0 100644--- a/src/core/page-body/segmenter.ts+++ b/src/core/page-body/segmenter.ts@@ -322,13 +322,7 @@ export class Segmenter {private blocked(text: string): boolean {segmenterWork.chars += text.length;- 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);+ return cutBlocked(this.st, text);}private line(text: string, term: string, byteStart: number): void {@@ -642,6 +636,20 @@ function keptRanges(whole: string, textLen: number, out: ScanOut, markers: Array}/** parseTimelineEntries' rule: would it read `line` as part of the open entry (a detail, or a blank before any)? */+/**+ * Whether no cut may go before the whole line `text` at parser state `st` (a segment's entry state is the state at its+ * cut): inside a code fence, a protected region, a withdrawal fence block, a timeline entry's detail run, after a+ * materialized marker, within a private key's context, or before a line holding a marker token or key text.+ */+export function cutBlocked(st: EntryState, text: string): boolean {+ 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);+}+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;diff --git a/test/large-pages/segmented-derived-linear.test.ts b/test/large-pages/segmented-derived-linear.test.tsindex a4da7f12b6..9059111bf5 100644--- a/test/large-pages/segmented-derived-linear.test.ts+++ b/test/large-pages/segmented-derived-linear.test.ts@@ -25,6 +25,10 @@* reads only its marker segments), blocks 5.95 x1.99, windows 2.00 x2.00 (a* window holds the whole block before its own), carry 0.52 x1.99.* Prefix-re-reading driver (n = 1 MiB): bytes and blocks x2.68.+ * Manifest row visits (`bodyRowWork.visits`, read-range.ts; fix lane C1, finding C2): the passes visit each manifest+ * row a bounded number of times (measured 33.1 per row at both sizes), so visits per row stay under VISITS_PER_ROW. Row counts stay below+ * MIN_RATIO_COUNT, so the bound is per row, not a doubling ratio: a pass that filters the whole manifest for every+ * block visits rows x blocks, and its visits per row grow with the page (8 segments 80 visits, 16 segments 288).*/import { afterAll, beforeAll, describe, expect, test } from 'bun:test';import { PGLiteEngine } from '../../src/core/pglite-engine.ts';@@ -49,10 +53,13 @@ import { EXTRACTION_PIPELINE_VERSION, planSegmentedExtraction } from '../../src/import type { Page } from '../../src/core/types.ts';import { conversationBody } from '../helpers/conversation-page.ts';import { countWorkAsync, describeWork, linearityViolations, MAX_DOUBLING_RATIO, type Sample } from '../helpers/work-counts.ts';+import { bodyRowWork } from '../../src/core/page-body/read-range.ts';const MB = 1024 * 1024;/** Per input byte, about 2x the measured value or more. */const PER_BYTE = { 'pass.bytes': 22, 'pass.blocks': 12, 'pass.windows': 4, 'pass.carry': 1.2 };+/** Manifest row visits per live row over every pass, about 2x the measured value. */+const VISITS_PER_ROW = 66;let engine: PGLiteEngine;let dir: string;@@ -115,7 +122,13 @@ async function prefixRereading(slug: string): Promise<void> {}const sample = async (bytes: number, slug: string, run: (slug: string) => Promise<void>): Promise<Sample> =>- ({ bytes, work: await countWorkAsync({ pass: segmentedPassWork }, () => run(slug)) });+ ({ bytes, work: await countWorkAsync({ pass: segmentedPassWork, read: bodyRowWork }, () => run(slug)) });++async function liveRows(slug: string): Promise<number> {+ const [row] = await engine.executeRaw<{ n: unknown }>(`SELECT count(*) AS n FROM page_body_manifest m JOIN pages p ON p.id=m.page_id+ WHERE p.slug=$1 AND m.gen_to IS NULL AND m.staging_id IS NULL`, [slug]);+ return Number(row!.n);+}beforeAll(async () => {dir = mkdtempSync(join(tmpdir(), 'segmented-linear-'));@@ -138,6 +151,10 @@ describe('derived pass work over a segmented page', () => {const b = await sample(8 * MB, 'notes/linear-8', passes);console.log(`[segmented-derived-linear] passes: ${describeWork(a, b)}`);expect(linearityViolations(a, b, PER_BYTE)).toEqual([]);+ const rows = [await liveRows('notes/linear-4'), await liveRows('notes/linear-8')];+ console.log(`[segmented-derived-linear] manifest visits per row: ${(a.work['read.visits']! / rows[0]!).toFixed(1)} (${rows[0]} rows), ${(b.work['read.visits']! / rows[1]!).toFixed(1)} (${rows[1]} rows)`);+ expect(a.work['read.visits']! / rows[0]!).toBeLessThanOrEqual(VISITS_PER_ROW);+ expect(b.work['read.visits']! / rows[1]!).toBeLessThanOrEqual(VISITS_PER_ROW);}, 300_000);test('forced probe: the same bounds fail a driver that re-reads the prefix before each block', async () => {diff --git a/test/large-pages/segmented-forced-cuts.test.ts b/test/large-pages/segmented-forced-cuts.test.tsnew file mode 100644index 0000000000..f5f3f348cd--- /dev/null+++ b/test/large-pages/segmented-forced-cuts.test.ts@@ -0,0 +1,135 @@+/**+ * Wave B PR 2 fix lane C1 (finding C3): a forced cut at a clean line boundary is a block boundary.+ *+ * 1. Protects: a segmented page with no structural cut candidate (ordinary short lines with no blank line or+ * heading, or a timeline of dated bullets) is cut only by force at each segment bound; bodyBlocks reads it as+ * blocks of at most one segment each (each forced cut fell after a newline before a line the segmenter's no-cut+ * rules allow), so the derived passes (timeline text, the stored canonical timeline the write path compares+ * against) and a rewrite of the page complete. A code fence that really spans forced cuts stays one block, and+ * one longer than BLOCK_MAX_BYTES still refuses page_body_segmented.+ * 2. Fails when: bodyBlocks joins every run of forced cuts into one block, so a 9.8 MB page of short lines or a+ * 12 MiB timeline of bullets is refused as one unsplittable run over 8 MiB.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { BLOCK_MAX_BYTES, bodyBlocks } from '../../src/core/page-body/segment-blocks.ts';+import { SEGMENT_MAX_BYTES } from '../../src/core/page-body/limits.ts';+import { segmentedTimelineText } from '../../src/core/timeline-extract.ts';+import { storedCanonicalTimeline } from '../../src/core/persistence/canonical-projections.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const MB = 1024 * 1024;++/** 9,799,999 bytes of lines of at most 49 bytes: no blank line, no heading, so every cut is forced. */+function shortLines(): string {+ const head = '---\ntitle: Short lines\ntype: note\n---\n';+ const lines: string[] = [];+ let bytes = Buffer.byteLength(head);+ for (let i = 0; bytes < 9_799_999 - 60; i++) {+ const line = 'line ' + String(i).padStart(8, '0') + ' acme-example noted the plan\n';+ lines.push(line);+ bytes += line.length;+ }+ const last = 'x'.repeat(9_799_999 - bytes - 1) + '\n';+ return head + lines.join('') + last;+}++/** A short truth, then a 12 MiB timeline of dated bullets with no blank line. */+function bulletTimeline(): { content: string; bullets: number } {+ const bullets: string[] = [];+ let bytes = 0;+ for (let i = 0; bytes < 12 * MB; i++) {+ const line = '- **20' + String(10 + (i % 15)) + '-0' + (1 + (i % 9)) + '-1' + (i % 10) + '** | Met acme-example about item ' + i + '\n';+ bullets.push(line);+ bytes += line.length;+ }+ return { content: '---\ntitle: Bullet timeline\ntype: note\n---\nA short truth.\n\n<!-- timeline -->\n\n' + bullets.join(''), bullets: bullets.length };+}++/** A code fence of about 28/32 x `bytes` spanning forced cuts, between two paragraphs. */+function longFence(bytes: number): string {+ const body = Array.from({ length: Math.ceil(bytes / 32) }, (_, i) => 'code line ' + String(i).padStart(10, '0') + ' x = 1;\n').join('');+ return '---\ntitle: Long fence\ntype: note\n---\nBefore the fence.\n\n```ts\n' + body + '```\n\nAfter the fence.\n';+}++async function forcedCuts(engine: BrainEngine, slug: string): Promise<{ id: number; forced: number; rows: number }> {+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug=$1', [slug]);+ const [row] = await engine.executeRaw<{ forced: unknown; rows: unknown }>(+ "SELECT count(*) FILTER (WHERE cut_kind='forced') AS forced, count(*) AS rows FROM page_body_manifest WHERE page_id=$1 AND gen_to IS NULL AND staging_id IS NULL", [page!.id]);+ return { id: Number(page!.id), forced: Number(row!.forced), rows: Number(row!.rows) };+}++async function blocks(engine: BrainEngine, page: { id: number; slug: string }): Promise<string[]> {+ const out: string[] = [];+ for await (const block of bodyBlocks(engine, page)) out.push(block.text);+ return out;+}++for (const kind of testBackends()) {+ describe('forced cuts at line boundaries (' + kind + ')', () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') {+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);+ engine = pg.engine;+ close = pg.close;+ } else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await engine.setConfig('pages.segmented_storage', 'on');+ }, 120_000);++ afterAll(async () => { await close(); });++ test('a 9,799,999-byte page of short lines cut only by force reads as one block per segment', async () => {+ const content = shortLines();+ expect(Buffer.byteLength(content)).toBe(9_799_999);+ expect((await importFromContent(engine, 'notes/short-lines', content, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const cuts = await forcedCuts(engine, 'notes/short-lines');+ expect(cuts.forced).toBeGreaterThanOrEqual(9);+ const texts = await blocks(engine, { id: cuts.id, slug: 'notes/short-lines' });+ expect(texts.length).toBeGreaterThanOrEqual(cuts.rows);+ for (const text of texts) expect(Buffer.byteLength(text)).toBeLessThanOrEqual(SEGMENT_MAX_BYTES);+ expect(texts.join('')).toBe(content.slice(content.indexOf('---\n', 4) + 4).trim() + '\n');+ expect((await segmentedTimelineText(engine, { id: cuts.id, slug: 'notes/short-lines', source_id: 'default' })).entries).toEqual([]);+ }, 300_000);++ test('a 12 MiB timeline of dated bullets: the stored canonical timeline and a rewrite of the page complete', async () => {+ const { content, bullets } = bulletTimeline();+ expect((await importFromContent(engine, 'notes/bullets', content, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const cuts = await forcedCuts(engine, 'notes/bullets');+ expect(cuts.forced).toBeGreaterThanOrEqual(12);+ const snapshot = (await engine.readPageSnapshot('notes/bullets', { sourceId: 'default' }))!;+ expect(snapshot.page.body_storage).toBe('segmented');+ expect((await storedCanonicalTimeline(engine, snapshot.page, 'notes/bullets')).size).toBe(bullets);+ const rewrite = content + '- **2026-01-01** | One more item\n';+ expect((await importFromContent(engine, 'notes/bullets', rewrite, { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const after = (await engine.readPageSnapshot('notes/bullets', { sourceId: 'default' }))!;+ expect((await storedCanonicalTimeline(engine, after.page, 'notes/bullets')).size).toBe(bullets + 1);+ }, 600_000);++ test('a code fence spanning forced cuts stays one block, and over BLOCK_MAX_BYTES it still refuses', async () => {+ expect((await importFromContent(engine, 'notes/fence', longFence(3 * MB), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const fence = await forcedCuts(engine, 'notes/fence');+ expect(fence.forced).toBeGreaterThanOrEqual(2);+ const texts = await blocks(engine, { id: fence.id, slug: 'notes/fence' });+ const holding = texts.filter(text => text.includes('```ts'));+ expect(holding).toHaveLength(1);+ const last = 'code line ' + String(Math.ceil(3 * MB / 32) - 1).padStart(10, '0') + ' x = 1;\n```\n';+ expect(holding[0]!.includes('code line 0000000000') && holding[0]!.includes(last)).toBe(true);+ expect(Buffer.byteLength(holding[0]!)).toBeGreaterThan(2.5 * MB);+ expect((await importFromContent(engine, 'notes/fence-long', longFence(BLOCK_MAX_BYTES + 2 * MB), { sourceId: 'default', noEmbed: true })).status).toBe('imported');+ const long = await forcedCuts(engine, 'notes/fence-long');+ const error = await blocks(engine, { id: long.id, slug: 'notes/fence-long' }).then(() => null, (e: unknown) => e as { code?: string });+ expect(error?.code).toBe('page_body_segmented');+ }, 600_000);+ });+}