Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

wip(large-pages): thin CLI pages whole pages, partial rendering, put_page large-page guard

garrytanab91c122974d
diff --git a/src/cli/main.ts b/src/cli/main.ts
index bbc5bcb8ba..68c3084abb 100755
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -49,7 +49,7 @@ import { cliCommandOf, exitCliError, exitOnRepairFailed, unknownFlagError, usage
import type { Notice } from '../core/agent-output.ts';
import { opError, opOwnsSource } from '../core/ops/contract.ts';
import { opParamValue } from './op-param-values.ts';
-import { serializeMarkdown } from '../core/markdown.ts';
+import { formatGetPage, readWholePageMarkdown, remoteErrorCode, wantsWholePage } from './page-render.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from '../core/cli-options.ts';
import { runCliPreflight } from '../core/cli-preflight.ts';
import { isBooleanLiteral, isKnownOpFlag } from '../core/op-flag-tokens.ts';
@@ -793,7 +793,13 @@ async function runThinClientRouted(
timeoutMs,
signal: sigintController.signal,
...(op.mutating ? { writeWaitMs: currentCliWriteWait().waitMs } : {}),
+ }).catch(async (e: unknown) => { // large pages: a page too big for one response is paged to its end, verified, then printed
+ if (op.name !== 'get_page' || remoteErrorCode(e) !== 'page_too_large_for_inline' || !wantsWholePage(params)) throw e;
+ const paged = await readWholePageMarkdown(async p => unpackToolResult(await callRemoteTool(cfg, 'get_page', p, { timeoutMs, signal: sigintController.signal })), params);
+ await writeStdoutFinal(params.json === true ? JSON.stringify({ slug: params.slug, revision: paged.revision, content: paged.markdown, windows: paged.windows }) + '\n' : paged.markdown);
+ return null;
});
+ if (raw === null) return;
// T15/FOV-1: lift the server's retrieval meta off the envelope before
// unpacking (old servers lack _meta — capture is simply skipped).
const envelopeMeta = extractResponseMeta(raw);
@@ -1626,15 +1632,7 @@ export function formatResult(
if (!pages.length) return 'Nothing volunteered (no entity cleared the confidence gate).\n';
return pages.map((p) => formatVolunteeredPage(p)).join('\n') + '\n';
}
- case 'get_page': {
- const r = result as any;
- if (r.error === 'ambiguous_slug') {
- return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
- }
- return serializeMarkdown(r.frontmatter || {}, r.compiled_truth || '', r.timeline || '', {
- type: r.type, title: r.title, tags: r.tags || [],
- });
- }
+ case 'get_page': return formatGetPage(result as Record<string, any>);
case 'list_pages': {
const pages = result as any[];
if (pages.length === 0) return 'No pages found.\n';
diff --git a/src/cli/page-render.ts b/src/cli/page-render.ts
new file mode 100644
index 0000000000..dcb7abe975
--- /dev/null
+++ b/src/cli/page-render.ts
@@ -0,0 +1,113 @@
+/**
+ * Large pages (Wave A): how `gbrain get` renders get_page, locally and over
+ * the thin client.
+ *
+ * A whole page prints as its markdown, as it always has. A partial response
+ * (body none / outline / window) prints only what it carries, and says on
+ * stderr that it is partial and how to read on, so `gbrain get > file` never
+ * writes part of a page as if it were all of it.
+ *
+ * The thin client asks for the whole page. A host that cannot send it in one
+ * response refuses with page_too_large_for_inline; the client then pages the
+ * round-trip markdown (view: 'markdown') to its end, checks the total size and
+ * sha256 the host reported, and prints it, or fails without printing.
+ */
+import { createHash } from 'node:crypto';
+import { serializeMarkdown } from '../core/markdown.ts';
+
+/** Window size the thin client asks for while paging a whole page. */
+export const REMOTE_PAGE_WINDOW_BYTES = 512 * 1024;
+const MAX_RESTARTS = 3;
+
+type GetPageResult = Record<string, any>;
+
+function partialNote(r: GetPageResult): string {
+ const size = r.size ?? {};
+ const total = typeof size.total_bytes === 'number' ? `${size.total_bytes} bytes` : 'unknown size';
+ if (r.window && typeof r.window.byte_start === 'number') {
+ const next = r.next_cursor ? ` Read on: gbrain get ${r.slug} --cursor ${r.next_cursor}` : '';
+ return `[gbrain] partial page: bytes ${r.window.byte_start}-${r.window.byte_end} of ${total} (lines ${r.window.line_start}-${r.window.line_end}).${next}`;
+ }
+ return `[gbrain] partial page (${r.body}, ${total}): no page body was printed. Whole page: gbrain get ${r.slug} --body full`;
+}
+
+function renderOutline(r: GetPageResult): string {
+ const o = r.outline;
+ const lines = [`# ${r.title ?? r.slug} — ${r.size?.total_bytes ?? '?'} bytes, ${r.size?.total_lines ?? '?'} lines, revision ${r.revision}`];
+ for (const e of o?.entries ?? []) {
+ const label = e.heading !== undefined ? `${'#'.repeat(e.level ?? 1)} ${e.heading ?? '(before first heading)'}` : e.first_line ?? '';
+ const dates = e.date_min ? ` [${e.date_min}${e.date_max && e.date_max !== e.date_min ? `..${e.date_max}` : ''}]` : '';
+ lines.push(`L${e.line_start}-${e.line_end}\t${e.byte_end - e.byte_start}B\t${label}${dates}`);
+ }
+ if (o?.next_from_index !== undefined) lines.push(`… ${o.total_entries - o.next_from_index} more entries: --outline-from ${o.next_from_index}`);
+ return lines.join('\n') + '\n';
+}
+
+/** stdout text for one get_page result; partial responses add a stderr note. */
+export function formatGetPage(r: GetPageResult): string {
+ if (r.error === 'ambiguous_slug') {
+ return `Ambiguous slug. Did you mean:\n${r.candidates.map((c: string) => ` ${c}`).join('\n')}\n`;
+ }
+ if (typeof r.body !== 'string') {
+ return serializeMarkdown(r.frontmatter || {}, r.compiled_truth || '', r.timeline || '', { type: r.type, title: r.title, tags: r.tags || [] });
+ }
+ process.stderr.write(partialNote(r) + '\n');
+ if (r.window) return r.window.text;
+ if (r.outline) return renderOutline(r);
+ return `revision: ${r.revision}\nsize: ${r.size?.total_bytes ?? '?'} bytes, ${r.size?.total_lines ?? '?'} lines\n` +
+ (r.chunks ? `chunks: ${r.chunks.total} (${r.chunks.embedded} embedded)\n` : '');
+}
+
+/** The canonical code of a tool error: a thin-client RemoteMcpError's detail, or an in-process OperationError (a legacy wire value moves the code to canonical). */
+export function remoteErrorCode(e: unknown): string | undefined {
+ const err = e as { detail?: { code?: string; canonical_code?: string }; canonical?: string; code?: unknown } | null;
+ if (err?.detail && typeof err.detail === 'object') return err.detail.canonical_code ?? err.detail.code;
+ return err?.canonical ?? (typeof err?.code === 'string' ? err.code : undefined);
+}
+
+/** True when a get_page call named no body mode, selector or round-trip flag: the caller wants the page as it is. */
+export function wantsWholePage(params: Record<string, unknown>): boolean {
+ return ['body', 'lines', 'bytes', 'around_chunk_id', 'cursor', 'include_content', 'content_only'].every(k => params[k] === undefined);
+}
+
+/**
+ * Page a whole page's round-trip markdown through windows. Restarts from the
+ * top when the page changes mid-read; throws rather than return a short or
+ * unverified body.
+ */
+export async function readWholePageMarkdown(
+ call: (params: Record<string, unknown>) => Promise<GetPageResult>,
+ params: Record<string, unknown>,
+): Promise<{ markdown: string; revision: string; windows: number }> {
+ const base = { slug: params.slug, ...(params.source_id !== undefined ? { source_id: params.source_id } : {}), body: 'window', view: 'markdown' };
+ for (let attempt = 0; attempt <= MAX_RESTARTS; attempt++) {
+ const parts: Buffer[] = [];
+ let r = await call({ ...base, max_bytes: REMOTE_PAGE_WINDOW_BYTES });
+ const { revision, size } = r;
+ let windows = 1;
+ let changed = false;
+ for (;;) {
+ if (!r.window || typeof r.window.byte_start !== 'number' || !size || typeof size.sha256 !== 'string') {
+ throw new Error(`get_page did not return a markdown window for ${String(params.slug)}; the page was not printed.`);
+ }
+ parts.push(Buffer.from(r.window.text, 'utf8'));
+ if (!r.next_cursor) break;
+ try {
+ r = await call({ ...base, cursor: r.next_cursor });
+ } catch (e) {
+ if (remoteErrorCode(e) !== 'revision_changed') throw e;
+ changed = true;
+ break;
+ }
+ if (r.revision !== revision) { changed = true; break; }
+ windows++;
+ }
+ if (changed) continue;
+ const whole = Buffer.concat(parts);
+ if (whole.length !== size.total_bytes || createHash('sha256').update(whole).digest('hex') !== size.sha256) {
+ throw new Error(`The paged copy of ${String(params.slug)} does not match the size and sha256 the host reported; the page was not printed.`);
+ }
+ return { markdown: whole.toString('utf8'), revision, windows };
+ }
+ throw new Error(`${String(params.slug)} kept changing while it was being read (${MAX_RESTARTS + 1} attempts); the page was not printed. Try again.`);
+}
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index 3d273d972b..7b96235240 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -328,7 +328,7 @@ export const CODES = {
page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Shows which page holds the slug now and its revision; a new attempt needs a new request_id.", requires_exclusive: false } },
page_projection_conflict: { class: 'retryable', summary: "Another worker installed a newer search projection of the page while this command prepared its own.", why: "The projection guard keeps the newer installation instead of overwriting it; the canonical page revision did not change.", docs: 'docs/guides/repair.md#page-projection-conflict', suggestion: "Re-run the same command; it re-reads the current projection. If it conflicts again, wait for the other worker to finish." },
page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed', fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },
- page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', legacy_error: 'invalid_params', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },
+ page_shrink_refused: { class: 'caller', summary: "put_page refused to replace a large page with content much smaller than the stored body; nothing was written.", why: "Above the inline read size (mcp.inline_body_bytes, 256 KB) a get_page read returns a window, not the body, so a replacement far smaller than the page is most often a window sent back as the whole page, which would delete the unread rest.", docs: 'docs/guides/windowed-reads.md#page_shrink_refused', suggestion: "Change part of the page with edit_page (revision from get_page body: 'none'). Pass allow_shrink: true only when the smaller content is the intended complete page.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } }, consent: [], actor: 'agent', why: "Returns the page's revision and size without its body; edit_page with that revision changes only the text it names.", requires_exclusive: false } },
page_too_large_for_inline: { class: 'caller', summary: "The whole page does not fit one result on this connection, so get_page did not return its body.", why: "A result is measured as the complete encoded frame; a body over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be cut or rejected by the client. Nothing was truncated: windowed reads cover the whole page in pieces.", docs: 'docs/guides/windowed-reads.md#page_too_large_for_inline', legacy_error: 'invalid_params', suggestion: "Read the outline (body: 'outline'), then windows (body: 'window' with lines, bytes, around_chunk_id or the returned next_cursor). To replace the page, edit it with edit_page and the revision from body: 'none'.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'outline' } }, consent: [], actor: 'agent', why: "Returns the page's size, revision and outline; each entry names the lines to read with body: 'window'.", requires_exclusive: false, verify: { mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}', body: 'none' } } } } },
parse_error: { class: 'caller', summary: "The request body is not valid JSON." },
parser_regression: { class: 'server', summary: "A file whose exact bytes imported before is now refused by gbrain's frontmatter reader.", why: "The same bytes imported under an earlier gbrain version, so only gbrain changed; with `sync.parser_regression=hold` such a file is held and the rest of the sync continues.", suggestion: 'Report it as a gbrain bug with the gbrain version, the file and the code; upgrade or pin the last good version, then sync again with --retry-failed.' },
diff --git a/src/core/operation-manifest.generated.ts b/src/core/operation-manifest.generated.ts
index 899ae59575..58d352ed8a 100644
--- a/src/core/operation-manifest.generated.ts
+++ b/src/core/operation-manifest.generated.ts
@@ -222,7 +222,7 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"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",
@@ -235,12 +235,79 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
},
"include_content": {
"type": "boolean",
- "description": "Full markdown + revision, for editing."
+ "description": "Full markdown + revision (body: 'full')."
},
"content_only": {
"type": "boolean",
"description": "Round-trip fields only."
},
+ "body": {
+ "type": "string",
+ "enum": [
+ "auto",
+ "full",
+ "none",
+ "outline",
+ "window"
+ ],
+ "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)."
+ },
"include_deleted": {
"type": "boolean",
"description": "Include soft-deleted pages."
@@ -333,6 +400,11 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"required": false,
"description": "Allow emptying the page."
},
+ "allow_shrink": {
+ "type": "boolean",
+ "required": false,
+ "description": "Allow content under half a >256 KB page."
+ },
"drop_timeline": {
"type": "boolean",
"required": false,
@@ -759,6 +831,10 @@ export const OPERATION_MANIFEST: OperationMeta[] = [
"type": "boolean",
"description": "Allow emptying a non-empty page."
},
+ "allow_shrink": {
+ "type": "boolean",
+ "description": "Allow content under half a >256 KB page."
+ },
"drop_timeline": {
"type": "boolean",
"description": "Content without a Timeline section deletes its dated entries."
diff --git a/src/core/ops/page-batch.ts b/src/core/ops/page-batch.ts
index b77388d269..c34c9f315b 100644
--- a/src/core/ops/page-batch.ts
+++ b/src/core/ops/page-batch.ts
@@ -19,6 +19,7 @@ const put_pages: Operation = {
content: { type: 'string', required: true, description: 'Complete markdown with frontmatter.' },
expected_revision: { type: 'string', description: 'Revision read; omit to create.' },
allow_empty: { type: 'boolean', description: 'Allow emptying a non-empty page.' },
+ allow_shrink: { type: 'boolean', description: 'Allow content under half a >256 KB page.' },
drop_timeline: { type: 'boolean', description: 'Content without a Timeline section deletes its dated entries.' },
},
},
diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.ts
index 2ce02ad1d8..58e447dbe1 100644
--- a/src/core/ops/pages.ts
+++ b/src/core/ops/pages.ts
@@ -17,6 +17,7 @@ import { decodeDeepResearchId, deepResearchPageUrl } from '../deep-research-id.t
import { PageSnapshotAmbiguousError, type PageSnapshot } from '../page-state/types.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { pageTrustForRead, projectFetchText, projectGetPage, readQuarantined } from './get-page-projection.ts';
+import { assertLargePageAdmission } from '../persistence/large-page-guard.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';
@@ -322,6 +323,7 @@ const put_page: Operation = {
slug: { type: 'string', description: 'Page slug.', required: true },
content: { type: 'string', required: true, description: 'Complete markdown (get_page include_content:true).' },
allow_empty: { type: 'boolean', required: false, description: 'Allow emptying the page.' },
+ allow_shrink: { type: 'boolean', required: false, description: 'Allow content under half a >256 KB page.' },
drop_timeline: { type: 'boolean', required: false, description: 'No Timeline in content: delete its entries.' },
wait_ms: WRITE_WAIT_PARAM,
// v0.39.3.0 provenance write-through (WARN-8 + A1 + CV6). Optional fields
@@ -347,6 +349,7 @@ const put_page: Operation = {
}
return { dry_run: true, action: 'put_page', slug: p.slug };
}
+ if (ctx.remote !== false && typeof p.slug === 'string') await assertLargePageAdmission(ctx.engine, p.slug, sourceId, p);
return submitPageMutation(ctx, { operation: 'put_page', params: p }).catch(error => rethrowNamingRevisionSource(ctx, sourceId, p, error));
},
cliHints: { name: 'put', positional: ['slug'], stdin: 'content' },
diff --git a/src/core/persistence/large-page-guard.ts b/src/core/persistence/large-page-guard.ts
new file mode 100644
index 0000000000..a5f1401e90
--- /dev/null
+++ b/src/core/persistence/large-page-guard.ts
@@ -0,0 +1,66 @@
+/**
+ * Large pages (Wave A): put_page's guard against replacing a large page with
+ * a window of it. Above the inline read size a get_page read returns an
+ * outline and windows, not the body, so a replacement must name the revision
+ * it read (force does not stand in for it) and may not be much smaller than
+ * the stored body unless the caller says so with allow_shrink: true.
+ */
+import { DEFAULT_INLINE_BODY_BYTES } from '../ops/get-page-body.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import type { PageSnapshot } from '../page-state/types.ts';
+import type { BrainEngine } from '../engine.ts';
+
+/** A replacement under this fraction of the stored body counts as a shrink. */
+export const SHRINK_REFUSE_FRACTION = 0.5;
+
+const bodyBytes = (compiled: string | null | undefined, timeline: string | null | undefined) =>
+ Buffer.byteLength(compiled ?? '', 'utf8') + Buffer.byteLength(timeline ?? '', 'utf8');
+
+const sizeFix = (slug: string, sourceId: string) => ({ argv: ['gbrain', 'get', '--source', sourceId, '--', slug],
+ mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId, body: 'none' } },
+ consent: [], actor: 'agent' as const, requires_exclusive: false, why: "Returns the page's revision and size without its body." });
+
+/**
+ * Admission (remote put_page): checked before the write is queued, so the
+ * refusal is immediate, carries its fix, and nothing is accepted. A page over
+ * the inline read size must be replaced against the revision the caller read
+ * (force does not stand in for it), and content under half its body is
+ * refused unless allow_shrink is true. The content's own bytes (frontmatter
+ * included) are measured here; preparation re-checks the parsed body.
+ */
+export async function assertLargePageAdmission(engine: Pick<BrainEngine, 'executeRaw'>, slug: string, sourceId: string, intent: Record<string, unknown>): Promise<void> {
+ if (typeof intent.content !== 'string') return;
+ const [row] = await engine.executeRaw<{ bytes: unknown }>(
+ `SELECT octet_length(compiled_truth) + COALESCE(octet_length(timeline), 0) AS bytes FROM pages WHERE slug = $1 AND source_id = $2 AND deleted_at IS NULL`, [slug, sourceId]);
+ const stored = Number(row?.bytes ?? 0);
+ if (stored <= DEFAULT_INLINE_BODY_BYTES) return;
+ if (intent.expected_revision === undefined && intent.force === true) {
+ const e = new OperationError('revision_required', `Page ${slug} is ${stored} bytes, over the ${DEFAULT_INLINE_BODY_BYTES}-byte inline read size; replacing it needs expected_revision (force does not apply). Nothing was written.`,
+ "Read the revision with get_page body: 'none' and change the part you mean with edit_page, or send the complete page with that expected_revision.");
+ e.fix = sizeFix(slug, sourceId);
+ e.contractVersion = 1;
+ throw e;
+ }
+ if (intent.allow_shrink !== true) assertNotShrunk(slug, sourceId, stored, Buffer.byteLength(intent.content, 'utf8'));
+}
+
+function assertNotShrunk(slug: string, sourceId: string, stored: number, next: number): void {
+ if (next >= stored * SHRINK_REFUSE_FRACTION) return;
+ throw opError('page_shrink_refused',
+ `Refusing to replace ${slug} (${stored} bytes) with ${next} bytes: under ${Math.round(SHRINK_REFUSE_FRACTION * 100)}% of the stored body. Nothing was written.`,
+ "A window or outline sent back as the page would delete the unread rest. Change part of the page with edit_page (revision from get_page body: 'none'); pass allow_shrink: true only when the smaller content is the intended complete page.",
+ { detail: JSON.stringify({ stored_bytes: stored, content_bytes: next, min_bytes: Math.ceil(stored * SHRINK_REFUSE_FRACTION) }), fix: sizeFix(slug, sourceId) });
+}
+
+/** Preparation: the same shrink rule on the parsed body, against the locked snapshot. */
+export function assertLargePageReplacement(
+ slug: string,
+ sourceId: string,
+ intent: Record<string, unknown>,
+ snapshot: PageSnapshot,
+ incoming: { compiled_truth: string; timeline?: string | null },
+): void {
+ const stored = bodyBytes(snapshot.page.compiled_truth, snapshot.page.timeline);
+ if (stored <= DEFAULT_INLINE_BODY_BYTES || intent.allow_shrink === true) return;
+ assertNotShrunk(slug, sourceId, stored, bodyBytes(incoming.compiled_truth, incoming.timeline));
+}
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index 8531440f59..762c6f524d 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -36,8 +36,8 @@ export const PAGE_BATCH_DEFAULT_WAIT_MS = 25_000;
const PREPARE_CONCURRENCY = 8;
/** Batch admission is one transaction over every page; it gets more than a single write's budget. */
const BATCH_ADMISSION_BUDGET_MS = 30_000;
-const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty', 'drop_timeline']);
-interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown; drop_timeline?: unknown }
+const PAGE_KEYS = new Set(['slug', 'content', 'expected_revision', 'allow_empty', 'allow_shrink', 'drop_timeline']);
+interface BatchPage { slug: string; content: string; expected_revision?: unknown; allow_empty?: unknown; allow_shrink?: unknown; drop_timeline?: unknown }
interface PageResult { index: number; slug: string; row?: WriteRequest; refusal?: OperationError; typeWarning?: PageTypeWarning | null; repeatOf?: number }
interface BatchMarker { id: string; index: number; size: number; repeats?: number[] }
@@ -50,10 +50,10 @@ function parsePages(value: unknown): BatchPage[] {
}
let bytes = 0;
const pages = value.map((page, index) => {
- if (!page || typeof page !== 'object' || Array.isArray(page)) throw invalid(`pages[${index}] must be an object {slug, content}; nothing was written.`, 'Pass each page as {slug, content} with optional expected_revision, allow_empty and drop_timeline.');
+ if (!page || typeof page !== 'object' || Array.isArray(page)) throw invalid(`pages[${index}] must be an object {slug, content}; nothing was written.`, 'Pass each page as {slug, content} with optional expected_revision, allow_empty, allow_shrink and drop_timeline.');
const record = page as Record<string, unknown>;
const extra = Object.keys(record).filter(key => !PAGE_KEYS.has(key));
- if (extra.length) throw invalid(`pages[${index}] has unsupported fields (${extra.join(', ')}); nothing was written.`, 'Each page accepts only slug, content, expected_revision, allow_empty and drop_timeline; put frontmatter inside content.');
+ if (extra.length) throw invalid(`pages[${index}] has unsupported fields (${extra.join(', ')}); nothing was written.`, 'Each page accepts only slug, content, expected_revision, allow_empty, allow_shrink and drop_timeline; put frontmatter inside content.');
if (typeof record.slug !== 'string' || !record.slug) throw invalid(`pages[${index}].slug must be a non-empty string; nothing was written.`, 'Give every page its slug, for example "notes/topic-name".');
if (typeof record.content !== 'string') throw invalid(`pages[${index}].content must be a string; nothing was written.`, 'Pass the complete markdown page, frontmatter included, as content.');
bytes += Buffer.byteLength(record.content);
@@ -80,7 +80,7 @@ function findRepeats(pages: BatchPage[]): Repeats {
pages.forEach((page, index) => bySlug.set(page.slug.toLowerCase(), [...(bySlug.get(page.slug.toLowerCase()) ?? []), index]));
const repeatOf: (number | undefined)[] = new Array(pages.length);
const refusals = new Map<number, OperationError>();
- const same = (a: BatchPage, b: BatchPage) => a.slug === b.slug && a.content === b.content && a.expected_revision === b.expected_revision && a.allow_empty === b.allow_empty;
+ const same = (a: BatchPage, b: BatchPage) => a.slug === b.slug && a.content === b.content && a.expected_revision === b.expected_revision && a.allow_empty === b.allow_empty && a.allow_shrink === b.allow_shrink;
for (const indexes of bySlug.values()) {
if (indexes.length < 2) continue;
const first = pages[indexes[0]!]!;
@@ -208,6 +208,7 @@ async function preparePages(own: OperationContext, shared: OperationContext, bat
const params: Record<string, unknown> = { slug: page.slug, content: page.content, source_id: sourceId };
if (page.expected_revision !== undefined) params.expected_revision = page.expected_revision;
if (page.allow_empty !== undefined) params.allow_empty = page.allow_empty;
+ if (page.allow_shrink !== undefined) params.allow_shrink = page.allow_shrink;
if (page.drop_timeline !== undefined) params.drop_timeline = page.drop_timeline;
try {
prepared[index] = await preparePageAdmission(ctx, { operation: 'put_page', params,
diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.ts
index 7b0a07762d..9fe451aef8 100644
--- a/src/core/persistence/page-prepare.ts
+++ b/src/core/persistence/page-prepare.ts
@@ -11,6 +11,7 @@ import type { GBrainConfig } from '../config.ts';
import type { Page, PageVersion } from '../types.ts';
import { importFromContent, verifyPageReadable, type ParsedPage } from '../import-file.ts';
import { comparableFrontmatter, frontmatterHoldMessageWithoutKeys, parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';
+import { assertLargePageReplacement } from './large-page-guard.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import { isOpPageSlug } from '../ops/context.ts';
@@ -401,10 +402,11 @@ export async function preparePageMutation(unbounded: BrainEngine, row: WriteRequ
if ((snapshot?.page.id ?? null) !== row.page_id) throw pageIdentityError(snapshot != null || row.page_id === null, 'The accepted page identity changed.');
const observedRevision = snapshot?.revision ?? null;
const activePack = pack?.manifest;
- if (row.operation === 'put_page' && p.allow_empty !== true && snapshot && !snapshot.page.deleted_at
- && typeof p.content === 'string' && `${snapshot.page.compiled_truth}\n${snapshot.page.timeline ?? ''}`.trim()) {
+ if (row.operation === 'put_page' && snapshot && !snapshot.page.deleted_at && typeof p.content === 'string'
+ && `${snapshot.page.compiled_truth}\n${snapshot.page.timeline ?? ''}`.trim()) {
const incoming = parseMarkdown(p.content, row.slug, { activePack });
- if (!`${incoming.compiled_truth}\n${incoming.timeline ?? ''}`.trim()) {
+ if (!preparedIntent && row.authority.remote) assertLargePageReplacement(row.slug, row.source_id, p, snapshot, incoming);
+ if (p.allow_empty !== true && !`${incoming.compiled_truth}\n${incoming.timeline ?? ''}`.trim()) {
throw new OperationError('invalid_params', `Refusing to overwrite existing non-empty page '${row.slug}' with empty content. Use capture --file PATH --slug SLUG for file input; set allow_empty:true to intentionally clear it.`,
'Use capture --file PATH --slug SLUG for file input, or pass allow_empty:true with the expected revision to intentionally clear it.');
}
diff --git a/test/large-page-roundtrip.test.ts b/test/large-page-roundtrip.test.ts
new file mode 100644
index 0000000000..4f24d3fea1
--- /dev/null
+++ b/test/large-page-roundtrip.test.ts
@@ -0,0 +1,160 @@
+/**
+ * Large pages (Wave A, T4/T13/T22): a windowed read can never be written back
+ * as the whole page, and every client that prints a page prints all of it.
+ *
+ * - get(auto) of a 2 MB page, then put_page of what came back, is refused
+ * (page_shrink_refused); force cannot stand in for expected_revision.
+ * - the local `gbrain get` prints the page byte-for-byte as it was written.
+ * - the thin client, refused a whole page, pages the round-trip markdown to
+ * its end and checks size + sha256; a page edited mid-read restarts, a
+ * mismatch fails without printing.
+ *
+ * Hermetic in-memory PGLite.
+ */
+import { describe, test, expect, beforeAll, afterAll, spyOn } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { registerLocalWriter } from '../src/core/persistence/identity.ts';
+import { serializeMarkdown } from '../src/core/markdown.ts';
+import { importFromContent } from '../src/core/import-file.ts';
+import { formatGetPage, readWholePageMarkdown, wantsWholePage } from '../src/cli/page-render.ts';
+
+let engine: PGLiteEngine;
+const noopLogger = { info: () => {}, warn: () => {}, error: () => {} };
+const getPage = operations.find(o => o.name === 'get_page')!;
+const putPage = operations.find(o => o.name === 'put_page')!;
+const CLIENT = 'client-large-pages-example';
+
+const localCtx = (): OperationContext => ({ engine, config: {} as GBrainConfig, logger: noopLogger, dryRun: false, remote: false, sourceId: 'default' } as OperationContext);
+const remoteCtx = (extra: Partial<OperationContext> = {}): OperationContext => ({ ...localCtx(), remote: true, transport: 'http',
+ auth: { token: 'fixture', clientId: CLIENT, principal: { kind: 'oauth_client', id: CLIENT }, scopes: ['read', 'write'], sourceId: 'default', allowedSources: ['default'] },
+ writeWaitMs: 60_000, ...extra } as unknown as OperationContext);
+
+const get = async (ctx: OperationContext, params: Record<string, unknown>) => await getPage.handler(ctx, params) as Record<string, any>;
+async function refusal(p: Promise<unknown>): Promise<OperationError> {
+ try { await p; } catch (e) { if (e instanceof OperationError) return e; throw e; }
+ throw new Error('expected a refusal');
+}
+const codeOf = (e: OperationError) => (e as any).canonical ?? e.code;
+
+function bigBody(marker: string): string {
+ const lines = ['# Conversation log with acme-example', ''];
+ for (let i = 0; i < 34_000; i++) lines.push(`**bob-example:** 2026-03-${String(1 + (i % 28)).padStart(2, '0')} ${marker} line ${i} about the widget plan`);
+ return lines.join('\n');
+}
+const SOURCE = serializeMarkdown({ source: 'chat-export' }, bigBody('v1'), '- 2026-03-01: Kickoff with acme-example', { type: 'note', title: 'Big log', tags: ['log'] });
+
+beforeAll(async () => {
+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536, env: {} });
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ await registerLocalWriter(engine, 'cli');
+ await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_secret_hash,client_name,scope,source_id)
+ VALUES($1,'fixture-hash','example-client','read write','default')`, [CLIENT]);
+ expect(Buffer.byteLength(SOURCE)).toBeGreaterThan(2 * 1024 * 1024);
+ expect((await importFromContent(engine, 'logs/big-example', SOURCE, { sourceId: 'default', noEmbed: true })).status).toBe('imported');
+}, 120_000);
+
+afterAll(async () => { resetGateway(); await engine.disconnect(); }, 30_000);
+
+describe('local gbrain get', () => {
+ test('prints the 2 MB page byte-for-byte as its source file (frontmatter adds only the import size stamps)', async () => {
+ const out = formatGetPage(await get(localCtx(), { slug: 'logs/big-example' }));
+ const split = (md: string) => { const end = md.indexOf('\n---\n', 4) + 5; return { fm: md.slice(0, end), body: md.slice(end) }; };
+ // The oversized-page import stamps (embed_skip, content_flag) are the ingest policy's, not the read's.
+ const unstamped = split(out).fm.replace(/^(embed_skip|content_flag):\n(?: {2}.*\n)+/gm, '');
+ expect(split(out).body === split(SOURCE).body).toBe(true);
+ expect(unstamped).toBe(split(SOURCE).fm);
+ expect(out.endsWith('- 2026-03-01: Kickoff with acme-example\n')).toBe(true);
+ }, 60_000);
+
+ test('a partial response prints only its window and says so on stderr', async () => {
+ const err = spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ const r = await get(localCtx(), { slug: 'logs/big-example', body: 'window', lines: { from: 10, count: 2 } });
+ const out = formatGetPage(r);
+ expect(out.split('\n').filter(Boolean)).toHaveLength(2);
+ expect(String(err.mock.calls[0]?.[0])).toContain('partial page: bytes');
+ } finally { err.mockRestore(); }
+ });
+});
+
+describe('put_page after a windowed read', () => {
+ test('get(auto) then put of what came back is page_shrink_refused, and nothing changes', async () => {
+ const r = await get(remoteCtx(), { slug: 'logs/big-example' });
+ expect(r.compiled_truth).toBeUndefined();
+ expect(r.content).toBeUndefined();
+ const before = (await engine.getPage('logs/big-example'))!.compiled_truth;
+ const naive = serializeMarkdown(r.frontmatter, r.window.text, '', { type: r.type, title: r.title, tags: r.tags });
+ const e = await refusal(putPage.handler(remoteCtx(), { slug: 'logs/big-example', content: naive, expected_revision: r.revision }));
+ expect(e.code).toBe('page_shrink_refused');
+ expect(e.suggestion).toContain('edit_page');
+ expect(e.suggestion).toContain('allow_shrink');
+ expect(e.fix?.mcp).toMatchObject({ tool: 'get_page', arguments: { slug: 'logs/big-example', body: 'none' } });
+ expect((await engine.getPage('logs/big-example'))!.compiled_truth).toBe(before);
+ }, 60_000);
+
+ test('force does not stand in for expected_revision on a large page', async () => {
+ const e = await refusal(putPage.handler(remoteCtx(), { slug: 'logs/big-example', content: SOURCE, force: true }));
+ expect(e.code).toBe('revision_required');
+ }, 60_000);
+
+ test('the complete page read through windows writes back unchanged in size', async () => {
+ const paged = await readWholePageMarkdown(p => get(remoteCtx(), p), { slug: 'logs/big-example' });
+ const edited = paged.markdown.replace('v1 line 33999', 'v1 line 33999 (edited)');
+ const res = await putPage.handler(remoteCtx(), { slug: 'logs/big-example', content: edited, expected_revision: paged.revision }) as Record<string, any>;
+ expect(res.status ?? res.write_request?.status).toBeDefined();
+ expect((await engine.getPage('logs/big-example'))!.compiled_truth).toContain('v1 line 33999 (edited)');
+ }, 120_000);
+
+ test('allow_shrink: true lets an intended smaller page through', async () => {
+ await putPage.handler(localCtx(), { slug: 'logs/shrink-example', content: SOURCE });
+ const r = await get(remoteCtx(), { slug: 'logs/shrink-example', body: 'none' });
+ await putPage.handler(remoteCtx(), { slug: 'logs/shrink-example', content: '---\ntype: note\ntitle: Short\n---\n\nSummary only.\n', expected_revision: r.revision, allow_shrink: true });
+ expect((await engine.getPage('logs/shrink-example'))!.compiled_truth.trim()).toBe('Summary only.');
+ }, 120_000);
+});
+
+describe('thin client', () => {
+ const thin = () => remoteCtx({ thinClient: true });
+
+ test('naming no mode, the whole page is refused over HTTP, never sent partial', async () => {
+ expect(wantsWholePage({ slug: 'logs/big-example' })).toBe(true);
+ const e = await refusal(get(thin(), { slug: 'logs/big-example' }));
+ expect(codeOf(e)).toBe('page_too_large_for_inline');
+ });
+
+ test('pages the round-trip markdown to its end and it equals include_content', async () => {
+ const whole = (await get(localCtx(), { slug: 'logs/big-example', include_content: true })).content as string;
+ const paged = await readWholePageMarkdown(p => get(thin(), p), { slug: 'logs/big-example' });
+ expect(paged.windows).toBeGreaterThan(3);
+ expect(paged.markdown === whole).toBe(true);
+ }, 60_000);
+
+ test('a page edited mid-read restarts and returns the new page whole', async () => {
+ await putPage.handler(localCtx(), { slug: 'logs/moving-example', content: SOURCE });
+ let calls = 0;
+ const paged = await readWholePageMarkdown(async p => {
+ if (++calls === 2) {
+ const cur = await get(localCtx(), { slug: 'logs/moving-example', include_content: true });
+ await putPage.handler(localCtx(), { slug: 'logs/moving-example', content: cur.content.replace('v1 line 3 ', 'v2 line 3 '), expected_revision: cur.revision });
+ }
+ return get(thin(), p);
+ }, { slug: 'logs/moving-example' });
+ expect(paged.markdown).toContain('v2 line 3 ');
+ expect(paged.markdown).toBe((await get(localCtx(), { slug: 'logs/moving-example', include_content: true })).content);
+ }, 120_000);
+
+ test('a copy that does not match the reported sha256 fails without returning text', async () => {
+ let calls = 0;
+ await expect(readWholePageMarkdown(async p => {
+ const r = await get(thin(), p);
+ if (++calls === 2) r.window.text = r.window.text.replace('line', 'LINE');
+ return r;
+ }, { slug: 'logs/big-example' })).rejects.toThrow(/does not match/);
+ }, 60_000);
+});