Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(large-pages): chunk projected spans, page-window document, egress budget, registry codes
garrytane648e54a5200
diff --git a/src/core/chunkers/recursive.ts b/src/core/chunkers/recursive.tsindex ea571de735..2cebde1ec1 100644--- a/src/core/chunkers/recursive.ts+++ b/src/core/chunkers/recursive.ts@@ -70,11 +70,23 @@ export interface ChunkOptions {* does not bump.*/maxTokens?: number;+ /** Record each chunk's projected UTF-8 byte span (TextChunk.byte_start/byte_end). Chunk text is unchanged. */+ spans?: boolean;}export interface TextChunk {text: string;index: number;+ /**+ * With `spans: true`: the chunk's position in the projected text it was cut+ * from (credentialSafeProjection(sanitizeRemoteBody(text))), as UTF-8 byte+ * offsets, end exclusive. The span starts at the chunk's first character and+ * ends after its last one; whitespace-only runs the chunker folded away lie+ * inside it, so the span's text equals the chunk text once whitespace is+ * ignored. Absent when the span cannot be traced.+ */+ byte_start?: number;+ byte_end?: number;}// The strict full-body sanitizer removes all Takes and non-world Facts. Takes content@@ -115,22 +127,103 @@ export function chunkText(text: string, opts?: ChunkOptions): TextChunk[] {const wordCount = countWords(stripped);if (wordCount <= chunkSize) {// Single-chunk path: still apply the maxChars cap.- const capped = capByChars(stripped.trim(), maxChars, maxTokens);- return capped.map((t, i) => ({ text: t, index: i }));+ const whole = trimmedRun({ text: stripped, segs: [{ t: 0, s: 0, n: stripped.length }] });+ return finish(stripped, capByChars(whole.text, maxChars, maxTokens).map(c => placed(whole, c)), opts?.spans === true);}// Recursively split, then greedily merge to target size- const pieces = recursiveSplit(stripped, 0, chunkSize);+ const pieces = recursiveSplit(stripped, 0, chunkSize, 0);const merged = greedyMerge(pieces, chunkSize);const withOverlap = applyOverlap(merged, chunkOverlap);// v0.32.7: hard char cap. Catches pathological CJK + whitespace-less text// that the word-level pipeline can't bound (a single Chinese paragraph can// exceed 8192 OpenAI embedding tokens at any word count).- const capped: string[] = [];+ const capped: Placed[] = [];for (const chunk of withOverlap) {- capped.push(...capByChars(chunk.trim(), maxChars, maxTokens));+ const run = trimmedRun(chunk);+ for (const c of capByChars(run.text, maxChars, maxTokens)) capped.push(placed(run, c));}- return capped.map((t, i) => ({ text: t, index: i }));+ return finish(stripped, capped, opts?.spans === true);+}++/** A substring of the projected text: `s` is its UTF-16 offset there. */+interface Piece { text: string; s: number }+/** `n` code units of a run's text at run offset `t` sit at projected offset `s`. */+interface Seg { t: number; s: number; n: number }+/** Text assembled from projected substrings (whitespace-only gaps may be folded away). */+interface Run { text: string; segs: Seg[] }+/** A run slice: `at` is its offset in the run's text. */+interface Slice { text: string; at: number }+interface Placed { text: string; start: number | null; end: number | null }++function runOffset(run: Run, t: number): number | null {+ for (const seg of run.segs) if (t >= seg.t && t < seg.t + seg.n) return seg.s + (t - seg.t);+ return null;+}++function placed(run: Run, c: Slice): Placed {+ if (c.text.length === 0) return { text: c.text, start: null, end: null };+ const start = runOffset(run, c.at);+ const last = runOffset(run, c.at + c.text.length - 1);+ return { text: c.text, start, end: last === null ? null : last + 1 };+}++function trimmedRun(run: Run): Run {+ const text = run.text.trim();+ const lead = run.text.length - run.text.trimStart().length;+ return lead === 0 && text.length === run.text.length ? run : sliceRun(run, lead, lead + text.length);+}++function sliceRun(run: Run, from: number, to: number): Run {+ const segs: Seg[] = [];+ for (const seg of run.segs) {+ const a = Math.max(from, seg.t);+ const b = Math.min(to, seg.t + seg.n);+ if (a < b) segs.push({ t: a - from, s: seg.s + (a - seg.t), n: b - a });+ }+ return { text: run.text.slice(from, to), segs };+}++function joinRuns(a: Run, b: Run): Run {+ return { text: a.text + b.text, segs: [...a.segs, ...b.segs.map(seg => ({ ...seg, t: seg.t + a.text.length }))] };+}++/** Chunks with indexes, plus UTF-8 spans in the projected text when asked for (one pass over it). */+function finish(stripped: string, chunks: Placed[], spans: boolean): TextChunk[] {+ const out: TextChunk[] = chunks.map((c, i) => ({ text: c.text, index: i }));+ if (!spans) return out;+ const wanted: number[] = [];+ for (const c of chunks) if (c.start !== null && c.end !== null) wanted.push(c.start, c.end);+ const bytes = utf16ToUtf8Offsets(stripped, wanted);+ chunks.forEach((c, i) => {+ if (c.start === null || c.end === null) return;+ out[i].byte_start = bytes.get(c.start);+ out[i].byte_end = bytes.get(c.end);+ });+ return out;+}++/** UTF-8 byte offset of each UTF-16 offset (offsets inside a surrogate pair count from the pair start). */+export function utf16ToUtf8Offsets(text: string, offsets: readonly number[]): Map<number, number> {+ const sorted = [...new Set(offsets)].sort((a, b) => a - b);+ const out = new Map<number, number>();+ let bytes = 0;+ let i = 0;+ for (const target of sorted) {+ while (i < target && i < text.length) {+ const c = text.charCodeAt(i);+ if (c < 0x80) bytes += 1;+ else if (c < 0x800) bytes += 2;+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < text.length) {+ const d = text.charCodeAt(i + 1);+ if (d >= 0xdc00 && d <= 0xdfff) { if (i + 1 === target) { out.set(target, bytes); } bytes += 4; i += 2; continue; }+ bytes += 3;+ } else bytes += 3;+ i++;+ }+ if (!out.has(target)) out.set(target, bytes);+ }+ return out;}/**@@ -164,9 +257,9 @@ function capByChars(maxChars: number,maxTokens: number = DEFAULT_MAX_CHUNK_TOKENS,knownEst?: number,-): string[] {+): Slice[] {if (text.length === 0) return [];- if (knownEst === undefined && text.length <= maxChars && fitsEmbedTokens(text, maxTokens)) return [text];+ if (knownEst === undefined && text.length <= maxChars && fitsEmbedTokens(text, maxTokens)) return [{ text, at: 0 }];const est = knownEst ?? probeEmbedTokens(text);const window = est <= maxTokens? maxChars@@ -175,9 +268,9 @@ function capByChars(// Emitting the text whole is the one path that skips the per-slice// re-check below, so a PROBED estimate has to be confirmed exactly first:// a sparse ASCII head can under-read a dense CJK tail.- if (knownEst !== undefined || text.length <= DENSITY_PROBE_CHARS) return [text];+ if (knownEst !== undefined || text.length <= DENSITY_PROBE_CHARS) return [{ text, at: 0 }];const exact = estimateEmbedTokens(text);- return exact <= maxTokens ? [text] : capByChars(text, maxChars, maxTokens, exact);+ return exact <= maxTokens ? [{ text, at: 0 }] : capByChars(text, maxChars, maxTokens, exact);}// The stride keeps its nominal window-minus-overlap value. Evening the// windows out (as the header-budget hard split does) is WRONG here: that@@ -188,20 +281,22 @@ function capByChars(// that trade and is the behavior this loop has always had.const overlap = Math.min(500, Math.floor(window / 10));const stride = Math.max(1, window - overlap);- const out: string[] = [];+ const out: Slice[] = [];let i = 0;while (i < text.length) {const end = safeSplitIndex(text, Math.min(text.length, i + window));- const slice = text.slice(i, end).trim();+ const raw = text.slice(i, end);+ const slice = raw.trim();+ const at = i + raw.length - raw.trimStart().length;if (slice.length > 0) {const sliceEst = fitsEmbedTokens(slice, maxTokens) ? 0 : estimateEmbedTokens(slice);if (sliceEst > maxTokens) {// Denser than the text average — re-derive locally, reusing the exact// figure just measured (it also guarantees window < slice.length, so// the recursion strictly shrinks).- out.push(...capByChars(slice, maxChars, maxTokens, sliceEst));+ for (const part of capByChars(slice, maxChars, maxTokens, sliceEst)) out.push({ text: part.text, at: at + part.at });} else {- out.push(slice);+ out.push({ text: slice, at });}}if (end >= text.length) break;@@ -230,29 +325,29 @@ function probeEmbedTokens(text: string): number {return Math.ceil((estimateEmbedTokens(head) * text.length) / head.length);}-function recursiveSplit(text: string, level: number, target: number): string[] {+function recursiveSplit(text: string, level: number, target: number, base: number): Piece[] {if (level >= DELIMITERS.length) {// Level 4: split on whitespace- return splitOnWhitespace(text, target);+ return splitOnWhitespace(text, target, base);}const delimiters = DELIMITERS[level];if (delimiters.length === 0) {- return splitOnWhitespace(text, target);+ return splitOnWhitespace(text, target, base);}- const pieces = splitAtDelimiters(text, delimiters);+ const pieces = splitAtDelimiters(text, delimiters, base);// If splitting didn't help (only 1 piece), try next levelif (pieces.length <= 1) {- return recursiveSplit(text, level + 1, target);+ return recursiveSplit(text, level + 1, target, base);}// Check if any piece is still too large, recurse deeper- const result: string[] = [];+ const result: Piece[] = [];for (const piece of pieces) {- if (countWords(piece) > target) {- result.push(...recursiveSplit(piece, level + 1, target));+ if (countWords(piece.text) > target) {+ result.push(...recursiveSplit(piece.text, level + 1, target, piece.s));} else {result.push(piece);}@@ -263,43 +358,43 @@ function recursiveSplit(text: string, level: number, target: number): string[] {/*** Split text at delimiter boundaries, preserving delimiters at the end- * of the piece that precedes them (lossless).+ * of the piece that precedes them (lossless). Each delimiter's next+ * occurrence is searched once and reused until the cursor passes it, so the+ * scan is linear in the text.*/-function splitAtDelimiters(text: string, delimiters: string[]): string[] {- const pieces: string[] = [];- let remaining = text;+function splitAtDelimiters(text: string, delimiters: string[], base: number): Piece[] {+ const pieces: Piece[] = [];+ const next = delimiters.map(() => -2);+ let pos = 0;- while (remaining.length > 0) {+ while (pos < text.length) {let earliest = -1;let earliestDelim = '';- for (const delim of delimiters) {- const idx = remaining.indexOf(delim);+ for (let d = 0; d < delimiters.length; d++) {+ if (next[d] !== -1 && next[d] < pos) next[d] = text.indexOf(delimiters[d], pos);+ const idx = next[d];if (idx !== -1 && (earliest === -1 || idx < earliest)) {earliest = idx;- earliestDelim = delim;+ earliestDelim = delimiters[d];}}if (earliest === -1) {- pieces.push(remaining);+ pieces.push({ text: text.slice(pos), s: base + pos });break;}// Include the delimiter with the preceding text- const piece = remaining.slice(0, earliest + earliestDelim.length);+ const end = earliest + earliestDelim.length;+ const piece = text.slice(pos, end);if (piece.trim().length > 0) {- pieces.push(piece);+ pieces.push({ text: piece, s: base + pos });}- remaining = remaining.slice(earliest + earliestDelim.length);+ pos = end;}- // Handle trailing content- if (remaining.trim().length > 0 && !pieces.includes(remaining)) {- // Already added above- }-- return pieces.filter(p => p.trim().length > 0);+ return pieces.filter(p => p.text.trim().length > 0);}/**@@ -309,16 +404,16 @@ function splitAtDelimiters(text: string, delimiters: string[]): string[] {* boundaries so we still bound chunk size and the chunker makes forward* progress. The downstream maxChars cap tightens this further.*/-function splitOnWhitespace(text: string, target: number): string[] {- const words = text.match(/\S+\s*/g) || [];+function splitOnWhitespace(text: string, target: number, base: number): Piece[] {+ const words = [...text.matchAll(/\S+\s*/g)];// No whitespace tokens, OR a single token longer than `target` chars// (greedy /\S+/g returns a CJK paragraph as one "word"). Slice by char.const noUsefulWhitespace =- words.length === 0 || (words.length === 1 && words[0].length > target);+ words.length === 0 || (words.length === 1 && words[0][0].length > target);if (noUsefulWhitespace) {if (text.trim().length === 0) return [];- const pieces: string[] = [];+ const pieces: Piece[] = [];const charsPerPiece = Math.max(1, target);// Cursor advances to wherever safeSplitIndex actually cut, so no astral// pair (emoji, non-BMP CJK) is halved and no code unit is skipped or@@ -328,17 +423,21 @@ function splitOnWhitespace(text: string, target: number): string[] {let end = safeSplitIndex(text, Math.min(text.length, i + charsPerPiece));if (end <= i) end = Math.min(text.length, i + 2);const slice = text.slice(i, end);- if (slice.trim().length > 0) pieces.push(slice);+ if (slice.trim().length > 0) pieces.push({ text: slice, s: base + i });i = end;}return pieces;}- const pieces: string[] = [];+ // Consecutive matches are contiguous, so a run of words is one substring.+ const pieces: Piece[] = [];for (let i = 0; i < words.length; i += target) {- const slice = words.slice(i, i + target).join('');+ const first = words[i];+ const last = words[Math.min(i + target, words.length) - 1];+ const from = first.index!;+ const slice = text.slice(from, last.index! + last[0].length);if (slice.trim().length > 0) {- pieces.push(slice);+ pieces.push({ text: slice, s: base + from });}}return pieces;@@ -350,28 +449,29 @@ function splitOnWhitespace(text: string, target: number): string[] {* stats grow with it (concatWordStats), so each piece is counted once instead* of recounting the whole chunk on every merge.*/-function greedyMerge(pieces: string[], target: number): string[] {+function greedyMerge(pieces: Piece[], target: number): Run[] {if (pieces.length === 0) return [];- const result: string[] = [];+ const result: Run[] = [];const limit = Math.ceil(target * 1.5);- let current = pieces[0];- let currentStats = wordStats(current);+ const runOf = (p: Piece): Run => ({ text: p.text, segs: [{ t: 0, s: p.s, n: p.text.length }] });+ let current = runOf(pieces[0]);+ let currentStats = wordStats(current.text);for (let i = 1; i < pieces.length; i++) {- const pieceStats = wordStats(pieces[i]);+ const pieceStats = wordStats(pieces[i].text);const combinedStats = concatWordStats(currentStats, pieceStats);if (wordCountOf(combinedStats) <= limit) {- current += pieces[i];+ current = joinRuns(current, runOf(pieces[i]));currentStats = combinedStats;} else {result.push(current);- current = pieces[i];+ current = runOf(pieces[i]);currentStats = pieceStats;}}- if (current.trim().length > 0) {+ if (current.text.trim().length > 0) {result.push(current);}@@ -382,14 +482,20 @@ function greedyMerge(pieces: string[], target: number): string[] {* Apply sentence-aware trailing overlap.* The last N words of chunk[i] are prepended to chunk[i+1].*/-function applyOverlap(chunks: string[], overlapWords: number): string[] {+function applyOverlap(chunks: Run[], overlapWords: number): Run[] {if (chunks.length <= 1 || overlapWords <= 0) return chunks;- const result: string[] = [chunks[0]];+ const result: Run[] = [chunks[0]];for (let i = 1; i < chunks.length; i++) {- const prevTrailing = extractTrailingContext(chunks[i - 1], overlapWords);- result.push(prevTrailing + chunks[i]);+ const prev = chunks[i - 1];+ const prevTrailing = extractTrailingContext(prev.text, overlapWords);+ // The trailing context is always a suffix of the previous chunk; a run+ // whose suffix cannot be traced keeps its text and loses its span.+ const tail = prev.text.endsWith(prevTrailing)+ ? sliceRun(prev, prev.text.length - prevTrailing.length, prev.text.length)+ : { text: prevTrailing, segs: [] };+ result.push(joinRuns(tail, chunks[i]));}return result;diff --git a/src/core/egress-budget.ts b/src/core/egress-budget.tsnew file mode 100644index 0000000000..7d64184547--- /dev/null+++ b/src/core/egress-budget.ts@@ -0,0 +1,73 @@+/**+ * Large pages (Wave A): the per-connection egress budget. Every MCP tool+ * result is measured as the complete JSON-RPC response frame it becomes+ * (content blocks, notices and `_meta` included, every string escaped), not as+ * the body's character count, and a result over the connection's cap is+ * replaced by a structured `result_too_large` error instead of a frame the+ * client cannot read (the TypeScript SDK's stdio reader refuses messages over+ * 10 MiB; Claude Code cuts tool results at about 25k tokens).+ *+ * Defaults: 4 MiB on stdio (under the SDK's 10 MiB stdio buffer with margin),+ * 1 MiB on HTTP. `mcp.max_result_bytes_stdio` / `mcp.max_result_bytes_http`+ * (DB plane, then the config file's `mcp` block) move a cap within+ * [EGRESS_CAP_MIN, EGRESS_CAP_MAX]. Trusted local CLI calls have no cap: they+ * never cross a transport.+ */+import type { BrainEngine } from './engine.ts';+import type { GBrainConfig } from './config.ts';++export type EgressTransport = 'stdio' | 'http';++export const EGRESS_CAP_DEFAULTS: Readonly<Record<EgressTransport, number>> = { stdio: 4 * 1024 * 1024, http: 1024 * 1024 };+export const EGRESS_CAP_CONFIG_KEYS: Readonly<Record<EgressTransport, string>> = {+ stdio: 'mcp.max_result_bytes_stdio',+ http: 'mcp.max_result_bytes_http',+};+/** A configured cap is clamped to this range: big enough for any windowed read, small enough for the SDK's 10 MiB stdio reader. */+export const EGRESS_CAP_MIN = 256 * 1024;+export const EGRESS_CAP_MAX = 9 * 1024 * 1024;+/** Bytes a frame spends outside the measured result: the request id and the transport's own framing (SSE `data:` lines). */+export const FRAME_RESERVE_BYTES = 1024;++export interface EgressCaller {+ remote: boolean;+ transport?: EgressTransport;+ engine?: Pick<BrainEngine, 'getConfig'>;+ config?: GBrainConfig | null;+}++/** The transport a caller's results travel over; null for the trusted local CLI. */+export function egressTransport(caller: Pick<EgressCaller, 'remote' | 'transport'>): EgressTransport | null {+ if (caller.remote === false) return null;+ return caller.transport === 'stdio' ? 'stdio' : 'http';+}++function parseCap(raw: unknown): number | null {+ const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : NaN;+ if (!Number.isFinite(n) || n <= 0) return null;+ return Math.min(EGRESS_CAP_MAX, Math.max(EGRESS_CAP_MIN, Math.floor(n)));+}++/**+ * The connection's result cap in bytes of the final encoded frame: Infinity+ * for the trusted local CLI, else the DB plane, the file plane, the default.+ * A config read that fails falls through; resolving a cap never fails a call.+ */+export async function resultByteCap(caller: EgressCaller): Promise<number> {+ const transport = egressTransport(caller);+ if (transport === null) return Number.POSITIVE_INFINITY;+ const key = EGRESS_CAP_CONFIG_KEYS[transport];+ try {+ const db = parseCap(await caller.engine?.getConfig(key));+ if (db !== null) return db;+ } catch {+ // Engine without a config table / transient error: the file plane decides.+ }+ const mcp = caller.config?.mcp as Record<string, unknown> | undefined;+ return parseCap(mcp?.[`max_result_bytes_${transport}`]) ?? EGRESS_CAP_DEFAULTS[transport];+}++/** Bytes of the complete JSON-RPC response frame carrying `result`, plus the framing reserve. */+export function encodedFrameBytes(result: unknown): number {+ return Buffer.byteLength(JSON.stringify({ jsonrpc: '2.0', id: 0, result }), 'utf8') + FRAME_RESERVE_BYTES;+}diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 01d96262e0..01dda4cd48 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -172,7 +172,7 @@ export async function upsertChunksOnce(// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a// later text rewrite that keeps the vector is detectable as content// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.- const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since)`;+ const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image, embedding_pending_since, projected_byte_start, projected_byte_end)`;let resolvedModel: string | null = gatewayModel;if (!resolvedModel) resolvedModel = (await modelRows)?.[0]?.value ?? null;resolvedModel = writeCol.embeddingModel || resolvedModel;@@ -206,6 +206,8 @@ export async function upsertChunksOnce(symbol_name_qualified: chunk.symbol_name_qualified || null,modality: chunk.modality ?? 'text',embedding_image: chunk.embedding_image ? '[' + Array.from(chunk.embedding_image).join(',') + ']' : null,+ projected_byte_start: chunk.projected_byte_start ?? null,+ projected_byte_end: chunk.projected_byte_end ?? null,};});@@ -253,10 +255,12 @@ export async function upsertChunksOnce(CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vector,- CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END+ CASE WHEN c.embedding IS NULL THEN now() ELSE NULL END,+ c.projected_byte_start, c.projected_byte_endFROM jsonb_to_recordset(${JSON.stringify(incoming)}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,- start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text)+ start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text,+ projected_byte_start bigint, projected_byte_end bigint)ON CONFLICT (page_id, chunk_index) DO UPDATE SETchunk_text = EXCLUDED.chunk_text,chunk_source = EXCLUDED.chunk_source,@@ -310,6 +314,8 @@ export async function upsertChunksOnce(doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END,symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,modality = EXCLUDED.modality,+ projected_byte_start = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_start ELSE COALESCE(EXCLUDED.projected_byte_start, content_chunks.projected_byte_start) END,+ projected_byte_end = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.projected_byte_end ELSE COALESCE(EXCLUDED.projected_byte_end, content_chunks.projected_byte_end) END,embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image),embedding_pending_since = CASEWHEN EXCLUDED.${col} IS NOT NULL THEN NULLdiff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 68ecadaa30..3d273d972b 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -325,9 +325,11 @@ export const CODES = {reasons: ['host_mismatch', 'transfer_in_progress', 'clone_in_progress', 'binding_missing', 'incarnation_changed', 'coordination_path_missing', 'local_path_missing', 'not_sent', 'outcome_unknown'],docs: 'docs/guides/troubleshooting.md#owner-unavailable',suggestion: 'Read gbrain sources writer status --source <id> --json on the brain host. A transfer or clone in progress: wait and retry. host_mismatch: run the step on the owner host, or give the worker and the shell one GBRAIN_HOME; never copy or regenerate host.json. Nothing claims or transfers ownership to run maintenance.' },- 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}' } }, 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_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}' } }, consent: [], actor: 'agent', why: "Confirms whether the page exists in this source before anything is recreated.", requires_exclusive: false } },+ 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_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.' },pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },@@ -408,8 +410,10 @@ export const CODES = {requires_local_engine: { class: 'host_only', summary: "This command needs the brain's local database, and this install is a thin client of a remote brain." },response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },- revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },- revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },+ result_too_large: { class: 'caller', summary: "The tool's result is larger than this connection can carry in one response, so it was replaced by this error; nothing was cut.", why: "Results are measured as the complete encoded JSON-RPC frame (every block, notice and escape). A frame over the connection's cap (mcp.max_result_bytes_stdio, 4 MiB; mcp.max_result_bytes_http, 1 MiB) would be rejected or silently cut by the client.", docs: 'docs/guides/windowed-reads.md#result_too_large', legacy_error: 'invalid_params', suggestion: "Ask for less in one call: a window (get_page body: 'window'), a page of rows (limit / from_index), or metadata only (get_versions include_body: false).", 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 and outline, which name the windows to read.", requires_exclusive: false } },+ revision_changed: { class: 'caller', summary: "The page changed since the cursor or chunk id was issued, so that position no longer names the same text.", why: "Cursors and chunk positions are bound to one page revision; reading on from them after an edit could skip or repeat text without saying so.", docs: 'docs/guides/windowed-reads.md#revision_changed', legacy_error: 'invalid_params', suggestion: "Read again from the position in fix (the same byte offset at the current revision), or start over with body: 'outline'.", 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 current revision and size.", requires_exclusive: false } },+ revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", 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: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },+ revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was 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: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },diff --git a/src/core/markdown-chunks.ts b/src/core/markdown-chunks.tsindex 505271aae6..e86196785f 100644--- a/src/core/markdown-chunks.ts+++ b/src/core/markdown-chunks.ts@@ -127,7 +127,8 @@ async function extractFencedChunks(/*** Truth then timeline prose chunks through a fence overlay, plus the* overlay's low-tier facts-fence rows as trailing chunks, each piece led by- * the fence trust marker naming the row tier (#5575 ENG-1). `fenced` slots+ * the fence trust marker naming the row tier (#5575 ENG-1). Prose chunks+ * carry their projected UTF-8 span (v244), the coordinates windowed reads use. `fenced` slots* the recognized code-fence chunks of the overlaid truth before them.*/async function overlaidChunks(page: { compiled_truth: string; timeline?: string | null }, maxTokens: number,@@ -137,7 +138,10 @@ async function overlaidChunks(page: { compiled_truth: string; timeline?: stringconst timeline = splitFenceOverlay(page.timeline ?? '', overlay);for (const [text, source] of [[truth.main, 'compiled_truth'], [timeline.main, 'timeline']] as const) {if (!text.trim()) continue;- for (const c of chunkText(text, { maxTokens })) chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: source });+ for (const c of chunkText(text, { maxTokens, spans: true })) {+ chunks.push({ chunk_index: chunks.length, chunk_text: c.text, chunk_source: source,+ ...(c.byte_start !== undefined && c.byte_end !== undefined ? { projected_byte_start: c.byte_start, projected_byte_end: c.byte_end } : {}) });+ }}if (fenced && truth.main.trim()) chunks.push(...await fenced(truth.main, chunks.length));for (const { tier, unconfirmed, body } of [...truth.lowTier, ...timeline.lowTier]) {diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 88c38e2341..016979e2c5 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -553,6 +553,13 @@ export interface OperationContext {* Shape only, never authority: nothing security-relevant reads it.*/resultRows?: 'lean' | 'full';+ /**+ * Large pages (Wave A): the caller identified itself as gbrain's thin client+ * (X-Gbrain-Client header). A thin client that names no `body` mode on+ * get_page renders compiled_truth as the whole page, so the read is full+ * or refused, never a window. Shape only, never authority.+ */+ thinClient?: boolean;/*** Whether this caller can call `opName` on its surface right now: the MCP* dispatch predicate (the stdio session's surface after any `request_tools`diff --git a/src/core/page-window/document.ts b/src/core/page-window/document.tsnew file mode 100644index 0000000000..a9cbf9e4c6--- /dev/null+++ b/src/core/page-window/document.ts@@ -0,0 +1,134 @@+/**+ * Large pages (Wave A read contract): the ONE text every partial page read is+ * cut from. A window, an outline, a chunk-centered window, an evidence block+ * and a bounded prefix are all slices of this projection, never of the raw+ * `compiled_truth` / `timeline` columns:+ *+ * withdrawal-overlaid body (readPageSnapshot)+ * -> fence overlay (held and purged facts rows out, rows below the page+ * tier moved after the truth under their trust marker)+ * -> sanitizeRemoteBody (Takes, non-world and withdrawn Facts rows,+ * malformed protected tails and materialized markers dropped, each+ * column WHOLE, before any slicing)+ * -> credentialSafeProjection (private-key spans become a token)+ *+ * joined the way serializeMarkdown joins compiled truth and timeline. A slice+ * can start inside what was a protected fence in the stored body and still+ * holds nothing private, because the protected text is gone before the cut.+ * This is the text the chunker cuts from, so a chunk's stored projected span+ * (content_chunks.projected_byte_start/end, v244) addresses it directly.+ *+ * Coordinates: UTF-8 byte offsets (`bytes`), the one unit for stored spans,+ * cursors, windows and caps.+ */+import type { BrainEngine } from '../engine.ts';+import { sanitizeRemoteBody } from '../remote-body.ts';+import { credentialSafeProjection } from '../credential-projection.ts';+import { safeSplitIndex } from '../text-safe.ts';+import { loadFenceChunkOverlay, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';++/** Separator serializeMarkdown writes between compiled truth and timeline. */+export const TIMELINE_SEPARATOR = '\n\n<!-- timeline -->\n\n';++/** Raw prefix a bounded-prefix reader sanitizes (64 KiB of the overlaid body). */+export const BOUNDED_PREFIX_BYTES = 64 * 1024;++export interface ProjectableBody {+ compiled_truth: string;+ timeline?: string | null;+ fenceOverlay?: FenceChunkOverlay;+}++/**+ * The projected page text in UTF-16 (JS string) coordinates: compiled truth,+ * then its low-tier fence rows under their markers, then the timeline after+ * TIMELINE_SEPARATOR. `timelineAt` is where the timeline text starts, -1 when+ * there is none. Frontmatter is not part of it.+ */+export function projectPageText(page: ProjectableBody, includeTimeline: boolean): { text: string; timelineAt: number } {+ const ownTruth = splitFenceOverlay(page.compiled_truth ?? '', page.fenceOverlay);+ const ownTimeline = splitFenceOverlay(page.timeline ?? '', page.fenceOverlay);+ const truth = [credentialSafeProjection(sanitizeRemoteBody(ownTruth.main)), ...[...ownTruth.lowTier, ...(includeTimeline ? ownTimeline.lowTier : [])]+ .map(({ tier, unconfirmed, body }) => markFenceChunk(tier, credentialSafeProjection(sanitizeRemoteBody(body)), unconfirmed))].join('\n\n');+ const timeline = includeTimeline ? credentialSafeProjection(sanitizeRemoteBody(ownTimeline.main)) : '';+ if (!timeline.trim()) return { text: truth, timelineAt: -1 };+ return { text: truth + TIMELINE_SEPARATOR + timeline, timelineAt: truth.length + TIMELINE_SEPARATOR.length };+}++/** The projected page as bytes: what windows, outlines and cursors address. */+export interface PageDocument {+ bytes: Buffer;+ /** Byte offset where the timeline text starts; -1 when the page has none. */+ timelineByte: number;+}++export function pageDocument(page: ProjectableBody): PageDocument {+ const { text, timelineAt } = projectPageText(page, true);+ return {+ bytes: Buffer.from(text, 'utf8'),+ timelineByte: timelineAt < 0 ? -1 : Buffer.byteLength(text.slice(0, timelineAt), 'utf8'),+ };+}++/**+ * The document for one page read through readPageSnapshot (so the withdrawal+ * overlay is already applied): its fence overlay is loaded, one query, and+ * only when the body has world facts rows.+ */+export async function readPageDocument(+ engine: Pick<BrainEngine, 'executeRaw'>,+ page: { source_id: string; slug: string; compiled_truth: string; timeline?: string | null },+): Promise<PageDocument> {+ const fenceOverlay = await loadFenceChunkOverlay(engine, { sourceId: page.source_id, slug: page.slug, compiled_truth: page.compiled_truth, timeline: page.timeline });+ return pageDocument({ compiled_truth: page.compiled_truth, timeline: page.timeline ?? '', fenceOverlay });+}++/**+ * Where a chunk's stored projected span lands in the document: compiled truth+ * spans are relative to the document start, timeline spans to the timeline+ * text. Null when the chunk has no span or it falls outside the document.+ */+export function chunkDocumentSpan(doc: PageDocument, chunk: {+ chunk_source: string; projected_byte_start?: number | null; projected_byte_end?: number | null;+}): { start: number; end: number } | null {+ const s = chunk.projected_byte_start;+ const e = chunk.projected_byte_end;+ if (typeof s !== 'number' || typeof e !== 'number' || !(e > s) || s < 0) return null;+ const base = chunk.chunk_source === 'timeline' ? doc.timelineByte : chunk.chunk_source === 'compiled_truth' ? 0 : -1;+ if (base < 0) return null;+ const start = base + s;+ const end = base + e;+ if (end > (chunk.chunk_source === 'timeline' || doc.timelineByte < 0 ? doc.bytes.length : doc.timelineByte)) return null;+ return { start, end };+}++/**+ * A stored span is trusted only while it still holds the chunk's text: the+ * chunker folds whitespace-only runs, so the comparison ignores whitespace.+ * A span recorded for an older body (the page changed, the chunks did not+ * yet) fails this check and the caller falls back.+ */+export function spanHoldsChunk(doc: PageDocument, span: { start: number; end: number }, chunkText: string): boolean {+ const slice = doc.bytes.subarray(span.start, span.end).toString('utf8');+ return slice.replace(/\s+/g, '') === chunkText.replace(/\s+/g, '');+}++/**+ * A bounded prefix of the sanitized projection, for helpers that show a lead+ * or synopsis (exact-slug and alias snippets, relational synopses,+ * safeSynopsis, pageLead, think anchor rows): the first `maxBytes` of the+ * (already withdrawal-overlaid) body, cut on a code point, then sanitized and+ * credential-projected like the whole page. Fail-closed by construction: the+ * prefix starts at the body start, so it can never begin inside a protected+ * fence, and a fence the cut leaves open is an unterminated tail the+ * sanitizer drops. O(maxBytes) whatever the page size.+ */+export function boundedProjectedPrefix(body: string | null | undefined, maxBytes: number = BOUNDED_PREFIX_BYTES): string {+ if (typeof body !== 'string' || body.length === 0) return '';+ // maxBytes UTF-8 bytes hold at most maxBytes UTF-16 code units; cut there first, then trim to the byte budget.+ let prefix = body.length > maxBytes ? body.slice(0, safeSplitIndex(body, maxBytes)) : body;+ while (Buffer.byteLength(prefix, 'utf8') > maxBytes) {+ prefix = prefix.slice(0, safeSplitIndex(prefix, Math.floor(prefix.length * 0.9)));+ }+ return credentialSafeProjection(sanitizeRemoteBody(prefix));+}diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex a73fbd1589..fe278501ec 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 243;+export const LATEST_SCHEMA_VERSION = 244;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 129cf41721..e75c32535d 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -244,6 +244,7 @@ import { v240 } from './v240-pages-name-lookup-indexes.ts';import { v241 } from './v241-persistence-request-slug-intent-index.ts';import { v242 } from './v242-extract-atoms-partial-input.ts';import { v243 } from './v243-persistence-consumer-process-start.ts';+import { v244 } from './v244-chunk-projected-spans.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -486,4 +487,5 @@ export const MIGRATIONS: Migration[] = [v241,v242,v243,+ v244,];diff --git a/src/core/schema-migrations/v244-chunk-projected-spans.ts b/src/core/schema-migrations/v244-chunk-projected-spans.tsnew file mode 100644index 0000000000..08bcab6f65--- /dev/null+++ b/src/core/schema-migrations/v244-chunk-projected-spans.ts@@ -0,0 +1,36 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Large pages (Wave A read contract): each prose chunk records where it sits in+// the projected text it was cut from, so `get_page { around_chunk_id }` and+// evidence delivery center a window on the exact chunk instead of searching+// the page for its text (which mis-anchors repeated conversation lines).+//+// Coordinates: UTF-8 byte offsets, end exclusive, into the chunk_source's+// projected text, credentialSafeProjection(sanitizeRemoteBody(<fence-overlaid+// compiled_truth or timeline>)), the same text the chunker cuts from and every+// windowed read is a slice of (src/core/page-window/document.ts). Not the+// raw stored column: the projection drops protected fences, so raw offsets+// would point a window into private text. Not start_line/end_line: those carry+// code-chunk line numbers inside a fence, and a line range cannot address a+// chunk that starts mid-line (word and character splits).+//+// NULL for code, image and low-tier fence chunks and for chunks written before+// this migration; readers fall back to locating the chunk text, and verify a+// stored span against the chunk text before trusting it (a span recorded for+// an older body can be stale). BIGINT: Wave B pages pass 2^31 bytes.+// Not in schema.sql's CREATE TABLE: added on every install, after the+// migration-added content_chunks columns, so fresh and upgraded brains share+// column ordinals (the v180 / v221 pattern). Metadata-only ADD COLUMNs; nothing+// to backfill.+export const v244: Migration = {+ version: 244,+ name: 'chunk_projected_spans',+ idempotent: true,+ sql: `+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS projected_byte_start BIGINT;+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS projected_byte_end BIGINT;+ `,+};diff --git a/src/core/search/evidence-delivery.ts b/src/core/search/evidence-delivery.tsindex a412ace5d6..16aafa801b 100644--- a/src/core/search/evidence-delivery.ts+++ b/src/core/search/evidence-delivery.ts@@ -30,9 +30,8 @@ import { pageReadFilter } from './read-policy-sql.ts';import { currentTextProjectionFilter, safeChunksFilter, requiresSafeChunks } from './safe-chunks.ts';import { resolveExcludePrivatePages } from './private-visibility.ts';import { safeSplitIndex } from '../text-safe.ts';-import { sanitizeRemoteBody } from '../remote-body.ts';-import { credentialSafeProjection } from '../credential-projection.ts';-import { loadFenceChunkOverlay, markFenceChunk, splitFenceOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';+import { loadFenceChunkOverlay, type FenceChunkOverlay } from '../eligibility/fence-overlay.ts';+import { projectPageText, TIMELINE_SEPARATOR } from '../page-window/document.ts';import { stripChunkHeader } from '../chunkers/code.ts';import { OperationError } from '../ops/contract.ts';import { blockDateHeaders, evidenceDateHeaderEnabled } from './evidence-date.ts';@@ -384,8 +383,7 @@ function sliceToTokenCount(text: string, max: number, tokenizer: 'cl100k' | 'heu// Locating chunks in the sanitized body// ----------------------------------------------------------------------------/** Separator serializeMarkdown writes between compiled truth and timeline. */-export const TIMELINE_SEPARATOR = '\n\n<!-- timeline -->\n\n';+export { TIMELINE_SEPARATOR };/** Whitespace runs collapsed to one space, with a map back to original offsets. */function squeeze(text: string): { s: string; map: number[] } {@@ -574,24 +572,16 @@ function fallbackBlock(hit: SearchResult, hits: SearchResult[], reason: string):}/**- * The page text evidence is cut from: the complete stored body, sanitized- * with the strict protected-body boundary BEFORE any slicing (Takes, non-world- * and withdrawn Facts rows, malformed protected tails, materialized markers),- * compiled truth and timeline each sanitized whole, run through the same- * credential-safe projection the chunkers cut from (private-key spans become- * newline-padded tokens), and joined the way serializeMarkdown joins them.- * Frontmatter is not part of it.+ * The page text evidence is cut from: the one projected page text every+ * windowed read slices (page-window/document.ts): the complete stored body,+ * sanitized with the strict protected-body boundary BEFORE any slicing (Takes,+ * non-world and withdrawn Facts rows, malformed protected tails, materialized+ * markers), compiled truth and timeline each sanitized whole, run through the+ * same credential-safe projection the chunkers cut from, and joined the way+ * serializeMarkdown joins them. Frontmatter is not part of it.*/export function pageEvidenceText(page: { compiled_truth: string; timeline: string; fenceOverlay?: FenceChunkOverlay }, includeTimeline: boolean): { text: string; timelineAt: number } {- // #5575 ENG-1: the page's chunks were cut through its fence overlay; the document is too (held and purged rows- // out, rows below the page tier after the truth under their trust marker, the way the marked chunks hold them).- const ownTruth = splitFenceOverlay(page.compiled_truth ?? '', page.fenceOverlay);- const ownTimeline = splitFenceOverlay(page.timeline ?? '', page.fenceOverlay);- const truth = [credentialSafeProjection(sanitizeRemoteBody(ownTruth.main)), ...[...ownTruth.lowTier, ...(includeTimeline ? ownTimeline.lowTier : [])]- .map(({ tier, unconfirmed, body }) => markFenceChunk(tier, credentialSafeProjection(sanitizeRemoteBody(body)), unconfirmed))].join('\n\n');- const timeline = includeTimeline ? credentialSafeProjection(sanitizeRemoteBody(ownTimeline.main)) : '';- if (!timeline.trim()) return { text: truth, timelineAt: -1 };- return { text: truth + TIMELINE_SEPARATOR + timeline, timelineAt: truth.length + TIMELINE_SEPARATOR.length };+ return projectPageText(page, includeTimeline);}function locateAnchor(doc: Doc, hit: SearchResult): Anchor {diff --git a/src/core/types.ts b/src/core/types.tsindex 3615cfed32..16dff0bd0a 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -694,6 +694,9 @@ export interface Chunk {* image search arm.*/modality?: 'text' | 'image';+ /** v244: UTF-8 byte span in the chunk_source's projected text (see ChunkInput); null when unrecorded. */+ projected_byte_start?: number | null;+ projected_byte_end?: number | null;/*** True when the stored vector is NULL. Cheap boolean (no vector egress) so* non-embedding readers can tell "vector missing" apart from `embedded_at`,@@ -813,6 +816,14 @@ export interface ChunkInput {parent_symbol_path?: string[];doc_comment?: string;symbol_name_qualified?: string;+ /**+ * v244: where a prose chunk sits in the projected text of its chunk_source+ * (credentialSafeProjection(sanitizeRemoteBody(<fence-overlaid compiled_truth+ * or timeline>))), as UTF-8 byte offsets, end exclusive. Absent for code,+ * image and low-tier fence chunks. Windowed reads center on it.+ */+ projected_byte_start?: number;+ projected_byte_end?: number;}// Searchdiff --git a/src/core/utils.ts b/src/core/utils.tsindex 82268e3620..4dd5edddc2 100644--- a/src/core/utils.ts+++ b/src/core/utils.ts@@ -457,6 +457,9 @@ export function rowToChunk(row: Record<string, unknown>, includeEmbedding = falsdoc_comment: (row.doc_comment as string | null | undefined) ?? null,symbol_name_qualified: (row.symbol_name_qualified as string | null | undefined) ?? null,modality: (row.modality as 'text' | 'image' | undefined) ?? undefined,+ // v244: projected UTF-8 span (bigint on Postgres); only when the SELECT carried the column.+ ...(row.projected_byte_start !== undefined && { projected_byte_start: row.projected_byte_start == null ? null : Number(row.projected_byte_start) }),+ ...(row.projected_byte_end !== undefined && { projected_byte_end: row.projected_byte_end == null ? null : Number(row.projected_byte_end) }),// Only present when the SELECT included it (getChunks); undefined elsewhere// so callers can tell "not selected" from "vector present"....(row.embedding_is_null !== undefined && { embedding_is_null: Boolean(row.embedding_is_null) }),