Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(large-pages): synopsis derivation rows per segment, shared segmented vector install, lane 4c tests (Wave B PR 4 lane 4c)
garrytanbd072f4ee9a0
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex f3dbaeb083..c7ce1e862a 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1022,6 +1022,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;// #7125 and #7117 (GBRA-145). `since` is restamped at the merge slot.{ since: '0.60.327.0', text: 'Fact extraction no longer rewrites the facts it stores: the prompt-injection filter used to delete words such as "System" before a parenthesis, so "Business System (ABS)" was saved as "Business [redacted](ABS)". Injection phrases are now neutralized only where stored facts are rendered into a model prompt (standing questions, turn context, proactive briefs). `gbrain doctor --only facts_redaction_marker` counts facts damaged earlier; `gbrain repair redacted-facts` previews what a source page can prove and changes nothing until you apply the printed `--apply --expect <hash>` command.' },{ since: '0.60.327.0', text: 'The embed sweep that finds chunks whose text changed after they were embedded now runs in 5,000-chunk batches, keeps its place between runs (at most 60 seconds per run) and starts a new pass once a day (`embed.content_drift.pass_interval_hours`, default 24); before, one statement covered the whole brain and a large brain cancelled it on every run. `gbrain doctor --only content_drift_sweep` shows each pass and any error.' },+ // PR 4 (Wave B incremental derivation, transcripts) — 4c, contextual synopsis per segment. `since` is restamped at the merge slot.+ { since: 'TBD', text: 'With contextual retrieval set to `per_chunk_synopsis`, a page stored in segments now gets per-chunk synopses instead of staying on the title tier: each chunk\'s synopsis reads the page title, the first 8 KiB of the page and up to 32 KB of its own segment, so the contextual re-embed (`gbrain reindex --markdown` and the per-chunk synopsis backfill) re-synopsizes only the segments an append or edit rewrote and leaves every other chunk\'s vector as it is. The page\'s spend cap (`embed.max_usd_per_page`) bounds the synopsis calls: when it is reached, the rest of the page keeps its title-tier vectors (`budget_limited`) and nothing more is spent. A chunk whose synopsis the model refuses is embedded at the title tier. Pages read whole are unchanged.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 50467fb8a4..cb11efdd7c 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -55,6 +55,7 @@ import {generatePerChunkSynopsis,SEGMENT_SYNOPSIS_LEAD_BYTES,segmentSynopsisWindows,+ SYNOPSIS_MAX_TOKENS,SYNOPSIS_PROMPT_VERSION,SYNOPSIS_DOC_MAX_CHARS,type GeneratePerChunkSynopsisResult,@@ -66,18 +67,17 @@ import type { ChunkInput, CRMode, Page } from './types.ts';import type { SourceRow } from './sources-ops.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 { digest, sha256 } 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 { installSegmentedVectors, listLiveEmbedSegments, listSegmentChunkRows, readSegmentedEmbedPage } from './page-body/segmented-embedding.ts';+import { planSegmentDerivations, segmentDerivationContextHash } from './page-body/derivations.ts';+import { SEGMENTED_CHUNKER_VERSION } from './page-body/segment-chunks.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@@ -485,22 +485,29 @@ 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 };+/** page_segment_derivations.pipeline_version of the synopsis pipeline (wave-b spec 8.6). */+export const SYNOPSIS_DERIVATION_VERSION = 1;/*** 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.+ * 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+ * (synopsisDocumentHash), so a chunk whose recorded input already matches keeps its vector. The pipeline's+ * page_segment_derivations rows (kind synopsis, one per occurrence, output = the window anchors) record each segment+ * done under a context hash over its entry state, the title, the lead's hash, the synopsis model, its output cap, the+ * segmented chunker version, the corpus generation and the write target: a rerun reads no chunk row of a settled+ * segment, 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`), the+ * segment `partial` and the windows already installed kept. A window whose synopsis is refused, empty or malformed+ * embeds at the title tier, which a synopsis page accepts (page_fallback; the segment is settled with the fallback in+ * its receipt, so it is not paid for again until its inputs change). Vectors install through installSegmentedVectors;+ * the page is stamped `per_chunk_synopsis` once every segment is settled.*/async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promise<ReembedPageResult> {const { engine } = args;@@ -532,34 +539,43 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promiconst 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]);+ const inputs = { title: page.title, lead_sha256: sha256(lead), synopsis_model: synopsisModel, synopsis_max_tokens: synopsisMaxTokens ?? SYNOPSIS_MAX_TOKENS,+ chunker_version: SEGMENTED_CHUNKER_VERSION, corpus_generation: corpusGeneration,+ embedding: { column: target.column.name, model: target.provenanceModel, dimensions: target.column.dimensions } };+ const segments = await listLiveEmbedSegments(engine, page.id);+ const live = segments.map(s => ({ occurrenceId: s.occurrenceId, sha256: s.sha256,+ contextHash: segmentDerivationContextHash('synopsis', { entryState: s.entryState, page: inputs }) }));+ const plan = planSegmentDerivations('synopsis', SYNOPSIS_DERIVATION_VERSION, live, await engine.readSegmentDerivations(page.id, { kind: 'synopsis' }));+ const derivation = (segment: typeof live[number], state: 'done' | 'partial', windows: unknown[], receipt: unknown) =>+ engine.upsertSegmentDerivations([{ pageId: page.id, kind: 'synopsis', occurrenceId: segment.occurrenceId, version: SYNOPSIS_DERIVATION_VERSION,+ segmentSha256: segment.sha256, contextHash: segment.contextHash, state, output: { windows }, receipt }]);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)) {+ for (const segment of plan.todo) {+ const anchors: Array<{ first_chunk: number; last_chunk: number; chunks: number; document_sha256: string; tier: EmbeddingTier }> = [];+ let segmentFallback: SynopsisFailureKind | null = null;+ for (const window of segmentSynopsisWindows(await listSegmentChunkRows(engine, page.id, segment.occurrenceId), lead)) {const provenance = { ...base, bodyHash: synopsisDocumentHash(window.document) };+ const anchor = { first_chunk: window.chunks[0]!.chunk_index, last_chunk: window.chunks.at(-1)!.chunk_index, chunks: window.chunks.length,+ document_sha256: provenance.bodyHash, tier: 'per_chunk_synopsis' as EmbeddingTier };const todo = window.chunks.filter(c => c.embedding_input_hash !== embeddingInputHash(provenance, 'per_chunk_synopsis', c));- if (todo.length === 0) continue;+ if (todo.length === 0) { anchors.push(anchor); 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' };+ if (decision.kind === 'refused') {+ await derivation(segment, 'partial', anchors, { reason: 'budget_limited', cap_usd: decision.capUsd, estimate_usd: decision.estimateUsd });+ 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));+ const inputTexts = 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 }) };+ return { kind: 'built' as const, tier, fallback: Array.isArray(synopsized) ? null : synopsized.cause, vectors: await embedBatch(inputTexts, { abortSignal: args.abortSignal }) };} catch (err) {return classifyEmbedError(err, err instanceof Error ? err.message : String(err));}@@ -570,18 +586,22 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promiif (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);+ const installed = await installSegmentedVectors(engine, page, target, todo.map((c, i) => ({ chunk_index: c.chunk_index, chunk_text: c.chunk_text,+ vector: built.vectors[i]!, hash: embeddingInputHash(built.tier === 'title' ? base : provenance, built.tier, c) })));if (installed < todo.length) return superseded;embedded += installed;+ if (built.fallback) segmentFallback ??= built.fallback;+ anchors.push({ ...anchor, tier: built.tier });}+ await derivation(segment, 'done', anchors, segmentFallback ? { fallback_kind: segmentFallback } : null);+ fallbackKind ??= segmentFallback;}+ await engine.retireSegmentDerivations(page.id, live.map(s => s.occurrenceId), { kind: 'synopsis' });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;+ const current = await readSegmentedEmbedPage(tx, { id: page.id });+ if (!current || current.title !== page.title || current.contextual_retrieval_mode !== page.contextual_retrieval_mode) return false;await tx.updatePageContextualRetrievalState(page.slug, page.source_id, 'per_chunk_synopsis', corpusGeneration);return true;});@@ -593,35 +613,6 @@ async function reembedSegmentedPage(args: ReembedPageArgs, initial: Page): Promireturn { 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 {diff --git a/src/core/page-body/segmented-embedding.ts b/src/core/page-body/segmented-embedding.tsindex 504545e53b..bf89ebe210 100644--- a/src/core/page-body/segmented-embedding.ts+++ b/src/core/page-body/segmented-embedding.ts@@ -3,13 +3,15 @@* (`readProjectionSnapshot` / `installPageEmbeddings`) reads the page body, its* fence overlay and every chunk of the page; a segmented page is embedded from* its stale chunk rows alone: keyset pages of live, vector-less rows with their- * text, the page title and the plain tier (the synopsis tier stays off for- * segmented pages, so no input depends on the rest of the body), metered by the+ * text, the page title and the plain tier (no input depends on the rest of the+ * body; per-chunk synopsis on a segmented page, whose input is the lead and one+ * window of the chunk's segment, is the contextual retrieval service's, spec+ * 8.6, and installs through installSegmentedVectors), metered by the* per-page budget and installed by chunk_index and exact text onto rows still* in the page's live body generation. It never reads a segment.*/import type { BrainEngine } from '../engine.ts';-import type { CRMode } from '../types.ts';+import type { ChunkInput, CRMode } from '../types.ts';import { jsonRowBatches } from '../batch-rows.ts';import { wrapChunkTextsForStoredMode } from '../embedding-context.ts';import { embeddingInputHash, plainEmbeddingTier } from '../embedding-input-hash.ts';@@ -124,12 +126,26 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb}const tier = plainEmbeddingTier(page.contextual_retrieval_mode);const provenance = embeddingInputContext(target, page.title, null, []);- const updates = chunks.map((chunk, i) => ({ chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text,- embedding: `[${Array.from(vectors[i]!).join(',')}]`, hash: embeddingInputHash(provenance, tier, chunk) }));+ return installSegmentedVectors(engine, page, target, chunks.map((chunk, i) => ({ chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text,+ vector: vectors[i]!, hash: embeddingInputHash(provenance, tier, chunk) })), opts.beforeInstall);+}++/** One vector to install on a segmented page: the row's chunk_index and exact text, and the recorded embedding input. */+export interface SegmentedVectorUpdate { chunk_index: number; chunk_text: string; vector: Float32Array; hash: string }++/**+ * Install vectors with their recorded inputs on the live rows of a segmented page with the same chunk_index and text,+ * under the page lock, while the page's slug, title and contextual mode and the write target (column, provenance+ * model) are those the inputs were built under; 0 when any moved. `beforeInstall` runs after the lock; throwing+ * installs nothing. Returns the rows that took a vector.+ */+export async function installSegmentedVectors(engine: BrainEngine, page: SegmentedEmbedPage, target: Awaited<ReturnType<typeof embeddingWriteTarget>>,+ vectors: readonly SegmentedVectorUpdate[], beforeInstall?: (tx: BrainEngine) => Promise<void>): Promise<number> {+ const updates = vectors.map(v => ({ chunk_index: v.chunk_index, chunk_text: v.chunk_text, embedding: `[${Array.from(v.vector).join(',')}]`, hash: v.hash }));const col = quoteIdentifier(target.column.name);return engine.transaction(async tx => {await tx.lockPageKeys([{ sourceId: page.source_id, slug: page.slug }]);- await opts.beforeInstall?.(tx);+ await beforeInstall?.(tx);const current = await readSegmentedEmbedPage(tx, { id: page.id });const now = await embeddingWriteTarget(tx);if (!current || current.slug !== page.slug || current.title !== page.title@@ -149,6 +165,29 @@ export async function embedSegmentedRows(engine: BrainEngine, page: SegmentedEmb});}+/** A live segment of a segmented page, newest first: its occurrence, text hash and entry state (manifest metadata only). */+export interface LiveEmbedSegment { occurrenceId: number; sha256: Uint8Array; entryState: unknown }++export async function listLiveEmbedSegments(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number): Promise<LiveEmbedSegment[]> {+ const rows = await engine.executeRaw<{ occurrence_id: number | string; sha256: Uint8Array; entry_state: unknown }>(+ `SELECT m.occurrence_id, m.sha256, m.entry_state FROM page_body_manifest m JOIN pages p ON p.id = m.page_id+ WHERE m.page_id = $1 AND m.staging_id IS NULL AND m.gen_from <= p.body_generation AND (m.gen_to IS NULL OR m.gen_to > p.body_generation)+ ORDER BY m.seq DESC`, [pageId]);+ return rows.map(row => ({ occurrenceId: Number(row.occurrence_id), sha256: new Uint8Array(row.sha256), entryState: row.entry_state }));+}++export interface SegmentChunkRow { chunk_index: number; chunk_text: string; chunk_source: NonNullable<ChunkInput['chunk_source']>; embedding_input_hash: string | null }++/** The live chunk rows of one segment of a segmented page in text order, with their recorded embedding inputs. */+export async function listSegmentChunkRows(engine: Pick<BrainEngine, 'executeRaw'>, pageId: number, occurrenceId: number): Promise<SegmentChunkRow[]> {+ const rows = await engine.executeRaw<SegmentChunkRow>(+ `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`, [pageId, occurrenceId]);+ return rows.map(row => ({ ...row, chunk_index: Number(row.chunk_index) }));+}+/*** Embed every vector-less live row of a segmented page (or only the rows of* `occurrenceIds`, the occurrences an append added; every live row withdiff --git a/test/e2e/synopsis-segment-hash-postgres.test.ts b/test/e2e/synopsis-segment-hash-postgres.test.tsnew file mode 100644index 0000000000..b9db15e4d9--- /dev/null+++ b/test/e2e/synopsis-segment-hash-postgres.test.ts@@ -0,0 +1,15 @@+/**+ * Contextual synopsis per segment, Postgres arm (wave-b spec 8.6, PR 4 lane 4c). Cases:+ * test/helpers/synopsis-segment-hash-cases.ts. PGLite arm: test/large-pages/synopsis-segment-hash.test.ts.+ */+import { afterAll, beforeAll, describe } from 'bun:test';+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';+import { defineSynopsisSegmentHashCases } from '../helpers/synopsis-segment-hash-cases.ts';+import { hasDatabase } from './helpers.ts';++(hasDatabase() ? describe : describe.skip)('synopsis segment hash [postgres]', () => {+ let brain: AppendBrain;+ beforeAll(async () => { brain = await openAppendBrain('postgres'); }, 120_000);+ afterAll(async () => { await brain.close(); }, 120_000);+ defineSynopsisSegmentHashCases({ getBrain: () => brain });+});diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.tsnew file mode 100644index 0000000000..bb9ef742c6--- /dev/null+++ b/test/helpers/synopsis-segment-hash-cases.ts@@ -0,0 +1,203 @@+/**+ * Contextual synopsis per segment (wave-b spec 8.6, PR 4 lane 4c), shared by the PGLite arm+ * (test/large-pages/synopsis-segment-hash.test.ts) and the Postgres arm (test/e2e/synopsis-segment-hash-postgres.test.ts).+ * The synopsis model is a fake with a call counter (the service's generateSynopsis seam) and the embedder is the brain's+ * fake; no provider is called.+ *+ * 1. Protects: under per_chunk_synopsis a segmented page leaves the title tier: every live chunk gets a synopsis vector+ * whose document is the title, the projected lead and one window of its own segment (within SYNOPSIS_DOC_MAX_CHARS),+ * one synopsis derivation row per live occurrence. A rerun calls nothing and reads no chunk row. An append (by a+ * remote writer) re-synopsizes only the chunks of its new segments: calls and segment reads equal those, and every+ * other chunk keeps its embedding_input_hash and vector. An exhausted per-page cap leaves the page on the title tier+ * with no synopsis call; with room, the same page takes the synopsis tier. A refused synopsis embeds its window at+ * the title tier and settles. An inline page keeps the synopsisBodyHash input.+ * 2. Fails when: a segmented page never leaves the title tier (the pre-lane skip), the synopsis input is hashed over every+ * chunk of the page (an append changes every chunk's input), a settled segment is read or paid for again, or a refused+ * reservation still calls the model.+ */+import { expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-retrieval-service.ts';+import { SYNOPSIS_DOC_MAX_CHARS, 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 { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';+import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';+import type { AppendBrain } from './append-brain.ts';++const WORDS = ['launch', 'pricing', 'roadmap', 'hiring', 'metrics', 'retention', 'design', 'latency', 'budget', 'customer'];+const paragraph = (d: number, k: number) =>+ [`day${d}`, `para${k}`, ...Array.from({ length: 98 }, (_, i) => WORDS[(d * 7 + k * 3 + i) % WORDS.length])].join(' ') + '.';+export const day = (d: number) => `## Day ${d}\n\n${[1, 2, 3, 4].map(k => paragraph(d, k)).join('\n\n')}\n\n`;+export const TITLE = 'Daily log';+export const LEAD = 'Opening note: this log tracks the acme-example 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 | null; embedding_input_hash: string | null; vector: string | null }++/** The service's segment chunk read (listSegmentChunkRows); counted to prove a settled segment is never read. */+const SEGMENT_CHUNK_READ = 'cc.occurrence_id = $2';++export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBrain }): void {+ const calls: GeneratePerChunkSynopsisArgs[] = [];+ let segmentReads = 0;+ let refuse: ((args: GeneratePerChunkSynopsisArgs) => boolean) | null = null;+ const generateSynopsis = async (args: GeneratePerChunkSynopsisArgs): Promise<GeneratePerChunkSynopsisResult> => {+ calls.push(args);+ if (refuse?.(args)) return { kind: 'refusal', detail: 'fixture refusal' };+ return { kind: 'success', synopsis: `Synopsis of chunk ${args.chunkIndex}.` };+ };+ const counting = (engine: BrainEngine): BrainEngine => new Proxy(engine, {+ get(target, prop) {+ const value = Reflect.get(target, prop, target);+ if (prop === 'executeRaw') return (sql: string, params?: unknown[]) => { if (sql.includes(SEGMENT_CHUNK_READ)) segmentReads++; return target.executeRaw(sql, params); };+ return typeof value === 'function' ? value.bind(target) : value;+ },+ });+ const reset = () => { calls.length = 0; segmentReads = 0; opts.getBrain().embedded.length = 0; };+ const run = (slug: string, globalMode: 'per_chunk_synopsis' | 'title' | 'none' = 'per_chunk_synopsis') =>+ reembedPageWithContextualRetrieval({ engine: counting(opts.getBrain().engine), pageSlug: slug, sourceId: 'default', globalMode, generateSynopsis, chunkConcurrency: 4 });+ const chunks = async (slug: string): Promise<ChunkRow[]> => (await opts.getBrain().engine.executeRaw<ChunkRow>(+ `SELECT c.chunk_index, c.chunk_text, c.chunk_source, c.occurrence_id, c.embedding_input_hash, c.embedding::text AS vector+ FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.source_id = 'default' AND p.slug = $1 AND ${chunkGenerationFilter('p', 'c')} ORDER BY c.chunk_index`, [slug]))+ .map(row => ({ ...row, chunk_index: Number(row.chunk_index), occurrence_id: row.occurrence_id === null ? null : Number(row.occurrence_id) }));+ const pageRow = async (slug: string) => (await opts.getBrain().engine.executeRaw<{ id: number; mode: string | null; generation: string | null; body_storage: string }>(+ "SELECT id, contextual_retrieval_mode AS mode, corpus_generation AS generation, body_storage FROM pages WHERE source_id = 'default' AND slug = $1", [slug]))+ .map(row => ({ ...row, id: Number(row.id) }))[0]!;+ const titleHash = async (c: ChunkRow) => embeddingInputHash(embeddingInputContext(await embeddingWriteTarget(opts.getBrain().engine), TITLE, null, []), 'title', c);+ const synopsisRows = async (pageId: number) => opts.getBrain().engine.readSegmentDerivations(pageId, { kind: 'synopsis' });+ const nonCode = (rows: ChunkRow[]) => rows.filter(c => c.chunk_source !== 'fenced_code');+ /** The cap is set high enough for a whole 2.3 MB page at the upper-bound estimate (uncached prompts at list price). */+ const roomyCap = () => opts.getBrain().engine.setConfig(PAGE_EMBED_CAP_KEY, '1000');++ test('append invalidation: a segmented page leaves the title tier, a rerun does no work, an append pays only for its new segments', async () => {+ const brain = opts.getBrain();+ await roomyCap();+ const slug = 'notes/synopsis-log';+ const { body, count } = days(2_300_000);+ await brain.seed(slug, page(body));+ const seeded = await pageRow(slug);+ expect(seeded.body_storage).toBe('segmented');+ const before = await chunks(slug);+ const occurrences = new Set(before.map(c => c.occurrence_id));+ expect(occurrences.size).toBeGreaterThan(1);++ reset();+ const first = await run(slug);+ expect(first).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: before.length });+ expect(calls.length).toBe(nonCode(before).length);+ expect(brain.embedded.length).toBe(before.length);+ expect(segmentReads).toBe(occurrences.size);+ 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(brain.embedded.every(text => text.includes('Synopsis of chunk'))).toBe(true);+ expect(await pageRow(slug)).toMatchObject({ mode: 'per_chunk_synopsis', generation: first.kind === 'success' ? first.corpus_generation : 'unset' });+ const done = await chunks(slug);+ expect(done.every(c => c.vector !== null)).toBe(true);+ for (const c of done) expect(c.embedding_input_hash).not.toBe(await titleHash(c));+ const rows = await synopsisRows(seeded.id);+ expect(rows.map(r => r.occurrenceId).sort()).toEqual([...occurrences].map(Number).sort());+ expect(rows.every(r => r.state === 'done')).toBe(true);++ reset();+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: 0 });+ expect({ calls: calls.length, embedded: brain.embedded.length, segmentReads }).toEqual({ calls: 0, embedded: 0, segmentReads: 0 });++ const appended = await brain.call('append_page', { slug, text: day(count + 1), request_id: randomUUID() }, { remote: true });+ expect(appended.isError).toBe(false);+ const after = await chunks(slug);+ const fresh = after.filter(c => !occurrences.has(c.occurrence_id));+ const freshOccurrences = new Set(fresh.map(c => c.occurrence_id));+ expect(fresh.length).toBeGreaterThan(0);+ expect(fresh.length).toBeLessThan(after.length / 2);+ const kept = new Map(done.map(c => [c.chunk_index, c]));+ for (const c of after.filter(row => occurrences.has(row.occurrence_id))) {+ expect(c.embedding_input_hash).toBe(kept.get(c.chunk_index)!.embedding_input_hash);+ expect(c.vector).toBe(kept.get(c.chunk_index)!.vector);+ }++ reset();+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: fresh.length });+ expect(calls.map(call => call.chunkIndex).sort((a, b) => a - b)).toEqual(nonCode(fresh).map(c => c.chunk_index));+ expect(segmentReads).toBe(freshOccurrences.size);+ expect(calls.some(call => call.documentText.includes(`## Day ${count + 1}`))).toBe(true);+ const settled = await synopsisRows(seeded.id);+ expect(new Set(settled.map(r => r.occurrenceId))).toEqual(new Set(after.map(c => c.occurrence_id!)));+ expect((await chunks(slug)).every(c => c.vector !== null)).toBe(true);+ }, 600_000);++ test('cap: an exhausted per-page cap keeps the title tier with no synopsis call; with room the page takes the synopsis tier', async () => {+ const brain = opts.getBrain();+ await roomyCap();+ const slug = 'notes/synopsis-capped';+ await brain.seed(slug, page(days(1_300_000).body));+ const { id } = await pageRow(slug);+ await brain.engine.executeRaw(`INSERT INTO page_embedding_budget (page_id, cap_usd, spent_usd) VALUES ($1, 1, 1)+ ON CONFLICT (page_id) DO UPDATE SET cap_usd = 1, spent_usd = 1`, [id]);+ const before = await pageRow(slug);+ reset();+ expect(await run(slug)).toEqual({ kind: 'skipped', reason: 'budget_limited' });+ expect({ calls: calls.length, embedded: brain.embedded.length }).toEqual({ calls: 0, embedded: 0 });+ expect(await pageRow(slug)).toEqual(before);+ expect((await chunks(slug)).some(c => c.vector !== null)).toBe(false);++ await brain.engine.executeRaw('UPDATE page_embedding_budget SET cap_usd = 1000 WHERE page_id = $1', [id]);+ reset();+ const all = await chunks(slug);+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: all.length });+ expect(calls.length).toBe(nonCode(all).length);+ expect((await pageRow(slug)).mode).toBe('per_chunk_synopsis');+ }, 300_000);++ test('a refused synopsis embeds its window at the title tier and settles; title and none stay with the segmented embedding path', async () => {+ const brain = opts.getBrain();+ await roomyCap();+ const slug = 'notes/synopsis-refused';+ await brain.seed(slug, page(days(1_300_000).body + '\nRefusal fixture.\n'));+ 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)]!;+ refuse = 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 {+ refuse = 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.vector !== null)).toBe(true);+ const rows = await synopsisRows((await pageRow(slug)).id);+ expect(rows.find(r => r.occurrenceId === refused.occurrence_id)).toMatchObject({ state: 'done', receipt: { fallback_kind: 'refusal' } });+ reset();+ expect(await run(slug)).toMatchObject({ kind: 'success', chunks_embedded: 0 });+ expect(calls.length).toBe(0);+ }, 300_000);++ test('an inline page keeps the synopsisBodyHash input', async () => {+ const brain = opts.getBrain();+ const slug = 'notes/synopsis-inline';+ await brain.seed(slug, page(days(40_000).body));+ expect((await pageRow(slug)).body_storage).toBe('inline');+ reset();+ const result = await run(slug);+ expect(result).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis' });+ const stored = await chunks(slug);+ const provenance = embeddingInputContext(await embeddingWriteTarget(brain.engine), TITLE, result.kind === 'success' ? result.corpus_generation : null, stored);+ for (const c of stored) expect(c.embedding_input_hash).toBe(embeddingInputHash(provenance, 'per_chunk_synopsis', c));+ expect(calls.every(call => call.documentText === stored.filter(c => c.chunk_source !== 'image_asset').map(c => c.chunk_text).join('\n\n'))).toBe(true);+ }, 300_000);+}diff --git a/test/large-pages/segmented-synopsis.test.ts b/test/large-pages/segmented-synopsis.test.tsdeleted file mode 100644index 2ba04f734a..0000000000--- a/test/large-pages/segmented-synopsis.test.ts+++ /dev/null@@ -1,187 +0,0 @@-/**- * 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/large-pages/synopsis-segment-hash.test.ts b/test/large-pages/synopsis-segment-hash.test.tsnew file mode 100644index 0000000000..3e49faed81--- /dev/null+++ b/test/large-pages/synopsis-segment-hash.test.ts@@ -0,0 +1,68 @@+/**+ * Contextual synopsis per segment, PGLite arm (wave-b spec 8.6, PR 4 lane 4c), plus the pure window packing and the+ * inline input-hash golden. Cases: test/helpers/synopsis-segment-hash-cases.ts. Postgres arm:+ * test/e2e/synopsis-segment-hash-postgres.test.ts.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { openAppendBrain, type AppendBrain } from '../helpers/append-brain.ts';+import { defineSynopsisSegmentHashCases } from '../helpers/synopsis-segment-hash-cases.ts';+import { acceptedEmbeddingInputHashes, embeddingInputHash, synopsisBodyHash } from '../../src/core/embedding-input-hash.ts';+import { SEGMENT_SYNOPSIS_WINDOW_BYTES, SYNOPSIS_DOC_MAX_CHARS, segmentSynopsisWindows } from '../../src/core/page-summary.ts';++let brain: AppendBrain;++beforeAll(async () => { brain = await openAppendBrain('pglite'); }, 120_000);+afterAll(async () => { await brain.close(); }, 120_000);++describe('synopsis segment hash [pglite]', () => {+ defineSynopsisSegmentHashCases({ getBrain: () => brain });+});++describe('inline synopsis input hash (golden)', () => {+ const chunks = [+ { chunk_text: 'Acme example kickoff notes.', chunk_source: 'compiled_truth' },+ { chunk_text: 'const x = 1;', chunk_source: 'fenced_code' },+ { chunk_text: 'diagram of the pipeline', chunk_source: 'image_asset' },+ { chunk_text: '2026-01-02 alice-example joined.', chunk_source: 'timeline' },+ ];+ const ctx = { column: 'embedding', model: 'openai:text-embedding-3-large', dimensions: 1536, title: 'Acme example notes', corpusGeneration: '0123456789abcdef', bodyHash: synopsisBodyHash(chunks) };++ test('the synopsisBodyHash-based input of a page read whole is byte for byte the pre-lane hash', () => {+ expect(ctx.bodyHash).toBe('7f24d78ef482a2ee487035dd1884bea7f9831fd9d14af23e4930ea5e9dd6fa49');+ expect(chunks.map(c => embeddingInputHash(ctx, 'per_chunk_synopsis', c))).toEqual([+ 'da28bbb1c4442a2a14e20b354faebea5866bf6cb8cb5dfca46dec70eba442244',+ 'c19d48403fee7292063b88db864ba4357b44b03865a98a5f9508d57dc8284cd3',+ '6b7641e37dd461f15fc48cdb29dc7b3d9e8cd270c145cb52e27a229cd89e3bb9',+ 'd95ed96ff2c4b63da1e20dfe1639fae72ccb597bb0afbf906214de21cfc25d3b',+ ]);+ expect(chunks.map(c => embeddingInputHash(ctx, 'title', c))).toEqual([+ '9a035be9c3732fa1184b906484e7d9863d10c644161c1ed925975b81cca4ebd4',+ 'fe291f01d54f51331864a6e28332a000d3a60abbb77c041844ef9640cb787701',+ 'a203118d6e7b65138f9814f024802ea3b64bf1b961a76eeb6aa42ff727d0ca89',+ 'fb81957f11ba923b11617aa6aa00269d130988bbd40d25da0b779c5f9594259a',+ ]);+ expect(acceptedEmbeddingInputHashes(ctx, 'per_chunk_synopsis', chunks[0]!)).toEqual([+ 'da28bbb1c4442a2a14e20b354faebea5866bf6cb8cb5dfca46dec70eba442244',+ '9a035be9c3732fa1184b906484e7d9863d10c644161c1ed925975b81cca4ebd4',+ ]);+ });+});++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]);+ expect(windows.length).toBeGreaterThan(2);+ 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(segmentSynopsisWindows(rows.slice(0, 3), '')[0]!.document).toBe(rows.slice(0, 3).map(r => r.chunk_text).join('\n\n'));+ });+});diff --git a/test/postgres-unit-arms.txt b/test/postgres-unit-arms.txtindex dd3c980bdc..9e84bd3168 100644--- a/test/postgres-unit-arms.txt+++ b/test/postgres-unit-arms.txt@@ -175,7 +175,6 @@ 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