Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
wip(fact-keys): schema, publication, retirement, withdrawal discovery, embed-path key threading
garrytan7a1803f70460
diff --git a/src/core/contextual-retrieval-service.ts b/src/core/contextual-retrieval-service.tsindex 0162bc6fe3..e982d953f8 100644--- a/src/core/contextual-retrieval-service.ts+++ b/src/core/contextual-retrieval-service.ts@@ -500,10 +500,9 @@ async function tryBuildPhase1(opts: {// the title tier wants slightly more context — but per D2 the// balanced default is title-only without summary. Keep it pure for// now; the title block alone is what 'balanced' ships.- const prefix = buildContextualPrefix(title, null);const wrappedTexts = chunks.map((c) =>modeRequiresWrapper(attemptMode)- ? wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source)+ ? wrapChunkForEmbedding(c.chunk_text, buildContextualPrefix(title, null, c.fact_keys), c.chunk_source): c.chunk_text,);diff --git a/src/core/embed-stale.ts b/src/core/embed-stale.tsindex 02b2b1ee87..e46d9857e9 100644--- a/src/core/embed-stale.ts+++ b/src/core/embed-stale.ts@@ -49,7 +49,7 @@ import { AbortError } from './abort-check.ts';export function carryChunkMetadata(loaded: Pick<Partial<Chunk>,'modality' | 'language' | 'symbol_name' | 'symbol_type' | 'start_line'- | 'end_line' | 'parent_symbol_path' | 'doc_comment' | 'symbol_name_qualified'>,+ | 'end_line' | 'parent_symbol_path' | 'doc_comment' | 'symbol_name_qualified' | 'fact_keys'>,base: ChunkInput,): ChunkInput {return {@@ -63,6 +63,7 @@ export function carryChunkMetadata(parent_symbol_path: loaded.parent_symbol_path ?? undefined,doc_comment: loaded.doc_comment ?? undefined,symbol_name_qualified: loaded.symbol_name_qualified ?? undefined,+ fact_keys: loaded.fact_keys,};}diff --git a/src/core/embedding-context.ts b/src/core/embedding-context.tsindex c8b14c94b3..7c2d84fdde 100644--- a/src/core/embedding-context.ts+++ b/src/core/embedding-context.ts@@ -42,9 +42,11 @@ const SUMMARY_HARD_CAP_CHARS = 300;export function buildContextualPrefix(title: string | null | undefined,synopsis: string | null | undefined,+ factKeys?: string | null,): string | null {const safeTitle = sanitizeTitle(title ?? '');const safeSynopsis = sanitizeSynopsis(synopsis ?? '');+ if (factKeys && !safeSynopsis) return `<context>${safeTitle}\nFacts: ${factKeys}\n</context>\n`;if (!safeTitle && !safeSynopsis) {return null;@@ -208,12 +210,11 @@ export function wrapChunkTextsForStoredMode(| { title?: string | null; contextual_retrieval_mode?: CRMode | null }| null| undefined,- chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null }>,+ chunks: ReadonlyArray<{ chunk_text: string; chunk_source?: string | null; fact_keys?: string | null }>,): string[] {const mode = page?.contextual_retrieval_mode;if (mode == null || !modeRequiresWrapper(mode)) {return chunks.map((c) => c.chunk_text);}- const prefix = buildContextualPrefix(page?.title ?? '', null);- return chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, prefix, c.chunk_source));+ return chunks.map((c) => wrapChunkForEmbedding(c.chunk_text, buildContextualPrefix(page?.title ?? '', null, c.fact_keys), c.chunk_source));}diff --git a/src/core/embedding-input-hash.ts b/src/core/embedding-input-hash.tsindex 6b8e5ed54e..337f89e88a 100644--- a/src/core/embedding-input-hash.ts+++ b/src/core/embedding-input-hash.ts@@ -4,7 +4,7 @@* `content_chunks.embedding_input_hash` is written in the same statement as the* vector. It digests the vector column, model and dimensions, the wrapping tier* 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+ * `none` and fenced code, the title prefix (with the chunk's fact keys, v209) 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@@ -28,7 +28,7 @@ export interface EmbeddingInputContext {bodyHash: string;}-type HashedChunk = { chunk_text: string; chunk_source?: string | null };+type HashedChunk = { chunk_text: string; chunk_source?: string | null; fact_keys?: string | null };/** The document a synopsis is generated from: every non-image chunk, in order. */export function synopsisBodyHash(chunks: ReadonlyArray<HashedChunk>): string {@@ -48,7 +48,7 @@ export function isContextualMode(mode: string | null | undefined): boolean {export function embeddingInputHash(ctx: EmbeddingInputContext, tier: EmbeddingTier, chunk: HashedChunk): string {const raw = tier === 'none' || chunk.chunk_source === 'fenced_code';const input = raw ? chunk.chunk_text- : tier === 'title' ? wrapChunkForEmbedding(chunk.chunk_text, buildContextualPrefix(ctx.title, null), chunk.chunk_source)+ : tier === 'title' ? wrapChunkForEmbedding(chunk.chunk_text, buildContextualPrefix(ctx.title, null, chunk.fact_keys), chunk.chunk_source): digest([ctx.title, ctx.bodyHash, chunk.chunk_text]);return digest(['embedding-input-v1', ctx.column, ctx.model, ctx.dimensions, tier,tier === 'per_chunk_synopsis' ? ctx.corpusGeneration : null, sha256(input)]);diff --git a/src/core/engine-sql/chunks.ts b/src/core/engine-sql/chunks.tsindex 3041d7ea8f..97b7c3d4ce 100644--- a/src/core/engine-sql/chunks.ts+++ b/src/core/engine-sql/chunks.ts@@ -157,7 +157,7 @@ export async function upsertChunksOnce(// #4246: embedded_text_hash records md5(chunk_text) AT EMBED TIME so a// later text rewrite that keeps the vector is detectable as content// drift (invalidateContentDriftEmbeddings). NULL when no embedding lands.- const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;+ const cols = `(page_id, chunk_index, chunk_text, chunk_source, ${writeColId}, model, token_count, embedded_at, embedded_text_hash, embedding_input_hash, fact_keys, language, symbol_name, symbol_type, start_line, end_line, parent_symbol_path, doc_comment, symbol_name_qualified, modality, embedding_image)`;let resolvedModel: string | null = null;try {// Keep the gateway lazy so module-load failure remains inside this soft@@ -193,6 +193,7 @@ export async function upsertChunksOnce(token_count: chunk.token_count || null,// #5553: embedding-input provenance travels only with the vector it describes.embedding_input_hash: embedding ? chunk.embedding_input_hash ?? null : null,+ fact_keys: chunk.fact_keys ?? null,language: chunk.language || null,symbol_name: chunk.symbol_name || null,symbol_type: chunk.symbol_type || null,@@ -244,16 +245,16 @@ export async function upsertChunksOnce(SELECT ${pageId}::int, c.chunk_index, c.chunk_text, c.chunk_source, c.embedding${trustedSql(writeCast)}, c.model, c.token_count,CASE WHEN c.embedding IS NULL THEN NULL ELSE now() END,CASE WHEN c.embedding IS NULL THEN NULL ELSE md5(c.chunk_text) END,- c.embedding_input_hash, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,+ c.embedding_input_hash, c.fact_keys, c.language, c.symbol_name, c.symbol_type, c.start_line, c.end_line,c.parent_symbol_path, c.doc_comment, c.symbol_name_qualified, c.modality, c.embedding_image::vectorFROM jsonb_to_recordset(${JSON.stringify(incoming)}::text::jsonb) AS c(chunk_index int, chunk_text text, chunk_source text,- embedding text, model text, token_count int, embedding_input_hash text, language text, symbol_name text, symbol_type text,+ embedding text, model text, token_count int, embedding_input_hash text, fact_keys text, language text, symbol_name text, symbol_type text,start_line int, end_line int, parent_symbol_path text[], doc_comment text, symbol_name_qualified text, modality text, embedding_image text)ON CONFLICT (page_id, chunk_index) DO UPDATE SETchunk_text = EXCLUDED.chunk_text,chunk_source = EXCLUDED.chunk_source,${col} = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.${col}+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.${col}WHEN content_chunks.${col} IS NULL THEN EXCLUDED.${col}WHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -261,7 +262,7 @@ export async function upsertChunksOnce(ELSE content_chunks.${col}END,model = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.model+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.modelWHEN content_chunks.${col} IS NULL THEN EXCLUDED.modelWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -270,7 +271,7 @@ export async function upsertChunksOnce(END,token_count = EXCLUDED.token_count,embedded_at = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text AND EXCLUDED.${col} IS NULL THEN NULL+ WHEN (EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys) AND EXCLUDED.${col} IS NULL THEN NULLWHEN content_chunks.${col} IS NULL AND EXCLUDED.${col} IS NOT NULL THEN EXCLUDED.embedded_atWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -278,7 +279,7 @@ export async function upsertChunksOnce(ELSE content_chunks.embedded_atEND,embedded_text_hash = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedded_text_hash+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.embedded_text_hashWHEN content_chunks.${col} IS NULL THEN EXCLUDED.embedded_text_hashWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -286,7 +287,7 @@ export async function upsertChunksOnce(ELSE content_chunks.embedded_text_hashEND,embedding_input_hash = CASE- WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.embedding_input_hash+ WHEN EXCLUDED.chunk_text != content_chunks.chunk_text OR EXCLUDED.fact_keys IS DISTINCT FROM content_chunks.fact_keys THEN EXCLUDED.embedding_input_hashWHEN content_chunks.${col} IS NULL THEN EXCLUDED.embedding_input_hashWHEN EXCLUDED.embedded_at IS NOT NULLAND (content_chunks.embedded_at IS NULL OR EXCLUDED.embedded_at > content_chunks.embedded_at)@@ -301,6 +302,7 @@ export async function upsertChunksOnce(parent_symbol_path = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.parent_symbol_path ELSE COALESCE(EXCLUDED.parent_symbol_path, content_chunks.parent_symbol_path) END,doc_comment = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.doc_comment ELSE COALESCE(EXCLUDED.doc_comment, content_chunks.doc_comment) END,symbol_name_qualified = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name_qualified ELSE COALESCE(EXCLUDED.symbol_name_qualified, content_chunks.symbol_name_qualified) END,+ fact_keys = EXCLUDED.fact_keys,modality = EXCLUDED.modality,embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`);await exec.query(text, params);@@ -332,7 +334,7 @@ export async function getChunks(SELECT cc.id, cc.page_id, cc.chunk_index, cc.chunk_text, cc.chunk_source,cc.model, cc.token_count, cc.embedded_at, cc.language,cc.symbol_name, cc.symbol_type, cc.start_line, cc.end_line,- cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality,+ cc.parent_symbol_path, cc.doc_comment, cc.symbol_name_qualified, cc.modality, cc.fact_keys,(cc.${colId} IS NULL) AS embedding_is_null${embedCol}FROM content_chunks ccdiff --git a/src/core/fact-keys.ts b/src/core/fact-keys.tsindex bc728cd1ea..abfdef6de7 100644--- a/src/core/fact-keys.ts+++ b/src/core/fact-keys.ts@@ -12,6 +12,8 @@* embedding input. The stored `chunk_text` is never changed.*/+import { buildContextualPrefix, wrapChunkForEmbedding } from './embedding-context.ts';+export type FactKeyAssignment = 'chunk' | 'page';/** Maximum fact-key characters attached to one chunk. */@@ -81,7 +83,5 @@ export function assignFactKeys(* title-wrapped (or raw, without a title) input unchanged.*/export function factKeyedEmbeddingInput(chunkText: string, title: string | null, factKeys: string | null): string {- const safeTitle = (title ?? '').replace(/<\/?context>/gi, '').replace(/\s+/g, ' ').trim().slice(0, 300);- if (!factKeys) return safeTitle ? `<context>${safeTitle}\n</context>\n${chunkText}` : chunkText;- return `<context>${safeTitle}\nFacts: ${factKeys}\n</context>\n${chunkText}`;+ return wrapChunkForEmbedding(chunkText, buildContextualPrefix(title, null, factKeys), null);}diff --git a/src/core/facts/backstop.ts b/src/core/facts/backstop.tsindex 218d479d57..046147348b 100644--- a/src/core/facts/backstop.ts+++ b/src/core/facts/backstop.ts@@ -136,6 +136,8 @@ export interface FactsBackstopCtx {sourceSlug?: string;/** #5888: when the source turn happened, for the capture-lane dedup window (default: now). */turnAt?: Date;+ /** v209 fact keys: the page revision this extraction reads (docs/designs/FACT_KEYS.md); null publishes no keys. */+ factKeys?: import('./fact-keys-publish.ts').FactKeysBinding | null;}/** Discriminated return shape based on FactsBackstopCtx.mode. */@@ -299,6 +301,8 @@ export async function runFactsBackstop(? { mode: 'queue', enqueued: false, queueDepth: 0, skipped }: { mode: 'inline', inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], skipped };}+ const { bindFactKeysSnapshot } = await import('./fact-keys-publish.ts');+ ctx = { ...ctx, factKeys: await bindFactKeysSnapshot(ctx.engine, ctx.sourceId, parsedPage.slug, parsedPage.compiled_truth).catch(() => null) };const { managedPersistenceEnabled } = await import('../persistence/ownership.ts');if (await managedPersistenceEnabled(ctx.engine)) {if (mode !== 'inline') {@@ -656,6 +660,10 @@ async function runPipelineBodyInner(// facts.default_visibility (fail-closed to 'private').const { resolveDefaultVisibility } = await import('./visibility.ts');const visibility = ctx.visibility ?? (await resolveDefaultVisibility(ctx.engine));+ if (ctx.factKeys && input.pageSlug === ctx.factKeys.slug && input.turnText === ctx.factKeys.text) {+ const { publishExtractedFactKeys } = await import('./fact-keys-publish.ts');+ await publishExtractedFactKeys(ctx.engine, ctx.factKeys, outcome.facts, visibility, resolveEntitySlugWithSource, abortSignal);+ }// #5888: one exact-duplicate check for the capture lanes, before either writer.const { facts, dropped } = await dedupCapturedFacts(ctx, await inferMissingSubjects(ctx, outcome.facts, visibility, input.pageSlug, managed), visibility, resolveEntitySlugWithSource);if (managed) return withCaptureDrops(dropped, facts.length || !dropped.length ? await publishManagedFacts(ctx.engine, managed, ctx, facts, visibility, input.pageSlug) : null);diff --git a/src/core/facts/fact-keys-publish.ts b/src/core/facts/fact-keys-publish.tsnew file mode 100644index 0000000000..d63444206d--- /dev/null+++ b/src/core/facts/fact-keys-publish.ts@@ -0,0 +1,223 @@+/**+ * Fact keys in chunk embeddings — publication (docs/designs/FACT_KEYS.md).+ *+ * Invariant: every searchable vector was built from the page's current key+ * rows. Keys are added or replaced only by prepare-then-swap: the changed+ * chunks are embedded with their new keys first, then the occurrence rows,+ * the chunk key text and the vectors change together in one guarded+ * transaction. Any failed check writes nothing, so the page keeps its previous+ * keys and vectors.+ *+ * Scope: pages embedded under the `title` tier (the `balanced` default).+ * Pages with protected fences, `embed_skip`, or another tier get no keys.+ * Visibility fails closed: a private fact never keys a world-visible page.+ */+import type { BrainEngine } from '../engine.ts';+import type { ChunkInput } from '../types.ts';+import { assignFactKeys } from '../fact-keys.ts';+import { wrapChunkTextsForStoredMode } from '../embedding-context.ts';+import { currentEmbeddingSignature, embedBatch } from '../embedding.ts';+import { installPageEmbeddings, readProjectionSnapshot, type ProjectionSnapshot } from '../page-state/projections.ts';+import { declarePersistenceProtocol } from '../persistence/protocol.ts';+import { privatePagesFilterFragment } from '../search/private-visibility.ts';+import { quoteIdentifier } from '../search/embedding-column.ts';+import { FACTS_FENCE_BEGIN } from '../facts-fence.ts';+import { TAKES_FENCE_BEGIN } from '../takes-fence.ts';++export const FACT_KEYS_CONFIG_KEY = 'search.fact_keys';+export const FACT_KEYS_EXTRACTOR_VERSION = 'facts-extractor-v1';++export interface FactKeysBinding {+ sourceId: string;+ slug: string;+ pageId: number;+ revision: string;+ sourceIncarnation: string;+ text: string;+}++export interface FactKeyItem {+ text: string;+ /** Resolved entity slug the fact is about, or '*' when unresolved. */+ subject: string;+ visibility: 'private' | 'world';+}++export type FactKeysSkipReason = 'disabled' | 'superseded' | 'protected' | 'not_title_mode' | 'embed_skip'+ | 'embedding_unconfigured' | 'embed_failed' | 'withdrawal_changed';++export type FactKeysPublishResult =+ | { published: true; items: number; chunks_rekeyed: number }+ | { published: false; reason: FactKeysSkipReason; detail?: string };++type EmbedFn = (texts: string[], opts?: { abortSignal?: AbortSignal }) => Promise<Float32Array[]>;++export async function factKeysEnabled(engine: Pick<BrainEngine, 'getConfig'>): Promise<boolean> {+ const value = (await engine.getConfig(FACT_KEYS_CONFIG_KEY))?.trim().toLowerCase();+ return value === 'on' || value === 'true' || value === '1';+}++/**+ * Binds key publication to the exact text the extractor reads. Null when the+ * feature is off or the stored page no longer holds `text`; extraction then+ * proceeds as before and publishes no keys.+ */+export async function bindFactKeysSnapshot(engine: BrainEngine, sourceId: string, slug: string | undefined, text: string): Promise<FactKeysBinding | null> {+ if (!slug || !await factKeysEnabled(engine)) return null;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot || snapshot.page.deleted_at || snapshot.page.compiled_truth !== text) return null;+ return { sourceId, slug, pageId: snapshot.page.id, revision: snapshot.revision, sourceIncarnation: snapshot.sourceIncarnation, text };+}++function hasProtectedFence(body: string): boolean {+ return body.includes(FACTS_FENCE_BEGIN) || body.includes(TAKES_FENCE_BEGIN);+}++async function pageIsWorldVisible(engine: BrainEngine, pageId: number): Promise<boolean> {+ const [row] = await engine.executeRaw<{ world: boolean }>(`SELECT (${privatePagesFilterFragment('p')}) AS world FROM pages p WHERE p.id=$1`, [pageId]);+ return row?.world === true;+}++/** Items that may key this page: not withdrawn, and never a private fact on a world page. */+async function admissibleItems(engine: BrainEngine, sourceId: string, pageId: number, items: readonly FactKeyItem[]): Promise<FactKeyItem[]> {+ if (!items.length) return [];+ const world = await pageIsWorldVisible(engine, pageId);+ const visible = items.filter(item => !world || item.visibility === 'world');+ if (!visible.length) return [];+ const withdrawn = await engine.executeRaw<{ i: number }>(`SELECT DISTINCT k.i FROM jsonb_to_recordset($2::text::jsonb) k(i int,text text,subject text,visibility text)+ JOIN fact_withdrawals w ON w.source_id=$1 AND w.visibility=k.visibility+ AND w.fact_hash IN (gbrain_fact_fingerprint(k.text),gbrain_fact_fingerprint_v1(k.text))+ AND (w.subject='*' OR k.subject='*' OR w.subject=k.subject)`,+ [sourceId, JSON.stringify(visible.map((item, i) => ({ i, ...item })))]);+ const drop = new Set(withdrawn.map(row => Number(row.i)));+ return visible.filter((_, i) => !drop.has(i));+}++async function vectorColumns(engine: BrainEngine): Promise<string[]> {+ const rows = await engine.executeRaw<{ column_name: string }>(`SELECT column_name FROM information_schema.columns+ WHERE table_name='content_chunks' AND udt_name IN ('vector','halfvec') AND column_name<>'embedding_image'`);+ return rows.map(row => row.column_name);+}++function sameInventory(a: ProjectionSnapshot['chunks'], b: ProjectionSnapshot['chunks']): boolean {+ return a.length === b.length && a.every((chunk, i) => chunk.id === b[i].id && chunk.chunk_index === b[i].chunk_index+ && chunk.chunk_text === b[i].chunk_text && (chunk.fact_keys ?? null) === (b[i].fact_keys ?? null));+}++/**+ * Publish occurrence keys for one bound page revision (`items` empty clears+ * them). `force` publishes even when the feature is off; the disable sweep+ * uses it with no items to strip keys.+ */+export async function publishPageFactKeys(engine: BrainEngine, binding: FactKeysBinding, rawItems: readonly FactKeyItem[],+ opts: { embed?: EmbedFn; force?: boolean; abortSignal?: AbortSignal } = {}): Promise<FactKeysPublishResult> {+ const clearing = rawItems.length === 0;+ if (!opts.force && !await factKeysEnabled(engine)) return { published: false, reason: 'disabled' };+ const prepared = await readProjectionSnapshot(engine, binding.slug, binding.sourceId, { requireLiveSource: true });+ const page = prepared?.snapshot.page;+ if (!prepared || !page || prepared.snapshot.revision !== binding.revision || page.id !== binding.pageId+ || prepared.snapshot.sourceIncarnation !== binding.sourceIncarnation || page.compiled_truth !== binding.text) {+ return { published: false, reason: 'superseded' };+ }+ if (!clearing) {+ if (Object.hasOwn(page.frontmatter ?? {}, 'embed_skip')) return { published: false, reason: 'embed_skip' };+ if (page.contextual_retrieval_mode !== 'title') return { published: false, reason: 'not_title_mode' };+ if (hasProtectedFence(page.compiled_truth) || hasProtectedFence(page.timeline ?? '')) return { published: false, reason: 'protected' };+ }+ const items = await admissibleItems(engine, binding.sourceId, page.id, rawItems);+ const keys = items.length ? assignFactKeys(items.map(item => item.text), prepared.chunks, 'chunk') : prepared.chunks.map(() => null);+ const changed = prepared.chunks.map((chunk, i) => ({ chunk, keys: keys[i] })).filter(({ chunk, keys: next }) => next !== (chunk.fact_keys ?? null));++ const signature = currentEmbeddingSignature();+ let vectors: Float32Array[] = [];+ if (changed.length && signature) {+ try {+ vectors = await (opts.embed ?? embedBatch)(+ wrapChunkTextsForStoredMode(page, changed.map(({ chunk, keys: next }) => ({ ...chunk, fact_keys: next }))),+ opts.abortSignal ? { abortSignal: opts.abortSignal } : {});+ } catch (error) {+ return { published: false, reason: 'embed_failed', detail: error instanceof Error ? error.message : String(error) };+ }+ if (vectors.length !== changed.length || vectors.some(v => !v?.length)) return { published: false, reason: 'embed_failed', detail: 'incomplete embedding batch' };+ } else if (changed.length && !clearing) {+ return { published: false, reason: 'embedding_unconfigured' };+ }++ class Abort extends Error { constructor(readonly reason: FactKeysSkipReason) { super(reason); } }+ try {+ await engine.transaction(async tx => {+ await declarePersistenceProtocol(tx as never);+ await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR SHARE', [binding.sourceId]);+ await tx.lockPageKeys([{ sourceId: binding.sourceId, slug: binding.slug }]);+ const current = await tx.readPageSnapshot(binding.slug, { sourceId: binding.sourceId });+ if (!current || current.page.deleted_at || current.revision !== binding.revision || current.page.id !== binding.pageId+ || current.sourceIncarnation !== binding.sourceIncarnation || current.page.compiled_truth !== binding.text+ || current.page.text_projection_revision !== current.revision) throw new Abort('superseded');+ if (!sameInventory(await tx.getChunks(binding.slug, { sourceId: binding.sourceId, includeUnsealed: true }), prepared.chunks)) throw new Abort('superseded');+ if (!opts.force && !await factKeysEnabled(tx)) throw new Abort('disabled');+ const recheck = await admissibleItems(tx, binding.sourceId, page.id, rawItems);+ if (recheck.length !== items.length || recheck.some((item, i) => item !== items[i])) throw new Abort('withdrawal_changed');+ await tx.executeRaw('DELETE FROM page_fact_keys WHERE page_id=$1', [page.id]);+ if (items.length) {+ await tx.executeRaw(`INSERT INTO page_fact_keys (page_id,source_id,page_revision,ordinal,item_text,item_fingerprint,subject,visibility,extractor_version)+ SELECT $1,$2,$3,k.ordinal,k.text,gbrain_fact_fingerprint(k.text),k.subject,k.visibility,$4+ FROM jsonb_to_recordset($5::text::jsonb) k(ordinal int,text text,subject text,visibility text)`,+ [page.id, binding.sourceId, binding.revision, FACT_KEYS_EXTRACTOR_VERSION,+ JSON.stringify(items.map((item, ordinal) => ({ ordinal, text: item.text, subject: item.subject, visibility: item.visibility })))]);+ }+ if (!changed.length) return;+ const ids = changed.map(({ chunk }) => chunk.id);+ await tx.executeRaw(`UPDATE content_chunks c SET fact_keys=k.keys FROM jsonb_to_recordset($2::text::jsonb) k(id int,keys text)+ WHERE c.page_id=$1 AND c.id=k.id`, [page.id, JSON.stringify(changed.map(({ chunk, keys: next }) => ({ id: chunk.id, keys: next })))]);+ const others = (await vectorColumns(tx)).filter(name => name !== prepared.embeddingColumn.name);+ if (others.length) {+ await tx.executeRaw(`UPDATE content_chunks SET ${others.map(name => `${quoteIdentifier(name)}=NULL`).join(',')} WHERE page_id=$1 AND id=ANY($2::int[])`, [page.id, ids]);+ }+ if (!vectors.length) {+ await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(prepared.embeddingColumn.name)}=NULL,embedded_at=NULL,+ embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [page.id, ids]);+ return;+ }+ const rekeyed: ProjectionSnapshot = { ...prepared, chunks: prepared.chunks.map((chunk, i) => ({ ...chunk, fact_keys: keys[i] })) };+ const installed = await installPageEmbeddings(tx, rekeyed, changed.map(({ chunk, keys: next }, i): ChunkInput => ({+ chunk_index: chunk.chunk_index, chunk_text: chunk.chunk_text, chunk_source: chunk.chunk_source,+ embedding: vectors[i], model: prepared.embeddingModel ?? undefined, fact_keys: next,+ })));+ if (!installed) throw new Abort('superseded');+ });+ } catch (error) {+ if (error instanceof Abort) return { published: false, reason: error.reason };+ throw error;+ }+ return { published: true, items: items.length, chunks_rekeyed: changed.length };+}++/** Remove a page's keys (prepare-then-swap with no items), whatever the setting. */+export async function clearPageFactKeys(engine: BrainEngine, sourceId: string, slug: string, opts: { embed?: EmbedFn } = {}): Promise<FactKeysPublishResult> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot || snapshot.page.deleted_at) return { published: false, reason: 'superseded' };+ return publishPageFactKeys(engine, { sourceId, slug, pageId: snapshot.page.id, revision: snapshot.revision,+ sourceIncarnation: snapshot.sourceIncarnation, text: snapshot.page.compiled_truth }, [], { ...opts, force: true });+}++/**+ * The facts backstop's hook: occurrence keys from the extractor's own output+ * for the bound revision, captured before notability filtering and dedup.+ * Never throws; a failed publication leaves the previous keys and vectors.+ */+export async function publishExtractedFactKeys(engine: BrainEngine, binding: FactKeysBinding,+ facts: ReadonlyArray<{ fact?: unknown; entity_slug?: string | null }>, visibility: 'private' | 'world',+ resolve: (engine: BrainEngine, sourceId: string, ref: string) => Promise<{ slug: string; source: string } | null>,+ abortSignal?: AbortSignal): Promise<FactKeysPublishResult> {+ try {+ const items: FactKeyItem[] = [];+ for (const f of facts) {+ if (typeof f.fact !== 'string' || !f.fact.trim()) continue;+ const resolved = f.entity_slug ? await resolve(engine, binding.sourceId, f.entity_slug) : null;+ items.push({ text: f.fact, subject: resolved && resolved.source !== 'fallback_slugify' ? resolved.slug : '*', visibility });+ }+ return await publishPageFactKeys(engine, binding, items, { abortSignal });+ } catch (error) {+ return { published: false, reason: 'superseded', detail: error instanceof Error ? error.message : String(error) };+ }+}diff --git a/src/core/facts/fact-keys-retire.ts b/src/core/facts/fact-keys-retire.tsnew file mode 100644index 0000000000..5e7800af94--- /dev/null+++ b/src/core/facts/fact-keys-retire.ts@@ -0,0 +1,12 @@+import type { BrainEngine } from '../engine.ts';++/**+ * Rows for any revision other than the page's current one are never used+ * again. Every path that seals a new chunk set calls this in its transaction;+ * the replacement chunks carry no keys, and upsertChunks drops any vector whose+ * key text changed.+ */+export async function retireStaleFactKeys(tx: Pick<BrainEngine, 'executeRaw'>, sourceId: string, slug: string): Promise<void> {+ await tx.executeRaw(`DELETE FROM page_fact_keys k USING pages p WHERE p.id=k.page_id AND p.source_id=$1 AND p.slug=$2+ AND k.page_revision IS DISTINCT FROM p.knowledge_revision::text`, [sourceId, slug]);+}diff --git a/src/core/facts/withdrawal-discovery.ts b/src/core/facts/withdrawal-discovery.tsindex 3be3d74686..60014c62d2 100644--- a/src/core/facts/withdrawal-discovery.ts+++ b/src/core/facts/withdrawal-discovery.ts@@ -65,6 +65,15 @@ export async function discoverWithdrawalTargets(engine: BrainEngine, sourceId: sAND (k.subject='*' OR f.entity_slug=k.subject)JOIN pages p ON p.source_id=f.source_id AND p.slug=COALESCE(f.source_markdown_slug,f.entity_slug)`, [sourceId, keys]);for (const row of provenance) affected.add(row.id);+ // v209 fact keys: pages whose chunk embeddings carry the claim as a key. An+ // unresolved key subject ('*') matches every subject-scoped withdrawal.+ const keyedPages = await engine.executeRaw<{ id: number }>(`SELECT DISTINCT fk.page_id AS id+ FROM jsonb_to_recordset($2::text::jsonb) k(visibility text,fact_hash text,subject text,norm text)+ JOIN page_fact_keys fk ON fk.source_id=$1 AND fk.visibility=k.visibility+ AND (fk.item_fingerprint=COALESCE(encode(sha256(convert_to(k.norm,'UTF8')),'hex'),k.fact_hash)+ OR gbrain_fact_fingerprint_v1(fk.item_text)=k.fact_hash)+ AND (k.subject='*' OR fk.subject='*' OR fk.subject=k.subject)`, [sourceId, keys]);+ for (const row of keyedPages) affected.add(Number(row.id));if (affected.size > WITHDRAWAL_LIMITS.targets) await refuseAffected(engine, sourceId, affected);const match = async (incoming: Array<{ id: number; slug: string; claim: string; visibility: string | null; ambiguous: boolean }>) => {if (!incoming.length) return;diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 0ecee0cbbc..ce79fad873 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -58,6 +58,7 @@ import { decorateEmbeddingDimError } from './embedding-dim-check.ts';import { resolveImportContextualMode } from './import-contextual-mode.ts';import { runGuardrails } from './guardrails.ts';import { parseFactsFence, renderFactsTable, restoreHiddenFactRows, factsGapWarning, replaceOrInsertFactsFence } from './facts-fence.ts';+import { retireStaleFactKeys } from './facts/fact-keys-retire.ts';/*** #2044 / #4548: row-level, visibility-aware fence merge for one page@@ -905,6 +906,7 @@ export async function importFromContent(// above admitted carry over; a new seal otherwise inherits nothing from an// older index, whose contextual vector may have included a private sibling.await tx.deleteChunks(slug, txOpts);+ await retireStaleFactKeys(tx, txOpts.sourceId, slug);if (chunks.length > 0) {const embeddingColumn = await stampEmbeddingInputs(tx, chunks, null,{ title: parsed.title, tier: effectiveCRMode === 'title' ? 'title' : 'none', corpusGeneration });@@ -1666,6 +1668,7 @@ async function applyImportTransaction(tx: BrainEngine, spec: ImportTransactionSp}if (spec.chunks !== undefined) {await tx.deleteChunks(spec.slug, txOpts);+ await retireStaleFactKeys(tx, spec.sourceId ?? 'default', spec.slug);if (spec.chunks.length > 0) {await tx.upsertChunks(spec.slug, spec.chunks, txOpts);} else {diff --git a/src/core/page-state/projections.ts b/src/core/page-state/projections.tsindex 8a9dc9d0db..2a80f05033 100644--- a/src/core/page-state/projections.ts+++ b/src/core/page-state/projections.ts@@ -13,6 +13,7 @@ import { getFtsLanguage } from '../fts-language.ts';import { getEmbeddingModel } from '../ai/gateway.ts';import { refreshProjectionStatistics } from '../search/projection-statistics.ts';import { belowSafeChunkFence } from '../search/safe-chunks.ts';+import { retireStaleFactKeys } from '../facts/fact-keys-retire.ts';import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode, plainEmbeddingTier, synopsisBodyHash,type EmbeddingInputContext, type EmbeddingTier } from '../embedding-input-hash.ts';@@ -174,6 +175,7 @@ export async function installPageProjection(engine: BrainEngine, prepared: Projeawait tx.upsertChunks(slug, chunks, { sourceId, expectedRevision: snapshot.revision, embeddingColumn: context.column });if (opts.code) await installCodeChunkEdges(tx, slug, sourceId, opts.code);if (opts.seal) {+ await retireStaleFactKeys(tx, sourceId, slug);await tx.executeRaw(`UPDATE pages SET chunker_version=$3WHERE source_id=$1 AND slug=$2`, [sourceId, slug, MARKDOWN_CHUNKER_VERSION]);await sealPageTextProjection(tx, slug, sourceId, current!);@@ -213,6 +215,12 @@ export async function installPageEmbeddings(engine: BrainEngine, prepared: Proje// so resolving again could send these vectors to a different model's column.const column = context.column;const tier = built?.tier ?? plainEmbeddingTier(current.page.contextual_retrieval_mode);+ // v209: a title-tier vector is current only when it was built from the+ // stored fact keys (the chunk's own when the caller carried them, else the+ // prepared row the caller embedded from).+ const preparedKeys = new Map(prepared.chunks.map(chunk => [chunk.chunk_index, chunk.fact_keys ?? null]));+ if (tier === 'title' && chunks.some(chunk => (chunk.embedding || chunk.embedding_image)+ && (chunk.fact_keys !== undefined ? chunk.fact_keys ?? null : preparedKeys.get(chunk.chunk_index) ?? null) !== (byIndex.get(chunk.chunk_index)!.fact_keys ?? null))) return false;const provenance = embeddingInputContext(context, current.page.title,built?.corpusGeneration !== undefined ? built.corpusGeneration : context.corpusGeneration, stored);// This is deliberately UPDATE-only: a late embed can never replace text,diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex dcc321b983..7f0a8650e5 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -97,6 +97,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('op_checkpoints', 'operational', 'Resumable operation checkpoints.'),carry('open_loops', 'user_data', 'Open loops and their status.'),carry('page_aliases', 'user_data', 'Page aliases.'),+ carry('page_fact_keys', 'user_data', 'Fact-key occurrence rows: paid extraction output per page revision; the carried vectors were built from them, so withdrawal must still find them.'),carry('page_generation_clock', 'operational', 'Page generation clock (derived side table, verified equal).'),carry('page_mention_state', 'operational', 'Entity mention index: per-page mention watermark; without it every page is due for a rescan.'),carry('page_projection_jobs', 'operational', 'Pending page projection work (derived side table, verified equal).'),diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 8ccddd487c..e9423d5c0e 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -151,6 +151,7 @@ CREATE TABLE IF NOT EXISTS content_chunks (embedded_at TIMESTAMPTZ,embedded_text_hash TEXT,embedding_input_hash TEXT,+ fact_keys TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),language TEXT,symbol_name TEXT,@@ -475,6 +476,21 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (PRIMARY KEY (source_id, element_kind, element_key));+CREATE TABLE IF NOT EXISTS page_fact_keys (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ page_revision TEXT NOT NULL,+ ordinal INTEGER NOT NULL,+ item_text TEXT NOT NULL,+ item_fingerprint TEXT NOT NULL,+ subject TEXT NOT NULL,+ visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ extractor_version TEXT NOT NULL,+ PRIMARY KEY (page_id, page_revision, ordinal)+);+CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx+ ON page_fact_keys (source_id, item_fingerprint, visibility, subject);+CREATE TABLE IF NOT EXISTS session_context_state (source_id TEXT NOT NULL,client_id TEXT NOT NULL DEFAULT 'local',diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 14c5f98a63..7d5a67c93d 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -321,6 +321,9 @@ CREATE TABLE IF NOT EXISTS content_chunks (embedded_text_hash TEXT,-- #5553 (v171): embedding-input provenance written with the vector.embedding_input_hash TEXT,+ -- v209: fact-key text carried by this chunk's title-tier embedding input+ -- (docs/designs/FACT_KEYS.md); changes only together with the vector.+ fact_keys TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata. Nullable — markdown chunks leave these NULL.-- Powers \`query --lang\`, \`code-def <symbol>\`, and \`code-refs <symbol>\`.@@ -886,6 +889,24 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (PRIMARY KEY (source_id, element_kind, element_key));+-- page_fact_keys (migration v209): occurrence keys, the facts extractor's own+-- output for one page revision before dedup (docs/designs/FACT_KEYS.md).+-- Withdrawal discovery joins on (source, fingerprint, visibility, subject).+CREATE TABLE IF NOT EXISTS page_fact_keys (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ page_revision TEXT NOT NULL,+ ordinal INTEGER NOT NULL,+ item_text TEXT NOT NULL,+ item_fingerprint TEXT NOT NULL,+ subject TEXT NOT NULL,+ visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ extractor_version TEXT NOT NULL,+ PRIMARY KEY (page_id, page_revision, ordinal)+);+CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx+ ON page_fact_keys (source_id, item_fingerprint, visibility, subject);+-- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):-- per-session cursor + boundary-tie dedup for the \`delta\` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentineldiff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex aadccdd67a..32f9849e03 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -209,6 +209,7 @@ import { v205 } from './v205-minion-spend-authorization.ts';import { v206 } from './v206-entity-mention-index.ts';import { v207 } from './v207-retrieval-feedback.ts';import { v208 } from './v208-delta-per-arm-cursor.ts';+import { v209 } from './v209-fact-keys.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -416,4 +417,5 @@ export const MIGRATIONS: Migration[] = [v206,v207,v208,+ v209,];diff --git a/src/core/schema-migrations/v209-fact-keys.ts b/src/core/schema-migrations/v209-fact-keys.tsnew file mode 100644index 0000000000..d6fd6d701c--- /dev/null+++ b/src/core/schema-migrations/v209-fact-keys.ts@@ -0,0 +1,36 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// Fact keys (docs/designs/FACT_KEYS.md). page_fact_keys holds the facts+// extractor's own output for one page revision (occurrence keys, captured+// before dedup), the provenance withdrawal discovery joins on.+// content_chunks.fact_keys is the derived key text a chunk's title-tier+// embedding input carries; it changes only together with that chunk's vector.+// Created empty; nullable column with no backfill (keys arrive with the next+// extraction). Keep in sync with src/schema.sql.+export const FACT_KEYS_SQL = `+ CREATE TABLE IF NOT EXISTS page_fact_keys (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ page_revision TEXT NOT NULL,+ ordinal INTEGER NOT NULL,+ item_text TEXT NOT NULL,+ item_fingerprint TEXT NOT NULL,+ subject TEXT NOT NULL,+ visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ extractor_version TEXT NOT NULL,+ PRIMARY KEY (page_id, page_revision, ordinal)+ );+ CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx+ ON page_fact_keys (source_id, item_fingerprint, visibility, subject);+ ALTER TABLE content_chunks ADD COLUMN IF NOT EXISTS fact_keys TEXT;+`;++export const v209: Migration = {+ version: 209,+ name: 'fact_keys',+ idempotent: true,+ sql: FACT_KEYS_SQL,+};diff --git a/src/core/types.ts b/src/core/types.tsindex 0c73f75d02..d7505cd82b 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -684,6 +684,8 @@ export interface Chunk {* (getChunks).*/embedding_is_null?: boolean;+ /** v209 fact keys: the key text this chunk's title-tier embedding input carries (docs/designs/FACT_KEYS.md). */+ fact_keys?: string | null;}/**@@ -769,6 +771,8 @@ export interface ChunkInput {embedding?: Float32Array;/** #5553: embedding-input provenance (see embedding-input-hash.ts); written only with `embedding`. */embedding_input_hash?: string;+ /** v209: fact-key text in the title-tier embedding input; the stored value changes only with the vector. */+ fact_keys?: string | null;model?: string;token_count?: number;/**diff --git a/src/schema.sql b/src/schema.sqlindex 7a0919b3a9..bfb119701b 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -317,6 +317,9 @@ CREATE TABLE IF NOT EXISTS content_chunks (embedded_text_hash TEXT,-- #5553 (v171): embedding-input provenance written with the vector.embedding_input_hash TEXT,+ -- v209: fact-key text carried by this chunk's title-tier embedding input+ -- (docs/designs/FACT_KEYS.md); changes only together with the vector.+ fact_keys TEXT,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),-- v0.19.0: code chunk metadata. Nullable — markdown chunks leave these NULL.-- Powers `query --lang`, `code-def <symbol>`, and `code-refs <symbol>`.@@ -882,6 +885,24 @@ CREATE TABLE IF NOT EXISTS retrieval_weights (PRIMARY KEY (source_id, element_kind, element_key));+-- page_fact_keys (migration v209): occurrence keys, the facts extractor's own+-- output for one page revision before dedup (docs/designs/FACT_KEYS.md).+-- Withdrawal discovery joins on (source, fingerprint, visibility, subject).+CREATE TABLE IF NOT EXISTS page_fact_keys (+ page_id INTEGER NOT NULL REFERENCES pages(id) ON DELETE CASCADE,+ source_id TEXT NOT NULL,+ page_revision TEXT NOT NULL,+ ordinal INTEGER NOT NULL,+ item_text TEXT NOT NULL,+ item_fingerprint TEXT NOT NULL,+ subject TEXT NOT NULL,+ visibility TEXT NOT NULL CHECK (visibility IN ('private','world')),+ extractor_version TEXT NOT NULL,+ PRIMARY KEY (page_id, page_revision, ordinal)+);+CREATE INDEX IF NOT EXISTS page_fact_keys_withdrawal_idx+ ON page_fact_keys (source_id, item_fingerprint, visibility, subject);+-- session_context_state (v0.45.7 / migration v126 — ambient recall issue #1):-- per-session cursor + boundary-tie dedup for the `delta` verb + heartbeat-- runtime. Key (source_id, client_id, session_id); client_id 'local' sentinel