Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(large-pages): windows fit the encoded frame; window/cursor/outline unit tests
garrytan172b43d171ef
diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex 5a91c3f0a4..1e87c4637e 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -310,46 +310,53 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIreturn { ...out, truncated: true };}- // window- const maxBytes = await windowBudget(ctx, req.maxBytes, DEFAULT_WINDOW_BYTES);+ // window: chosen, then measured as the final encoded frame; text that escapes heavily shrinks the window until it fits.const sel = req.selector;- let win: WindowSlice | null;let cursorMax = req.maxBytes ?? DEFAULT_WINDOW_BYTES;- if (!sel) win = windowFrom(doc.bytes, 0, maxBytes);- else if (sel.kind === 'lines') win = windowForLines(doc.bytes, sel.from, sel.count, maxBytes);- else if (sel.kind === 'bytes') win = windowForBytes(doc.bytes, sel.offset, Math.min(sel.length, maxBytes));- else if (sel.kind === 'cursor') {- const c = decodeCursor(sel.raw);- if (!c || c.page_id !== page.id) {- throw invalidParam(ctx, 'get_page', 'cursor', `get_page: cursor is not a window cursor for page ${page.slug}.`, { example: 'gpw1.…' });+ const select = async (maxBytes: number): Promise<WindowSlice | null> => {+ if (!sel) return windowFrom(doc.bytes, 0, maxBytes);+ if (sel.kind === 'lines') return windowForLines(doc.bytes, sel.from, sel.count, maxBytes);+ if (sel.kind === 'bytes') return windowForBytes(doc.bytes, sel.offset, Math.min(sel.length, maxBytes));+ if (sel.kind === 'cursor') {+ const c = decodeCursor(sel.raw);+ if (!c || c.page_id !== page.id) {+ throw invalidParam(ctx, 'get_page', 'cursor', `get_page: cursor is not a window cursor for page ${page.slug}.`, { example: 'gpw1.…' });+ }+ if (c.view !== req.view) {+ throw invalidParam(ctx, 'get_page', 'view', `get_page: this cursor pages view '${c.view}'; pass view: '${c.view}' with it.`, { choices: ['read', 'markdown'], example: c.view });+ }+ if (c.revision !== revision) {+ const position = Math.min(c.offset, doc.bytes.length);+ throw opError('revision_changed', `Page ${page.slug} changed since this cursor was issued (revision ${c.revision}, now ${revision}).`,+ `Continue from the same byte offset at the current revision (bytes: { offset: ${position}, length: ${c.max_bytes} }), or start over from the outline.`,+ { legacy_error: 'invalid_params', detail: JSON.stringify({ revision, cursor_revision: c.revision, offset: position }),+ fix: readFix('Reads on from the same byte offset at the current revision.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],+ mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'window', ...(markdown ? { view: 'markdown' } : {}), bytes: { offset: position, length: c.max_bytes } } } }) });+ }+ cursorMax = c.max_bytes;+ return windowFrom(doc.bytes, c.offset, Math.min(c.max_bytes, maxBytes));}- if (c.view !== req.view) {- throw invalidParam(ctx, 'get_page', 'view', `get_page: this cursor pages view '${c.view}'; pass view: '${c.view}' with it.`, { choices: ['read', 'markdown'], example: c.view });- }- if (c.revision !== revision) {- const position = Math.min(c.offset, doc.bytes.length);- throw opError('revision_changed', `Page ${page.slug} changed since this cursor was issued (revision ${c.revision}, now ${revision}).`,- `Continue from the same byte offset at the current revision (bytes: { offset: ${position}, length: ${c.max_bytes} }), or start over from the outline.`,- { legacy_error: 'invalid_params', detail: JSON.stringify({ revision, cursor_revision: c.revision, offset: position }),- fix: readFix('Reads on from the same byte offset at the current revision.', { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug],- mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'window', ...(markdown ? { view: 'markdown' } : {}), bytes: { offset: position, length: c.max_bytes } } } }) });- }- cursorMax = c.max_bytes;- win = windowFrom(doc.bytes, c.offset, Math.min(c.max_bytes, await windowBudget(ctx, c.max_bytes, DEFAULT_WINDOW_BYTES)));- } else {const around = await aroundChunk(ctx, page, doc, sel.chunkId, req.contextLines, maxBytes, revision);out.anchor = around.anchor;if (around.span) out.chunk_span = around.span;- if (!around.window) {- // T46: no exact position for the chunk, so no estimated neighborhood either: the chunk itself, without coordinates.- return { ...out, window: { text: envelopeText(around.chunkText, quarantined, trust) }, truncated: true };- }- win = around.window;+ // T46: no exact position for the chunk, so no estimated neighborhood either: the chunk itself, without coordinates.+ if (!around.window) out.window = { text: envelopeText(around.chunkText, quarantined, trust) };+ return around.window;+ };+ const cap = await resultByteCap({ remote: ctx.remote, transport: ctx.transport, engine: ctx.engine, config: ctx.config });+ let maxBytes = await windowBudget(ctx, req.maxBytes ?? (sel?.kind === 'cursor' ? decodeCursor(sel.raw)?.max_bytes : undefined), DEFAULT_WINDOW_BYTES);+ for (let attempt = 0; ; attempt++) {+ const win = await select(maxBytes);+ if (!win) return { ...out, truncated: true };+ out.window = { ...win, text: envelopeText(win.text, quarantined, trust) };+ out.truncated = win.byte_start > 0 || win.byte_end < doc.bytes.length;+ if (win.byte_end < doc.bytes.length) out.next_cursor = encodeCursor({ page_id: page.id, revision, view: req.view, offset: win.byte_end, max_bytes: cursorMax });+ else delete out.next_cursor;+ if (!Number.isFinite(cap) || attempt >= 6) return out;+ const frame = encodedFrameBytes({ content: [{ type: 'text', text: JSON.stringify(out) }] }) + ENVELOPE_RESERVE_BYTES - FRAME_RESERVE_BYTES;+ if (frame <= cap || win.byte_end - win.byte_start <= 1) return out;+ maxBytes = Math.max(1, Math.floor((win.byte_end - win.byte_start) * (cap / frame) * 0.9));}- out.window = { ...win, text: envelopeText(win.text, quarantined, trust) };- out.truncated = win.byte_start > 0 || win.byte_end < doc.bytes.length;- if (win.byte_end < doc.bytes.length) out.next_cursor = encodeCursor({ page_id: page.id, revision, view: req.view, offset: win.byte_end, max_bytes: cursorMax });- return out;}diff --git a/test/get-page-body-modes.test.ts b/test/get-page-body-modes.test.tsindex f6005eeb2f..558e24dcd4 100644--- a/test/get-page-body-modes.test.ts+++ b/test/get-page-body-modes.test.ts@@ -14,6 +14,7 @@ import { importFromContent } from '../src/core/import-file.ts';import { serializeMarkdown } from '../src/core/markdown.ts';import { pageDocument } from '../src/core/page-window/document.ts';import { decodeCursor } from '../src/core/page-window/window.ts';+import { encodedFrameBytes } from '../src/core/egress-budget.ts';import { normalizeLoweredClaim } from '../src/core/facts/withdrawal-schema.ts';let engine: PGLiteEngine;@@ -209,6 +210,17 @@ describe('around_chunk_id', () => {expect(r.window.byte_start).toBeGreaterThan(doc.length * 0.8);});+ test('whitespace the chunker folds still resolves to the exact stored span', async () => {+ const para = (i: number) => `para ${i}: spaced\t\ttext with runs of whitespace \t and trailing `.repeat(12);+ await put('logs/spaced', Array.from({ length: 300 }, (_, i) => para(i)).join('\n \n\t\n \n'));+ const chunks = await engine.getChunks('logs/spaced', { sourceId: 'default' } as any);+ const target = chunks[chunks.length - 2];+ expect(target.chunk_text).not.toBe((await projection('logs/spaced')).subarray(target.projected_byte_start!, target.projected_byte_end!).toString('utf8'));+ const r = await get(ctx(), { slug: 'logs/spaced', around_chunk_id: target.id, context_lines: 0 });+ expect(r.anchor).toBe('stored_span');+ expect(r.window.text.replace(/\s+/g, '')).toContain(target.chunk_text.replace(/\s+/g, ''));+ });+test('timeline chunks resolve inside the timeline', async () => {await put('logs/with-timeline', 'Overview of acme-example.', Array.from({ length: 2000 }, (_, i) => `- 2026-01-${String(1 + i % 28).padStart(2, '0')}: event ${i} happened at the widget plant`).join('\n'));const chunks = (await engine.getChunks('logs/with-timeline', { sourceId: 'default' } as any)).filter(c => c.chunk_source === 'timeline');@@ -310,6 +322,15 @@ describe('egress', () => {await expectCode(get(ctx({ transport: 'http', thinClient: true }), { slug: 'logs/huge' }), 'page_too_large_for_inline');});+ test('escape-heavy text shrinks the window until the encoded frame fits the cap', async () => {+ await put('blobs/escapes', Array.from({ length: 4000 }, (_, i) => `${i} ${'"\\'.repeat(60)}`).join('\n'));+ const r = await get(ctx({ transport: 'http' }), { slug: 'blobs/escapes', body: 'window', max_bytes: 1_000_000 });+ const frame = encodedFrameBytes({ content: [{ type: 'text', text: JSON.stringify(r) }] });+ expect(frame).toBeLessThanOrEqual(1024 * 1024);+ expect(Buffer.byteLength(r.window.text)).toBeGreaterThan(64 * 1024);+ expect(typeof r.next_cursor).toBe('string');+ });+test('windows stay under the cap the connection allows', async () => {const r = await get(ctx({ transport: 'http' }), { slug: 'logs/huge', body: 'window', max_bytes: 5_000_000 });expect(Buffer.byteLength(r.window.text)).toBeLessThanOrEqual(1024 * 1024);diff --git a/test/page-window.test.ts b/test/page-window.test.tsnew file mode 100644index 0000000000..102aad0414--- /dev/null+++ b/test/page-window.test.ts@@ -0,0 +1,101 @@+/**+ * Large pages (Wave A, T30): one canonical unit. Windows, cursors and outlines+ * address UTF-8 byte offsets snapped to code points and line starts; astral+ * characters, CRLF and lone long lines never split a character or lose a byte.+ */+import { describe, test, expect } from 'bun:test';+import {+ decodeCursor, encodeCursor, lineNumberAt, lineOffset, lineStartOf, pageOutline, totalLines,+ windowAround, windowForBytes, windowForLines, windowFrom,+} from '../src/core/page-window/window.ts';++const buf = (s: string) => Buffer.from(s, 'utf8');+const pageAll = (b: Buffer, max: number) => {+ const parts: Buffer[] = [];+ let at = 0;+ for (let i = 0; i < 100_000 && at < b.length; i++) {+ const w = windowFrom(b, at, max);+ expect(w.byte_start).toBe(at);+ expect(Buffer.byteLength(w.text)).toBe(w.byte_end - w.byte_start);+ expect(w.text).not.toContain('\uFFFD');+ parts.push(buf(w.text));+ at = w.byte_end;+ }+ return Buffer.concat(parts);+};++describe('windows', () => {+ test('astral and multi-byte text pages losslessly at every window size', () => {+ const b = buf(Array.from({ length: 300 }, (_, i) => `${i} 😀 naïve 日本語 𝄞`).join('\n'));+ for (const max of [1, 3, 5, 7, 64, 1000]) expect(pageAll(b, max).equals(b)).toBe(true);+ });++ test('CRLF lines keep their carriage returns and count as one line each', () => {+ const b = buf('a\r\nbb\r\nccc\r\n');+ expect(totalLines(b)).toBe(3);+ const w = windowForLines(b, 2, 1, 1000);+ expect(w.text).toBe('bb\r\n');+ expect(w.line_start).toBe(2);+ expect(pageAll(b, 4).equals(b)).toBe(true);+ });++ test('a byte selector snaps back to its line start', () => {+ const b = buf('first line\nsecond 😀 line\nthird\n');+ const inside = b.indexOf('😀') + 2;+ const w = windowForBytes(b, inside, 100);+ expect(w.byte_start).toBe(lineStartOf(b, inside));+ expect(w.text.startsWith('second')).toBe(true);+ expect(lineNumberAt(b, inside)).toBe(2);+ expect(lineOffset(b, 3)).toBe(b.indexOf('third'));+ });++ test('a single line longer than the window is cut on code points and marked', () => {+ const b = buf('😀'.repeat(1000));+ const w = windowFrom(b, 0, 10);+ expect(w.forced_cut).toBe(true);+ expect(w.byte_end % 4).toBe(0);+ });++ test('windows around a span hold the span and the requested context', () => {+ const lines = Array.from({ length: 100 }, (_, i) => `line ${i}`);+ const b = buf(lines.join('\n'));+ const start = b.indexOf('line 50');+ const w = windowAround(b, { start, end: start + 7 }, 2, 10_000);+ expect(w.text.split('\n').filter(Boolean)).toEqual(['line 48', 'line 49', 'line 50', 'line 51', 'line 52']);+ });+});++describe('outline', () => {+ test('headings inside code fences are not headings', () => {+ const b = buf('# Top\n\ntext\n\n```\n# not a heading\n```\n\n## Real\n\nmore\n');+ const o = pageOutline(b);+ expect(o.kind).toBe('headings');+ expect(o.entries.map(e => e.heading)).toEqual(['Top', 'Real']);+ expect(o.entries[o.entries.length - 1].byte_end).toBe(b.length);+ });++ test('pages without headings outline as blocks with date ranges, paged by from/limit', () => {+ const b = buf(Array.from({ length: 30_000 }, (_, i) => `2026-0${1 + (i % 9)}-1${i % 10} note ${i}`).join('\n'));+ const first = pageOutline(b, 0, 2);+ expect(first.kind).toBe('blocks');+ expect(first.entries).toHaveLength(2);+ expect(first.entries[0].date_min).toMatch(/^2026-0\d-1\d$/);+ expect(first.next_from_index).toBe(2);+ const all = pageOutline(b, 0, 500);+ expect(all.entries[0].byte_start).toBe(0);+ for (let i = 1; i < all.entries.length; i++) expect(all.entries[i].byte_start).toBe(all.entries[i - 1].byte_end);+ });+});++describe('cursor', () => {+ test('round-trips and rejects tampering', () => {+ const c = { page_id: 7, revision: 'r-1', view: 'read' as const, offset: 1234, max_bytes: 40_000 };+ expect(decodeCursor(encodeCursor(c))).toEqual(c);+ expect(decodeCursor('gpw1.!!')).toBeNull();+ expect(decodeCursor('nope')).toBeNull();+ const forge = (v: unknown) => 'gpw1.' + Buffer.from(JSON.stringify(v)).toString('base64url');+ expect(decodeCursor(forge([7, 'r', 'read', -1, 10]))).toBeNull();+ expect(decodeCursor(forge([7, 'r', 'raw', 0, 10]))).toBeNull();+ expect(decodeCursor(forge([7, 'r', 'read', 0, 0]))).toBeNull();+ });+});