Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(segmented synopsis): staging vector reuse windows chunks over the lead the write stores, so a lead edit carries nothing
garrytand510a3456cfe
diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.tsindex 525b074fab..0b2efa2653 100644--- a/src/core/import-chunk-reuse.ts+++ b/src/core/import-chunk-reuse.ts@@ -88,8 +88,10 @@ export async function reuseStoredChunkVectors(* unchanged chunk inside a rewritten tail keeps its vector and only new text* reaches the provider. Returns how many chunks got one.*/-export async function reuseSegmentChunkVectors(exec: BrainEngine, { pageId, retiredOccurrences, chunks, title, corpusGeneration, tier }: {- pageId: number; retiredOccurrences: readonly number[]; chunks: SegmentChunkInput[]; title: string; corpusGeneration: string | null; tier: 'title' | 'none' }): Promise<number> {+export async function reuseSegmentChunkVectors(exec: BrainEngine, { pageId, retiredOccurrences, chunks, title, corpusGeneration, tier, truthLead }: {+ pageId: number; retiredOccurrences: readonly number[]; chunks: SegmentChunkInput[]; title: string; corpusGeneration: string | null; tier: 'title' | 'none';+ /** The truth_lead the write stores (a synopsis window opens with it); omitted when the body is unchanged (the stored one). */+ truthLead?: string }): Promise<number> {if (retiredOccurrences.length === 0 || chunks.length === 0) return 0;const target = await embeddingWriteTarget(exec);const provenance = embeddingInputContext(target, title, corpusGeneration, []);@@ -107,7 +109,7 @@ export async function reuseSegmentChunkVectors(exec: BrainEngine, { pageId, reti// synopsis input (its segment window over the page lead) hashes to the stored row's recorded input.const synopsis = mode && modeRequiresSynopsis(mode as CRMode)? segmentSynopsisInputHashes(embeddingInputContext(target, title, rows[0]!.corpus_generation, []),- await segmentSynopsisLead(exec, { id: pageId, slug: rows[0]!.slug, source_id: rows[0]!.source_id }), chunks)+ await segmentSynopsisLead(exec, { id: pageId, slug: rows[0]!.slug, source_id: rows[0]!.source_id }, truthLead), chunks): null;const stored = rows.map(row => ({ chunk_text: row.chunk_text, chunk_source: row.chunk_source, embedding: parseEmbedding(row.embedding),token_count: row.token_count, model: row.model, embedding_input_hash: row.embedding_input_hash }))diff --git a/src/core/page-body/ingest.ts b/src/core/page-body/ingest.tsindex 81c93f6647..b16bd15a5e 100644--- a/src/core/page-body/ingest.ts+++ b/src/core/page-body/ingest.ts@@ -334,7 +334,7 @@ async function stageBody(engine: BrainEngine, input: SegmentedBodyInput, stagingconst chunkable = await occurrencesWithoutChunks(engine, input.live.id, expectedGeneration, rows);const chunks = await stageOccurrenceChunks(engine, { pageId: input.live.id, sourceId: input.sourceId, slug: input.slug, generation: newGeneration,occurrences: chunkable, title: input.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking,- retiredOccurrences: retireChunkOccurrences });+ retiredOccurrences: retireChunkOccurrences, truthLead: body.truth_lead });await faultPoint('segmented:chunks_staged', { sourceId: input.sourceId });const kept = new Set(rows.filter((_, i) => matched[i]).map(row => row.occurrenceId));retireChunkOccurrences.push(...chunkable.filter(row => kept.has(row.occurrenceId)).map(row => row.occurrenceId));@@ -377,6 +377,8 @@ export const segmentChunkWork = { batches: 0, chunks: 0 };export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId: number; sourceId: string; slug: string; generation: number;occurrences: readonly ManifestRowInput[]; title: string; frontmatter: JsonObject; flags: JsonObject; chunking: SegmentChunkingContext;retiredOccurrences: readonly number[];+ /** The truth_lead the write stores, for the vector reuse onto a page stored under per-chunk synopsis; omitted, the stored one. */+ truthLead?: string;/** Projection: each batch inserts under the page guard, after re-reading which occurrences still lack rows, so two projections never both chunk one;* a page whose generation moved past `generation` stops the projection before it inserts. */guarded?: boolean;@@ -420,7 +422,8 @@ export async function stageOccurrenceChunks(engine: BrainEngine, input: { pageId}}if (chunks.length && input.retiredOccurrences.length) await reuseSegmentChunkVectors(engine, { pageId: input.pageId,- retiredOccurrences: input.retiredOccurrences, chunks, title: input.title, corpusGeneration: input.chunking.corpusGeneration, tier: input.chunking.tier });+ retiredOccurrences: input.retiredOccurrences, chunks, title: input.title, corpusGeneration: input.chunking.corpusGeneration, tier: input.chunking.tier,+ truthLead: input.truthLead });segmentChunkWork.batches++;segmentChunkWork.chunks += chunks.length;if (input.hold) input.hold.push(...chunks);diff --git a/src/core/page-body/segment-synopsis.ts b/src/core/page-body/segment-synopsis.tsindex ea3a21412b..96f59e4913 100644--- a/src/core/page-body/segment-synopsis.ts+++ b/src/core/page-body/segment-synopsis.ts@@ -10,10 +10,13 @@ import { SEGMENT_SYNOPSIS_LEAD_BYTES, segmentSynopsisWindows } from '../page-sumimport { overlaidBoundedPrefix, pageLeadSource } from '../page-window/bounded-lead.ts';import { boundedProjectedPrefix } from '../page-window/document.ts';-/** The lead a segmented page's synopsis documents open with: its stored truth_lead after the withdrawal overlay, sanitized and cut. */-export async function segmentSynopsisLead(engine: BrainEngine, page: { id: number; slug: string; source_id: string }): Promise<string> {- const truthLead = await pageLeadSource(engine, { id: page.id, body_storage: 'segmented', compiled_truth: '' });- return boundedProjectedPrefix(await overlaidBoundedPrefix(engine, { slug: page.slug, source_id: page.source_id, compiled_truth: truthLead }), SEGMENT_SYNOPSIS_LEAD_BYTES);+/**+ * The lead a segmented page's synopsis documents open with: its truth_lead after the withdrawal overlay, sanitized and+ * cut. `truthLead` is the lead a write is about to store; omitted, the stored one.+ */+export async function segmentSynopsisLead(engine: BrainEngine, page: { id: number; slug: string; source_id: string }, truthLead?: string): Promise<string> {+ const lead = truthLead ?? await pageLeadSource(engine, { id: page.id, body_storage: 'segmented', compiled_truth: '' });+ return boundedProjectedPrefix(await overlaidBoundedPrefix(engine, { slug: page.slug, source_id: page.source_id, compiled_truth: lead }), SEGMENT_SYNOPSIS_LEAD_BYTES);}type SegmentChunk = { chunk_text: string; chunk_source?: string | null; occurrence_id?: number | null };diff --git a/src/core/page-body/splice.ts b/src/core/page-body/splice.tsindex 5f04260034..2f31fe92eb 100644--- a/src/core/page-body/splice.ts+++ b/src/core/page-body/splice.ts@@ -395,7 +395,8 @@ export async function spliceSegmentedBody(engine: BrainEngine, input: SegmentedS};const chunkable = await occurrencesWithoutChunks(engine, page.id, page.generation, changed);const chunks = await stageOccurrenceChunks(engine, { pageId: page.id, sourceId: input.sourceId, slug: input.slug, generation, occurrences: chunkable,- title: page.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking, retiredOccurrences: retireChunkOccurrences });+ title: page.title, frontmatter: input.frontmatter, flags: body.body_flags, chunking: input.chunking, retiredOccurrences: retireChunkOccurrences,+ truthLead: body.truth_lead });await faultPoint('segmented:chunks_staged', { sourceId: input.sourceId });const kept = new Set(out.filter(item => !fresh.includes(item)).map(item => item.row.occurrenceId));retireChunkOccurrences.push(...chunkable.filter(row => kept.has(row.occurrenceId)).map(row => row.occurrenceId));diff --git a/test/helpers/synopsis-segment-hash-cases.ts b/test/helpers/synopsis-segment-hash-cases.tsindex 30736ccbe1..f50da7e5af 100644--- a/test/helpers/synopsis-segment-hash-cases.ts+++ b/test/helpers/synopsis-segment-hash-cases.ts@@ -24,7 +24,7 @@ import { reembedPageWithContextualRetrieval } from '../../src/core/contextual-reimport { SYNOPSIS_DOC_MAX_CHARS, 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 { segmentSynopsisLead } from '../../src/core/page-body/segment-synopsis.ts';+import { segmentSynopsisInputHashes, segmentSynopsisLead } from '../../src/core/page-body/segment-synopsis.ts';import { PAGE_EMBED_CAP_KEY } from '../../src/core/page-embedding-budget.ts';import { chunkGenerationFilter } from '../../src/core/search/safe-chunks.ts';import { embedStalePages } from '../../src/core/embed-stale.ts';@@ -290,6 +290,38 @@ export function defineSynopsisSegmentHashCases(opts: { getBrain: () => AppendBraexpect(after.every(c => c.vector !== null)).toBe(true);}, 300_000);+ test('lead edit: a write that changes the page lead carries no synopsis vector onto its new rows (every window opens with the new lead)', async () => {+ const brain = opts.getBrain();+ await roomyCap();+ const slug = 'notes/synopsis-lead-edit';+ const { body } = days(1_300_000);+ await brain.seed(slug, page(body));+ const { id } = await pageRow(slug);+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis' });+ const before = await chunks(slug);+ const stampedGeneration = (await pageRow(slug)).generation;+ const oldLead = await segmentSynopsisLead(brain.engine, { id, slug, source_id: 'default' });+ const editedLead = LEAD.replace('launch.', 'pilots.');+ expect(Buffer.byteLength(editedLead)).toBe(Buffer.byteLength(LEAD));+ await brain.seed(slug, page(body).replace(LEAD, editedLead));+ const after = await chunks(slug);+ const occurrences = new Set(before.map(c => c.occurrence_id));+ const fresh = after.filter(c => !occurrences.has(c.occurrence_id));+ expect(fresh.length).toBeGreaterThan(1);+ const newLead = await segmentSynopsisLead(brain.engine, { id, slug, source_id: 'default' });+ expect(newLead).not.toBe(oldLead);+ // Under the stored (old) lead, every fresh chunk but the edited one's window would match a retired row's input.+ const retiredHashes = new Set(before.filter(c => !after.some(a => a.occurrence_id === c.occurrence_id)).map(c => c.embedding_input_hash));+ const base = embeddingInputContext(await embeddingWriteTarget(brain.engine), TITLE, stampedGeneration, []);+ const underOld = segmentSynopsisInputHashes(base, oldLead, fresh);+ expect(fresh.filter(c => retiredHashes.has(underOld.get(c) ?? null)).length).toBeGreaterThan(0);+ expect(fresh.filter(c => c.vector !== null)).toEqual([]);+ reset();+ expect(await run(slug)).toMatchObject({ kind: 'success', mode_applied: 'per_chunk_synopsis', chunks_embedded: after.length });+ expect(calls.length).toBe(nonCode(after).length);+ expect(calls.every(call => call.documentText.startsWith(editedLead))).toBe(true);+ }, 300_000);+test('an inline page keeps the synopsisBodyHash input', async () => {const brain = opts.getBrain();const slug = 'notes/synopsis-inline';