Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
perf(import): linear stripCodeBlocks scan; exact cl100k counts memoized per pre-token
time-attack811d973b1e66
diff --git a/src/core/chunkers/token-estimate.ts b/src/core/chunkers/token-estimate.tsindex 3d52af9e25..49e217ffae 100644--- a/src/core/chunkers/token-estimate.ts+++ b/src/core/chunkers/token-estimate.ts@@ -24,7 +24,7 @@ export const DEFAULT_MAX_CHUNK_TOKENS = 2000;// 2-3x off for code. Lazy-init so dev and compiled-binary both only pay// the init cost once. Falls back to the heuristic if the encoder fails// to load (vanishingly unlikely but keeps the chunker available).-let tiktokenEncoder: { encode: (s: string) => Uint32Array; free: () => void } | null = null;+let tiktokenEncoder: { encode: (s: string) => Uint32Array; encode_ordinary: (s: string) => Uint32Array; free: () => void } | null = null;let tiktokenInitialized = false;// v0.20.0 Cathedral II Layer 8 (D1) — re-exported from code.ts so@@ -53,30 +53,120 @@ export function cl100kAvailable(): boolean {export function estimateTokens(text: string): number {if (!text) return 0;loadEncoder();- if (tiktokenEncoder) {+ if (!tiktokenEncoder) return Math.max(1, Math.ceil(text.length / 4));+ return pieceCounting ? countByPieces(tiktokenEncoder, text) : encodeCount(tiktokenEncoder, text);+}++function encodeCount(encoder: NonNullable<typeof tiktokenEncoder>, text: string): number {+ try {+ return encoder.encode(text).length;+ } catch {+ // Code legitimately contains tiktoken special-token strings (e.g. CLIP/GPT+ // tokenizers embed the literal "<|endoftext|>"). The default encode() uses+ // disallowed_special='all' and THROWS on those, crashing reindex-code on+ // valid source files. For a token COUNT we don't need special-token+ // semantics: re-encode treating them as ordinary text (never throws),+ // heuristic only if even that fails.try {- return tiktokenEncoder.encode(text).length;+ return (+ encoder as unknown as {+ encode: (s: string, allowed: string[], disallowed: string[]) => Uint32Array;+ }+ ).encode(text, [], []).length;} catch {- // Code legitimately contains tiktoken special-token strings (e.g. CLIP/GPT- // tokenizers embed the literal "<|endoftext|>"). The default encode() uses- // disallowed_special='all' and THROWS on those, crashing reindex-code on- // valid source files. For a token COUNT we don't need special-token- // semantics: re-encode treating them as ordinary text (never throws),- // heuristic only if even that fails.- try {- return (- tiktokenEncoder as unknown as {- encode: (s: string, allowed: string[], disallowed: string[]) => Uint32Array;- }- ).encode(text, [], []).length;- } catch {- return Math.max(1, Math.ceil(text.length / 4));+ return Math.max(1, Math.ceil(text.length / 4));+ }+ }+}++/**+ * cl100k's pre-tokenizer pattern restricted to ASCII (\p{L} = [A-Za-z],+ * \p{N} = [0-9], \s = [\t\n\v\f\r ]). cl100k encodes each pre-token+ * independently and the count is the sum over pre-tokens, so ASCII text can be+ * split here and each pre-token's count memoized: prose repeats a small+ * vocabulary, which turns ~0.5 ms of WASM encoding per 3k-char chunk into+ * map lookups.+ */+const ASCII_PRETOKEN = /'(?:[sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD])|[^\r\nA-Za-z0-9]?[A-Za-z]+|[0-9]{1,3}| ?[^\t\n\v\f\r A-Za-z0-9]+[\r\n]*|[\t\n\v\f\r ]*[\r\n]+|[\t\n\v\f\r ]+(?![^\t\n\v\f\r ])|[\t\n\v\f\r ]+/y;++/**+ * Two cuts always end a pre-token whatever script surrounds them: a newline+ * followed by an ASCII letter or digit (no cl100k alternative continues from+ * a newline into one, and none that can end there looks ahead), and a space+ * between two ASCII letters (the letter run before it ends there and the+ * space opens the next word's pre-token). Segments between cuts count+ * independently, so only segments holding non-ASCII text go to the encoder:+ * lines first, then words inside a line that has curly quotes or accents.+ */+const LINE_CUT = /\n(?=[A-Za-z0-9])/g;+const WORD_CUT = /[A-Za-z](?= [A-Za-z])/g;+const NON_ASCII = /[^\x00-\x7f]/g;+const PRETOKEN_MEMO_MAX_ENTRIES = 50_000;+const PRETOKEN_MEMO_MAX_CHARS = 64;+const pretokenCounts = new Map<string, number>();+let pieceCounting = true;++/**+ * Same count as encodeCount: segments and pre-tokens go through+ * encode_ordinary, which is what encodeCount's special-token retry computes+ * and what encode() returns on text without special tokens, minus encode()'s+ * ~50 µs per-call special-token regex build.+ */+function countByPieces(encoder: NonNullable<typeof tiktokenEncoder>, text: string): number {+ let total = 0;+ let encodeFrom = -1;+ const visit = (from: number, to: number, cut: RegExp, inner?: RegExp): void => {+ let nonAscii = -1;+ let start = from;+ while (start < to) {+ cut.lastIndex = start;+ const end = Math.min(to, (cut.exec(text)?.index ?? to) + 1);+ if (nonAscii < start) {+ NON_ASCII.lastIndex = start;+ nonAscii = NON_ASCII.exec(text)?.index ?? text.length;+ }+ if (nonAscii >= end) {+ if (encodeFrom !== -1) total += encoder.encode_ordinary(text.slice(encodeFrom, start)).length;+ encodeFrom = -1;+ total += countAscii(encoder, text, start, end);+ } else if (inner) {+ visit(start, end, inner);+ } else if (encodeFrom === -1) {+ encodeFrom = start;}+ start = end;}+ };+ visit(0, text.length, LINE_CUT, WORD_CUT);+ if (encodeFrom !== -1) total += encoder.encode_ordinary(text.slice(encodeFrom)).length;+ return total;+}++function countAscii(encoder: NonNullable<typeof tiktokenEncoder>, text: string, start: number, end: number): number {+ let total = 0;+ ASCII_PRETOKEN.lastIndex = start;+ while (ASCII_PRETOKEN.lastIndex < end) {+ const piece = ASCII_PRETOKEN.exec(text)![0];+ let count = pretokenCounts.get(piece);+ if (count === undefined) {+ count = encoder.encode_ordinary(piece).length;+ if (piece.length <= PRETOKEN_MEMO_MAX_CHARS) {+ if (pretokenCounts.size >= PRETOKEN_MEMO_MAX_ENTRIES) pretokenCounts.clear();+ pretokenCounts.set(piece, count);+ }+ }+ total += count;}- return Math.max(1, Math.ceil(text.length / 4));+ return total;}+/** Test seam: false counts every text with one whole-text encode (the reference path). */+export const __testing = {+ setPieceCounting(on: boolean): void {+ pieceCounting = on;+ },+};+const CJK_CHARS_G = new RegExp(`[${CJK_SLUG_CHARS}]`, 'g');/**diff --git a/src/core/markdown-code.ts b/src/core/markdown-code.tsindex 96e18734f9..cd0814dad9 100644--- a/src/core/markdown-code.ts+++ b/src/core/markdown-code.ts@@ -7,30 +7,45 @@ import { inlineCodeEndAt, scanMarkdownCode, type MarkdownCodeMap } from './fence* Inline spans follow CommonMark (#6133): a run of n backticks closes at the* next run of exactly n on the same line (fence-scan.ts finds the spans), so* ``a `b` c`` is one span; a bare CR does not end the line here.+ * Runs between newlines, backticks and (with onHtmlComment) `<!--` are copied+ * as whole slices, so cost is linear in the text rather than per character.*/export function stripCodeBlocks(content: string, opts: { onHtmlComment?: (start: number, end: number) => void } = {}): string {+ const fenceMarker = / {0,3}(`{3,}|~{3,})([^\n]*)/y;+ const special = opts.onHtmlComment ? /\n|`|<!--/g : /\n|`/g;let fence: string | undefined;let inline: MarkdownCodeMap | undefined;let out = '';let i = 0;while (i < content.length) {if (i === 0 || content[i - 1] === '\n') {- const newline = content.indexOf('\n', i);- const end = newline === -1 ? content.length : newline + 1;- const line = content.slice(i, end);- const marker = /^ {0,3}(`{3,}|~{3,})([^\n]*)/.exec(line);+ fenceMarker.lastIndex = i;+ const marker = fence || /^ {0,3}[`~]/.test(content.slice(i, i + 4)) ? fenceMarker.exec(content) : null;if (fence || (marker && (marker[1][0] === '~' || !marker[2].includes('`')))) {+ const newline = content.indexOf('\n', i);+ const end = newline === -1 ? content.length : newline + 1;if (!fence) fence = marker![1];else if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;- out += line.replace(/[^\r\n]/g, ' ');+ out += content.slice(i, end).replace(/[^\r\n]/g, ' ');i = end;continue;}}- if (opts.onHtmlComment && content.startsWith('<!--', i)) {+ special.lastIndex = i;+ const next = special.exec(content);+ const at = next ? next.index : content.length;+ out += content.slice(i, at);+ i = at;+ if (!next) break;+ if (next[0] === '\n') {+ out += '\n';+ i++;+ continue;+ }+ if (next[0] === '<!--') {const close = content.indexOf('-->', i + 4);const end = close === -1 ? content.length : close + 3;- opts.onHtmlComment(i, end);+ opts.onHtmlComment!(i, end);out += content.slice(i, end).replace(/[^\r\n]/g, ' ');i = end;continue;@@ -42,20 +57,15 @@ export function stripCodeBlocks(content: string, opts: { onHtmlComment?: (start:i = afterFence;continue;}- if (content[i] === '`') {- inline ??= scanMarkdownCode(content.replace(/\r(?!\n)/g, ' '));- const end = inlineCodeEndAt(inline, i);- if (end === -1) {- out += content[i];- i++;- continue;- }- out += content.slice(i, end).replace(/[^\r\n]/g, ' ');- i = end;+ inline ??= scanMarkdownCode(content.replace(/\r(?!\n)/g, ' '));+ const end = inlineCodeEndAt(inline, i);+ if (end === -1) {+ out += '`';+ i++;continue;}- out += content[i];- i++;+ out += content.slice(i, end).replace(/[^\r\n]/g, ' ');+ i = end;}return out;}diff --git a/test/chunkers/token-estimate-pieces.test.ts b/test/chunkers/token-estimate-pieces.test.tsnew file mode 100644index 0000000000..2efb0ebf6a--- /dev/null+++ b/test/chunkers/token-estimate-pieces.test.ts@@ -0,0 +1,167 @@+/**+ * estimateTokens counts ASCII text by memoized cl100k pre-tokens instead of+ * one whole-text WASM encode. Both paths must give the exact same count, and+ * so the same chunk boundaries, for every input: the fuzz compares the counts+ * directly, the fixtures compare whole chunker outputs with the reference+ * (whole-text encode) path forced through the test seam.+ */++import { afterEach, describe, expect, test } from 'bun:test';+import { __testing, estimateEmbedTokens, estimateTokens } from '../../src/core/chunkers/token-estimate.ts';+import { chunkText } from '../../src/core/chunkers/recursive.ts';+import { chunkCodeText } from '../../src/core/chunkers/code.ts';+import { prepareMarkdownChunks } from '../../src/core/markdown-chunks.ts';++afterEach(() => __testing.setPieceCounting(true));++function reference<T>(fn: () => T): T {+ __testing.setPieceCounting(false);+ try {+ return fn();+ } finally {+ __testing.setPieceCounting(true);+ }+}++async function referenceAsync<T>(fn: () => Promise<T>): Promise<T> {+ __testing.setPieceCounting(false);+ try {+ return await fn();+ } finally {+ __testing.setPieceCounting(true);+ }+}++function rng(seed: number): () => number {+ let s = seed >>> 0;+ return () => {+ s = (s + 0x6d2b79f5) >>> 0;+ let t = s;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const ALPHABET = [+ 'the', 'The', ' quick', 'BROWN', 'fox', 'a', 'Z', 'x', ' ', ' ', ' ', ' ', '\n', '\n', '\n\n', '\r\n', '\r', '\t', '\v', '\f',+ "'s", "'S", "'t", "'re", "'RE", "'Ve", "'m", "'ll", "'lL", "'d", "'", "'x", '1', '12', '1234567', '0', '.', ',', '!', '?', '-', '--',+ '...', '()', '{', '}', '[', ']', '#', '##', '* ', '- ', '`', '```', '|', '/', '\\', '_', 'snake_case', 'http://', '.com', '=', '+',+ '\u0000', '\u001f', '\u007f', '<|endoftext|>', '<|fim_prefix|>', '<|', '|>', 'é', 'café', '\u0301', '\u00a0', '\u0085', '\ufeff',+ '\u2014', '\u2019', '\u201c', '中文', '日本語', '한국어', '。', ',', '😀', '👍🏽', '𝔸', 'ſ', '\u212a', '٣', 'full', '\ud800', '\udc00',+ '\u2028', '\u3000', 'ß', 'İ',+];++function randomText(r: () => number, maxPieces: number): string {+ const n = Math.floor(r() * maxPieces);+ let s = '';+ for (let k = 0; k < n; k++) s += ALPHABET[Math.floor(r() * ALPHABET.length)];+ return s;+}++function asciiText(r: () => number, maxPieces: number): string {+ let s = '';+ const n = Math.floor(r() * maxPieces);+ for (let k = 0; k < n; k++) s += String.fromCharCode(Math.floor(r() * 128));+ return s;+}++describe('estimateTokens piece counting equals the whole-text encode', () => {+ test('reference path is the raw cl100k encoder', () => {+ const { get_encoding } = require('@dqbd/tiktoken');+ const enc = get_encoding('cl100k_base');+ try {+ for (const s of ['hello world', "it's 2026, isn't it?\n\nNext line", 'naïve café 中文 😀', ' \n\t x']) {+ expect(reference(() => estimateTokens(s))).toBe(enc.encode(s).length);+ }+ } finally {+ enc.free();+ }+ });++ test('fuzz: biased markdown-ish alphabet incl. non-ASCII and special-token text', () => {+ const r = rng(4242);+ for (let k = 0; k < 10_000; k++) {+ const s = randomText(r, 60);+ const expected = reference(() => estimateTokens(s));+ if (estimateTokens(s) !== expected) throw new Error(`count mismatch on ${JSON.stringify(s)}`);+ }+ });++ test('fuzz: every ASCII code point', () => {+ const r = rng(7);+ for (let k = 0; k < 8_000; k++) {+ const s = asciiText(r, 80);+ const expected = reference(() => estimateTokens(s));+ if (estimateTokens(s) !== expected) throw new Error(`count mismatch on ${JSON.stringify(s)}`);+ }+ });++ test('long pre-tokens beyond the memo length and repeated calls stay exact', () => {+ const inputs = ['a'.repeat(5_000), ' '.repeat(300) + 'x', '-'.repeat(1_000) + '\n' + 'b'.repeat(70), `${'word '.repeat(2_000)}\n${'9'.repeat(400)}`];+ for (let pass = 0; pass < 2; pass++) {+ for (const s of inputs) expect(estimateTokens(s)).toBe(reference(() => estimateTokens(s)));+ }+ });+});++const PROSE = Array.from({ length: 900 }, (_, i) => ['alpha', "isn't", 'beta,', 'gamma.', 'Delta', '42', '(note)', 'https://example.com/a?b=c'][i % 8]).join(' ');+const CJK = '中文段落内容测试,这是一个很长的句子。'.repeat(400);+const KOREAN_URLS = Array.from({ length: 200 }, (_, i) => `설정 항목 ${i}: https://example.com/path/${i}?q=값 참조`).join(' ');+const DENSE_JSON = JSON.stringify(Array.from({ length: 400 }, (_, i) => ({ id: i, url: `https://ex.io/${i}/x?y=${i * 7}`, tag: `t${i}` })));+const NEAR_LIMIT = 'x1y2z3'.repeat(999) + ' tail';++const MARKDOWN_PAGE = [+ '# Title',+ '',+ PROSE,+ '',+ '```ts',+ Array.from({ length: 120 }, (_, i) => `export function f${i}(a: number): number { return a * ${i}; } // ${'c'.repeat(i % 40)}`).join('\n'),+ '```',+ '',+ 'Curly quotes \u201cmixed\u201d \u2014 em dash, caf\u00e9, 😀 emoji.',+ CJK.slice(0, 3_000),+ '',+ '~~~py',+ Array.from({ length: 80 }, (_, i) => `def g${i}(x):\n return x + ${i}`).join('\n'),+ '~~~',+ '',+ DENSE_JSON.slice(0, 7_000),+].join('\n');++describe('chunkers produce identical chunks with piece counting', () => {+ const texts = { PROSE, CJK, KOREAN_URLS, DENSE_JSON, NEAR_LIMIT, MARKDOWN_PAGE };++ test('chunkText: chunk text, order and token counts', () => {+ for (const [name, text] of Object.entries(texts)) {+ for (const maxTokens of [undefined, 512]) {+ const actual = chunkText(text, { maxTokens });+ const expected = reference(() => chunkText(text, { maxTokens }));+ expect({ name, maxTokens, chunks: actual }).toEqual({ name, maxTokens, chunks: expected });+ expect(actual.length).toBeGreaterThan(0);+ for (const c of actual) {+ expect(estimateTokens(c.text)).toBe(reference(() => estimateTokens(c.text)));+ expect(estimateEmbedTokens(c.text)).toBe(reference(() => estimateEmbedTokens(c.text)));+ }+ }+ }+ });++ test('prepareMarkdownChunks: truth, timeline and fenced code chunks', async () => {+ const page = { compiled_truth: MARKDOWN_PAGE, timeline: `- 2026-01-01: ${PROSE.slice(0, 2_500)}`, frontmatter: {} };+ for (const maxTokens of [undefined, 512]) {+ const actual = await prepareMarkdownChunks(page, maxTokens);+ const expected = await referenceAsync(() => prepareMarkdownChunks(page, maxTokens));+ expect(actual).toEqual(expected);+ expect(actual.some((c) => c.chunk_source === 'fenced_code')).toBe(true);+ }+ });++ test('chunkCodeText: symbol chunks and oversize caps', async () => {+ const source = Array.from({ length: 60 }, (_, i) => `export function h${i}(): string {\n return ${JSON.stringify(KOREAN_URLS.slice(i * 40, i * 40 + 400))};\n}`).join('\n\n');+ const actual = await chunkCodeText(source, 'fixture.ts');+ const expected = await referenceAsync(() => chunkCodeText(source, 'fixture.ts'));+ expect(actual).toEqual(expected);+ });+});diff --git a/test/markdown-code-equivalence.test.ts b/test/markdown-code-equivalence.test.tsnew file mode 100644index 0000000000..bfc163ea21--- /dev/null+++ b/test/markdown-code-equivalence.test.ts@@ -0,0 +1,139 @@+import { describe, expect, test } from 'bun:test';+import { inlineCodeEndAt, scanMarkdownCode, type MarkdownCodeMap } from '../src/core/fence-scan.ts';+import { stripCodeBlocks } from '../src/core/markdown-code.ts';++/** The per-character stripCodeBlocks the slice-copying version replaced, kept verbatim as the oracle. */+function referenceStripCodeBlocks(content: string, opts: { onHtmlComment?: (start: number, end: number) => void } = {}): string {+ let fence: string | undefined;+ let inline: MarkdownCodeMap | undefined;+ let out = '';+ let i = 0;+ while (i < content.length) {+ if (i === 0 || content[i - 1] === '\n') {+ const newline = content.indexOf('\n', i);+ const end = newline === -1 ? content.length : newline + 1;+ const line = content.slice(i, end);+ const marker = /^ {0,3}(`{3,}|~{3,})([^\n]*)/.exec(line);+ if (fence || (marker && (marker[1][0] === '~' || !marker[2].includes('`')))) {+ if (!fence) fence = marker![1];+ else if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = undefined;+ out += line.replace(/[^\r\n]/g, ' ');+ i = end;+ continue;+ }+ }+ if (opts.onHtmlComment && content.startsWith('<!--', i)) {+ const close = content.indexOf('-->', i + 4);+ const end = close === -1 ? content.length : close + 3;+ opts.onHtmlComment(i, end);+ out += content.slice(i, end).replace(/[^\r\n]/g, ' ');+ i = end;+ continue;+ }+ if (content.startsWith('```', i)) {+ const end = content.indexOf('```', i + 3);+ const afterFence = end === -1 ? content.length : end + 3;+ out += content.slice(i, afterFence).replace(/[^\r\n]/g, ' ');+ i = afterFence;+ continue;+ }+ if (content[i] === '`') {+ inline ??= scanMarkdownCode(content.replace(/\r(?!\n)/g, ' '));+ const end = inlineCodeEndAt(inline, i);+ if (end === -1) {+ out += content[i];+ i++;+ continue;+ }+ out += content.slice(i, end).replace(/[^\r\n]/g, ' ');+ i = end;+ continue;+ }+ out += content[i];+ i++;+ }+ return out;+}++function rng(seed: number): () => number {+ let s = seed >>> 0;+ return () => {+ s = (s + 0x6d2b79f5) >>> 0;+ let t = s;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++const ALPHABET = [+ '`', '`', '`', '``', '```', '````', '~', '~~~', '~~~~', ' ', ' ', ' ', ' ', '\n', '\n', '\r\n', '\r', '\t',+ '<!--', '-->', '<!-', '--', '<', '>', '-', 'a', 'b', 'x', 'js', 'Z', '1', '#', '* ', '\\', '|', '.', 'é', '中', '😀', '𝔸',+];++function randomMarkdown(r: () => number): string {+ const n = Math.floor(r() * 80);+ let s = '';+ for (let k = 0; k < n; k++) s += ALPHABET[Math.floor(r() * ALPHABET.length)];+ return s;+}++function both(input: string, withComments: boolean) {+ const run = (fn: typeof stripCodeBlocks) => {+ const calls: Array<[number, number]> = [];+ const out = fn(input, withComments ? { onHtmlComment: (s, e) => calls.push([s, e]) } : {});+ return { out, calls };+ };+ return { actual: run(stripCodeBlocks), expected: run(referenceStripCodeBlocks) };+}++describe('stripCodeBlocks matches the per-character reference', () => {+ test('fuzz: output and onHtmlComment calls are identical', () => {+ const r = rng(6844);+ for (let k = 0; k < 40_000; k++) {+ const input = randomMarkdown(r);+ for (const withComments of [false, true]) {+ const { actual, expected } = both(input, withComments);+ if (actual.out !== expected.out || JSON.stringify(actual.calls) !== JSON.stringify(expected.calls)) {+ throw new Error(`mismatch (comments=${withComments}) on ${JSON.stringify(input)}`);+ }+ expect(actual.out.length).toBe(input.length);+ }+ }+ });++ test('fixtures: fences, CR line endings, unclosed spans and comments', () => {+ const fixtures = [+ '',+ 'plain text with no code',+ '```ts\nconst a = 1;\n```\nafter `inline` and ``a `b` c`` done',+ '~~~\ncode ``` inside\n~~~~\nprose',+ '````\n```\nstill code\n````\nout',+ '```js `x`\nnot a fence ``` closes here\n',+ ' ```\r\nfenced\r\n ```\r\nafter\r\n',+ 'a `b\rc` d\r```\r~~~\rtext',+ '<!-- note `x` -->\n```\n<!-- inside -->\n```\n<!-- unclosed',+ '`unclosed inline\n```unclosed triple',+ ' ```\nindented four is not a fence\n```',+ '😀 `𝔸` 中文 ~~~\n~~~ 😀\n𝔸\n~~~',+ ];+ for (const input of fixtures) {+ for (const withComments of [false, true]) {+ const { actual, expected } = both(input, withComments);+ expect(actual).toEqual(expected);+ }+ }+ });++ test('large mixed documents are identical', () => {+ const r = rng(68);+ for (let k = 0; k < 50; k++) {+ let doc = '';+ while (doc.length < 20_000) doc += randomMarkdown(r) + (r() < 0.2 ? '\n```py\nprint(1)\n```\n' : ' words and more words. ');+ for (const withComments of [false, true]) {+ const { actual, expected } = both(doc, withComments);+ expect(actual).toEqual(expected);+ }+ }+ });+});