Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(large-pages): contextual synopsis per segment on segmented pages (Wave B PR 4 lane 4c, spec 8.6)
garrytan66bb2deb625a
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 7f98af30a8..50467fb8a4 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -51,7 +51,10 @@ import {} from './embedding-context.ts';import {DEFAULT_SYNOPSIS_MODEL,+ estimateSynopsisCallUsd,generatePerChunkSynopsis,+ SEGMENT_SYNOPSIS_LEAD_BYTES,+ segmentSynopsisWindows,SYNOPSIS_PROMPT_VERSION,SYNOPSIS_DOC_MAX_CHARS,type GeneratePerChunkSynopsisResult,@@ -61,11 +64,20 @@ import { runSlidingPool } from './worker-pool.ts';import type { BrainEngine } from './engine.ts';import type { ChunkInput, CRMode, Page } from './types.ts';import type { SourceRow } from './sources-ops.ts';-import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot } from './page-state/projections.ts';+import { embeddingInputContext, embeddingWriteTarget, installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot } from './page-state/projections.ts';import { reconcileContextualEmbeddingInputs } from './page-state/contextual-proof.ts';import { digest } from './persistence/digest.ts';import { isLargePageBytes } from './page-size-policy.ts';import { isSegmentedPage, pageBodyBytes } from './page-body/page-shape.ts';+import { readSegmentedEmbedPage, type SegmentedEmbedPage } from './page-body/segmented-embedding.ts';+import { embeddingInputHash, synopsisDocumentHash, type EmbeddingTier } from './embedding-input-hash.ts';+import { currentEmbeddingSignature } from './embedding.ts';+import { estimatePageEmbedUsd, reservePageSpend, spendGrant } from './page-embedding-budget.ts';+import { overlaidBoundedPrefix, pageLeadSource } from './page-window/bounded-lead.ts';+import { boundedProjectedPrefix } from './page-window/document.ts';+import { jsonRowBatches } from './batch-rows.ts';+import { quoteIdentifier, vectorCastSuffix } from './search/embedding-column.ts';+import { chunkGenerationFilter, currentTextProjectionFilter } from './search/safe-chunks.ts';/*** v3 = chunks embed with optional contextual retrieval wrapper. The@@ -310,9 +322,7 @@ export async function reembedPageWithContextualRetrieval(if (initial.deleted_at != null) {return { kind: 'skipped', reason: 'soft_deleted' };}- // Wave B: a segmented page's vectors come from its stale chunk rows (page-body/segmented-embedding.ts); its contextual- // synopsis per segment is spec 8.6. Nothing is stamped: its vectors were not rebuilt under this mode.- if (isSegmentedPage(initial)) return { kind: 'skipped', reason: 'page_body_segmented' };+ if (isSegmentedPage(initial)) return reembedSegmentedPage(args, initial);const prepared = await readProjectionSnapshot(args.engine, args.pageSlug, args.sourceId, { allowUnsealed: true });if (!prepared) return { kind: 'skipped', reason: 'page_missing' };@@ -473,6 +483,145 @@ export async function reembedPageWithContextualRetrieval(}}+/** Embedding-input chars a synopsis adds to a title-wrapped chunk at most (embedding-context's synopsis cap plus its markup). */+const SYNOPSIS_WRAPPER_CHARS = 320;++type SegmentSynopsisRow = SynopsisChunk & { embedding_input_hash: string | null };++/**+ * Wave B spec 8.6: per-chunk synopsis on a segmented page, segment by segment, never reading the body whole. Only a+ * page whose resolved mode is `per_chunk_synopsis` runs (the title and none tiers of a segmented page come from the+ * segmented embedding path, so those are skipped as `page_body_segmented`). Each segment's chunks are packed into+ * windows (segmentSynopsisWindows); a chunk's synopsis document is the page title, the first 8 KiB of the projected+ * lead and its window, and its recorded input names that document's hash, so a chunk whose recorded input already+ * matches keeps its vector and an append pays only for the windows of its new segments. Segments run newest first, so+ * a per-page cap spends on the newest text, as the embedding path's grants do. Each window with work reserves its synopsis calls and their embedding against the page's spend cap (`synopsis:<model>`) first: a held page+ * or a refused reservation leaves the title tier in place (`budget_limited`), keeping windows already installed. A+ * window whose synopsis is refused, empty or malformed embeds at the title tier, which a synopsis page accepts+ * (page_fallback). Vectors install like the segmented embedding path's, by chunk_index and text onto rows of the live+ * generation while the page's title, mode and write target are unchanged; the page is stamped+ * `per_chunk_synopsis` once every window is current.+ */+async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promise<ReembedPageResult> {+ const { engine } = args;+ const page = await readSegmentedEmbedPage(engine, { sourceId: args.sourceId, slug: args.pageSlug });+ if (!page) return { kind: 'skipped', reason: 'page_body_segmented' };+ const source = await loadSourceRow(engine, page.source_id);+ const resolution = resolveContextualRetrievalMode({+ pageFrontmatter: initial.frontmatter ?? {},+ source: {+ id: source.id,+ contextual_retrieval_mode: source.contextual_retrieval_mode ?? null,+ trust_frontmatter_overrides: source.trust_frontmatter_overrides ?? false,+ },+ globalMode: args.globalMode,+ killSwitchDisabled: args.killSwitchDisabled ?? false,+ });+ if (resolution.mode !== 'per_chunk_synopsis') return { kind: 'skipped', reason: 'page_body_segmented' };+ if ((await engine.executeRaw(`SELECT 1 FROM page_embedding_budget WHERE page_id = $1 AND state <> 'open'`, [page.id])).length) {+ return { kind: 'skipped', reason: 'budget_limited' };+ }+ const superseded: ReembedPageResult = { kind: 'transient_error', cause: 'db',+ detail: 'The page, its title or its contextual mode changed during the synopsis pass; retry from its current state.' };+ const synopsisModel = args.synopsisModel ?? args.haikuModel ?? DEFAULT_SYNOPSIS_MODEL;+ const synopsisMaxTokens = args.synopsisMaxTokens ?? (await resolveSynopsisMaxTokens(engine));+ const corpusGeneration = computeCorpusGeneration({ crMode: 'per_chunk_synopsis', synopsisModel, synopsisDocMaxChars: SYNOPSIS_DOC_MAX_CHARS });+ const target = await embeddingWriteTarget(engine);+ const base = embeddingInputContext(target, page.title, corpusGeneration, []);+ const titlePrefix = buildContextualPrefix(page.title, null);+ const embedSignature = currentEmbeddingSignature();+ const lead = boundedProjectedPrefix(await overlaidBoundedPrefix(engine,+ { slug: page.slug, source_id: page.source_id, compiled_truth: await pageLeadSource(engine, initial) }), SEGMENT_SYNOPSIS_LEAD_BYTES);+ const occurrences = await engine.executeRaw<{ occurrence_id: string | number }>(+ 'SELECT occurrence_id FROM page_body_manifest WHERE page_id = $1 AND gen_to IS NULL AND staging_id IS NULL ORDER BY seq DESC', [page.id]);++ let embedded = 0;+ let fallbackKind: SynopsisFailureKind | null = null;+ for (const { occurrence_id } of occurrences) {+ const rows = await engine.executeRaw<SegmentSynopsisRow>(+ `SELECT cc.chunk_index, cc.chunk_text, cc.chunk_source, cc.embedding_input_hash+ FROM content_chunks cc JOIN pages p ON p.id = cc.page_id+ WHERE cc.page_id = $1 AND cc.occurrence_id = $2 AND ${currentTextProjectionFilter('p')} AND ${chunkGenerationFilter('p', 'cc')}+ ORDER BY cc.chunk_index`, [page.id, occurrence_id]);+ for (const window of segmentSynopsisWindows(rows, lead)) {+ const provenance = { ...base, bodyHash: synopsisDocumentHash(window.document) };+ const todo = window.chunks.filter(c => c.embedding_input_hash !== embeddingInputHash(provenance, 'per_chunk_synopsis', c));+ if (todo.length === 0) continue;+ const estimateUsd = todo.reduce((usd, c) => usd+ + (c.chunk_source === 'fenced_code' ? 0 : estimateSynopsisCallUsd(synopsisModel, window.document, c.chunk_text, synopsisMaxTokens)), 0)+ + estimatePageEmbedUsd(todo.reduce((n, c) => n + wrapChunkForEmbedding(c.chunk_text, titlePrefix, c.chunk_source).length + SYNOPSIS_WRAPPER_CHARS, 0), embedSignature);+ const decision = await reservePageSpend(engine, page, `synopsis:${synopsisModel}`, estimateUsd);+ if (decision.kind === 'refused') return { kind: 'skipped', reason: 'budget_limited' };+ const built = await spendGrant(decision.kind === 'grant' ? decision.grant : undefined, async () => {+ const synopsized = await synopsisWrappedTexts({ chunks: todo, sourceText: window.document, title: page.title, args, synopsisModel, synopsisMaxTokens });+ if (!Array.isArray(synopsized) && synopsized.kind !== 'page_level_fallback_requested') return synopsized;+ const tier: EmbeddingTier = Array.isArray(synopsized) ? 'per_chunk_synopsis' : 'title';+ if (!Array.isArray(synopsized)) fallbackKind ??= synopsized.cause;+ const inputs = Array.isArray(synopsized) ? synopsized : todo.map(c => wrapChunkForEmbedding(c.chunk_text, titlePrefix, c.chunk_source));+ try {+ return { kind: 'built' as const, tier, vectors: await embedBatch(inputs, { abortSignal: args.abortSignal }) };+ } catch (err) {+ return classifyEmbedError(err, err instanceof Error ? err.message : String(err));+ }+ });+ if (built.kind !== 'built') {+ return { kind: built.kind === 'permanent' ? 'permanent_error' : 'transient_error', cause: built.cause, detail: built.detail };+ }+ if (built.vectors.length !== todo.length || built.vectors.some(v => !v?.length || !v.every(Number.isFinite))) {+ return { kind: 'transient_error', cause: 'embed', detail: 'Embedding provider returned an incomplete or invalid batch' };+ }+ const updates = todo.map((c, i) => ({ chunk_index: c.chunk_index, chunk_text: c.chunk_text,+ embedding: `[${Array.from(built.vectors[i]!).join(',')}]`,+ hash: embeddingInputHash(built.tier === 'title' ? base : provenance, built.tier, c) }));+ const installed = await installSegmentedSynopsisVectors(engine, page, target, updates);+ if (installed < todo.length) return superseded;+ embedded += installed;+ }+ }++ const stamped = await engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);+ if (!sameSegmentedEmbedPage(page, await readSegmentedEmbedPage(tx, { id: page.id }))) return false;+ await tx.updatePageContextualRetrievalState(page.slug, page.source_id, 'per_chunk_synopsis', corpusGeneration);+ return true;+ });+ if (!stamped) return superseded;+ if (fallbackKind !== null) {+ return { kind: 'page_fallback', mode_attempted: 'per_chunk_synopsis', mode_applied: 'per_chunk_synopsis',+ chunks_embedded: embedded, corpus_generation: corpusGeneration, fallback_kind: fallbackKind };+ }+ return { kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: embedded, corpus_generation: corpusGeneration };+}++function sameSegmentedEmbedPage(page: SegmentedEmbedPage, current: SegmentedEmbedPage | null): boolean {+ return current !== null && current.slug === page.slug && current.title === page.title+ && current.contextual_retrieval_mode === page.contextual_retrieval_mode;+}++/** Install one window's vectors with their recorded inputs onto the live rows with the same chunk_index and text; 0 when the page or write target moved. */+async function installSegmentedSynopsisVectors(engine: BrainEngine, page: SegmentedEmbedPage,+ target: Awaited<ReturnType<typeof embeddingWriteTarget>>,+ updates: Array<{ chunk_index: number; chunk_text: string; embedding: string; hash: string }>): Promise<number> {+ const col = quoteIdentifier(target.column.name);+ return engine.transaction(async tx => {+ await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);+ const now = await embeddingWriteTarget(tx);+ if (!sameSegmentedEmbedPage(page, await readSegmentedEmbedPage(tx, { id: page.id }))+ || now.column.name !== target.column.name || now.provenanceModel !== target.provenanceModel) return 0;+ let installed = 0;+ for (const batch of jsonRowBatches(updates, update => update)) {+ installed += (await tx.executeRaw(`UPDATE content_chunks cc SET ${col} = v.embedding${vectorCastSuffix(target.column)},+ embedding_input_hash = v.hash, embedded_at = now(), embedded_text_hash = md5(cc.chunk_text), model = COALESCE($3, cc.model),+ embedding_pending_since = NULL+ FROM jsonb_to_recordset($2::text::jsonb) AS v(chunk_index int, chunk_text text, embedding text, hash text), pages p+ WHERE cc.page_id = $1 AND p.id = cc.page_id AND cc.chunk_index = v.chunk_index AND cc.chunk_text = v.chunk_text+ AND ${chunkGenerationFilter('p', 'cc')}+ RETURNING cc.id`, [page.id, batch, target.model])).length;+ }+ return installed;+ });+}+// ── Internal helpers ────────────────────────────────────────────────interface Phase1Success {@@ -546,27 +695,51 @@ async function tryBuildPhase1(opts: {// generate synopsis per chunk through a bounded sliding pool, then// batch embed at the end (D27 P2-2).const sourceText = readSourceTextWithFallback(page, chunks);- const wrappedTexts: string[] = new Array(chunks.length);- const chunkConcurrency = clampContextualChunkConcurrency(- args.chunkConcurrency ?? resolveContextualChunkConcurrency(),- );+ const wrappedTexts = await synopsisWrappedTexts({ chunks, sourceText, title, args, synopsisModel, synopsisMaxTokens });+ if (!Array.isArray(wrappedTexts)) return wrappedTexts;+ // All chunks synthesized successfully. Single batch embed (D27 P2-2).+ try {+ const embeddings = await embedBatch(wrappedTexts, { abortSignal: args.abortSignal });+ return {+ kind: 'success',+ embeddedChunks: chunks.map((c, i) => ({+ ...c,+ chunk_text: c.chunk_text, // canonical (D20-T1)+ embedding: embeddings[i],+ token_count: Math.ceil(wrappedTexts[i].length / 4),+ })),+ };+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ return classifyEmbedError(err, detail);+ }+}++type SynopsisChunk = Pick<ChunkInput, 'chunk_index' | 'chunk_text' | 'chunk_source'>;++/**+ * The embedding input of each chunk under per-chunk synopsis over `sourceText`: a synopsis per chunk through a bounded+ * sliding pool (fenced code passes through raw), or the first failing chunk's Phase 1 result.+ */+async function synopsisWrappedTexts(opts: {+ chunks: readonly SynopsisChunk[];+ sourceText: string;+ title: string;+ args: ReembedPageArgs;+ synopsisModel: string;+ synopsisMaxTokens?: number;+}): Promise<string[] | Exclude<Phase1Result, Phase1Success>> {+ const { chunks, args } = opts;+ const wrappedTexts: string[] = new Array(chunks.length);const poolResult = await runSlidingPool({- items: chunks,- workers: chunkConcurrency,+ items: [...chunks],+ workers: clampContextualChunkConcurrency(args.chunkConcurrency ?? resolveContextualChunkConcurrency()),signal: args.abortSignal,onError: 'abort',failureLabel: (c) => String(c.chunk_index),onItem: async (c, i) => {- wrappedTexts[i] = await buildWrappedChunkText({- chunk: c,- sourceText,- title,- page,- args,- synopsisModel,- synopsisMaxTokens,- });+ wrappedTexts[i] = await buildWrappedChunkText({ ...opts, chunk: c });},});@@ -580,23 +753,7 @@ async function tryBuildPhase1(opts: {if (poolResult.aborted || args.abortSignal?.aborted) {return { kind: 'transient', cause: 'timeout', detail: 'aborted' };}-- // All chunks synthesized successfully. Single batch embed (D27 P2-2).- try {- const embeddings = await embedBatch(wrappedTexts, { abortSignal: args.abortSignal });- return {- kind: 'success',- embeddedChunks: chunks.map((c, i) => ({- ...c,- chunk_text: c.chunk_text, // canonical (D20-T1)- embedding: embeddings[i],- token_count: Math.ceil(wrappedTexts[i].length / 4),- })),- };- } catch (err) {- const detail = err instanceof Error ? err.message : String(err);- return classifyEmbedError(err, detail);- }+ return wrappedTexts;}class ChunkSynopsisPhase1Error extends Error {@@ -607,16 +764,15 @@ class ChunkSynopsisPhase1Error extends Error {}async function buildWrappedChunkText(opts: {- chunk: ChunkInput;+ chunk: SynopsisChunk;sourceText: string;title: string;- page: Page;args: ReembedPageArgs;synopsisModel: string;/** #3883: resolved output-token cap (undefined → page-summary default). */synopsisMaxTokens?: number;}): Promise<string> {- const { chunk: c, sourceText, title, page, args, synopsisModel, synopsisMaxTokens } = opts;+ const { chunk: c, sourceText, title, args, synopsisModel, synopsisMaxTokens } = opts;// Code chunks always bypass the wrapper (D20-T4) — pass through.if (c.chunk_source === 'fenced_code') {@@ -647,7 +803,7 @@ async function buildWrappedChunkText(opts: {synopsisResult = await (args.generateSynopsis ?? generatePerChunkSynopsis)({documentText: sourceText,chunkText: c.chunk_text,- pageTitle: page.title,+ pageTitle: title,pageSlug: args.pageSlug,sourceId: args.sourceId,chunkIndex: c.chunk_index,diff --git a/src/core/embedding-input-hash.ts b/src/core/embedding-input-hash.tsindex 6b8e5ed54e..bb515a5e5a 100644--- a/src/core/embedding-input-hash.ts+++ b/src/core/embedding-input-hash.ts@@ -6,8 +6,10 @@* the vector was built under, and the exact embedding input: the chunk text for* `none` and fenced code, the title prefix plus the chunk text for `title`, and* (because a generated synopsis cannot be recomputed) the page's synopsis- * corpus generation, the full title the synopsis prompt read, the document-body hash and the chunk text for- * `per_chunk_synopsis`. A projection rebuild keeps a vector only when the stored+ * corpus generation, the full title the synopsis prompt read, the hash of the synopsis document and the chunk text+ * for `per_chunk_synopsis`. The document of a page read whole is every chunk (`synopsisBodyHash`); a segmented+ * page's is its lead and the window of one segment around the chunk (wave-b spec 8.6, `segmentSynopsisWindows`), so+ * a synopsis vector there depends on its own segment and the lead, never on the rest of the body. A projection rebuild keeps a vector only when the stored* hash equals one recomputed from the current page, so an unchanged input keeps* its vector and any change to it (title, body in synopsis mode, model, column,* dimensions, wrapper bytes) nulls it. `embedded_text_hash` keeps its meaning.@@ -24,15 +26,24 @@ export interface EmbeddingInputContext {title: string;/** The page's stored corpus generation; only the synopsis tier digests it. */corpusGeneration: string | null;- /** `synopsisBodyHash` of the page's installed chunk set. */+ /** `synopsisDocumentHash` of the synopsis document: `synopsisBodyHash` of the page's installed chunk set, or a segmented page's window document. */bodyHash: string;}type HashedChunk = { chunk_text: string; chunk_source?: string | null };-/** The document a synopsis is generated from: every non-image chunk, in order. */+/** The document a synopsis of a page read whole is generated from: every non-image chunk, in order. */+export function synopsisDocument(chunks: ReadonlyArray<HashedChunk>): string {+ return chunks.filter(c => c.chunk_source !== 'image_asset').map(c => c.chunk_text).join('\n\n');+}++/** The `bodyHash` of a synopsis document, the exact text the synopsis prompt reads. */+export function synopsisDocumentHash(document: string): string {+ return sha256(document);+}+export function synopsisBodyHash(chunks: ReadonlyArray<HashedChunk>): string {- return sha256(chunks.filter(c => c.chunk_source !== 'image_asset').map(c => c.chunk_text).join('\n\n'));+ return synopsisDocumentHash(synopsisDocument(chunks));}/** The tier a plain re-embed uses for a stored mode (mirrors wrapChunkTextsForStoredMode). */diff --git a/src/core/page-summary.ts b/src/core/page-summary.tsindex 7e75c38ab4..e58131fb9e 100644--- a/src/core/page-summary.ts+++ b/src/core/page-summary.ts@@ -35,6 +35,7 @@ import { chat, type ChatOpts, type ChatResult } from './ai/gateway.ts';import { logSynopsisFailure, type SynopsisFailureKind } from './audit-synopsis.ts';import { sanitizeSynopsis } from './embedding-context.ts';import { resolveTierDefault } from './model-config.ts';+import { reservationCostUsd } from './budget/reservation-cost.ts';import { safeSplitIndex } from './text-safe.ts';/**@@ -281,6 +282,55 @@ export function buildPagePrompt(pageTitle: string, documentText: string): string].join('\n');}+/** Wave B spec 8.6: the share of the page lead (the projected `truth_lead`) a segmented page's synopsis document opens with. */+export const SEGMENT_SYNOPSIS_LEAD_BYTES = 8 * 1024;+/** Wave B spec 8.6: the most text of one segment a segmented page's synopsis document carries around a chunk. */+export const SEGMENT_SYNOPSIS_WINDOW_BYTES = 32 * 1024;+const SEGMENT_SYNOPSIS_GAP = '\n\n[...]\n\n';++export interface SegmentSynopsisWindow<C> { document: string; chunks: C[] }++/**+ * The synopsis documents of one segment of a segmented page (wave-b spec 8.6): the segment's chunks, in order, packed+ * greedily into windows of at most SEGMENT_SYNOPSIS_WINDOW_BYTES (and, with the lead, at most SYNOPSIS_DOC_MAX_CHARS,+ * so buildPagePrompt never cuts a window), each document the lead, a gap marker and the window. Every chunk sits in the+ * one window that holds it; a chunk larger than a window is a window alone. A document depends only on the lead and+ * this segment's chunks, so an append or edit elsewhere on the page leaves it, and the vectors built from it, as they+ * are; the chunks of one window share one document, so the prompt cache serves all but the first call.+ */+export function segmentSynopsisWindows<C extends { chunk_text: string; chunk_source?: string | null }>(chunks: readonly C[], lead: string): SegmentSynopsisWindow<C>[] {+ const prefix = lead ? lead + SEGMENT_SYNOPSIS_GAP : '';+ const maxChars = Math.min(SEGMENT_SYNOPSIS_WINDOW_BYTES, SYNOPSIS_DOC_MAX_CHARS - prefix.length);+ const windows: SegmentSynopsisWindow<C>[] = [];+ let open: { chunks: C[]; texts: string[]; chars: number; bytes: number } | null = null;+ const close = () => { if (open) windows.push({ document: prefix + open.texts.join('\n\n'), chunks: open.chunks }); };+ for (const chunk of chunks) {+ if (chunk.chunk_source === 'image_asset') continue;+ const chars = chunk.chunk_text.length + 2;+ const bytes = Buffer.byteLength(chunk.chunk_text, 'utf8') + 2;+ if (open && open.chars + chars <= maxChars && open.bytes + bytes <= SEGMENT_SYNOPSIS_WINDOW_BYTES) {+ open.chunks.push(chunk); open.texts.push(chunk.chunk_text); open.chars += chars; open.bytes += bytes;+ continue;+ }+ close();+ open = { chunks: [chunk], texts: [chunk.chunk_text], chars, bytes };+ }+ close();+ return windows;+}++/** Input chars of a synopsis call outside its document and chunk: the system prompt and the prompt's tags. */+const SYNOPSIS_PROMPT_OVERHEAD_CHARS = SYNOPSIS_SYSTEM_PROMPT.length + 256;+/** The rate (USD per million tokens) an unpriced synopsis model reserves at. */+const UNPRICED_SYNOPSIS_RATE = { input: 15, output: 75 };++/** What one synopsis call over `documentText` and `chunkText` may cost at most: the uncached prompt plus the full output ceiling. */+export function estimateSynopsisCallUsd(model: string, documentText: string, chunkText: string, maxTokens: number = SYNOPSIS_MAX_TOKENS): number {+ const input = Math.ceil((Math.min(documentText.length, SYNOPSIS_DOC_MAX_CHARS) + chunkText.length + SYNOPSIS_PROMPT_OVERHEAD_CHARS) / 4);+ return reservationCostUsd(model, 'chat', input, maxTokens)+ ?? (input * UNPRICED_SYNOPSIS_RATE.input + maxTokens * UNPRICED_SYNOPSIS_RATE.output) / 1_000_000;+}+export function buildChunkPrompt(chunkText: string): string {return ['',diff --git a/test/large-pages/contextual-reembed-segmented.test.ts b/test/large-pages/contextual-reembed-segmented.test.tsindex 48baaf54a0..aae4f9b60c 100644--- a/test/large-pages/contextual-reembed-segmented.test.ts+++ b/test/large-pages/contextual-reembed-segmented.test.ts@@ -2,12 +2,12 @@* Wave B: contextual re-embed (`reembedPageWithContextualRetrieval`, the* `contextual_reindex_per_chunk` handler) on a segmented page.*- * 1. Protects: a segmented page is skipped with the reason- * `page_body_segmented` (its contextual synopsis per segment is spec 8.6,- * PR 4; its vectors come from the segmented embedding path), its mode- * stamp and chunk vectors are left as they are, and the handler's job- * result names the reason. A page that does not exist is still- * `page_missing`.+ * 1. Protects: under the title and none modes a segmented page is skipped+ * with the reason `page_body_segmented` (its vectors come from the+ * segmented embedding path), its mode stamp and chunk vectors are left as+ * they are, and the handler's job result names the reason. A page that+ * does not exist is still `page_missing`. Per-chunk synopsis on a+ * segmented page (spec 8.6) runs: segmented-synopsis.test.ts.* 2. Fails when: a segmented page is reported as missing (the projection* snapshot is null for it), or the skip stamps a mode its vectors were* never rebuilt for.@@ -37,7 +37,7 @@ afterAll(async () => {await closePostgres?.();});-test('a segmented page is skipped as page_body_segmented, its mode and vectors untouched', async () => withEnv(env, async () => {+test('under title and none a segmented page is skipped as page_body_segmented, its mode and vectors untouched', async () => withEnv(env, async () => {for (const engine of engines) {await engine.setConfig('pages.segmented_storage', 'on');await importFromContent(engine, 'notes/contextual', conversationPage(2 * 1024 * 1024, { seed: 91 }), { noEmbed: true });@@ -48,7 +48,7 @@ test('a segmented page is skipped as page_body_segmented, its mode and vectors u(SELECT count(*)::int FROM content_chunks c WHERE c.page_id = p.id AND c.embedded_at IS NOT NULL) AS embedded FROM pages p WHERE p.id = $1`, [page.id]);const before = await state();- for (const globalMode of ['title', 'per_chunk_synopsis', 'none'] as const) {+ for (const globalMode of ['title', 'none'] as const) {expect(await reembedPageWithContextualRetrieval({ engine, pageSlug: 'notes/contextual', sourceId: 'default', globalMode })).toEqual({ kind: 'skipped', reason: 'page_body_segmented' });}diff --git a/test/large-pages/segmented-synopsis.test.ts b/test/large-pages/segmented-synopsis.test.tsnew file mode 100644index 0000000000..2ba04f734a--- /dev/null+++ b/test/large-pages/segmented-synopsis.test.ts@@ -0,0 +1,187 @@+/**+ * Contextual synopsis per segment on a segmented page (wave-b spec 8.6, PR 4 lane 4c).+ *+ * 1. Protects: reembedPageWithContextualRetrieval on a segmented page whose resolved mode is per_chunk_synopsis+ * gives every live chunk a synopsis vector whose document is the title, the first 8 KiB of the projected lead and+ * one window of its own segment (never more than SYNOPSIS_DOC_MAX_CHARS, never the rest of the body); its recorded+ * input names that document, so a rerun calls nothing and an append pays only for the chunks of its new segments,+ * while the vectors of unchanged segments keep their recorded inputs. Each window reserves against the per-page+ * spend cap first: a cap that admits nothing leaves the page as it was (budget_limited). A refused synopsis embeds+ * its window at the title tier (page_fallback). Title and none stay with the segmented embedding path.+ * 2. Fails when: the segmented page is skipped as page_body_segmented under per_chunk_synopsis (the title-tier forcing+ * never lifts), the synopsis input is hashed over every chunk of the page (an append re-synopsizes the whole page),+ * the document is cut by buildPagePrompt, or a synopsis call runs past a refused reservation.+ * 3. Runs on PGLite, and on Postgres when DATABASE_URL is set. The synopsis model and the embedding provider are fakes.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import type { BrainEngine } from '../../src/core/engine.ts';+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../../src/core/ai/gateway.ts';+import { importFromContent } from '../../src/core/import-file.ts';+import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';+import { SYNOPSIS_DOC_MAX_CHARS, SEGMENT_SYNOPSIS_LEAD_BYTES, SEGMENT_SYNOPSIS_WINDOW_BYTES, segmentSynopsisWindows, type GeneratePerChunkSynopsisArgs, type GeneratePerChunkSynopsisResult } from '../../src/core/page-summary.ts';+import { embeddingInputHash } from '../../src/core/embedding-input-hash.ts';+import { embeddingInputContext, embeddingWriteTarget } from '../../src/core/page-state/projections.ts';+import { resolveActiveEmbeddingColumnFromEngine } from '../../src/core/search/embedding-column.ts';+import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';+import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';+import { testBackends } from '../helpers/test-backends.ts';++const WORDS = ['launch', 'pricing', 'roadmap', 'hiring', 'metrics', 'retention', 'design', 'latency', 'budget', 'customer'];+const paragraph = (day: number, k: number) =>+ [`day${day}`, `para${k}`, ...Array.from({ length: 98 }, (_, i) => WORDS[(day * 7 + k * 3 + i) % WORDS.length])].join(' ') + '.';+const day = (d: number) => `## Day ${d}\n\n${[1, 2, 3, 4].map(k => paragraph(d, k)).join('\n\n')}\n\n`;+const TITLE = 'Daily log';+const LEAD = 'Opening note: this log tracks the launch.';+const page = (body: string) => `---\ntitle: ${TITLE}\ntype: note\n---\n\n${LEAD}\n\n${body}`;+function days(bytes: number): { body: string; count: number } {+ let body = '';+ let count = 0;+ while (Buffer.byteLength(body) < bytes) body += day(++count);+ return { body, count };+}++interface ChunkRow { chunk_index: number; chunk_text: string; chunk_source: string; occurrence_id: number; embedding_input_hash: string | null; embedded: boolean }++describe('segmentSynopsisWindows (pure)', () => {+ test('packs a segment\'s chunks in order into windows the prompt never cuts; each chunk in exactly one window', () => {+ const lead = 'Lead paragraph. '.repeat(400);+ const rows = Array.from({ length: 40 }, (_, i) => ({ chunk_index: i, chunk_text: `chunk ${i} `.repeat(300), chunk_source: i === 7 ? 'image_asset' : 'compiled_truth' }));+ rows.push({ chunk_index: 40, chunk_text: 'x'.repeat(SEGMENT_SYNOPSIS_WINDOW_BYTES + 10), chunk_source: 'compiled_truth' });+ const windows = segmentSynopsisWindows(rows, lead);+ expect(windows.flatMap(w => w.chunks.map(c => c.chunk_index))).toEqual(rows.filter(r => r.chunk_source !== 'image_asset').map(r => r.chunk_index));+ expect(windows.at(-1)!.chunks.map(c => c.chunk_index)).toEqual([40]);+ for (const w of windows.slice(0, -1)) {+ expect(w.document.length).toBeLessThanOrEqual(SYNOPSIS_DOC_MAX_CHARS);+ expect(w.document.startsWith(lead)).toBe(true);+ expect(Buffer.byteLength(w.document) - Buffer.byteLength(lead)).toBeLessThanOrEqual(SEGMENT_SYNOPSIS_WINDOW_BYTES + 16);+ for (const c of w.chunks) expect(w.document).toContain(c.chunk_text);+ }+ expect(windows.length).toBeGreaterThan(2);+ expect(segmentSynopsisWindows(rows.slice(0, 3), '')[0]!.document).toBe(rows.slice(0, 3).map(r => r.chunk_text).join('\n\n'));+ });+});++for (const kind of testBackends()) {+ describe(`segmented per-chunk synopsis (${kind})`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ const embedded: string[] = [];+ const calls: GeneratePerChunkSynopsisArgs[] = [];+ let refuseChunk: ((args: GeneratePerChunkSynopsisArgs) => boolean) | null = null;+ const generateSynopsis = async (args: GeneratePerChunkSynopsisArgs): Promise<GeneratePerChunkSynopsisResult> => {+ calls.push(args);+ if (refuseChunk?.(args)) return { kind: 'refusal', detail: 'test refusal' };+ return { kind: 'success', synopsis: `Synopsis of chunk ${args.chunkIndex}.` };+ };+ const run = (slug: string, globalMode: 'per_chunk_synopsis' | 'title' | 'none' = 'per_chunk_synopsis') =>+ reembedPageWithContextualRetrieval({ engine, pageSlug: slug, sourceId: 'default', globalMode, generateSynopsis, chunkConcurrency: 4 });+ const chunks = async (slug: string): Promise<ChunkRow[]> => (await engine.executeRaw<ChunkRow>(+ `SELECT c.chunk_index, c.chunk_text, c.chunk_source, c.occurrence_id, c.embedding_input_hash, c.embedding IS NOT NULL AS embedded+ FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.slug = $1 AND ${chunkGenerationFilter('p', 'c')} ORDER BY c.chunk_index`, [slug]))+ .map(row => ({ ...row, chunk_index: Number(row.chunk_index), occurrence_id: Number(row.occurrence_id) }));+ const stamp = async (slug: string) => (await engine.executeRaw<{ mode: string | null; generation: string | null; body_storage: string }>(+ 'SELECT contextual_retrieval_mode AS mode, corpus_generation AS generation, body_storage FROM pages WHERE slug = $1', [slug]))[0]!;+ const titleHash = async (c: ChunkRow) => embeddingInputHash(embeddingInputContext(await embeddingWriteTarget(engine), TITLE, null, []), 'title', c);++ 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();+ }+ const dims = (await resolveActiveEmbeddingColumnFromEngine(engine)).dimensions;+ await engine.setConfig('pages.segmented_storage', 'on');+ await engine.setConfig('embed.max_usd_per_page', '1000');+ configureGateway({ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: dims, env: { OPENAI_API_KEY: 'sk-test' } });+ __setEmbedTransportForTests((async ({ values }: { values: string[] }) => {+ embedded.push(...values);+ return { embeddings: values.map(() => Array.from({ length: dims }, (_, j) => (j === 0 ? 1 : 0))), usage: { tokens: values.length } };+ }) as never);+ }, 120_000);+ afterAll(async () => { __setEmbedTransportForTests(null); resetGateway(); await close?.(); });++ test('every chunk gets a synopsis over its own segment window; a rerun calls nothing; an append pays only for its new segments', async () => {+ const slug = 'notes/synopsis-log';+ const { body, count } = days(2_300_000);+ await importFromContent(engine, slug, page(body), { noEmbed: true });+ expect((await stamp(slug)).body_storage).toBe('segmented');+ const before = await chunks(slug);+ expect(new Set(before.map(c => c.occurrence_id)).size).toBeGreaterThan(1);++ calls.length = 0; embedded.length = 0;+ const first = await run(slug);+ expect(first).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: before.length });+ expect(calls.length).toBe(before.filter(c => c.chunk_source !== 'fenced_code').length);+ expect(embedded.length).toBe(before.length);+ for (const call of calls) {+ expect(call.documentText.length).toBeLessThanOrEqual(SYNOPSIS_DOC_MAX_CHARS);+ expect(call.documentText.startsWith(LEAD)).toBe(true);+ expect(call.documentText).toContain(call.chunkText);+ expect(Buffer.byteLength(call.documentText)).toBeLessThan(SEGMENT_SYNOPSIS_LEAD_BYTES + SEGMENT_SYNOPSIS_WINDOW_BYTES + 64);+ }+ expect(embedded.every(text => text.includes('Synopsis of chunk'))).toBe(true);+ expect(await stamp(slug)).toMatchObject({ mode: 'per_chunk_synopsis', generation: first.kind === 'success' ? first.corpus_generation : 'unset' });+ const done = await chunks(slug);+ expect(done.every(c => c.embedded && c.embedding_input_hash !== null)).toBe(true);+ for (const c of done) expect(c.embedding_input_hash).not.toBe(await titleHash(c));++ calls.length = 0; embedded.length = 0;+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: 0 });+ expect(calls.length).toBe(0);+ expect(embedded.length).toBe(0);++ await importFromContent(engine, slug, page(body + day(count + 1)), { noEmbed: true });+ const appended = await chunks(slug);+ const oldOccurrences = new Set(done.map(c => c.occurrence_id));+ const fresh = appended.filter(c => !oldOccurrences.has(c.occurrence_id));+ expect(fresh.length).toBeGreaterThan(0);+ expect(fresh.length).toBeLessThan(appended.length / 2);+ const kept = new Map(done.map(c => [c.chunk_index, c.embedding_input_hash]));+ for (const c of appended.filter(row => oldOccurrences.has(row.occurrence_id))) expect(c.embedding_input_hash).toBe(kept.get(c.chunk_index)!);++ calls.length = 0; embedded.length = 0;+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: fresh.length });+ expect(calls.map(call => call.chunkIndex).sort((a, b) => a - b)).toEqual(fresh.filter(c => c.chunk_source !== 'fenced_code').map(c => c.chunk_index));+ expect(calls.some(call => call.documentText.includes(`## Day ${count + 1}`))).toBe(true);+ expect((await chunks(slug)).every(c => c.embedded)).toBe(true);+ }, 600_000);++ test('a per-page cap that admits nothing calls no model and leaves the page as it was', async () => {+ const slug = 'notes/synopsis-capped';+ await importFromContent(engine, slug, page(days(1_300_000).body), { noEmbed: true });+ const pageId = Number((await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]))[0]!.id);+ await engine.executeRaw('INSERT INTO page_embedding_budget (page_id, cap_usd) VALUES ($1, 0.0000001) ON CONFLICT (page_id) DO UPDATE SET cap_usd = EXCLUDED.cap_usd', [pageId]);+ const before = await stamp(slug);+ calls.length = 0; embedded.length = 0;+ expect(await run(slug)).toEqual({ kind: 'skipped', reason: 'budget_limited' });+ expect(calls.length).toBe(0);+ expect(embedded.length).toBe(0);+ expect(await stamp(slug)).toEqual(before);+ expect((await chunks(slug)).some(c => c.embedded)).toBe(false);+ }, 300_000);++ test('a refused synopsis embeds its window at the title tier; title and none modes stay with the segmented embedding path', async () => {+ const slug = 'notes/synopsis-refused';+ await importFromContent(engine, slug, page(days(1_300_000).body), { noEmbed: true });+ for (const mode of ['title', 'none'] as const) expect(await run(slug, mode)).toEqual({ kind: 'skipped', reason: 'page_body_segmented' });+ const all = await chunks(slug);+ const refused = all[Math.floor(all.length / 2)]!;+ refuseChunk = args => args.chunkIndex === refused.chunk_index;+ try {+ expect(await run(slug)).toMatchObject({ kind: 'page_fallback', mode_applied: 'per_chunk_synopsis', fallback_kind: 'refusal', chunks_embedded: all.length });+ } finally {+ refuseChunk = null;+ }+ const after = await chunks(slug);+ const titled: number[] = [];+ for (const c of after) if (c.embedding_input_hash === await titleHash(c)) titled.push(c.chunk_index);+ expect(titled).toContain(refused.chunk_index);+ expect(titled.length).toBeLessThan(after.length);+ expect(after.every(c => c.embedded)).toBe(true);+ }, 300_000);+ });+}diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex 9e84bd3168..dd3c980bdc 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -175,6 +175,7 @@ test/large-pages/segmented-storage-visibility.test.tstest/large-pages/segmented-sweep-budget.test.tstest/large-pages/segmented-sweep-deferral.test.tstest/large-pages/segmented-switch.test.ts+test/large-pages/segmented-synopsis.test.tstest/large-pages/segmented-think-compile-leads.serial.test.tstest/large-pages/segmented-timeline-heap.test.tstest/large-pages/segmented-timeline-retract-versions.test.ts