Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(large-pages): fetch windows large pages from the search hit's chunk with next_id continuation
garrytan5ac298f3d378
diff --git a/src/core/deep-research-id.ts b/src/core/deep-research-id.tsindex 9e8f151a72..9324f8db85 100644--- a/src/core/deep-research-id.ts+++ b/src/core/deep-research-id.ts@@ -5,14 +5,32 @@ import type { PageKey } from './page-state/types.ts';const NAMESPACE = 'gbrain-page:';const PREFIX = `${NAMESPACE}v1:`;-export function encodeDeepResearchId(sourceId: string | undefined, slug: string): string {+/**+ * Large pages (Wave A, T24): an id may carry where to read in the page: the+ * search hit's chunk (`{ c: chunk_id }`) or a window continuation+ * (`{ w: cursor }`). The page identity decodes the same with or without it,+ * and the anchor grants nothing: fetch re-authorizes the page every time.+ */+export interface DeepResearchAnchor { chunkId?: number; cursor?: string }++export function encodeDeepResearchId(sourceId: string | undefined, slug: string, anchor?: DeepResearchAnchor): string {if (!isValidSourceId(sourceId) || typeof slug !== 'string' || validateSlug(slug) !== slug) {throw new Error('Invalid search result identity');}- return PREFIX + Buffer.from(JSON.stringify([sourceId, slug]), 'utf8').toString('base64url');+ const extra = anchor?.chunkId !== undefined ? [{ c: anchor.chunkId }] : anchor?.cursor !== undefined ? [{ w: anchor.cursor }] : [];+ return PREFIX + Buffer.from(JSON.stringify([sourceId, slug, ...extra]), 'utf8').toString('base64url');}-export function decodeDeepResearchId(id: string): PageKey | null {+function anchorOf(value: unknown): DeepResearchAnchor | null {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;+ const keys = Object.keys(value);+ const v = value as Record<string, unknown>;+ if (keys.length === 1 && keys[0] === 'c' && Number.isSafeInteger(v.c) && (v.c as number) > 0) return { chunkId: v.c as number };+ if (keys.length === 1 && keys[0] === 'w' && typeof v.w === 'string' && v.w.length > 0 && v.w.length <= 512) return { cursor: v.w };+ return null;+}++function decodeParts(id: string): { key: PageKey; anchor: DeepResearchAnchor | null } | null {if (id !== id.trim() && id.trim().startsWith(NAMESPACE)) throw new Error('Invalid result id encoding');if (!id.startsWith(NAMESPACE)) return null;if (!id.startsWith(PREFIX)) throw new Error('Unsupported result id version');@@ -20,12 +38,22 @@ export function decodeDeepResearchId(id: string): PageKey | null {if (!/^[A-Za-z0-9_-]+$/.test(payload)) throw new Error('Invalid result id encoding');const bytes = Buffer.from(payload, 'base64url');const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));- if (!Array.isArray(value) || value.length !== 2 ||+ const anchor = Array.isArray(value) && value.length === 3 ? anchorOf(value[2]) : null;+ if (!Array.isArray(value) || (value.length !== 2 && !(value.length === 3 && anchor)) ||typeof value[0] !== 'string' || typeof value[1] !== 'string' ||- encodeDeepResearchId(value[0], value[1]) !== id) {+ encodeDeepResearchId(value[0], value[1], anchor ?? undefined) !== id) {throw new Error('Invalid result id payload');}- return { sourceId: value[0], slug: value[1] };+ return { key: { sourceId: value[0], slug: value[1] }, anchor };+}++export function decodeDeepResearchId(id: string): PageKey | null {+ return decodeParts(id)?.key ?? null;+}++/** The read position an id carries, or null (a plain page id, or a legacy slug). Throws like decodeDeepResearchId on a malformed id. */+export function decodeDeepResearchAnchor(id: string): DeepResearchAnchor | null {+ return decodeParts(id)?.anchor ?? null;}export function deepResearchPageUrl(sourceId: string, slug: string): string {diff --git a/src/core/ops/context.ts b/src/core/ops/context.tsindex 1aa9ad8624..5f4a49efea 100644--- a/src/core/ops/context.ts+++ b/src/core/ops/context.ts@@ -1228,7 +1228,9 @@ export function stampEvidenceSafe(results: SearchResult[]): void {}export function stampDeepResearchIds(results: SearchResult[]): void {- for (const r of results) if (r.result_type !== 'fact') (r as SearchResult & { id?: string }).id = encodeDeepResearchId(r.source_id, r.slug);+ // Large pages (T24): the id names the hit's chunk, so fetch can return that evidence from a page too large to send whole.+ for (const r of results) if (r.result_type !== 'fact') (r as SearchResult & { id?: string }).id = encodeDeepResearchId(r.source_id, r.slug,+ Number.isSafeInteger(r.chunk_id) && r.chunk_id > 0 ? { chunkId: r.chunk_id } : undefined);}/** T4 — shared eval-capture for the `search` op (keyword-only + cheap-hybrid paths). */diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex c9874d7a45..5a91c3f0a4 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -30,9 +30,10 @@*/import type { Page } from '../types.ts';import type { OperationContext, ParamDef } from './contract.ts';-import { opError } from './contract.ts';+import { opError, OperationError } from './contract.ts';import { invalidParam, readFix } from './op-fix.ts';import { serializePageToMarkdown } from '../markdown.ts';+import { deepResearchPageUrl, encodeDeepResearchId } from '../deep-research-id.ts';import { encodedFrameBytes, EGRESS_CAP_CONFIG_KEYS, egressTransport, FRAME_RESERVE_BYTES, resultByteCap } from '../egress-budget.ts';import { DEFAULT_INLINE_BODY_BYTES, chunkDocumentSpan, readPageDocument, spanHoldsChunk, type PageDocument } from '../page-window/document.ts';import {@@ -351,3 +352,49 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadIreturn out;}++/**+ * Large pages (T24): fetch's window for a page over the inline read size, on+ * the search/fetch-only surface. A chunk anchor (from the search result id)+ * centers the window on that hit; a cursor anchor reads on. A chunk that is no+ * longer on the page falls back to the first window, and a cursor from an+ * older revision reads on from the same byte offset, so a fetch-only client+ * can always finish the page.+ */+export async function readFetchWindow(ctx: OperationContext, input: PartialReadInput, anchor: { chunkId?: number; cursor?: string } | null):+ Promise<{ partial: Record<string, any>; anchorStatus: 'chunk' | 'cursor' | 'start' | 'chunk_not_current' | 'cursor_rebased' }> {+ const req = (selector?: Selector): BodyRequest => ({ mode: 'window', view: 'read', contextLines: DEFAULT_CONTEXT_LINES, outlineFrom: 0, legacyThin: false, ...(selector ? { selector } : {}) });+ const stale = (e: unknown) => e instanceof OperationError && (e.canonical ?? e.code) === 'revision_changed';+ if (anchor?.chunkId !== undefined) {+ try { return { partial: await readPartialBody(ctx, input, req({ kind: 'around', chunkId: anchor.chunkId })), anchorStatus: 'chunk' }; }+ catch (e) { if (!stale(e)) throw e; return { partial: await readPartialBody(ctx, input, req()), anchorStatus: 'chunk_not_current' }; }+ }+ if (anchor?.cursor !== undefined) {+ try { return { partial: await readPartialBody(ctx, input, req({ kind: 'cursor', raw: anchor.cursor })), anchorStatus: 'cursor' }; }+ catch (e) {+ const c = decodeCursor(anchor.cursor);+ if (!stale(e) || !c) throw e;+ return { partial: await readPartialBody(ctx, input, req({ kind: 'bytes', offset: c.offset, length: c.max_bytes })), anchorStatus: 'cursor_rebased' };+ }+ }+ return { partial: await readPartialBody(ctx, input, req()), anchorStatus: 'start' };+}++/** fetch's response for a windowed page: the window as `text`, its position and the continuation id in metadata. */+export async function fetchWindowResult(ctx: OperationContext, input: PartialReadInput, id: string, anchor: { chunkId?: number; cursor?: string } | null): Promise<Record<string, unknown>> {+ const { page, revision, tags, quarantined, trust } = input;+ const { partial, anchorStatus } = await readFetchWindow(ctx, input, anchor);+ const w = partial.window ?? { text: '' };+ return {+ id,+ title: page.title,+ text: w.text,+ url: deepResearchPageUrl(page.source_id, page.slug),+ metadata: {+ revision, type: page.type, source_id: page.source_id, updated_at: page.updated_at, tags, ...(quarantined ? { quarantined } : {}), ...(trust ?? {}),+ truncated: true, total_bytes: partial.size?.total_bytes, anchor: anchorStatus,+ ...(typeof w.byte_start === 'number' ? { window: { byte_start: w.byte_start, byte_end: w.byte_end, line_start: w.line_start, line_end: w.line_end } } : {}),+ ...(partial.next_cursor ? { next_id: encodeDeepResearchId(page.source_id, page.slug, { cursor: partial.next_cursor }) } : {}),+ },+ };+}diff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 58e447dbe1..ad8a4183cd 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -13,12 +13,12 @@ import { assertPurgeParams } from '../persistence/purge-params.ts';import { clampSearchLimit, type BrainEngine } from '../engine.ts';import type { Page } from '../types.ts';-import { decodeDeepResearchId, deepResearchPageUrl } from '../deep-research-id.ts';+import { decodeDeepResearchAnchor, decodeDeepResearchId, deepResearchPageUrl } from '../deep-research-id.ts';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 { assertFullReadFits, bodyBytes, fetchWindowResult, 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';@@ -243,7 +243,7 @@ const fetch_page: Operation = {name: 'fetch',idempotent: true,outputRedaction: { exempt: 'explicit page read by slug/id; governed by page visibility, not output redaction (CEO-17 raw-read exception)' },- description: "Fetch the full text of one search result by its opaque, source-qualified `id` (OpenAI deep-research contract: the search/fetch pair). Pass the id unchanged; it does not grant access. Legacy slug ids work only when unambiguous within your current read scope. Returns { id, title, text, url, metadata } — `text` is the page's canonical markdown. For fuzzy slugs, soft-delete recovery, or lossless edit round-trips, use get_page.",+ description: "Fetch the full text of one search result by its opaque, source-qualified `id` (OpenAI deep-research contract: the search/fetch pair). Pass the id unchanged; it does not grant access. Legacy slug ids work only when unambiguous within your current read scope. Returns { id, title, text, url, metadata } — `text` is the page's canonical markdown; a page over 256 KB returns the window around the searched chunk instead, with metadata.total_bytes and metadata.next_id (fetch it to read on). For fuzzy slugs, soft-delete recovery, or lossless edit round-trips, use get_page.",params: {id: { type: 'string', required: true, description: 'Opaque result id from a prior `search` call. Pass unchanged. Unambiguous legacy slugs are also accepted.' },include_quarantined: { type: 'boolean', description: 'Admin: quarantined body.' },@@ -293,6 +293,9 @@ const fetch_page: Operation = {// Same boundaries as get_page: untrusted readers never see takes or private facts fences, nor a quarantined body (#6259).const visibleBody = ctx.remote === false ? page : stripPrivacyFencesForRemoteReader(page);const quarantined = readQuarantined(ctx, page, p.include_quarantined === true);+ if (ctx.remote !== false && !quarantined?.body_omitted && bodyBytes(visibleBody) > await inlineBodyBytes(ctx)) {+ return fetchWindowResult(ctx, { page, visibleBody: visibleBody as Page, revision: snapshot!.revision, tags, quarantined, trust: readable.trust, extras: {} }, id, identity ? decodeDeepResearchAnchor(id) : null);+ }return {id: identity ? id : page.slug,title: page.title,diff --git a/test/fetch-large-page.test.ts b/test/fetch-large-page.test.tsnew file mode 100644index 0000000000..c9cbca3fd2--- /dev/null+++ b/test/fetch-large-page.test.ts@@ -0,0 +1,101 @@+/**+ * Large pages (Wave A, T24): the search/fetch-only surface reads a page too+ * large to send whole. A search result id names the hit's chunk, so fetch+ * returns that evidence rather than the first window; metadata.next_id reads+ * on to the end; stale anchors still finish the page. Hermetic PGLite.+ */+import { describe, test, expect, beforeAll, afterAll } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operations, 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 { decodeDeepResearchAnchor, decodeDeepResearchId, encodeDeepResearchId } from '../src/core/deep-research-id.ts';++let engine: PGLiteEngine;+const fetchOp = operations.find(o => o.name === 'fetch')!;+const searchOp = operations.find(o => o.name === 'search')!;+const ctx = (): OperationContext => ({ engine, config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false,+ remote: true, transport: 'http', sourceId: 'default', auth: { allowedSources: ['default'] } } as unknown as OperationContext);+const fetch = async (id: string) => await fetchOp.handler(ctx(), { id }) as Record<string, any>;++function log(lines: number, marker: (i: number) => string = () => ''): string {+ return ['# Planning log', '', ...Array.from({ length: lines }, (_, i) => `- 2026-05-${String(1 + (i % 28)).padStart(2, '0')} entry ${i} about the acme-example widget plan${marker(i)}`)].join('\n');+}+async function put(slug: string, body: string) {+ const r = await importFromContent(engine, slug, serializeMarkdown({}, body, '', { type: 'note', title: slug, tags: [] }), { sourceId: 'default', noEmbed: true, forceRechunk: true });+ expect(r.status).toBe('imported');+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('search.mcp_keyword_only', 'true');+ await put('notes/long-example', log(6000, i => (i === 5800 ? ' quasarneedle deep hit' : '')));+ await put('notes/short-example', 'A short page about quasarneedle short.');+}, 120_000);+afterAll(async () => { await engine.disconnect(); }, 60_000);++describe('fetch on a large page', () => {+ test('a deep search hit fetches its own evidence, not the first window', async () => {+ const hits = await searchOp.handler(ctx(), { query: 'quasarneedle deep' }) as any[];+ const hit = hits.find(h => h.slug === 'notes/long-example');+ expect(hit).toBeDefined();+ expect(decodeDeepResearchId(hit.id)).toEqual({ sourceId: 'default', slug: 'notes/long-example' });+ expect(decodeDeepResearchAnchor(hit.id)).toEqual({ chunkId: hit.chunk_id });+ const page = await fetch(hit.id);+ expect(page.id).toBe(hit.id);+ expect(page.text).toContain('quasarneedle deep hit');+ expect(page.metadata.anchor).toBe('chunk');+ expect(page.metadata.truncated).toBe(true);+ expect(page.metadata.window.byte_start).toBeGreaterThan(page.metadata.total_bytes / 2);+ expect(page.url).toBe('gbrain://page/default/notes/long-example');+ }, 60_000);++ test('next_id pages the whole read projection, in order, using only fetch', async () => {+ const snap = await engine.readPageSnapshot('notes/long-example', { sourceId: 'default' });+ const doc = pageDocument({ compiled_truth: snap!.page.compiled_truth, timeline: snap!.page.timeline }).bytes;+ const parts: string[] = [];+ let page = await fetch(encodeDeepResearchId('default', 'notes/long-example'));+ expect(page.metadata.anchor).toBe('start');+ for (let i = 0; i < 500; i++) {+ parts.push(page.text);+ if (!page.metadata.next_id) break;+ page = await fetch(page.metadata.next_id);+ expect(page.metadata.anchor).toBe('cursor');+ }+ expect(Buffer.from(parts.join(''), 'utf8').equals(doc)).toBe(true);+ }, 120_000);++ test('a chunk anchor from before a re-chunk falls back to the first window; an old continuation reads on from its offset', async () => {+ await put('notes/moving-example', log(6000));+ const first = await fetch(encodeDeepResearchId('default', 'notes/moving-example'));+ const next = first.metadata.next_id as string;+ const staleChunk = encodeDeepResearchId('default', 'notes/moving-example', { chunkId: 987654321 });+ await put('notes/moving-example', log(6001));+ const fromChunk = await fetch(staleChunk);+ expect(fromChunk.metadata.anchor).toBe('chunk_not_current');+ expect(fromChunk.metadata.window.byte_start).toBe(0);+ const rebased = await fetch(next);+ expect(rebased.metadata.anchor).toBe('cursor_rebased');+ expect(rebased.metadata.window.byte_start).toBeLessThanOrEqual(first.metadata.window.byte_end);+ expect(rebased.metadata.window.byte_start).toBeGreaterThan(0);+ }, 120_000);++ test('a small page still fetches whole, whatever the id carries', async () => {+ const hits = await searchOp.handler(ctx(), { query: 'quasarneedle short' }) as any[];+ const hit = hits.find(h => h.slug === 'notes/short-example');+ const page = await fetch(hit.id);+ expect(page.text).toContain('A short page about quasarneedle short.');+ expect(page.text.startsWith('---\n')).toBe(true);+ expect(page.metadata.truncated).toBeUndefined();+ }, 60_000);++ test('ids reject malformed anchors', () => {+ const wrap = (v: unknown) => 'gbrain-page:v1:' + Buffer.from(JSON.stringify(v)).toString('base64url');+ for (const bad of [['default', 'notes/x', { c: 0 }], ['default', 'notes/x', { c: 'x' }], ['default', 'notes/x', { w: '' }], ['default', 'notes/x', { c: 1, w: 'a' }], ['default', 'notes/x', 5]]) {+ expect(() => decodeDeepResearchId(wrap(bad))).toThrow();+ }+ });+});