Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(large-pages): get_page body modes, windows, cursors, outline
garrytande2d90529641
diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 01dda4cd48..536120afe3 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -356,6 +356,7 @@ export async function getChunks(cc.model, cc.token_count, cc.embedded_at, cc.language,cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality,+ cc.projected_byte_start, cc.projected_byte_end,(cc.${colId} IS NULL) AS embedding_is_null${embedCol}FROM content_chunks ccdiff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsnew file mode 100644index 0000000000..8aadc42e75--- /dev/null+++ b/src/core/ops/get-page-body.ts@@ -0,0 +1,350 @@+/**+ * Large pages (Wave A read contract): get_page body modes.+ *+ * body: 'full' the page as today (compiled_truth, timeline, and `content`+ * with include_content); refused with+ * page_too_large_for_inline when the complete result does not+ * fit the connection's egress cap. Trusted local reads are+ * never refused.+ * body: 'auto' (default) 'full' up to mcp.inline_body_bytes (256 KB of+ * body), else the outline plus the first window.+ * body: 'none' metadata, revision, size and chunk/embedding counts, no text:+ * the cheap read before edit_page / put_page.+ * body: 'outline' metadata, size and a paged outline.+ * body: 'window' metadata, size and one window chosen by ONE selector:+ * lines {from, count}, bytes {offset, length}, around_chunk_id+ * (+ context_lines) or cursor; none = from the start.+ *+ * A partial shape NEVER carries compiled_truth, timeline or content, so no+ * caller can mistake a window for the page and write it back whole. Windows+ * and outlines slice the read projection (page-window/document.ts), the same+ * text for every caller; view 'markdown' slices the canonical round-trip+ * markdown `content` instead (thin-client complete downloads), with its+ * sha256 for verification.+ *+ * Precedence: an explicit `body` wins; without it include_content or+ * content_only mean 'full' (content_only keeps the round-trip shape), a+ * selector means 'window', gbrain's thin client means 'full' (an older thin+ * client renders compiled_truth as the whole page), a trusted local read means+ * 'full', anything else 'auto'.+ */+import type { Page } from '../types.ts';+import type { OperationContext, ParamDef } from './contract.ts';+import { opError } from './contract.ts';+import { invalidParam, readFix } from './op-fix.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { encodedFrameBytes, EGRESS_CAP_CONFIG_KEYS, egressTransport, FRAME_RESERVE_BYTES, resultByteCap } from '../egress-budget.ts';+import { chunkDocumentSpan, readPageDocument, spanHoldsChunk, type PageDocument } from '../page-window/document.ts';+import {+ DEFAULT_CONTEXT_LINES, DEFAULT_OUTLINE_LIMIT, DEFAULT_WINDOW_BYTES, MAX_CONTEXT_LINES, MAX_OUTLINE_LIMIT, MAX_WINDOW_BYTES,+ decodeCursor, encodeCursor, pageOutline, sha256Hex, totalLines, windowAround, windowForBytes, windowForLines, windowFrom,+ type WindowSlice, type WindowView,+} from '../page-window/window.ts';+import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';+import type { QuarantinedView } from './get-page-projection.ts';++export const BODY_MODES = ['auto', 'full', 'none', 'outline', 'window'] as const;+export type BodyMode = typeof BODY_MODES[number];+export const INLINE_BODY_BYTES_KEY = 'mcp.inline_body_bytes';+/** `auto` returns the whole body up to this many bytes of compiled truth plus timeline. */+export const DEFAULT_INLINE_BODY_BYTES = 256 * 1024;+/** Room a partial response keeps for its metadata, notices and escaping inside the egress cap. */+const ENVELOPE_RESERVE_BYTES = 64 * 1024;+/** The first window `auto` returns next to the outline. */+const AUTO_WINDOW_BYTES = 16_000;++export const GET_PAGE_BODY_PARAMS: Record<string, ParamDef> = {+ body: { type: 'string', enum: [...BODY_MODES], description: "auto (default: whole body up to 256 KB, else outline + first window), full, none (revision + size only), outline, window." },+ lines: { type: 'object', description: 'Window selector: 1-based lines.', properties: { from: { type: 'number', required: true }, count: { type: 'number', required: true } } },+ bytes: { type: 'object', description: 'Window selector: UTF-8 bytes, snapped to line starts.', properties: { offset: { type: 'number', required: true }, length: { type: 'number', required: true } } },+ around_chunk_id: { type: 'number', description: 'Window selector: center on a search hit chunk_id.' },+ context_lines: { type: 'number', description: 'Lines around around_chunk_id (default 20).' },+ cursor: { type: 'string', description: 'Window selector: next_cursor from the previous window.' },+ max_bytes: { type: 'number', description: 'Window size in bytes (default 40000).' },+ view: { type: 'string', enum: ['read', 'markdown'], description: "Window text: read (default) or markdown (round-trip content)." },+ outline_from: { type: 'number', description: 'Outline entry to start from (next_from_index).' },+};++type Selector =+ | { kind: 'lines'; from: number; count: number }+ | { kind: 'bytes'; offset: number; length: number }+ | { kind: 'around'; chunkId: number }+ | { kind: 'cursor'; raw: string };++export interface BodyRequest {+ mode: BodyMode;+ selector?: Selector;+ view: WindowView;+ maxBytes?: number;+ contextLines: number;+ outlineFrom: number;+ /** The caller named no mode and is gbrain's thin client (full or refused, never a window). */+ legacyThin: boolean;+}++const SELECTOR_EXAMPLE = { slug: 'notes/acme-example-log', body: 'window', lines: { from: 1, count: 200 } };++function int(v: unknown): v is number { return typeof v === 'number' && Number.isSafeInteger(v); }++/** Validate and resolve the body-mode params; throws invalid_params naming the conflict. */+export function parseBodyRequest(ctx: Pick<OperationContext, 'remote' | 'transport' | 'thinClient'>, p: Record<string, unknown>): BodyRequest {+ const bad = (param: string, message: string, example: unknown = SELECTOR_EXAMPLE) => invalidParam(ctx, 'get_page', param, message, { example });+ const body = p.body;+ if (body !== undefined && (typeof body !== 'string' || !(BODY_MODES as readonly string[]).includes(body))) {+ throw invalidParam(ctx, 'get_page', 'body', `get_page: body must be one of ${BODY_MODES.join(', ')}.`, { choices: BODY_MODES, example: 'none' });+ }+ const selectors: Selector[] = [];+ if (p.lines !== undefined) {+ const l = p.lines as Record<string, unknown> | null;+ if (!l || typeof l !== 'object' || !int(l.from) || !int(l.count) || l.from < 1 || l.count < 1) {+ throw bad('lines', 'get_page: lines must be { from: <1-based line>, count: <lines> } with positive integers.', { from: 1, count: 200 });+ }+ selectors.push({ kind: 'lines', from: l.from, count: l.count });+ }+ if (p.bytes !== undefined) {+ const b = p.bytes as Record<string, unknown> | null;+ if (!b || typeof b !== 'object' || !int(b.offset) || !int(b.length) || b.offset < 0 || b.length < 1) {+ throw bad('bytes', 'get_page: bytes must be { offset: <byte offset >= 0>, length: <bytes >= 1> }.', { offset: 0, length: DEFAULT_WINDOW_BYTES });+ }+ selectors.push({ kind: 'bytes', offset: b.offset, length: b.length });+ }+ if (p.around_chunk_id !== undefined) {+ if (!int(p.around_chunk_id) || p.around_chunk_id < 1) throw bad('around_chunk_id', 'get_page: around_chunk_id must be a positive chunk_id from a search result.', 8812);+ selectors.push({ kind: 'around', chunkId: p.around_chunk_id });+ }+ if (p.cursor !== undefined) {+ if (typeof p.cursor !== 'string' || !p.cursor) throw bad('cursor', 'get_page: cursor must be the next_cursor string from the previous window.', 'gpw1.…');+ selectors.push({ kind: 'cursor', raw: p.cursor });+ }+ if (selectors.length > 1) {+ throw bad(selectors[1].kind === 'around' ? 'around_chunk_id' : selectors[1].kind, `get_page: pass one window selector, not ${selectors.length} (got ${selectors.map(s => s.kind === 'around' ? 'around_chunk_id' : s.kind).join(' and ')}).`);+ }+ const includeContent = p.include_content === true;+ const contentOnly = p.content_only === true;+ let mode: BodyMode;+ if (typeof body === 'string') {+ mode = body as BodyMode;+ if ((includeContent || contentOnly) && mode !== 'full') {+ throw bad('body', `get_page: include_content and content_only return the whole page; they cannot be combined with body: '${mode}'.`, { slug: 'notes/acme-example-log', body: 'full', include_content: true });+ }+ if (selectors.length && mode !== 'window' && mode !== 'auto') {+ throw bad('body', `get_page: a window selector needs body: 'window' (got body: '${mode}').`);+ }+ if (mode === 'auto' && selectors.length) mode = 'window';+ } else if (includeContent || contentOnly) {+ if (selectors.length) throw bad('include_content', 'get_page: include_content returns the whole page; drop it to read a window.');+ mode = 'full';+ } else if (selectors.length) mode = 'window';+ else if (ctx.thinClient === true || ctx.remote === false) mode = 'full';+ else mode = 'auto';+ const view = p.view === undefined ? 'read' : p.view;+ if (view !== 'read' && view !== 'markdown') throw invalidParam(ctx, 'get_page', 'view', "get_page: view must be 'read' or 'markdown'.", { choices: ['read', 'markdown'], example: 'markdown' });+ if (view === 'markdown' && (mode !== 'window' || selectors[0]?.kind === 'around')) {+ throw bad('view', "get_page: view: 'markdown' pages the round-trip markdown with body: 'window' and a lines, bytes or cursor selector.", { slug: 'notes/acme-example-log', body: 'window', view: 'markdown', bytes: { offset: 0, length: 1_000_000 } });+ }+ let maxBytes: number | undefined;+ if (p.max_bytes !== undefined) {+ if (!int(p.max_bytes) || p.max_bytes < 1) throw bad('max_bytes', 'get_page: max_bytes must be a positive integer.', DEFAULT_WINDOW_BYTES);+ maxBytes = p.max_bytes;+ }+ let contextLines = DEFAULT_CONTEXT_LINES;+ if (p.context_lines !== undefined) {+ if (!int(p.context_lines) || p.context_lines < 0) throw bad('context_lines', 'get_page: context_lines must be a non-negative integer.', DEFAULT_CONTEXT_LINES);+ contextLines = Math.min(MAX_CONTEXT_LINES, p.context_lines);+ }+ let outlineFrom = 0;+ if (p.outline_from !== undefined) {+ if (!int(p.outline_from) || p.outline_from < 0) throw bad('outline_from', 'get_page: outline_from must be a non-negative integer (the previous next_from_index).', 100);+ outlineFrom = p.outline_from;+ }+ return { mode, ...(selectors[0] ? { selector: selectors[0] } : {}), view, ...(maxBytes !== undefined ? { maxBytes } : {}), contextLines, outlineFrom,+ legacyThin: typeof body !== 'string' && ctx.thinClient === true && !includeContent && !contentOnly && !selectors.length };+}++export async function inlineBodyBytes(ctx: Pick<OperationContext, 'engine' | 'config'>): Promise<number> {+ try {+ const n = Number(await ctx.engine.getConfig(INLINE_BODY_BYTES_KEY));+ if (Number.isFinite(n) && n > 0) return Math.floor(n);+ } catch { /* config unreadable: the file plane, then the default */ }+ const file = Number((ctx.config?.mcp as Record<string, unknown> | undefined)?.inline_body_bytes);+ return Number.isFinite(file) && file > 0 ? Math.floor(file) : DEFAULT_INLINE_BODY_BYTES;+}++/** Bytes of the body a full read returns (compiled truth plus timeline). */+export function bodyBytes(page: Pick<Page, 'compiled_truth' | 'timeline'>): number {+ return Buffer.byteLength(page.compiled_truth ?? '', 'utf8') + Buffer.byteLength(page.timeline ?? '', 'utf8');+}++function sizeFix(slug: string, sourceId: string, why: string) {+ return readFix(why, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'outline' } } });+}++/**+ * A full read must fit the connection: measured as the complete encoded frame+ * of the result (content[0] holds the JSON text, which the JSON-RPC frame+ * escapes again). Trusted local reads have no cap.+ */+export async function assertFullReadFits(ctx: OperationContext, page: Pick<Page, 'slug' | 'source_id' | 'compiled_truth' | 'timeline'>, result: unknown, req: BodyRequest): Promise<void> {+ const cap = await resultByteCap({ remote: ctx.remote, transport: ctx.transport, engine: ctx.engine, config: ctx.config });+ if (!Number.isFinite(cap)) return;+ const raw = bodyBytes(page);+ // Escaping grows text at most ~12x through two JSON levels; well under the cap needs no measurement.+ if (raw * 12 + ENVELOPE_RESERVE_BYTES < cap) return;+ const frame = encodedFrameBytes({ content: [{ type: 'text', text: JSON.stringify(result) }] }) + ENVELOPE_RESERVE_BYTES - FRAME_RESERVE_BYTES;+ if (frame <= cap) return;+ const transport = egressTransport(ctx)!;+ throw opError('page_too_large_for_inline',+ `Page ${page.slug} is too large to return whole on this connection (about ${frame} bytes encoded; the cap is ${cap}).`,+ req.legacyThin+ ? 'This gbrain CLI is older than the host and reads pages whole. Upgrade it (gbrain upgrade) to page through large pages, or read windows over MCP with get_page body: \'window\'.'+ : "Read it in windows: get_page body: 'outline' lists the sections, then body: 'window' with lines, bytes, around_chunk_id or next_cursor. Edit with edit_page (revision from body: 'none').",+ { legacy_error: 'invalid_params', detail: JSON.stringify({ total_bytes: raw, result_bytes: frame, max_result_bytes: cap, transport, config_key: EGRESS_CAP_CONFIG_KEYS[transport] }),+ fix: sizeFix(page.slug, page.source_id, "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.") });+}++/** The largest window this caller may receive: the request, the per-window ceiling and the egress cap minus metadata room. */+async function windowBudget(ctx: OperationContext, requested: number | undefined, fallback: number): Promise<number> {+ const cap = await resultByteCap({ remote: ctx.remote, transport: ctx.transport, engine: ctx.engine, config: ctx.config });+ // A window's text can grow ~2x through the two JSON levels of a frame (newlines, quotes).+ const egressRoom = Number.isFinite(cap) ? Math.max(4096, Math.floor((cap - ENVELOPE_RESERVE_BYTES) / 2)) : Number.POSITIVE_INFINITY;+ const ceiling = ctx.remote === false ? Number.POSITIVE_INFINITY : MAX_WINDOW_BYTES;+ return Math.max(1, Math.min(requested ?? fallback, ceiling, egressRoom));+}++export interface PartialReadInput {+ page: Page;+ /** The body this caller may see (privacy fences already stripped for untrusted readers): the source of view 'markdown'. */+ visibleBody: Page;+ revision: string;+ tags: string[];+ quarantined: QuarantinedView | null;+ trust?: TrustFields;+ extras: Record<string, unknown>;+}++function envelopeText(text: string, quarantined: QuarantinedView | null, trust?: TrustFields): string {+ return quarantined?.body_enveloped && text ? renderTrustedText(text, { trust_tier: 'external_untrusted', origin: trust?.origin ?? 'quarantined' }) : text;+}++/** Resolve a chunk-centered window: stored span first, then an unambiguous text match, else the chunk itself. */+async function aroundChunk(ctx: OperationContext, page: Page, doc: PageDocument, chunkId: number, contextLines: number, maxBytes: number, revision: string):+ Promise<{ window: WindowSlice | null; chunkText: string; anchor: 'stored_span' | 'located' | 'chunk_only'; span?: { byte_start: number; byte_end: number } }> {+ const rows = await ctx.engine.executeRaw<{ chunk_text: string; chunk_source: string; projected_byte_start: unknown; projected_byte_end: unknown }>(+ `SELECT chunk_text, chunk_source, projected_byte_start, projected_byte_end FROM content_chunks+ WHERE id = $1 AND page_id = $2 AND COALESCE(modality, 'text') = 'text'`, [chunkId, page.id]);+ const row = rows[0];+ if (!row) {+ throw opError('revision_changed', `Chunk ${chunkId} is not part of page ${page.slug} at its current revision.`,+ "The page was re-chunked or edited since that search. Search again for a current chunk_id, or read the page's outline.",+ { legacy_error: 'invalid_params', detail: JSON.stringify({ revision, chunk_id: chunkId }),+ fix: sizeFix(page.slug, page.source_id, "Returns the current revision and outline; search again for a current chunk_id.") });+ }+ const chunk = { chunk_source: row.chunk_source,+ projected_byte_start: row.projected_byte_start == null ? null : Number(row.projected_byte_start),+ projected_byte_end: row.projected_byte_end == null ? null : Number(row.projected_byte_end) };+ const stored = chunkDocumentSpan(doc, chunk);+ if (stored && spanHoldsChunk(doc, stored, row.chunk_text)) {+ return { window: windowAround(doc.bytes, stored, contextLines, maxBytes), chunkText: row.chunk_text, anchor: 'stored_span', span: { byte_start: stored.start, byte_end: stored.end } };+ }+ // No stored span (a chunk written before spans were recorded) or a stale one: accept a text match only when it is unique.+ const needle = Buffer.from(row.chunk_text.trim(), 'utf8');+ if (needle.length >= 16) {+ const at = doc.bytes.indexOf(needle);+ if (at !== -1 && doc.bytes.indexOf(needle, at + 1) === -1) {+ const span = { start: at, end: at + needle.length };+ return { window: windowAround(doc.bytes, span, contextLines, maxBytes), chunkText: row.chunk_text, anchor: 'located', span: { byte_start: span.start, byte_end: span.end } };+ }+ }+ return { window: null, chunkText: row.chunk_text, anchor: 'chunk_only' };+}++/**+ * The partial (none / outline / window / auto-above-threshold) response. Never+ * carries compiled_truth, timeline or content.+ */+export async function readPartialBody(ctx: OperationContext, input: PartialReadInput, req: BodyRequest): Promise<Record<string, unknown>> {+ const { page, revision, tags, quarantined, trust, extras } = input;+ const base: Record<string, unknown> = {+ slug: page.slug, source_id: page.source_id, type: page.type, title: page.title, revision, tags,+ frontmatter: page.frontmatter ?? {}, ...(page.deleted_at ? { deleted_at: page.deleted_at } : {}),+ ...(trust ?? {}), ...extras,+ };+ const omitted = quarantined?.body_omitted === true;+ const mode = req.mode === 'auto' ? 'outline' : req.mode;+ if (omitted) return { ...base, body: mode, truncated: true, body_omitted: true };++ const markdown = req.view === 'markdown';+ const doc: PageDocument = markdown+ ? { bytes: Buffer.from(serializePageToMarkdown(input.visibleBody, tags), 'utf8'), timelineByte: -1 }+ : await readPageDocument(ctx.engine, page);+ const size: Record<string, unknown> = {+ total_bytes: doc.bytes.length, total_lines: totalLines(doc.bytes),+ ...(doc.timelineByte >= 0 ? { timeline_byte_start: doc.timelineByte } : {}),+ ...(markdown ? { sha256: sha256Hex(doc.bytes) } : {}),+ };+ const out: Record<string, unknown> = { ...base, body: mode, view: req.view, size };++ if (mode === 'none') {+ const [counts] = await ctx.engine.executeRaw<{ total: unknown; embedded: unknown }>(+ `SELECT count(*) AS total, count(*) FILTER (WHERE embedded_at IS NOT NULL) AS embedded FROM content_chunks WHERE page_id = $1`, [page.id]);+ const fm = (page.frontmatter ?? {}) as Record<string, unknown>;+ return { ...out, chunks: { total: Number(counts?.total ?? 0), embedded: Number(counts?.embedded ?? 0) },+ ...(fm.embed_skip ? { embed_skip: true } : {}), truncated: doc.bytes.length > 0 };+ }++ if (mode === 'outline') {+ const limit = Math.min(MAX_OUTLINE_LIMIT, DEFAULT_OUTLINE_LIMIT);+ out.outline = pageOutline(doc.bytes, req.outlineFrom, limit);+ if (req.mode === 'auto') {+ const first = windowFrom(doc.bytes, 0, await windowBudget(ctx, req.maxBytes, AUTO_WINDOW_BYTES));+ out.window = { ...first, text: envelopeText(first.text, quarantined, trust) };+ out.truncated = true;+ if (first.byte_end < doc.bytes.length) out.next_cursor = encodeCursor({ page_id: page.id, revision, view: 'read', offset: first.byte_end, max_bytes: req.maxBytes ?? DEFAULT_WINDOW_BYTES });+ out.auto_reason = 'over_inline_bytes';+ return out;+ }+ return { ...out, truncated: true };+ }++ // window+ const maxBytes = await windowBudget(ctx, req.maxBytes, DEFAULT_WINDOW_BYTES);+ 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.…' });+ }+ 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;+ }+ 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/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 06921045ee..8fba212896 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -17,6 +17,7 @@ import { decodeDeepResearchId, deepResearchPageUrl } from '../deep-research-id.timport { PageSnapshotAmbiguousError, type PageSnapshot } from '../page-state/types.ts';import { serializePageToMarkdown } from '../markdown.ts';import { pageTrustForRead, projectFetchText, projectGetPage, readQuarantined } from './get-page-projection.ts';+import { assertFullReadFits, bodyBytes, GET_PAGE_BODY_PARAMS, inlineBodyBytes, parseBodyRequest, readPartialBody } from './get-page-body.ts';import { MIN_TRUST_PARAM } from '../eligibility/policy.ts';import { stampRowTrust } from '../eligibility/stamp.ts';import { isAutoLinkEnabled } from '../link-extraction.ts';@@ -84,12 +85,13 @@ const get_page: Operation = {name: 'get_page',idempotent: true,outputRedaction: { exempt: 'explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)' },- description: 'Read a page by slug. To edit, pass include_content:true and send `content` to put_page, or use edit_page.',+ description: "Read a page by slug. Pages over 256 KB come back as an outline plus a first window, never a partial body in compiled_truth/content: read on with body: 'window' (lines, bytes, around_chunk_id from a search hit, or next_cursor). body: 'none' returns just the revision and size for edit_page/put_page. Whole markdown for a round trip: include_content:true (refused when the page does not fit this connection).",params: {slug: { type: 'string', description: 'Page slug.', required: true },fuzzy: { type: 'boolean', description: 'Fuzzy slug match.' },- include_content: { type: 'boolean', description: 'Full markdown + revision, for editing.' },- content_only: { type: 'boolean', description: 'Round-trip fields only.' },+ include_content: { type: 'boolean', description: "Full markdown + revision (body: 'full')." },+ content_only: { type: 'boolean', description: 'Round-trip fields only (implies include_content).' },+ ...GET_PAGE_BODY_PARAMS,include_deleted: { type: 'boolean', description: 'Include soft-deleted pages.' },include_timeline_entries: { type: 'boolean', description: 'Also return timeline rows.' },grammar_diagnostics: { type: 'boolean', description: 'Also return every line-grammar finding for the page.', fullSurfaceOnly: true },@@ -101,7 +103,10 @@ const get_page: Operation = {const slug = p.slug as string;const fuzzy = (p.fuzzy as boolean) || false;const includeDeleted = (p.include_deleted as boolean) === true;- const includeContent = (p.include_content as boolean) === true;+ // Large pages: resolve the body mode first, so a malformed selector fails before any read.+ const bodyRequest = parseBodyRequest(ctx, p);+ const contentOnly = p.content_only === true;+ const includeContent = p.include_content === true || contentOnly;const includeTimelineEntries = (p.include_timeline_entries as boolean) === true;// #4329: honor a per-call source_id (pre-fix it was silently dropped).// resolveRequestedScope (inside federatedSearchScope) enforces the remote@@ -212,11 +217,21 @@ const get_page: Operation = {// Read-only, over the same visibility-filtered body the reader gets.const lineGrammar = p.grammar_diagnostics === true ? await (await import('../line-grammar-report.ts')).lineGrammarReport(ctx.engine, { slug: page.slug, sourceId: page.source_id, body: visibleBody.compiled_truth }) : undefined;const quarantined = readQuarantined(ctx, page, p.include_quarantined === true); // #6259+ const fileHeld = held ? { file_held: fileHeldField(held, isUntrustedReader) } : {};+ const whole = bodyRequest.mode === 'full'+ || (bodyRequest.mode === 'auto' && bodyBytes(visibleBody) <= await inlineBodyBytes(ctx));+ if (!whole) {+ const partial = await readPartialBody(ctx, { page, visibleBody, revision: snapshot!.revision, tags, quarantined, trust: readable.trust,+ extras: { ...(quarantined ? { quarantined } : {}), ...(timelineEntries ? { timeline_entries: timelineEntries } : {}), ...fileHeld,+ ...(resolved_slug ? { resolved_slug } : {}), ...(content_flag ? { content_flag } : {}) } }, bodyRequest);+ return lineGrammar ? { ...partial, line_grammar: lineGrammar } : partial;+ }const projected = projectGetPage(visibleBody, {- revision: snapshot!.revision, tags, includeContent, contentOnly: (p.content_only as boolean) === true, resolved_slug, content_flag, quarantined, trust: readable.trust,+ revision: snapshot!.revision, tags, includeContent, contentOnly, resolved_slug, content_flag, quarantined, trust: readable.trust,...(timelineEntries ? { timeline_entries: timelineEntries } : {}),- ...(held ? { file_held: fileHeldField(held, isUntrustedReader) } : {}),+ ...fileHeld,});+ if (ctx.remote !== false) await assertFullReadFits(ctx, visibleBody, projected, bodyRequest);return lineGrammar ? { ...projected, line_grammar: lineGrammar } : projected;},scope: 'read', mutating: false,diff --git a/src/core/page-window/window.ts b/src/core/page-window/window.tsnew file mode 100644index 0000000000..458210efb6--- /dev/null+++ b/src/core/page-window/window.ts@@ -0,0 +1,359 @@+/**+ * Large pages (Wave A read contract): windows, outlines and cursors over one+ * PageDocument (document.ts). Every offset is a UTF-8 byte offset into the+ * document's bytes; every cut lands on a code point, and on a line start+ * whenever the selected range holds one ("forced" cuts are reported). A+ * window is bounded by bytes whatever the selector, so a page that is one+ * long line still pages.+ */+import { createHash } from 'node:crypto';++/**+ * Default window size: about 10k tokens of English (four bytes a token), which+ * leaves room under Claude Code's 25k-token tool-result cap for the metadata,+ * notices and JSON escaping around it.+ */+export const DEFAULT_WINDOW_BYTES = 40_000;+/** Largest window one call may ask for; the connection's egress cap may lower it. */+export const MAX_WINDOW_BYTES = 1024 * 1024;+export const DEFAULT_CONTEXT_LINES = 20;+export const MAX_CONTEXT_LINES = 2000;+export const DEFAULT_OUTLINE_LIMIT = 100;+export const MAX_OUTLINE_LIMIT = 500;+/** Outline block size for pages without headings (conversation logs). */+export const OUTLINE_BLOCK_BYTES = 64 * 1024;+const HEADING_MAX_CHARS = 200;+const FIRST_LINE_MAX_CHARS = 120;++const NL = 0x0a;++export interface WindowSlice {+ text: string;+ byte_start: number;+ byte_end: number;+ /** 1-based line of byte_start, and of the window's last byte (equal to line_start for an empty window). */+ line_start: number;+ line_end: number;+ /** The window ends mid-line because the line alone is longer than the window. */+ forced_cut?: true;+}++function snapCodePoint(buf: Buffer, b: number): number {+ let i = Math.max(0, Math.min(b, buf.length));+ while (i > 0 && i < buf.length && (buf[i] & 0xc0) === 0x80) i--;+ return i;+}++function nextCodePoint(buf: Buffer, b: number): number {+ let i = Math.min(buf.length, b + 1);+ while (i < buf.length && (buf[i] & 0xc0) === 0x80) i++;+ return i;+}++/** Start of the line holding byte `b` (0 for the first line). */+export function lineStartOf(buf: Buffer, b: number): number {+ if (b <= 0) return 0;+ const nl = buf.lastIndexOf(NL, Math.min(b, buf.length) - 1);+ return nl + 1;+}++/** 1-based line number of byte `b`. */+export function lineNumberAt(buf: Buffer, b: number): number {+ let n = 1;+ let i = buf.indexOf(NL, 0);+ while (i !== -1 && i < b) { n++; i = buf.indexOf(NL, i + 1); }+ return n;+}++export function totalLines(buf: Buffer): number {+ if (buf.length === 0) return 0;+ let n = 0;+ let i = buf.indexOf(NL, 0);+ while (i !== -1) { n++; i = buf.indexOf(NL, i + 1); }+ return buf[buf.length - 1] === NL ? n : n + 1;+}++/** Byte offset where 1-based line `line` starts; buf.length past the last line. */+export function lineOffset(buf: Buffer, line: number): number {+ let at = 0;+ for (let n = 1; n < line; n++) {+ const nl = buf.indexOf(NL, at);+ if (nl === -1) return buf.length;+ at = nl + 1;+ }+ return at;+}++/**+ * Where a window starting at `start` ends when it may grow to `maxEnd`: the+ * last line start inside (start, maxEnd], else a code point boundary (a forced+ * cut), never before `minEnd`.+ */+function windowEnd(buf: Buffer, start: number, maxEnd: number, minEnd = start + 1): { end: number; forced: boolean } {+ if (maxEnd >= buf.length) return { end: buf.length, forced: false };+ const floor = Math.min(buf.length, Math.max(minEnd, start + 1));+ const atLine = lineStartOf(buf, maxEnd);+ if (atLine >= floor && atLine > start) return { end: atLine, forced: false };+ let end = snapCodePoint(buf, maxEnd);+ if (end < floor) end = snapCodePoint(buf, floor) < floor ? nextCodePoint(buf, snapCodePoint(buf, floor)) : floor;+ return { end: Math.min(end, buf.length), forced: true };+}++export function sliceWindow(buf: Buffer, start: number, end: number, forced = false): WindowSlice {+ const lineStart = lineNumberAt(buf, start);+ let lineEnd = lineStart;+ if (end > start) {+ let i = buf.indexOf(NL, start);+ while (i !== -1 && i < end - 1) { lineEnd++; i = buf.indexOf(NL, i + 1); }+ }+ return {+ text: buf.subarray(start, end).toString('utf8'),+ byte_start: start, byte_end: end, line_start: lineStart, line_end: lineEnd,+ ...(forced ? { forced_cut: true as const } : {}),+ };+}++/** A window from a clean boundary (a cursor position or the document start). */+export function windowFrom(buf: Buffer, offset: number, maxBytes: number): WindowSlice {+ const start = snapCodePoint(buf, offset);+ if (start >= buf.length) return sliceWindow(buf, buf.length, buf.length);+ const { end, forced } = windowEnd(buf, start, start + maxBytes);+ return sliceWindow(buf, start, end, forced);+}++/** `lines: { from, count }` (1-based), bounded by maxBytes. */+export function windowForLines(buf: Buffer, from: number, count: number, maxBytes: number): WindowSlice {+ const start = lineOffset(buf, from);+ if (start >= buf.length) return sliceWindow(buf, buf.length, buf.length);+ const target = lineOffset(buf, from + count);+ if (target - start <= maxBytes) return sliceWindow(buf, start, target);+ const { end, forced } = windowEnd(buf, start, start + maxBytes);+ return sliceWindow(buf, start, end, forced);+}++/**+ * `bytes: { offset, length }`: the start moves back to its line start when+ * that is within `length` bytes (else to a code point), the end to the last+ * line start in range (else a code point).+ */+export function windowForBytes(buf: Buffer, offset: number, length: number): WindowSlice {+ const at = Math.max(0, Math.min(offset, buf.length));+ if (at >= buf.length) return sliceWindow(buf, buf.length, buf.length);+ const ls = lineStartOf(buf, at);+ const start = at - ls <= length ? ls : snapCodePoint(buf, at);+ const { end, forced } = windowEnd(buf, start, start + length);+ return sliceWindow(buf, start, end, forced);+}++/**+ * A window around `span` (a chunk's position): the span's lines plus+ * `contextLines` lines on each side, cut to maxBytes around the span. A span+ * longer than maxBytes yields its first maxBytes.+ */+export function windowAround(buf: Buffer, span: { start: number; end: number }, contextLines: number, maxBytes: number): WindowSlice {+ const cs = Math.max(0, Math.min(span.start, buf.length));+ const ce = Math.max(cs, Math.min(span.end, buf.length));+ let ws = lineStartOf(buf, cs);+ for (let k = 0; k < contextLines && ws > 0; k++) ws = lineStartOf(buf, ws - 1);+ let we = ce;+ if (we < buf.length && (we === cs || buf[we - 1] !== NL)) {+ const nl = buf.indexOf(NL, Math.max(cs, ce - 1));+ we = nl === -1 ? buf.length : nl + 1;+ }+ for (let k = 0; k < contextLines && we < buf.length; k++) {+ const nl = buf.indexOf(NL, we);+ we = nl === -1 ? buf.length : nl + 1;+ }+ if (we - ws <= maxBytes) return sliceWindow(buf, ws, we);+ if (ce - cs >= maxBytes) {+ const ls = lineStartOf(buf, cs);+ const start = cs - ls <= maxBytes / 4 ? ls : snapCodePoint(buf, cs);+ const { end, forced } = windowEnd(buf, start, start + maxBytes);+ return sliceWindow(buf, start, end, forced);+ }+ const before = Math.floor((maxBytes - (ce - cs)) / 2);+ let start = Math.max(ws, snapCodePoint(buf, cs - before));+ if (start > 0) {+ const nl = buf.indexOf(NL, start - 1);+ if (nl !== -1 && nl + 1 <= cs) start = nl + 1;+ }+ const { end, forced } = windowEnd(buf, start, Math.min(we, start + maxBytes), ce);+ return sliceWindow(buf, start, end, forced);+}++// ---------------------------------------------------------------------------+// Outline+// ---------------------------------------------------------------------------++export interface OutlineEntry {+ /** ATX heading text (headings outline), null for the text before the first heading. */+ heading?: string | null;+ level?: number;+ /** First non-empty line of a block (blocks outline: pages with fewer than two headings). */+ first_line?: string;+ line_start: number;+ line_end: number;+ byte_start: number;+ byte_end: number;+ /** Earliest and latest YYYY-MM-DD date written in the entry's text. */+ date_min?: string;+ date_max?: string;+}++export interface PageOutline {+ kind: 'headings' | 'blocks';+ entries: OutlineEntry[];+ total_entries: number;+ from_index: number;+ /** Pass as outline_from to read the next entries; absent on the last page. */+ next_from_index?: number;+}++const HEADING = /^ {0,3}(#{1,6})[ \t]+(.*?)[ \t]*#*[ \t]*$/;+const FENCE = /^ {0,3}(```|~~~)/;+const DATE = /\b((?:19|20)\d{2})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])\b/g;++function clip(text: string, max: number): string {+ if (text.length <= max) return text;+ let cut = max;+ const c = text.charCodeAt(cut - 1);+ if (c >= 0xd800 && c <= 0xdbff) cut--;+ return `${text.slice(0, cut)}…`;+}++/**+ * The page outline, paged by entry index. Headings (outside code fences) when+ * the page has at least two; otherwise line-aligned blocks of about+ * OUTLINE_BLOCK_BYTES, each with its first line. Entries carry the line and+ * byte range to pass to a window read, and the date range written inside.+ * Built from the projected document only, so it can name nothing a window+ * could not show.+ */+export function pageOutline(buf: Buffer, from = 0, limit = DEFAULT_OUTLINE_LIMIT): PageOutline {+ const headings: Array<{ start: number; n: number; level: number; text: string }> = [];+ let inFence = false;+ let at = 0;+ let n = 1;+ while (at < buf.length) {+ const nl = buf.indexOf(NL, at);+ const end = nl === -1 ? buf.length : nl + 1;+ // Only a line whose first non-space byte is '#', '`' or '~' can open a heading or a fence.+ let k = at;+ while (k < end && k - at < 3 && buf[k] === 0x20) k++;+ const lead = buf[k];+ if (lead === 0x23 || lead === 0x60 || lead === 0x7e) {+ const text = buf.subarray(at, nl === -1 ? end : nl).toString('utf8');+ if (FENCE.test(text)) inFence = !inFence;+ else if (!inFence) {+ const h = HEADING.exec(text);+ if (h) headings.push({ start: at, n, level: h[1].length, text: clip(h[2], HEADING_MAX_CHARS) });+ }+ }+ at = end;+ n++;+ }+ const lines = totalLines(buf);+ const bounds: Array<{ start: number; end: number; heading?: string | null; level?: number }> = [];+ let kind: PageOutline['kind'] = 'headings';+ if (headings.length >= 2) {+ if (headings[0].start > 0 && buf.subarray(0, headings[0].start).toString('utf8').trim()) {+ bounds.push({ start: 0, end: headings[0].start, heading: null });+ }+ headings.forEach((h, i) => bounds.push({ start: h.start, end: headings[i + 1]?.start ?? buf.length, heading: h.text, level: h.level }));+ } else {+ kind = 'blocks';+ let pos = 0;+ while (pos < buf.length) {+ const { end } = windowEnd(buf, pos, pos + OUTLINE_BLOCK_BYTES);+ bounds.push({ start: pos, end });+ pos = end;+ }+ }+ const total = bounds.length;+ const entries: OutlineEntry[] = [];+ // Line numbers accumulate across bounds in one pass over the newlines.+ let line = 1;+ let counted = 0;+ const lineAt = (b: number) => {+ let i = buf.indexOf(NL, counted);+ while (i !== -1 && i < b) { line++; i = buf.indexOf(NL, i + 1); }+ counted = b;+ return line;+ };+ for (let i = 0; i < Math.min(total, from + limit); i++) {+ const bound = bounds[i];+ const lineStart = lineAt(bound.start);+ if (i < from) continue;+ const text = buf.subarray(bound.start, bound.end).toString('utf8');+ let min: string | undefined;+ let max: string | undefined;+ for (const m of text.matchAll(DATE)) {+ if (!min || m[0] < min) min = m[0];+ if (!max || m[0] > max) max = m[0];+ }+ let lineEnd = lineStart;+ for (let j = text.indexOf('\n'); j !== -1 && j < text.length - 1; j = text.indexOf('\n', j + 1)) lineEnd++;+ entries.push({+ ...(kind === 'headings' ? { heading: bound.heading ?? null, ...(bound.level ? { level: bound.level } : {}) } : {}),+ ...(kind === 'blocks' ? { first_line: clip(firstLine(text), FIRST_LINE_MAX_CHARS) } : {}),+ line_start: lineStart, line_end: Math.min(lineEnd, lines), byte_start: bound.start, byte_end: bound.end,+ ...(min ? { date_min: min, date_max: max } : {}),+ });+ }+ return { kind, entries, total_entries: total, from_index: from, ...(from + entries.length < total ? { next_from_index: from + entries.length } : {}) };+}++function firstLine(text: string): string {+ let at = 0;+ while (at < text.length) {+ const nl = text.indexOf('\n', at);+ const line = text.slice(at, nl === -1 ? text.length : nl).trim();+ if (line) return line;+ if (nl === -1) break;+ at = nl + 1;+ }+ return '';+}++// ---------------------------------------------------------------------------+// Cursors+// ---------------------------------------------------------------------------++/** Which text a window slices: the read projection, or the canonical round-trip markdown (`content`). */+export type WindowView = 'read' | 'markdown';++export interface WindowCursor {+ /** Page id and revision the position belongs to. */+ page_id: number;+ revision: string;+ view: WindowView;+ offset: number;+ max_bytes: number;+}++const CURSOR_PREFIX = 'gpw1.';++/** Opaque, revision-bound continuation token. Not a credential: it names a position and grants nothing. */+export function encodeCursor(c: WindowCursor): string {+ return CURSOR_PREFIX + Buffer.from(JSON.stringify([c.page_id, c.revision, c.view, c.offset, c.max_bytes]), 'utf8').toString('base64url');+}++export function decodeCursor(raw: string): WindowCursor | null {+ if (typeof raw !== 'string' || !raw.startsWith(CURSOR_PREFIX)) return null;+ const payload = raw.slice(CURSOR_PREFIX.length);+ if (!/^[A-Za-z0-9_-]+$/.test(payload)) return null;+ try {+ const v: unknown = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ if (!Array.isArray(v) || v.length !== 5) return null;+ const [page_id, revision, view, offset, max_bytes] = v;+ if (!Number.isSafeInteger(page_id) || typeof revision !== 'string' || (view !== 'read' && view !== 'markdown')+ || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(max_bytes) || max_bytes <= 0) return null;+ return { page_id, revision, view, offset, max_bytes };+ } catch {+ return null;+ }+}++export function sha256Hex(buf: Buffer): string {+ return createHash('sha256').update(buf).digest('hex');+}diff --git a/test/get-page-body-modes.test.ts b/test/get-page-body-modes.test.tsnew file mode 100644index 0000000000..b50d0caf3a--- /dev/null+++ b/test/get-page-body-modes.test.ts@@ -0,0 +1,317 @@+/**+ * Large pages (Wave A read contract): get_page body modes, selectors, cursors+ * and the privacy boundary of windowed reads.+ *+ * Every partial read is a slice of the read projection (withdrawal-overlaid,+ * fence-overlaid, sanitized, credential-projected); it never carries+ * compiled_truth / timeline / content. Hermetic in-memory PGLite.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { createHash } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, OperationError, type OperationContext } from '../src/core/operations.ts';+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 { normalizeLoweredClaim } from '../src/core/facts/withdrawal-schema.ts';++let engine: PGLiteEngine;+const get_page = operations.find(o => o.name === 'get_page')!;++function ctx(overrides: Partial<OperationContext> = {}): OperationContext {+ return { engine: engine as any, config: {} as any, logger: { info() {}, warn() {}, error() {} } as any, dryRun: false,+ remote: true, transport: 'stdio', sourceId: 'default', ...overrides } as OperationContext;+}+const local = () => ctx({ remote: false, transport: undefined });++async function put(slug: string, body: string, timeline = '', frontmatter: Record<string, unknown> = {}) {+ const r = await importFromContent(engine, slug, serializeMarkdown(frontmatter, body, timeline, { type: 'note', title: slug, tags: [] }),+ { sourceId: 'default', noEmbed: true, forceRechunk: true });+ expect(r.status).toBe('imported');+}++async function get(c: OperationContext, params: Record<string, unknown>): Promise<Record<string, any>> {+ return await get_page.handler(c, params) as Record<string, any>;+}++async function projection(slug: string): Promise<Buffer> {+ const snap = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ return pageDocument({ compiled_truth: snap!.page.compiled_truth, timeline: snap!.page.timeline }).bytes;+}++async function expectCode(p: Promise<unknown>, code: string): Promise<OperationError> {+ try { await p; } catch (e) {+ expect(e).toBeInstanceOf(OperationError);+ const err = e as OperationError;+ expect((err as any).canonical ?? err.code).toBe(code);+ return err;+ }+ throw new Error(`expected ${code}`);+}++/** A conversation log: dated lines, many repeated, well past the 256 KB inline size. */+function conversation(lines: number): string {+ const out: string[] = ['# Log with acme-example', ''];+ for (let i = 0; i < lines; i++) {+ const day = String(1 + (i % 28)).padStart(2, '0');+ out.push(i % 7 === 0 ? `**alice-example:** ok sounds good` : `**bob-example:** 2026-03-${day} line ${i} about the widget plan, needle-${i}`);+ }+ return out.join('\n');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await put('notes/small', 'A small page about acme-example.');+ await put('logs/big', conversation(9000));+ await put('logs/mid', conversation(6000));+}, 120_000);++afterAll(async () => { await engine.disconnect(); }, 60_000);++describe('mode resolution', () => {+ test('a small page under auto keeps the full shape', async () => {+ const r = await get(ctx(), { slug: 'notes/small' });+ expect(r.compiled_truth).toContain('A small page');+ expect(r.window).toBeUndefined();+ });++ test('a page over the inline size under auto is an outline plus a first window, never a body field', async () => {+ const r = await get(ctx(), { slug: 'logs/big' });+ expect(r.compiled_truth).toBeUndefined();+ expect(r.timeline).toBeUndefined();+ expect(r.content).toBeUndefined();+ expect(r.body).toBe('outline');+ expect(r.truncated).toBe(true);+ expect(r.size.total_bytes).toBe((await projection('logs/big')).length);+ expect(r.size.total_lines).toBeGreaterThan(9000);+ expect(r.window.byte_start).toBe(0);+ expect(r.window.text.length).toBeGreaterThan(0);+ expect(typeof r.next_cursor).toBe('string');+ expect(r.outline.entries.length).toBeGreaterThan(0);+ });++ test('trusted local reads and include_content stay whole', async () => {+ const r = await get(local(), { slug: 'logs/big' });+ expect(typeof r.compiled_truth).toBe('string');+ const c = await get(ctx(), { slug: 'logs/big', include_content: true });+ expect(typeof c.content).toBe('string');+ const only = await get(ctx(), { slug: 'logs/big', content_only: true });+ expect(typeof only.content).toBe('string');+ expect(only.compiled_truth).toBeUndefined();+ });++ test("gbrain's thin client naming no mode gets the whole page", async () => {+ const r = await get(ctx({ thinClient: true, transport: 'http' }), { slug: 'logs/big' });+ expect(typeof r.compiled_truth).toBe('string');+ });++ test('body none returns revision, size and chunk counts without text', async () => {+ const r = await get(ctx(), { slug: 'logs/mid', body: 'none' });+ expect(typeof r.revision).toBe('string');+ expect(r.window).toBeUndefined();+ expect(r.compiled_truth).toBeUndefined();+ expect(r.chunks.total).toBeGreaterThan(10);+ expect(r.size.total_bytes).toBeGreaterThan(256 * 1024);+ });++ test('conflicting selectors and modes are invalid_params', async () => {+ await expectCode(get(ctx(), { slug: 'logs/big', lines: { from: 1, count: 5 }, bytes: { offset: 0, length: 10 } }), 'invalid_params');+ await expectCode(get(ctx(), { slug: 'logs/big', body: 'outline', lines: { from: 1, count: 5 } }), 'invalid_params');+ await expectCode(get(ctx(), { slug: 'logs/big', body: 'window', include_content: true }), 'invalid_params');+ await expectCode(get(ctx(), { slug: 'logs/big', lines: { from: 0, count: 5 } }), 'invalid_params');+ await expectCode(get(ctx(), { slug: 'logs/big', body: 'everything' }), 'invalid_params');+ });+});++describe('windows', () => {+ test('cursor paging covers the projection exactly, in order, line-aligned', async () => {+ const doc = await projection('logs/big');+ const parts: Buffer[] = [];+ let r = await get(ctx(), { slug: 'logs/big', body: 'window', max_bytes: 30_000 });+ for (let i = 0; i < 1000; i++) {+ parts.push(Buffer.from(r.window.text, 'utf8'));+ expect(Buffer.byteLength(r.window.text)).toBeLessThanOrEqual(30_000);+ if (r.window.byte_end < doc.length) expect(doc[r.window.byte_end - 1]).toBe(0x0a);+ if (!r.next_cursor) break;+ r = await get(ctx(), { slug: 'logs/big', cursor: r.next_cursor });+ }+ expect(Buffer.concat(parts).equals(doc)).toBe(true);+ });++ test('lines and bytes selectors snap to line starts', async () => {+ const doc = await projection('logs/big');+ const r = await get(ctx(), { slug: 'logs/big', lines: { from: 100, count: 3 } });+ expect(r.window.line_start).toBe(100);+ expect(r.window.line_end).toBe(102);+ expect(r.window.text.split('\n').filter(Boolean)).toHaveLength(3);+ const b = await get(ctx(), { slug: 'logs/big', bytes: { offset: 5003, length: 2000 } });+ expect(b.window.byte_start).toBeLessThanOrEqual(5003);+ expect(b.window.byte_start === 0 || doc[b.window.byte_start - 1] === 0x0a).toBe(true);+ expect(b.window.text).toBe(doc.subarray(b.window.byte_start, b.window.byte_end).toString('utf8'));+ });++ test('a stale cursor is revision_changed with the same offset in its fix', async () => {+ await put('logs/moving', conversation(6000));+ const r = await get(ctx(), { slug: 'logs/moving', body: 'window' });+ const offset = decodeCursor(r.next_cursor)!.offset;+ await put('logs/moving', conversation(6001));+ const err = await expectCode(get(ctx(), { slug: 'logs/moving', cursor: r.next_cursor }), 'revision_changed');+ expect(JSON.stringify(err.fix?.mcp?.arguments)).toContain(`"offset":${offset}`);+ });++ test('a cursor for another page is invalid_params', async () => {+ const r = await get(ctx(), { slug: 'logs/big', body: 'window' });+ await put('logs/other', conversation(6000));+ await expectCode(get(ctx(), { slug: 'logs/other', cursor: r.next_cursor }), 'invalid_params');+ });++ test('a long single line pages with forced cuts on code points', async () => {+ await put('blobs/one-line', '😀é'.repeat(200_000));+ const r = await get(ctx(), { slug: 'blobs/one-line', body: 'window', max_bytes: 1001 });+ expect(r.window.forced_cut).toBe(true);+ expect(r.window.text).not.toContain('\uFFFD');+ expect(Buffer.byteLength(r.window.text)).toBeLessThanOrEqual(1001);+ });++ test('view markdown pages the round-trip content and its sha256 verifies the whole', async () => {+ const whole = (await get(ctx(), { slug: 'logs/big', include_content: true })).content as string;+ const parts: string[] = [];+ let r = await get(ctx(), { slug: 'logs/big', body: 'window', view: 'markdown', bytes: { offset: 0, length: 200_000 } });+ const sha = r.size.sha256;+ for (let i = 0; i < 100; i++) {+ expect(r.content).toBeUndefined();+ parts.push(r.window.text);+ if (!r.next_cursor) break;+ r = await get(ctx(), { slug: 'logs/big', body: 'window', view: 'markdown', cursor: r.next_cursor });+ }+ expect(parts.join('')).toBe(whole);+ expect(createHash('sha256').update(parts.join(''), 'utf8').digest('hex')).toBe(sha);+ });+});++describe('around_chunk_id', () => {+ test('centers on the exact stored span, even on repeated text', async () => {+ const para = 'the same message repeated in this conversation again and again. '.repeat(30);+ await put('logs/repeats', Array.from({ length: 190 }, () => para).join('\n\n'));+ const chunks = await engine.getChunks('logs/repeats', { sourceId: 'default' } as any);+ expect(chunks.length).toBeGreaterThan(20);+ const doc = await projection('logs/repeats');+ const target = chunks[Math.floor(chunks.length * 0.9)];+ expect(typeof target.projected_byte_start).toBe('number');+ const r = await get(ctx(), { slug: 'logs/repeats', around_chunk_id: target.id, context_lines: 0 });+ expect(r.anchor).toBe('stored_span');+ expect(r.chunk_span.byte_start).toBe(target.projected_byte_start);+ expect(r.window.byte_start).toBeLessThanOrEqual(target.projected_byte_start!);+ expect(r.window.byte_end).toBeGreaterThanOrEqual(target.projected_byte_end!);+ expect(r.window.byte_start).toBeGreaterThan(doc.length * 0.8);+ });++ 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');+ const target = chunks[chunks.length - 1];+ const r = await get(ctx(), { slug: 'logs/with-timeline', around_chunk_id: target.id, max_bytes: 4000 });+ expect(r.anchor).toBe('stored_span');+ expect(r.chunk_span.byte_start).toBeGreaterThanOrEqual(r.size.timeline_byte_start);+ expect(r.window.text.replace(/\s+/g, '')).toContain(target.chunk_text.replace(/\s+/g, '').slice(0, 200));+ });++ test('a chunk id that is not on the page is revision_changed', async () => {+ const other = (await engine.getChunks('notes/small', { sourceId: 'default' } as any))[0];+ await expectCode(get(ctx(), { slug: 'logs/big', around_chunk_id: other.id }), 'revision_changed');+ await expectCode(get(ctx(), { slug: 'logs/big', around_chunk_id: 987654321 }), 'revision_changed');+ });++ test('a chunk without a span and with ambiguous text returns only the chunk itself', async () => {+ const para = 'identical paragraph text for the ambiguity case, repeated verbatim. '.repeat(30);+ await put('logs/legacy', Array.from({ length: 200 }, () => para).join('\n\n'));+ await engine.executeRaw(`UPDATE content_chunks SET projected_byte_start = NULL, projected_byte_end = NULL+ WHERE page_id = (SELECT id FROM pages WHERE slug = 'logs/legacy')`);+ const chunk = (await engine.getChunks('logs/legacy', { sourceId: 'default' } as any))[5];+ const r = await get(ctx(), { slug: 'logs/legacy', around_chunk_id: chunk.id });+ expect(r.anchor).toBe('chunk_only');+ expect(r.window.text).toBe(chunk.chunk_text);+ expect(r.window.byte_start).toBeUndefined();+ expect(r.next_cursor).toBeUndefined();+ });+});++describe('privacy boundary (remote windows are slices of the sanitized projection)', () => {+ const PRIVATE = 'PRIVATE-TAKE-SECRET-alice-example';+ const filler = (n: number) => Array.from({ length: n }, (_, i) => `public line ${i} about acme-example widgets and plans`).join('\n');+ const takes = `## Takes\n\n<!--- gbrain:takes:begin -->\n| # | claim | kind | who | weight | since | source |\n|---|-------|------|-----|--------|-------|--------|\n${Array.from({ length: 50 }, (_, i) => `| ${i + 1} | ${PRIVATE} ${i} | take | alice-example | 0.8 | 2026-04 | note |`).join('\n')}\n<!--- gbrain:takes:end -->`;++ test('a window whose raw offset starts inside a balanced takes fence holds no take', async () => {+ const body = `${filler(4000)}\n\n## Hidden heading in prose\n\n${takes}\n\n${filler(4000)}`;+ await put('people/fenced', body);+ const snap = await engine.readPageSnapshot('people/fenced', { sourceId: 'default' });+ const rawOffset = Buffer.byteLength(snap!.page.compiled_truth.slice(0, snap!.page.compiled_truth.indexOf(PRIVATE)), 'utf8');+ const doc = await projection('people/fenced');+ expect(doc.toString('utf8')).not.toContain(PRIVATE);+ for (const sel of [{ bytes: { offset: rawOffset, length: 20_000 } }, { bytes: { offset: Math.max(0, rawOffset - 50), length: 400_000 } }, { lines: { from: 4005, count: 200 } }]) {+ const r = await get(ctx(), { slug: 'people/fenced', ...sel });+ expect(r.window.text).not.toContain(PRIVATE);+ expect(r.window.text).not.toContain('gbrain:takes');+ }+ let r = await get(ctx(), { slug: 'people/fenced', body: 'window', max_bytes: 50_000 });+ for (let i = 0; i < 100 && r; i++) {+ expect(r.window.text).not.toContain(PRIVATE);+ r = r.next_cursor ? await get(ctx(), { slug: 'people/fenced', cursor: r.next_cursor }) : null as any;+ }+ });++ test('a malformed (unterminated) fence hides everything after its opener', async () => {+ const body = `${filler(5000)}\n\n<!--- gbrain:takes:begin -->\n| 1 | ${PRIVATE} | take | alice-example | 0.8 | 2026-04 | note |\n${filler(3000)}`;+ await put('people/malformed', body);+ const r = await get(ctx(), { slug: 'people/malformed', bytes: { offset: 300_000, length: 100_000 } });+ expect(r.window.text).not.toContain(PRIVATE);+ const all = await get(ctx(), { slug: 'people/malformed', body: 'window', max_bytes: 1_000_000 });+ expect(all.window.text).not.toContain(PRIVATE);+ });++ test('outline metadata never names a heading inside a protected fence', async () => {+ const hiddenHeading = '## SECRET-HEADING-alice-example';+ const facts = `<!--- gbrain:facts:begin -->\n\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n| 1 | private fact about alice-example | fact | 1.0 | private | high | 2026-01-01 | | note | |\n<!--- gbrain:facts:end -->`;+ const body = `# Top\n\n${filler(3000)}\n\n## Section two\n\n${filler(3000)}\n\n<!--- gbrain:takes:begin -->\n${hiddenHeading}\n<!--- gbrain:takes:end -->\n\n${facts}\n\n${filler(1000)}`;+ await put('people/outline', body);+ const r = await get(ctx(), { slug: 'people/outline', body: 'outline' });+ const json = JSON.stringify(r.outline);+ expect(json).not.toContain('SECRET-HEADING');+ expect(json).not.toContain('private fact');+ expect(r.outline.entries.map((e: any) => e.heading)).toContain('Section two');+ });++ test('a world fact withdrawn in the ledger is not in any window', async () => {+ const claim = 'acme-example withdrawn world fact claim';+ const facts = `<!--- gbrain:facts:begin -->\n\n| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |\n|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|\n| 1 | ${claim} | fact | 1.0 | world | high | 2026-01-01 | | note | |\n| 2 | acme-example kept world fact | fact | 1.0 | world | high | 2026-01-01 | | note | |\n<!--- gbrain:facts:end -->`;+ await put('companies/withdrawn', `${filler(3000)}\n\n${facts}\n\n${filler(3000)}`);+ const before = await get(ctx(), { slug: 'companies/withdrawn', body: 'window', max_bytes: 1_000_000 });+ expect(before.window.text).toContain(claim);+ await engine.executeRaw(`INSERT INTO fact_withdrawals (source_id, visibility, subject, fact_hash) VALUES ('default', 'world', 'companies/withdrawn', $1)`,+ [createHash('sha256').update(normalizeLoweredClaim(claim)).digest('hex')]);+ const after = await get(ctx(), { slug: 'companies/withdrawn', body: 'window', max_bytes: 1_000_000 });+ expect(after.window.text).not.toContain(claim);+ expect(after.window.text).toContain('kept world fact');+ const outline = await get(ctx(), { slug: 'companies/withdrawn', body: 'outline' });+ expect(JSON.stringify(outline)).not.toContain(claim);+ });+});++describe('egress', () => {+ test('body full over the connection cap is page_too_large_for_inline with a windowed fix', async () => {+ await put('logs/huge', conversation(30_000));+ const err = await expectCode(get(ctx({ transport: 'http' }), { slug: 'logs/huge', body: 'full' }), 'page_too_large_for_inline');+ expect(err.fix?.mcp?.arguments).toMatchObject({ slug: 'logs/huge', body: 'outline' });+ const ok = await get(ctx({ transport: 'stdio' }), { slug: 'logs/huge', body: 'full' });+ expect(typeof ok.compiled_truth).toBe('string');+ await expectCode(get(ctx({ transport: 'http', thinClient: true }), { slug: 'logs/huge' }), 'page_too_large_for_inline');+ });++ 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);+ });+});