Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(get): section and grep slices of a page, chars on every get_page response (#7180)
garrytan37444df6892a
diff --git a/src/cli/page-render.ts b/src/cli/page-render.tsindex e76df8e4b8..04758a8d9a 100644--- a/src/cli/page-render.ts+++ b/src/cli/page-render.ts@@ -3,7 +3,7 @@* 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+ * (body none / outline / window, a section, grep blocks) 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.*@@ -62,6 +62,20 @@ function renderOutline(r: GetPageResult): string {return lines.join('\n') + '\n';}+/** A section or grep read (#7180): its text on stdout, where it sits in the page on stderr. */+function renderSlice(r: GetPageResult): string {+ const more = r.truncated ? ' Truncated: some of it was not printed.' : '';+ if (r.section) {+ const s = r.section;+ const next = r.next?.arguments?.lines ? ` Read on: gbrain get ${r.slug} --lines '${JSON.stringify(r.next.arguments.lines)}'` : '';+ process.stderr.write(`[gbrain] section ${(s.heading_path ?? [s.heading]).join(' > ')}: lines ${s.line_start}-${s.line_end}, ${r.chars} chars.${more}${next}\n`);+ return s.text.endsWith('\n') ? s.text : `${s.text}\n`;+ }+ const g = r.grep;+ process.stderr.write(`[gbrain] grep ${JSON.stringify(g.term)}: ${g.total_matches} matching paragraph${g.total_matches === 1 ? '' : 's'}${g.omitted_matches ? `, ${g.returned_matches} printed` : ''}, ${r.chars} chars.${more}\n`);+ return g.blocks.map((b: GetPageResult) => `-- lines ${b.line_start}-${b.line_end} (match at ${b.match_starts.join(', ')})\n${b.text}\n`).join('');+}+/** stdout text for one get_page result; partial responses add a stderr note. */export function formatGetPage(r: GetPageResult): string {if (r.error === 'ambiguous_slug') {@@ -70,6 +84,7 @@ export function formatGetPage(r: GetPageResult): string {if (typeof r.body !== 'string') {return serializeMarkdown(r.frontmatter || {}, r.compiled_truth || '', r.timeline || '', { type: r.type, title: r.title, tags: r.tags || [] });}+ if (r.section || r.grep) return renderSlice(r);process.stderr.write(partialNote(r) + '\n');if (r.window) return r.window.text;if (r.outline) return renderOutline(r);@@ -86,7 +101,7 @@ export function remoteErrorCode(e: unknown): string | 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);+ return ['body', 'lines', 'bytes', 'around_chunk_id', 'cursor', 'include_content', 'content_only', 'section', 'grep'].every(k => params[k] === undefined);}/**diff --git a/src/core/ops/get-page-body.ts b/src/core/ops/get-page-body.tsindex 37bbbb039e..76787ae57a 100644--- a/src/core/ops/get-page-body.ts+++ b/src/core/ops/get-page-body.ts@@ -51,6 +51,7 @@ import { TIMELINE_SEPARATOR } from '../page-window/document.ts';import { renderTrustedText, type TrustFields } from '../eligibility/labels.ts';import { pageTrustForRead, type QuarantinedView } from './get-page-projection.ts';import { chunkGenerationProbe, chunkManifestReads } from '../search/safe-chunks.ts';+import { GET_PAGE_SLICE_PARAMS, parseSliceRequest, readGrep, readSection, sliceCharBudget, type SliceRequest } from './get-page-slice.ts';export const BODY_MODES = ['auto', 'full', 'none', 'outline', 'window'] as const;export type BodyMode = typeof BODY_MODES[number];@@ -75,6 +76,7 @@ export const GET_PAGE_BODY_PARAMS: Record<string, ParamDef> = {max_bytes: { type: 'number', description: 'Window bytes (40000).', fullSurfaceOnly: true },view: { type: 'string', enum: ['read', 'markdown'], description: 'markdown: page the round-trip content.', fullSurfaceOnly: true },outline_from: { type: 'number', description: 'Outline next_from_index.', fullSurfaceOnly: true },+ ...GET_PAGE_SLICE_PARAMS,};type Selector =@@ -92,6 +94,8 @@ export interface BodyRequest {outlineFrom: number;/** The caller named no mode and is gbrain's thin client (full or refused, never a window). */legacyThin: boolean;+ /** section or grep (#7180): one part of the read view instead of a window. */+ slice?: SliceRequest;}const SELECTOR_EXAMPLE = { slug: 'notes/acme-example-log', body: 'window', lines: { from: 1, count: 200 } };@@ -105,6 +109,8 @@ export function parseBodyRequest(ctx: Pick<OperationContext, 'remote' | 'transpoif (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 slice = parseSliceRequest(ctx, p);+ if (slice) return { mode: 'window', view: 'read', contextLines: DEFAULT_CONTEXT_LINES, outlineFrom: 0, legacyThin: false, slice };const selectors: Selector[] = [];if (p.lines !== undefined) {const l = p.lines as Record<string, unknown> | null;@@ -337,6 +343,8 @@ interface WindowDocument {from(offset: number, maxBytes: number): Promise<WindowSlice>;lines(from: number, count: number, maxBytes: number): Promise<WindowSlice>;bytes(offset: number, length: number): Promise<WindowSlice>;+ /** The whole document in order, one segment (or the inline page) at a time: what section and grep scan. */+ stream(): AsyncIterable<Buffer>;/** around_chunk_id's text: the inline document, or the segmented read view. */inline?: PageDocument;segments?: SegmentedDocument;@@ -349,6 +357,7 @@ function inlineDocument(doc: PageDocument): WindowDocument {from: async (offset, maxBytes) => windowFrom(doc.bytes, offset, maxBytes),lines: async (from, count, maxBytes) => windowForLines(doc.bytes, from, count, maxBytes),bytes: async (offset, length) => windowForBytes(doc.bytes, offset, length),+ stream: async function* () { yield doc.bytes; },};}@@ -378,6 +387,7 @@ async function segmentedWindows(ctx: OperationContext, input: PartialReadInput,from: (offset, maxBytes) => seg.from(offset, maxBytes),lines: (from, count, maxBytes) => seg.lines(from, count, maxBytes),bytes: (offset, length) => seg.bytes(offset, length),+ stream: () => seg.stream(),} };}@@ -455,7 +465,7 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI};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 };+ if (omitted) return { ...base, body: mode, truncated: true, body_omitted: true, chars: 0 };const markdown = req.view === 'markdown';let doc: WindowDocument;@@ -477,8 +487,17 @@ export async function readPartialBody(ctx: OperationContext, input: PartialReadI// A segmented read is returned only while the page is still at the revision its caller was authorized for.const confirmed = async (result: Record<string, unknown>) => {if (doc.segments) await confirmBodyPin(ctx.engine, doc.segments.body);- return result;+ const text = (result.window as { text?: unknown } | undefined)?.text;+ return 'chars' in result ? result : { ...result, chars: typeof text === 'string' ? text.length : 0 };};+ if (req.slice) {+ const wrap = (text: string) => envelopeText(text, quarantined, trust);+ const budget = await sliceCharBudget(ctx);+ const sliced = req.slice.kind === 'section'+ ? await readSection(page, doc.stream(), req.slice.heading, budget, wrap)+ : await readGrep(doc.stream(), req.slice.term, req.slice.context, budget, wrap);+ return confirmed({ ...out, ...sliced });+ }if (mode === 'none') return confirmed(await noneResult(ctx, page, out, doc.total > 0));diff --git a/src/core/ops/get-page-projection.ts b/src/core/ops/get-page-projection.tsindex 06b37536b9..2d44ffc7aa 100644--- a/src/core/ops/get-page-projection.ts+++ b/src/core/ops/get-page-projection.ts@@ -80,6 +80,8 @@ export interface GetPageProjectionOpts {* and revision included, so the write goes back to the page that was read), without* the duplicate compiled_truth / timeline / frontmatter the full shape carries* next to `content` (a 30 KB page otherwise comes back as ~62 KB).+ * Both shapes carry `chars` (#7180): the characters of page text the response+ * holds (compiled_truth, timeline and `content`), so a caller can budget.*/export function projectGetPage(page: Page, o: GetPageProjectionOpts) {const { revision, tags, resolved_slug, content_flag, quarantined } = o;@@ -96,6 +98,7 @@ export function projectGetPage(page: Page, o: GetPageProjectionOpts) {};if (o.includeContent && o.contentOnly) {const deletedAt = visibleBody.deleted_at;+ const text = omitted ? undefined : content();return {slug: visibleBody.slug,source_id: visibleBody.source_id,@@ -103,16 +106,19 @@ export function projectGetPage(page: Page, o: GetPageProjectionOpts) {title: visibleBody.title,revision,tags,- ...(omitted ? {} : { content: content() }),+ ...(text === undefined ? {} : { content: text }),+ chars: text?.length ?? 0,...(deletedAt ? { deleted_at: deletedAt } : {}),...extras,};}+ const text = o.includeContent && !omitted ? content() : undefined;return {...visibleBody,revision,tags,- ...(o.includeContent && !omitted ? { content: content() } : {}),+ ...(text === undefined ? {} : { content: text }),+ chars: (visibleBody.compiled_truth ?? '').length + (visibleBody.timeline ?? '').length + (text?.length ?? 0),// #5575 A6: the reading shape carries the page's trust; the content_only round-trip shape stays minimal....(o.trust ?? {}),...extras,diff --git a/src/core/ops/get-page-slice.ts b/src/core/ops/get-page-slice.tsnew file mode 100644index 0000000000..fc72b36678--- /dev/null+++ b/src/core/ops/get-page-slice.ts@@ -0,0 +1,301 @@+/**+ * #7180: get_page `section` and `grep`, one part of a page instead of the whole.+ *+ * section: "<heading>" the section under the first ATX heading whose text+ * equals it (case-insensitive, whitespace folded): the+ * heading line down to the next heading of the same or+ * a higher level (or the timeline separator), with the+ * ancestor headings in heading_path. A miss is+ * invalid_params naming up to SECTION_HEADINGS_LISTED+ * of the page's headings.+ * grep: "<term>" the paragraphs (blank-line-separated blocks) holding+ * context: N a line that contains the term (plain substring,+ * case-insensitive, never a regex), each with N+ * paragraphs either side (default 1, at most 5);+ * windows that overlap or touch merge into one block.+ * Capped at GREP_MAX_MATCHES matching paragraphs and+ * the character budget; total_matches counts them all.+ *+ * Both read the read projection (page-window/document.ts), the text every+ * window and outline is cut from, after get_page authorized and loaded the+ * page: a slice shows nothing a window could not, and its line numbers are+ * the ones body: 'window' lines takes. The document arrives as a stream of+ * buffers (one for an inline page, one per segment for a segmented page) and+ * is scanned line by line, so a segmented page is never held whole: memory is+ * the returned text plus one segment and at most context paragraphs.+ */+import type { OperationContext, ParamDef } from './contract.ts';+import { opError } from './contract.ts';+import { invalidParam, readFix } from './op-fix.ts';+import { resultByteCap } from '../egress-budget.ts';+import { FENCE, HEADING, HEADING_MAX_CHARS, clip } from '../page-window/window.ts';++export const GET_PAGE_SLICE_PARAMS: Record<string, ParamDef> = {+ section: { type: 'string', description: 'Only the section under this heading (case-insensitive, first match), with its heading_path.', fullSurfaceOnly: true },+ grep: { type: 'string', description: 'Only the paragraphs containing this text (case-insensitive substring, not a regex), with line numbers and total_matches.', fullSurfaceOnly: true },+ context: { type: 'number', description: 'With grep: paragraphs of context either side (default 1, max 5).', fullSurfaceOnly: true },+};++export const DEFAULT_GREP_CONTEXT = 1;+export const MAX_GREP_CONTEXT = 5;+/** Matching paragraphs one grep returns; the rest are counted in total_matches. */+export const GREP_MAX_MATCHES = 50;+/** Characters of page text one section or grep returns (fewer when the connection's egress cap is smaller). */+export const SLICE_MAX_CHARS = 100_000;+/** Headings a section miss lists. */+export const SECTION_HEADINGS_LISTED = 20;+const MAX_QUERY_CHARS = 500;+/** A line longer than this is scanned in pieces that share its line number. */+const LINE_PIECE_BYTES = 1024 * 1024;+/** Room a sliced response keeps for its metadata inside the egress cap. */+const RESERVE_BYTES = 64 * 1024;+const TIMELINE_LINE = '<!-- timeline -->';+const NL = 0x0a;++export type SliceRequest = { kind: 'section'; heading: string } | { kind: 'grep'; term: string; context: number };++const SECTION_EXAMPLE = { slug: 'notes/acme-example-log', section: 'Next steps' };+const GREP_EXAMPLE = { slug: 'notes/acme-example-log', grep: 'widget', context: 2 };++/** The slice a get_page call asks for, or undefined; throws invalid_params on a malformed value or a conflicting param. */+export function parseSliceRequest(ctx: Pick<OperationContext, 'remote' | 'transport'>, p: Record<string, unknown>): SliceRequest | undefined {+ const bad = (param: string, message: string, example: unknown) => invalidParam(ctx, 'get_page', param, message, { example });+ if (p.section === undefined && p.grep === undefined) {+ if (p.context !== undefined) throw bad('context', 'get_page: context applies to grep; pass grep with it.', GREP_EXAMPLE);+ return undefined;+ }+ if (p.section !== undefined && p.grep !== undefined) throw bad('grep', 'get_page: pass section or grep, not both.', GREP_EXAMPLE);+ const param = p.section !== undefined ? 'section' : 'grep';+ const example = param === 'section' ? SECTION_EXAMPLE : GREP_EXAMPLE;+ const value = p[param];+ if (typeof value !== 'string' || !value.trim() || value.length > MAX_QUERY_CHARS) {+ throw bad(param, `get_page: ${param} must be a non-empty string of at most ${MAX_QUERY_CHARS} characters.`, example);+ }+ for (const other of ['lines', 'bytes', 'around_chunk_id', 'cursor', 'include_content', 'content_only']) {+ if (p[other] !== undefined && p[other] !== false) throw bad(param, `get_page: ${param} returns part of the read view; it does not combine with ${other}.`, example);+ }+ if (p.body !== undefined && p.body !== 'auto' && p.body !== 'window') throw bad('body', `get_page: ${param} does not combine with body: '${String(p.body)}'.`, example);+ if (p.view !== undefined && p.view !== 'read') throw bad('view', `get_page: ${param} reads view 'read' only.`, example);+ if (param === 'section') {+ if (p.context !== undefined) throw bad('context', 'get_page: context applies to grep, not section.', GREP_EXAMPLE);+ return { kind: 'section', heading: value };+ }+ let context = DEFAULT_GREP_CONTEXT;+ if (p.context !== undefined) {+ if (typeof p.context !== 'number' || !Number.isSafeInteger(p.context) || p.context < 0) {+ throw bad('context', 'get_page: context must be a non-negative integer (paragraphs either side of a match).', GREP_EXAMPLE);+ }+ context = Math.min(MAX_GREP_CONTEXT, p.context);+ }+ return { kind: 'grep', term: value, context };+}++/** The first n UTF-16 units of text, never splitting a surrogate pair. */+function head(text: string, n: number): string {+ if (text.length <= n) return text;+ const c = text.charCodeAt(n - 1);+ return text.slice(0, c >= 0xd800 && c <= 0xdbff ? n - 1 : n);+}++interface Line { text: string; line: number; continued: boolean }++/** The document's lines (1-based) across buffer boundaries; a line over LINE_PIECE_BYTES arrives in pieces (continued). */+async function* documentLines(stream: AsyncIterable<Buffer>): AsyncGenerator<Line> {+ let carry: Buffer[] = [];+ let carryBytes = 0;+ let line = 1;+ let continued = false;+ const take = (tail: Buffer): string => {+ const text = (carry.length ? Buffer.concat([...carry, tail]) : tail).toString('utf8');+ carry = [];+ carryBytes = 0;+ return text;+ };+ for await (const buf of stream) {+ let at = 0;+ for (let nl = buf.indexOf(NL); nl !== -1; nl = buf.indexOf(NL, at)) {+ yield { text: take(buf.subarray(at, nl)), line, continued };+ line++;+ continued = false;+ at = nl + 1;+ }+ if (at < buf.length) {+ carry.push(buf.subarray(at));+ carryBytes += buf.length - at;+ }+ if (carryBytes <= LINE_PIECE_BYTES) continue;+ const joined = Buffer.concat(carry);+ let cut = joined.length;+ while (cut > 0 && (joined[cut - 1]! & 0xc0) === 0x80) cut--;+ if (cut > 0 && joined[cut - 1]! >= 0xc0) cut--;+ if (cut === 0) cut = joined.length;+ carry = cut < joined.length ? [joined.subarray(cut)] : [];+ carryBytes = joined.length - cut;+ yield { text: joined.subarray(0, cut).toString('utf8'), line, continued };+ continued = true;+ }+ if (carryBytes > 0) yield { text: take(Buffer.alloc(0)), line, continued };+}++const fold = (s: string) => s.replace(/\s+/g, ' ').trim().toLowerCase();++/** Characters this caller may receive in one slice. */+export async function sliceCharBudget(ctx: OperationContext): Promise<number> {+ const cap = await resultByteCap({ remote: ctx.remote, transport: ctx.transport, engine: ctx.engine, config: ctx.config });+ // A character is at most 3 UTF-8 bytes, and escaping through the frame's two JSON levels can double it.+ return Number.isFinite(cap) ? Math.max(4096, Math.min(SLICE_MAX_CHARS, Math.floor((cap - RESERVE_BYTES) / 6))) : SLICE_MAX_CHARS;+}++interface SliceTarget { slug: string; source_id: string }++/** The response fields of a section read, or the invalid_params miss naming the page's headings. */+export async function readSection(page: SliceTarget, stream: AsyncIterable<Buffer>, heading: string, budget: number,+ wrap: (text: string) => string): Promise<Record<string, unknown>> {+ const want = fold(heading.replace(/^\s*#{1,6}(?=\s)/, ''));+ const stack: Array<{ level: number; text: string }> = [];+ const listed: string[] = [];+ let headings = 0;+ let fence = false;+ let hit: { level: number; text: string; path: string[]; line_start: number } | null = null;+ const kept: string[] = [];+ let chars = 0, lastKept = 0, lastText = 0, omitted = 0, firstOmitted = 0;+ for await (const l of documentLines(stream)) {+ let h: RegExpExecArray | null = null;+ if (!l.continued) {+ if (FENCE.test(l.text)) fence = !fence;+ else if (!fence) h = HEADING.exec(l.text);+ if (!fence && l.text.trim() === TIMELINE_LINE) {+ if (hit) break;+ stack.length = 0;+ continue;+ }+ }+ if (h) {+ const level = h[1]!.length;+ const text = h[2]!;+ if (hit && level <= hit.level) break;+ while (stack.length && stack[stack.length - 1]!.level >= level) stack.pop();+ if (!hit) {+ headings++;+ if (listed.length < SECTION_HEADINGS_LISTED) listed.push(clip(text, HEADING_MAX_CHARS));+ if (fold(text) === want) hit = { level, text, path: [...stack.map(s => s.text), text], line_start: l.line };+ }+ stack.push({ level, text });+ }+ if (!hit || !l.text.trim()) continue;+ lastText = l.line;+ const piece = (l.continued || !kept.length ? '' : '\n'.repeat(l.line - lastKept)) + l.text;+ if (omitted || chars + piece.length > budget) {+ if (!omitted) firstOmitted = l.line;+ omitted += piece.length;+ continue;+ }+ kept.push(piece);+ chars += piece.length;+ lastKept = l.line;+ }+ if (!hit) {+ const more = headings > listed.length ? ` (first ${listed.length} of ${headings})` : '';+ throw opError('invalid_params',+ `get_page: page ${page.slug} has no heading ${JSON.stringify(clip(heading, HEADING_MAX_CHARS))}. ${headings ? `Headings${more}: ${listed.map(t => JSON.stringify(t)).join(', ')}.` : 'It has no headings.'}`,+ headings ? 'Pass section as one of the listed headings (case-insensitive), or read the outline for every heading and its lines.' : 'Search it with grep, or read it in windows from its outline.',+ { detail: JSON.stringify({ headings: listed, total_headings: headings }),+ fix: readFix("Returns the page's outline: every heading with its line range.",+ { argv: ['gbrain', 'get', '--source', page.source_id, '--body', 'outline', '--', page.slug], mcp: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'outline' } } }) });+ }+ const text = wrap(kept.join(''));+ const lineEnd = Math.max(lastText, hit.line_start);+ return {+ body: 'section',+ section: { heading: hit.text, level: hit.level, heading_path: hit.path, line_start: hit.line_start, line_end: lineEnd, text },+ chars: text.length,+ truncated: omitted > 0,+ ...(omitted ? { omitted_chars: omitted, next: { tool: 'get_page', arguments: { slug: page.slug, source_id: page.source_id, body: 'window', lines: { from: firstOmitted, count: lineEnd - firstOmitted + 1 } } } } : {}),+ };+}++interface Paragraph { line_start: number; line_end: number; text: string; match: boolean }+interface Block { line_start: number; line_end: number; match_starts: number[]; parts: string[] }++/** The response fields of a grep read: merged blocks of matching paragraphs and their context, capped, with total_matches. */+export async function readGrep(stream: AsyncIterable<Buffer>, term: string, context: number, budget: number,+ wrap: (text: string) => string): Promise<Record<string, unknown>> {+ const needle = term.toLowerCase();+ const blocks: Block[] = [];+ let current: Block | null = null;+ let afterLeft = 0;+ let pending: Paragraph[] = [];+ let gap = 0;+ let total = 0, returned = 0, chars = 0;+ let full = false, clipped = false;+ /** Append p to b within the character budget (cut at the budget once); false when nothing of it fit. */+ const add = (b: Block, p: Paragraph): boolean => {+ if (full) return false;+ const sep = b.parts.length ? '\n'.repeat(p.line_start - b.line_end) : '';+ let piece = sep + p.text;+ if (chars + piece.length > budget) {+ full = clipped = true;+ const room = budget - chars - sep.length;+ if (room <= 0) return false;+ piece = sep + head(p.text, room);+ }+ b.parts.push(piece);+ chars += piece.length;+ b.line_end = p.line_end;+ return true;+ };+ const close = (p: Paragraph) => {+ if (!p.match) {+ if (current && afterLeft > 0) {+ add(current, p);+ afterLeft--;+ return;+ }+ gap++;+ pending.push(p);+ if (pending.length > context) pending.shift();+ return;+ }+ total++;+ if (full || returned >= GREP_MAX_MATCHES) {+ full = true;+ current = null;+ return;+ }+ if (!current || (afterLeft === 0 && gap > context)) {+ const first = pending[0] ?? p;+ current = { line_start: first.line_start, line_end: first.line_start, match_starts: [], parts: [] };+ blocks.push(current);+ }+ for (const q of pending) add(current, q);+ pending = [];+ gap = 0;+ afterLeft = context;+ if (add(current, p)) {+ current.match_starts.push(p.line_start);+ returned++;+ }+ };+ let para: Paragraph | null = null;+ for await (const l of documentLines(stream)) {+ if (!l.continued && !l.text.trim()) {+ if (para) close(para);+ para = null;+ continue;+ }+ if (!para) para = { line_start: l.line, line_end: l.line, text: '', match: false };+ const sep = para.text && !l.continued ? '\n' : '';+ if (para.text.length <= budget) para.text += sep + head(l.text, budget + 1 - para.text.length);+ para.line_end = l.line;+ if (!para.match && l.text.toLowerCase().includes(needle)) para.match = true;+ }+ if (para) close(para);+ const out = blocks.filter(b => b.match_starts.length)+ .map(b => ({ line_start: b.line_start, line_end: b.line_end, match_starts: b.match_starts, text: wrap(b.parts.join('')) }));+ return {+ body: 'grep',+ grep: { term, context, total_matches: total, returned_matches: returned, omitted_matches: total - returned, blocks: out },+ chars: out.reduce((n, b) => n + b.text.length, 0),+ truncated: total > returned || clipped,+ };+}diff --git a/src/core/ops/known-as-of.ts b/src/core/ops/known-as-of.tsindex 9bea00610b..5148f237fc 100644--- a/src/core/ops/known-as-of.ts+++ b/src/core/ops/known-as-of.ts@@ -20,7 +20,7 @@ export const VERSIONS_DIFF_PARAM: ParamDef = { type: 'boolean', fullSurfaceOnly:/** get_page parameters that select a body window, a fuzzy match or an edit view, none of which a historical read serves. */const GET_PAGE_UNSUPPORTED = ['fuzzy', 'include_content', 'content_only', 'include_timeline_entries', 'grammar_diagnostics', 'include_quarantined',- 'lines', 'bytes', 'around_chunk_id', 'context_lines', 'cursor', 'max_bytes', 'view', 'outline_from'] as const;+ 'lines', 'bytes', 'around_chunk_id', 'context_lines', 'cursor', 'max_bytes', 'view', 'outline_from', 'section', 'grep', 'context'] as const;/*** The one source a recorded-time read targets: the explicit or ambient source, else the only granted source whosediff --git a/src/core/ops/pages.ts b/src/core/ops/pages.tsindex 741c9d2f17..ef32da8d9a 100644--- a/src/core/ops/pages.ts+++ b/src/core/ops/pages.ts@@ -89,15 +89,15 @@ 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: include_content:true, send `content` to put_page; or edit_page. >256 KB: outline+window, then `next`.',+ description: 'Read a page; `section` or `grep` reads one part. Edit: include_content:true, `content` to put_page, or edit_page. >256 KB: outline+window, then `next`.',params: {slug: { type: 'string', description: 'Page slug.', required: true },- fuzzy: { type: 'boolean', description: 'Fuzzy slug match.' },- include_content: { type: 'boolean', description: 'Markdown + revision, to edit.' },- content_only: { type: 'boolean', description: 'Round-trip fields only.' },+ fuzzy: { type: 'boolean', description: 'Fuzzy match.' },+ include_content: { type: 'boolean', description: 'Markdown + revision.' },+ content_only: { type: 'boolean', description: 'Round-trip fields.' },...GET_PAGE_BODY_PARAMS,include_deleted: { type: 'boolean', description: 'Soft-deleted too.' },- include_timeline_entries: { type: 'boolean', description: 'Timeline rows too.' },+ include_timeline_entries: { type: 'boolean', description: 'Timeline rows.' },grammar_diagnostics: { type: 'boolean', description: 'Also return every line-grammar finding for the page.', fullSurfaceOnly: true },source_id: { type: 'string', description: "One source, or '__all__'." },include_quarantined: { type: 'boolean', description: 'Admin: quarantined body.' },diff --git a/test/get-page-content-roundtrip-2225.test.ts b/test/get-page-content-roundtrip-2225.test.tsindex 89fd0d7365..2c9dd92703 100644--- a/test/get-page-content-roundtrip-2225.test.ts+++ b/test/get-page-content-roundtrip-2225.test.ts@@ -192,7 +192,7 @@ describe('content_only round trip across sources', () => {test('lean keys are pinned and include source_id', async () => {await putPage.handler(localCtx('work'), { slug: 'companies/keys-example', content: PAGE('Keys.') });const page = await lean('companies/keys-example', 'work');- expect(Object.keys(page).sort()).toEqual(['content', 'revision', 'slug', 'source_id', 'tags', 'title', 'type']);+ expect(Object.keys(page).sort()).toEqual(['chars', 'content', 'revision', 'slug', 'source_id', 'tags', 'title', 'type']);expect(page.source_id).toBe('work');}, 30_000);diff --git a/test/get-page-slices.test.ts b/test/get-page-slices.test.tsnew file mode 100644index 0000000000..ea99ac8be8--- /dev/null+++ b/test/get-page-slices.test.ts@@ -0,0 +1,378 @@+/**+ * #7180: get_page section and grep (gbrain get --section / --grep).+ *+ * 1. Protects: a section is the first heading whose text equals the request+ * (case-insensitive) down to the next heading of the same or higher level,+ * never a heading inside a code fence, never past the timeline separator,+ * with its heading_path and line numbers that body: 'window' lines reads+ * back; a miss names at most 20 headings. grep returns the paragraphs with+ * a line containing the term (literal, case-insensitive) with N paragraphs+ * of context, merges windows that overlap or touch, caps matches and+ * characters and counts every match. Every response carries chars. Remote+ * slices are cut from the read projection after authorization, so they+ * show nothing a window could not. A segmented page answers the same+ * slices as its inline twin by streaming segments.+ * 2. Fails when: a slice reads stored text, a heading match is substring or+ * case-sensitive, a fenced line counts as a heading, a section runs into a+ * sibling or the timeline, grep treats the term as a regex, a cap is not+ * applied or not reported, chars is missing, or the default response gains+ * slice fields.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { GBrainConfig } from '../src/core/config.ts';+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 { segmentedReadWork } from '../src/core/page-window/segmented.ts';+import { GREP_MAX_MATCHES, MAX_GREP_CONTEXT, SLICE_MAX_CHARS } from '../src/core/ops/get-page-slice.ts';+import { formatGetPage } from '../src/cli/page-render.ts';+import { parseOpArgs } from '../src/cli/main.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { testBackends } from './helpers/test-backends.ts';+import { PRIVATE, importSegmented, privacyFacts, privacyTakes, privateTokensIn } from './helpers/segmented-privacy-fixture.ts';++const getPage = operations.find(o => o.name === 'get_page')!;+let engine: BrainEngine;++const ctx = (remote: boolean): OperationContext => ({ engine, config: {} as GBrainConfig, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote,+ sourceId: 'default', ...(remote ? { transport: 'http', auth: { token: 'fixture', clientId: 'slice-client', principal: { kind: 'oauth_client', id: 'slice-client' },+ scopes: ['read'], sourceId: 'default', allowedSources: ['default'] } } : {}) } as unknown as OperationContext);+const get = async (params: Record<string, unknown>, remote = false) => await getPage.handler(ctx(remote), 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');+}++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');+}++/** The read projection's lines, 1-based (index 0 unused). */+async function projectionLines(slug: string): Promise<string[]> {+ const snap = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ return ['', ...pageDocument({ compiled_truth: snap!.page.compiled_truth, timeline: snap!.page.timeline }).bytes.toString('utf8').split('\n')];+}+const lineOf = (lines: string[], needle: string) => lines.findIndex(l => l.includes(needle));++/** What body: 'window' returns for lines [from, to]: the read-back check for a slice's line numbers. */+async function windowLines(slug: string, from: number, to: number, remote = false): Promise<string> {+ const r = await get({ slug, body: 'window', lines: { from, count: to - from + 1 }, max_bytes: 1_000_000 }, remote);+ return r.window.text.replace(/\n+$/, '');+}++const SECTIONS = [+ '# Project acme-example', '', 'Intro paragraph.', '',+ '## Goals', '', 'Ship the widget.', '',+ '### Stretch Goals', '', 'Ship the gadget too.', '',+ '## Next Steps', '', '```md', '# not a heading', '## Goals', '```', '', 'Call alice-example.', '',+ '## Goals', '', 'A second goals section.', '',+ '# Appendix', '', 'Last words.',+].join('\n');++const PARAGRAPHS = [+ 'Paragraph 1 intro.',+ 'Paragraph 2 tock.',+ 'Paragraph 3 has the NEEDLE.',+ 'Paragraph 4 filler.',+ 'Paragraph 5 needle again, tock.',+ 'Paragraph 6 filler.',+ 'Paragraph 7 filler.',+ 'Paragraph 8 abc only.',+ 'Paragraph 9 Needle at the end.',+ 'Paragraph 10 literal a.c here.',+ 'Paragraph 11 line one\nline two mentions zebra\nline three',+].join('\n\n');++/** A long day log: one paragraph per day under its own heading, a unique token on day 150. */+function dayLog(days: number): string {+ const day = (d: number) => [`## Day ${d}`, '', ...Array.from({ length: 120 }, (_, i) => `- ${d}.${i} alice-example asked acme-example about the widget plan${d === 150 && i === 7 ? ' zzuniquetoken' : ''}`), ''].join('\n');+ const truth = Array.from({ length: days }, (_, d) => day(d)).join('\n');+ const timeline = Array.from({ length: 1_000 }, (_, i) => `- 2024-01-${String(1 + (i % 28)).padStart(2, '0')}: entry ${i} with acme-example`).join('\n');+ return `---\ntitle: Widget log\ntype: note\ntags: [log]\n---\n${truth}\n\n<!-- timeline -->\n\n${timeline}\n`;+}++for (const kind of testBackends()) {+ describe(`get_page section and grep (${kind})`, () => {+ let close: () => Promise<void>;++ beforeAll(async () => {+ if (kind === 'postgres') ({ engine, close } = await isolatedPersistencePostgres(process.env.DATABASE_URL!));+ else {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ close = () => engine.disconnect();+ }+ await importSegmented(engine, 'logs/days-segmented', dayLog(240));+ await engine.setConfig('pages.segmented_storage', 'off');+ await importFromContent(engine, 'logs/days-inline', dayLog(240), { sourceId: 'default', noEmbed: true });+ await put('notes/sections', SECTIONS, '- 2024-01-02: timeline entry about the widget');+ await put('notes/paras', PARAGRAPHS);+ await put('notes/many-headings', Array.from({ length: 30 }, (_, i) => `## H${i + 1}\n\nbody ${i + 1}`).join('\n\n'));+ await put('notes/many-matches', Array.from({ length: 120 }, (_, i) => `item ${i} mentions target`).join('\n\n'));+ await put('notes/big-section', ['# Top', '', '## Big', '', ...Array.from({ length: 1_500 }, (_, i) => `line ${i} ${'x'.repeat(90)} target`), '', '## After', '', 'tail'].join('\n'));+ await put('notes/private-bits', ['## Public part', '', 'zzpublicprose is visible.', '', privacyTakes(), '', privacyFacts(), '', '## Closing', '', 'zzpublicprose again.'].join('\n'));+ }, 600_000);++ afterAll(async () => { await close(); });++ describe('section', () => {+ test('the first heading equal to the request, case-insensitive, with its heading path, down to the next same-level heading', async () => {+ const lines = await projectionLines('notes/sections');+ for (const remote of [false, true]) {+ const r = await get({ slug: 'notes/sections', section: 'goals' }, remote);+ expect(r.body).toBe('section');+ expect(r.compiled_truth).toBeUndefined();+ expect(r.timeline).toBeUndefined();+ expect(r.section.heading).toBe('Goals');+ expect(r.section.level).toBe(2);+ expect(r.section.heading_path).toEqual(['Project acme-example', 'Goals']);+ expect(r.section.text).toBe('## Goals\n\nShip the widget.\n\n### Stretch Goals\n\nShip the gadget too.');+ expect(r.section.line_start).toBe(lineOf(lines, '## Goals'));+ expect(r.section.line_end).toBe(lineOf(lines, 'Ship the gadget too.'));+ expect(await windowLines('notes/sections', r.section.line_start, r.section.line_end, remote)).toBe(r.section.text);+ expect(r.chars).toBe(r.section.text.length);+ expect(r.truncated).toBe(false);+ }+ });++ test('a nested heading carries every ancestor; whitespace and a leading ## in the request fold away', async () => {+ const r = await get({ slug: 'notes/sections', section: ' STRETCH goals ' });+ expect(r.section.heading).toBe('Stretch Goals');+ expect(r.section.heading_path).toEqual(['Project acme-example', 'Goals', 'Stretch Goals']);+ expect(r.section.text).toBe('### Stretch Goals\n\nShip the gadget too.');+ const hashed = await get({ slug: 'notes/sections', section: '## next steps' });+ expect(hashed.section.heading).toBe('Next Steps');+ });++ test('a fenced line is not a heading: the section keeps its code block and stops at the next real heading', async () => {+ const r = await get({ slug: 'notes/sections', section: 'Next Steps' });+ expect(r.section.text).toContain('# not a heading');+ expect(r.section.text).toContain('Call alice-example.');+ expect(r.section.text).not.toContain('A second goals section.');+ const miss = await refusal(get({ slug: 'notes/sections', section: 'not a heading' }));+ expect(miss.code).toBe('invalid_params');+ });++ test('a top-level section ends at the timeline separator', async () => {+ const r = await get({ slug: 'notes/sections', section: 'appendix' });+ expect(r.section.heading_path).toEqual(['Appendix']);+ expect(r.section.text).toBe('# Appendix\n\nLast words.');+ expect(JSON.stringify(r)).not.toContain('timeline entry');+ });++ test('a miss is invalid_params naming the headings, at most 20, with the total and an outline fix', async () => {+ const few = await refusal(get({ slug: 'notes/sections', section: 'Budget' }));+ expect(few.code).toBe('invalid_params');+ for (const h of ['Project acme-example', 'Goals', 'Stretch Goals', 'Next Steps', 'Appendix']) expect(few.message).toContain(JSON.stringify(h));+ expect(JSON.parse(String(few.detail))).toEqual({ headings: ['Project acme-example', 'Goals', 'Stretch Goals', 'Next Steps', 'Goals', 'Appendix'], total_headings: 6 });+ expect((few.fix as any).mcp.arguments.body).toBe('outline');+ const many = await refusal(get({ slug: 'notes/many-headings', section: 'H99' }, true));+ const detail = JSON.parse(String(many.detail));+ expect(detail.headings).toHaveLength(20);+ expect(detail.headings[0]).toBe('H1');+ expect(detail.total_headings).toBe(30);+ expect(many.message).toContain('first 20 of 30');+ expect(many.message).not.toContain('"H21"');+ });++ test('a section over the character budget is cut, says how much was omitted and where to read on', async () => {+ const r = await get({ slug: 'notes/big-section', section: 'big' });+ expect(r.truncated).toBe(true);+ expect(r.chars).toBeLessThanOrEqual(SLICE_MAX_CHARS);+ expect(r.chars).toBe(r.section.text.length);+ expect(r.omitted_chars).toBeGreaterThan(0);+ expect(r.section.text).not.toContain('## After');+ const lines = await projectionLines('notes/big-section');+ expect(r.section.line_end).toBe(lineOf(lines, 'line 1499 '));+ const from = r.next.arguments.lines.from;+ expect(from).toBeGreaterThan(r.section.line_start);+ expect(lines[from]).not.toBe('');+ expect(r.section.text.endsWith(lines[from - 1]!)).toBe(true);+ expect(r.next.arguments.lines.count).toBe(r.section.line_end - from + 1);+ });+ });++ describe('grep', () => {+ test('matching paragraphs with one paragraph of context, overlapping windows merged, line numbers from the read view', async () => {+ const lines = await projectionLines('notes/paras');+ const at = (n: number) => lineOf(lines, `Paragraph ${n} `);+ for (const remote of [false, true]) {+ const r = await get({ slug: 'notes/paras', grep: 'needle' }, remote);+ expect(r.body).toBe('grep');+ expect(r.compiled_truth).toBeUndefined();+ expect(r.grep).toMatchObject({ term: 'needle', context: 1, total_matches: 3, returned_matches: 3, omitted_matches: 0 });+ expect(r.truncated).toBe(false);+ expect(r.grep.blocks.map((b: any) => [b.line_start, b.line_end, b.match_starts])).toEqual([[at(2), at(6), [at(3), at(5)]], [at(8), at(10), [at(9)]]]);+ for (const b of r.grep.blocks) expect(await windowLines('notes/paras', b.line_start, b.line_end, remote)).toBe(b.text);+ expect(r.grep.blocks[0].text).not.toContain('Paragraph 7');+ expect(r.chars).toBe(r.grep.blocks.reduce((n: number, b: any) => n + b.text.length, 0));+ }+ });++ test('windows that touch merge; context 0 returns the matches alone; context is clamped to 5', async () => {+ const lines = await projectionLines('notes/paras');+ const at = (n: number) => lineOf(lines, `Paragraph ${n} `);+ const touch = await get({ slug: 'notes/paras', grep: 'tock' });+ expect(touch.grep.blocks.map((b: any) => [b.line_start, b.line_end, b.match_starts])).toEqual([[at(1), at(6), [at(2), at(5)]]]);+ const bare = await get({ slug: 'notes/paras', grep: 'needle', context: 0 });+ expect(bare.grep.blocks.map((b: any) => b.text)).toEqual(['Paragraph 3 has the NEEDLE.', 'Paragraph 5 needle again, tock.', 'Paragraph 9 Needle at the end.']);+ const wide = await get({ slug: 'notes/paras', grep: 'zebra', context: 99 });+ expect(wide.grep.context).toBe(MAX_GREP_CONTEXT);+ expect(wide.grep.blocks[0].line_start).toBe(at(6));+ const multi = await get({ slug: 'notes/paras', grep: 'ZEBRA', context: 0 });+ expect(multi.grep.blocks).toEqual([{ line_start: at(11), line_end: at(11) + 2, match_starts: [at(11)], text: 'Paragraph 11 line one\nline two mentions zebra\nline three' }]);+ });++ test('the term is a literal substring, never a regex', async () => {+ const r = await get({ slug: 'notes/paras', grep: 'a.c', context: 0 });+ expect(r.grep.total_matches).toBe(1);+ expect(r.grep.blocks[0].text).toBe('Paragraph 10 literal a.c here.');+ const none = await get({ slug: 'notes/paras', grep: '.*' });+ expect(none.grep).toMatchObject({ total_matches: 0, blocks: [] });+ expect(none.chars).toBe(0);+ });++ test('matches past the cap are counted, not returned', async () => {+ const r = await get({ slug: 'notes/many-matches', grep: 'TARGET', context: 0 }, true);+ expect(r.grep).toMatchObject({ total_matches: 120, returned_matches: GREP_MAX_MATCHES, omitted_matches: 120 - GREP_MAX_MATCHES });+ expect(r.truncated).toBe(true);+ const starts = r.grep.blocks.flatMap((b: any) => b.match_starts);+ expect(starts).toHaveLength(GREP_MAX_MATCHES);+ expect(r.grep.blocks.map((b: any) => b.text).join('\n')).not.toContain('item 50 ');+ });++ test('returned text stops at the character budget and says it was cut', async () => {+ const r = await get({ slug: 'notes/big-section', grep: 'target' });+ expect(r.grep.total_matches).toBe(1);+ expect(r.truncated).toBe(true);+ expect(r.chars).toBeLessThanOrEqual(SLICE_MAX_CHARS);+ expect(r.chars).toBeGreaterThan(SLICE_MAX_CHARS - 200);+ });+ });++ describe('chars and the default shape', () => {+ test('a whole-page read keeps its shape and carries chars', async () => {+ for (const remote of [false, true]) {+ const r = await get({ slug: 'notes/sections' }, remote);+ expect(typeof r.compiled_truth).toBe('string');+ for (const k of ['body', 'section', 'grep', 'window']) expect(r[k]).toBeUndefined();+ expect(r.chars).toBe(r.compiled_truth.length + r.timeline.length);+ const c = await get({ slug: 'notes/sections', include_content: true }, remote);+ expect(c.chars).toBe(c.compiled_truth.length + c.timeline.length + c.content.length);+ const lean = await get({ slug: 'notes/sections', include_content: true, content_only: true }, remote);+ expect(lean.chars).toBe(lean.content.length);+ }+ });++ test('windows carry the window text length; body none carries 0', async () => {+ const w = await get({ slug: 'notes/paras', body: 'window', lines: { from: 1, count: 3 } }, true);+ expect(w.chars).toBe(w.window.text.length);+ const none = await get({ slug: 'notes/paras', body: 'none' }, true);+ expect(none.chars).toBe(0);+ });+ });++ describe('parameters', () => {+ test('conflicts and malformed values are invalid_params naming the param', async () => {+ const cases: Array<Record<string, unknown>> = [+ { section: 'Goals', grep: 'x' }, { context: 2 }, { section: 'Goals', context: 2 }, { section: ' ' }, { grep: '' },+ { grep: 'x', context: -1 }, { grep: 'x', context: 1.5 }, { grep: 'x', context: '2' }, { section: 'Goals', include_content: true },+ { section: 'Goals', content_only: true }, { grep: 'x', lines: { from: 1, count: 2 } }, { grep: 'x', cursor: 'gpw1.x' },+ { section: 'Goals', body: 'none' }, { section: 'Goals', body: 'full' }, { grep: 'x', view: 'markdown' }, { section: 'x'.repeat(501) },+ ];+ for (const extra of cases) {+ const e = await refusal(get({ slug: 'notes/sections', ...extra }, true));+ expect({ extra, code: e.code }).toEqual({ extra, code: 'invalid_params' });+ }+ const historical = await refusal(get({ slug: 'notes/sections', section: 'Goals', known_as_of: '2026-01-01T00:00:00Z' }));+ expect(historical.message).toContain('section');+ });++ test('body auto or window with a slice still slices', async () => {+ expect((await get({ slug: 'notes/sections', section: 'Goals', body: 'window' }, true)).section.heading).toBe('Goals');+ expect((await get({ slug: 'notes/sections', grep: 'widget', body: 'auto' }, true)).grep.total_matches).toBe(2);+ });+ });++ describe('trust boundary', () => {+ test('a remote slice is cut from the read projection: private fences stay hidden, public text shows', async () => {+ const g = await get({ slug: 'notes/private-bits', grep: 'zz', context: 5 }, true);+ expect(privateTokensIn(JSON.stringify(g), { ledger: false })).toEqual([]);+ expect(JSON.stringify(g)).toContain('zzpublicprose');+ expect((await get({ slug: 'notes/private-bits', grep: PRIVATE.takes }, true)).grep.total_matches).toBe(0);+ const miss = await refusal(get({ slug: 'notes/private-bits', section: `${PRIVATE.takesHeading} takes` }, true));+ expect(JSON.parse(String(miss.detail)).headings).toEqual(['Public part', 'Closing']);+ expect(privateTokensIn(miss.message.replace(`"${PRIVATE.takesHeading} takes"`, '') + String(miss.detail), { ledger: false })).toEqual([]);+ const s = await get({ slug: 'notes/private-bits', section: 'Public part' }, true);+ expect(privateTokensIn(JSON.stringify(s), { ledger: false })).toEqual([]);+ expect(s.section.text).toContain('zzpublicprose is visible.');+ });++ test('a slice carries the same metadata as a window read; a private page stays missing', async () => {+ const w = await get({ slug: 'notes/private-bits', body: 'window' }, true);+ const s = await get({ slug: 'notes/private-bits', section: 'Closing' }, true);+ for (const k of ['slug', 'source_id', 'type', 'title', 'revision', 'tags', 'frontmatter', 'size', 'trust_tier', 'origin']) expect({ k, v: s[k] }).toEqual({ k, v: w[k] });+ await put('notes/hidden-example', '## Secret plan\n\nzzhiddenbody', '', { visibility: 'private' });+ const full = await refusal(get({ slug: 'notes/hidden-example' }, true));+ const sliced = await refusal(get({ slug: 'notes/hidden-example', section: 'Secret plan' }, true));+ expect(sliced.code).toBe(full.code);+ expect(sliced.message).toBe(full.message);+ expect(JSON.stringify(sliced.toJSON?.() ?? sliced)).not.toContain('zzhiddenbody');+ });+ });++ describe('segmented page', () => {+ test('section and grep stream the segments and match the inline twin, locally and remotely', async () => {+ const [seg] = await engine.executeRaw<{ body_storage: string }>('SELECT body_storage FROM pages WHERE slug=$1', ['logs/days-segmented']);+ expect(seg?.body_storage).toBe('segmented');+ const strip = (r: Record<string, any>) => ({ section: r.section, grep: r.grep, chars: r.chars, truncated: r.truncated, omitted_chars: r.omitted_chars, lines: r.next?.arguments?.lines });+ const cases: Array<Record<string, unknown>> = [{ section: 'Day 150' }, { section: 'day 3' }, { grep: 'zzuniquetoken', context: 1 }, { grep: 'acme-example', context: 0 }];+ for (const remote of [false, true]) {+ for (const c of cases) {+ const a = await get({ slug: 'logs/days-segmented', ...c }, remote);+ const b = await get({ slug: 'logs/days-inline', ...c }, remote);+ expect(a.body_storage).toBe('segmented');+ expect({ c, remote, r: strip(a) }).toEqual({ c, remote, r: strip(b) });+ }+ }+ const unique = await get({ slug: 'logs/days-segmented', grep: 'zzuniquetoken', context: 0 }, true);+ expect(unique.grep.total_matches).toBe(1);+ expect(unique.grep.blocks[0].text).toContain('- 150.7 alice-example');+ expect(await windowLines('logs/days-segmented', unique.grep.blocks[0].line_start, unique.grep.blocks[0].line_end, true)).toBe(unique.grep.blocks[0].text);+ const capped = await get({ slug: 'logs/days-segmented', grep: 'acme-example', context: 0 }, true);+ expect(capped.truncated).toBe(true);+ expect(capped.grep.total_matches).toBeGreaterThan(240);+ });++ test('an early section stops reading once it ends', async () => {+ const none = await get({ slug: 'logs/days-segmented', body: 'none' });+ segmentedReadWork.bytes = 0;+ const r = await get({ slug: 'logs/days-segmented', section: 'Day 2' });+ expect(r.section.heading_path).toEqual(['Day 2']);+ expect(segmentedReadWork.bytes).toBeLessThan(Number(none.size.total_bytes) / 4);+ });+ });+ });+}++describe('gbrain get --section / --grep', () => {+ test('the flags parse to get_page params', () => {+ expect(parseOpArgs(getPage, ['notes/a', '--section', 'Next Steps'])).toEqual({ slug: 'notes/a', section: 'Next Steps' });+ expect(parseOpArgs(getPage, ['notes/a', '--grep', 'widget', '--context', '2'])).toEqual({ slug: 'notes/a', grep: 'widget', context: 2 });+ });++ test('a section prints its text; grep prints each block under its line range', () => {+ const section = { slug: 'notes/a', body: 'section', chars: 12, truncated: false, section: { heading: 'Goals', heading_path: ['Top', 'Goals'], line_start: 5, line_end: 7, text: '## Goals\n\nok' } };+ expect(formatGetPage(section)).toBe('## Goals\n\nok\n');+ const grep = { slug: 'notes/a', body: 'grep', chars: 4, truncated: false,+ grep: { term: 'x', context: 1, total_matches: 2, returned_matches: 2, omitted_matches: 0, blocks: [{ line_start: 3, line_end: 3, match_starts: [3], text: 'a x' }, { line_start: 9, line_end: 11, match_starts: [11], text: 'b\n\nx' }] } };+ expect(formatGetPage(grep)).toBe('-- lines 3-3 (match at 3)\na x\n-- lines 9-11 (match at 11)\nb\n\nx\n');+ });+});