Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(get): thin client spools paged windows to a 0600 temp file until the sha256 verifies
garrytand81ca6ff7f5d
diff --git a/src/cli/page-render.ts b/src/cli/page-render.tsindex 34aa4b74db..b1c0c4edc0 100644--- a/src/cli/page-render.ts+++ b/src/cli/page-render.ts@@ -11,7 +11,8 @@* 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 window by window, or fails without- * printing.+ * printing. The windows wait in a 0600 temp file until the copy verifies, so+ * a page of any size prints with one window in memory.** A segmented page (Wave B) is never returned whole by get_page. Locally the* refusal is page_body_segmented and `gbrain get` streams the page instead:@@ -20,7 +21,10 @@* string, so above PAGE_MAX_BYTES it refuses, locally and over the thin* client, with a fix that drops `--json`.*/-import { createHash } from 'node:crypto';+import { createHash, randomBytes } from 'node:crypto';+import { open, rm, type FileHandle } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import type { BrainEngine } from '../core/engine.ts';import { serializeMarkdown } from '../core/markdown.ts';import { opError } from '../core/ops/contract.ts';@@ -86,31 +90,63 @@ export function wantsWholePage(params: Record<string, unknown>): boolean {}/**- * 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. The windows are kept as they arrived (`parts`); `markdown`- * joins them on demand.+ * @internal Work the thin client's paged read does, for the memory test: windows written to the spool (`spooled`)+ * and read back from it to print (`replayed`). Counts, not time.*/-export async function readWholePageMarkdown(- call: (params: Record<string, unknown>) => Promise<GetPageResult>,- params: Record<string, unknown>,-): Promise<{ parts: Buffer[]; markdown: string; revision: string; windows: number }> {+export const pagedReadWork = { spooled: 0, replayed: 0 };++type PagedCall = (params: Record<string, unknown>) => Promise<GetPageResult>;+interface SpooledPage { revision: string; windows: number; bytes: number; parts(): AsyncIterable<Buffer> }++/**+ * Page a whole page's round-trip markdown through windows into a 0600 temp file, then hand `use` the verified copy;+ * `parts()` reads it back window by window as the windows arrived. Restarts from the top when the page changes+ * mid-read; throws rather than hand over a short or unverified copy. The temp file is removed whatever happens.+ */+async function withSpooledPage<T>(call: PagedCall, params: Record<string, unknown>, use: (page: SpooledPage) => Promise<T>): Promise<T> {+ const path = join(tmpdir(), `gbrain-page-${process.pid}-${randomBytes(8).toString('hex')}.md`);+ const spool = await open(path, 'wx+', 0o600);+ try {+ const { lengths, revision } = await spoolWholePage(call, params, spool);+ const bytes = lengths.reduce((n, length) => n + length, 0);+ return await use({ revision, windows: lengths.length, bytes, async *parts() {+ for (let i = 0, at = 0; i < lengths.length; at += lengths[i]!, i++) {+ const part = Buffer.allocUnsafe(lengths[i]!);+ for (let filled = 0; filled < part.length;) {+ const { bytesRead } = await spool.read(part, filled, part.length - filled, at + filled);+ if (bytesRead === 0) throw new Error(`The spooled copy of ${String(params.slug)} was truncated; the rest of the page was not printed.`);+ filled += bytesRead;+ }+ pagedReadWork.replayed++;+ yield part;+ }+ } });+ } finally {+ await spool.close().catch(() => undefined);+ await rm(path, { force: true });+ }+}++/** The paging loop of withSpooledPage: the byte length of each window written to `spool`, once size and sha256 verify. */+async function spoolWholePage(call: PagedCall, params: Record<string, unknown>, spool: FileHandle): Promise<{ lengths: number[]; revision: string }> {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[] = [];+ await spool.truncate(0);+ const lengths: number[] = [];const hash = createHash('sha256');let bytes = 0;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.`);}const part = Buffer.from(r.window.text, 'utf8');- parts.push(part);hash.update(part);+ for (let written = 0; written < part.length;) written += (await spool.write(part, written, part.length - written, bytes + written)).bytesWritten;+ lengths.push(part.length);+ pagedReadWork.spooled++;bytes += part.length;if (!r.next_cursor) break;try {@@ -121,13 +157,12 @@ export async function readWholePageMarkdown(break;}if (r.revision !== revision) { changed = true; break; }- windows++;}if (changed) continue;if (bytes !== size.total_bytes || hash.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 { parts, get markdown() { return Buffer.concat(parts).toString('utf8'); }, revision, windows };+ return { lengths, revision };}throw new Error(`${String(params.slug)} kept changing while it was being read (${MAX_RESTARTS + 1} attempts); the page was not printed. Try again.`);}@@ -139,17 +174,30 @@ function jsonTooLargeError(slug: string, sourceId: string | undefined, bytes: nu{ fix: readFix('Prints the page whole without holding it as one string.', { argv: ['gbrain', 'get', ...(sourceId ? ['--source', sourceId] : []), '--', slug] }) });}+/**+ * A whole page's round-trip markdown as one string, paged and verified as `printPagedPage` does it: for `--json`,+ * which refuses a page over PAGE_MAX_BYTES before this holds it.+ */+export async function readWholePageMarkdown(call: PagedCall, params: Record<string, unknown>): Promise<{ markdown: string; revision: string; windows: number }> {+ return withSpooledPage(call, params, async page => {+ const parts: Buffer[] = [];+ for await (const part of page.parts()) parts.push(part);+ return { markdown: Buffer.concat(parts, page.bytes).toString('utf8'), revision: page.revision, windows: page.windows };+ });+}+/** The thin client's whole-page read after a page_too_large_for_inline refusal: page, verify, then print each window (or one --json document). */-export async function printPagedPage(call: (params: Record<string, unknown>) => Promise<GetPageResult>, params: Record<string, unknown>,- write: (text: string) => Promise<void>): Promise<void> {- const json = params.json === true;- const paged = await readWholePageMarkdown(async p => {- const r = await call(p);- if (json && r.size?.total_bytes > PAGE_MAX_BYTES) throw jsonTooLargeError(String(params.slug), params.source_id as string | undefined, r.size.total_bytes);- return r;- }, params);- if (json) await write(JSON.stringify({ slug: params.slug, revision: paged.revision, content: paged.markdown, windows: paged.windows }) + '\n');- else for (const part of paged.parts) await write(part.toString('utf8'));+export async function printPagedPage(call: PagedCall, params: Record<string, unknown>, write: (text: string) => Promise<void>): Promise<void> {+ if (params.json === true) {+ const paged = await readWholePageMarkdown(async p => {+ const r = await call(p);+ if (r.size?.total_bytes > PAGE_MAX_BYTES) throw jsonTooLargeError(String(params.slug), params.source_id as string | undefined, r.size.total_bytes);+ return r;+ }, params);+ await write(JSON.stringify({ slug: params.slug, revision: paged.revision, content: paged.markdown, windows: paged.windows }) + '\n');+ return;+ }+ await withSpooledPage(call, params, async page => { for await (const part of page.parts()) await write(part.toString('utf8')); });}/** What the local get_page call returns when `streamSegmentedGet` printed the page itself. */diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 77b39ff41b..bf03957699 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -667,6 +667,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: 'TBD', text: 'The pre-push secret scan (`gbrain sources push` and the automatic pushes) now scans a staged file over 25 MiB in bounded 8 Mi-character windows streamed from git, instead of refusing the push as `blocked_unscannable`: a clean large file pushes, and one holding a secret is refused as `blocked_secrets` naming its file and line. A staged file over 512 MiB still refuses as `blocked_unscannable`.' },{ since: 'TBD', text: 'On Postgres, title search, the source-scoped vector scan, the chunk windows search reads around its hits and `get_page` now read the new `page_body_manifest` table for every page, inline ones included, whether or not `pages.segmented_storage` is on. A database role that neither owns the tables nor bypasses row level security needs `SELECT` on it, or those reads fail with `permission_denied` (42501). Row level security is on for the new segment tables (`page_segment_texts`, `page_body_manifest`, `page_body_stagings`, `page_body_staging_parts`, `page_view_digests`) and is re-enabled on every schema replay, as for `pages`, so a role without a policy reads none of their rows. Grant the table together with the source-scoped policies in docs/ENGINES.md ("Segmented page tables"), never with an open policy, or the role reads every source\'s segment text. A runtime role that owns the tables or bypasses row level security, the default setup, needs nothing.' },{ since: 'TBD', text: 'MCP `get_page` of a page stored in segments no longer reports `size.body_bytes` or `size.body_lines` (the stored body) to a remote caller, and its `page_body_segmented` refusal names the size of the body that caller may read, as for an inline page; the difference told how much text privacy fences and withdrawals hide. A local `gbrain get` still reports both.' },+ { since: 'TBD', text: '`gbrain get` against a remote brain of a page too large for one response holds one window in memory instead of the whole page: the windows wait in a temp file readable only by you in the system temp directory (`TMPDIR`), as large as the page and removed when the command ends, until their size and sha256 verify. Nothing prints before they do, as before. `--json` still refuses a page over 24 MiB.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/test/large-pages/paged-read-spool.test.ts b/test/large-pages/paged-read-spool.test.tsnew file mode 100644index 0000000000..98e498650e--- /dev/null+++ b/test/large-pages/paged-read-spool.test.ts@@ -0,0 +1,89 @@+/**+ * The thin client's paged whole-page read (`printPagedPage`) spools the windows+ * to a temp file until the copy verifies, then prints them one at a time.+ *+ * 1. Protects: a 64 MiB page prints byte for byte with the heap (after+ * Bun.gc(true)) under 16 MiB above the baseline at every sampled write, so+ * a 128 or 256 MiB page prints in bounded memory; a copy whose sha256 does+ * not verify prints nothing; the spool is a 0600 file in os.tmpdir(),+ * removed after a print and after a refusal.+ * 2. Fails when: the read keeps every window in memory until the hash+ * verifies (the whole page is held when the first window prints), prints+ * a window before the hash verifies, or leaves the spool behind.+ * 3. Existing coverage: large-page-roundtrip.test.ts and segmented-get-cli.test.ts+ * check the printed bytes and the sha256 refusal over a real get_page; neither+ * measures memory.+ * 4. No production seam: the host is a synthetic get_page; pagedReadWork is the+ * module's own work counter. No database, so no engine arms.+ */+import { afterAll, expect, test } from 'bun:test';+import { createHash } from 'node:crypto';+import { mkdtempSync, readdirSync, rmSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { pagedReadWork, printPagedPage, REMOTE_PAGE_WINDOW_BYTES } from '../../src/cli/page-render.ts';+import { withEnv } from '../helpers/with-env.ts';++const MiB = 1024 * 1024;+const PAGE_BYTES = 64 * MiB;+const WINDOWS = PAGE_BYTES / REMOTE_PAGE_WINDOW_BYTES;+const HEAP_SLACK = 16 * MiB;++const spoolDir = mkdtempSync(join(tmpdir(), 'gbrain-paged-spool-'));+afterAll(() => rmSync(spoolDir, { recursive: true, force: true }));++/** Window `i` of the synthetic page: REMOTE_PAGE_WINDOW_BYTES of ASCII lines that name the window. */+function windowText(i: number): string {+ const line = `window ${String(i).padStart(4, '0')} of the large example page, bob-example talks about the widget plan\n`;+ return line.repeat(Math.ceil(REMOTE_PAGE_WINDOW_BYTES / line.length)).slice(0, REMOTE_PAGE_WINDOW_BYTES);+}++const pageSha = (() => {+ const hash = createHash('sha256');+ for (let i = 0; i < WINDOWS; i++) hash.update(windowText(i));+ return hash.digest('hex');+})();++/** A get_page host serving the synthetic page in markdown windows; `sha256` is what it reports. */+function host(sha256 = pageSha) {+ return async (p: Record<string, unknown>) => {+ const i = p.cursor === undefined ? 0 : Number(p.cursor);+ return { slug: p.slug, revision: 'rev-1', size: { total_bytes: PAGE_BYTES, sha256 },+ window: { byte_start: i * REMOTE_PAGE_WINDOW_BYTES, text: windowText(i) }, ...(i + 1 < WINDOWS ? { next_cursor: String(i + 1) } : {}) };+ };+}++function heapUsed(): number {+ Bun.gc(true);+ return process.memoryUsage().heapUsed;+}++test('a 64 MiB page prints window by window with the heap bounded by a window, not the page', () => withEnv({ TMPDIR: spoolDir }, async () => {+ pagedReadWork.spooled = pagedReadWork.replayed = 0;+ const hash = createHash('sha256');+ let writes = 0, bytes = 0, peak = 0, spoolMode = -1;+ const baseline = heapUsed();+ await printPagedPage(host(), { slug: 'logs/spool-example' }, async text => {+ const [spool] = writes === 0 ? readdirSync(spoolDir) : [];+ if (spool) spoolMode = statSync(join(spoolDir, spool)).mode & 0o777;+ if (writes % 16 === 0) peak = Math.max(peak, heapUsed() - baseline);+ hash.update(text);+ bytes += Buffer.byteLength(text);+ writes++;+ });+ console.log(JSON.stringify({ peakHeapMiB: +(peak / MiB).toFixed(1), writes }));+ expect(peak).toBeLessThan(HEAP_SLACK);+ expect(bytes).toBe(PAGE_BYTES);+ expect(hash.digest('hex')).toBe(pageSha);+ expect(writes).toBe(WINDOWS);+ expect(spoolMode).toBe(0o600);+ expect(pagedReadWork).toEqual({ spooled: WINDOWS, replayed: WINDOWS });+ expect(readdirSync(spoolDir)).toEqual([]);+}), 120_000);++test('a copy whose sha256 does not verify prints nothing and leaves no spool behind', () => withEnv({ TMPDIR: spoolDir }, async () => {+ const writes: string[] = [];+ await expect(printPagedPage(host('0'.repeat(64)), { slug: 'logs/spool-example' }, async text => { writes.push(text); })).rejects.toThrow(/does not match/);+ expect(writes).toEqual([]);+ expect(readdirSync(spoolDir)).toEqual([]);+}), 120_000);