Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix: close raw embedding provenance bypasses in import and repair
time-attackf8e9c08df496
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ceab2ec1f5..e9f7a43ac5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -36,6 +36,7 @@ cost to replace any cleared vectors.- The shared page-state writer clears active vectors and their completion stamps atomically on a contextual-to-`none` transition, in both PGLite and PostgreSQL.- Projection rebuilds no longer accept an unstamped vector on an explicit `none` page as proof that it came from raw text; they still preserve verified current inputs and grandfather pre-contextual NULL-mode pages.+- Markdown re-import cannot reinstate an unstamped title vector after the mode switch and label it as raw. Repairing a pre-contextual NULL-mode page into `none` records raw provenance for retained vectors so a later rebuild does not discard them.## [0.60.68.0] - 2026-10-05diff --git a/src/core/embed-reuse.ts b/src/core/embed-reuse.tsindex d4e6d79773..a485d7dc73 100644--- a/src/core/embed-reuse.ts+++ b/src/core/embed-reuse.ts@@ -8,10 +8,17 @@// therefore re-embedded a byte-identical body (measured: 0/5 hits where 4/5 were// recoverable). Keying on the header-stripped body fixes that.//-// LEAF module (imports only `stripChunkHeader`) so it is unit-testable with-// literal arrays — no DB, no API key.+// Pure reuse policy and planner, testable without a DB or API key.import { stripChunkHeader } from './chunkers/code.ts';+import { embeddingInputHash, type EmbeddingInputContext, type EmbeddingTier } from './embedding-input-hash.ts';++export function canReuseMarkdownVector(hash: string | null | undefined, storedMode: string | null | undefined,+ tier: EmbeddingTier, provenance: EmbeddingInputContext, chunk: { chunk_text: string; chunk_source?: string | null; model?: string | null }): boolean {+ if (tier === 'none' && storedMode != null && storedMode !== 'none') return false;+ if (hash == null) return tier === 'none' && storedMode == null && chunk.model === provenance.model;+ return hash === embeddingInputHash(provenance, tier, chunk);+}export interface ReusableChunk {chunk_text: string;diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 0ecee0cbbc..7861968c89 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -17,11 +17,10 @@ import { detectCodeLanguage, CHUNKER_VERSION } from './chunkers/code.ts';import { sanitizeRemoteBody } from './remote-body.ts';import { installPageEmbeddings, installPageProjection, preparePageProjection, projectionBelowSafeFence, queuePageProjection, readProjectionSnapshot, resealSafeChunks,sealPageTextProjection, stampEmbeddingInputs, embeddingWriteTarget, embeddingInputContext, type ProjectionSnapshot } from './page-state/projections.ts';-import { embeddingInputHash } from './embedding-input-hash.ts';import { sanitizeText } from './batch-rows.ts';import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';-import { planEmbeddingReuse } from './embed-reuse.ts';+import { canReuseMarkdownVector, planEmbeddingReuse } from './embed-reuse.ts';import { extractCodeRefs, imageOfCandidates } from './link-extraction.ts';import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';// #3374 — import-path embeds ride the shared retry loop (429 retry-after +@@ -765,10 +764,7 @@ export async function importFromContent(// Reuse is keyed on chunk source + text, so a stored chunk's current-input// hash is the hash its matching new chunk would record.const stored = (await engine.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true, requireSafeChunks: true }))- .filter(chunk => {- const hash = recorded.get(chunk.chunk_index);- return hash == null ? tier === 'none' && chunk.model === target.provenanceModel : hash === embeddingInputHash(provenance, tier, chunk);- });+ .filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), existing.contextual_retrieval_mode, tier, provenance, chunk));for (const [i, matched] of planEmbeddingReuse(stored, chunks, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {chunks[i].embedding = matched.embedding as Float32Array;chunks[i].token_count = matched.token_count ?? undefined;diff --git a/src/core/repair/contextual-mode.ts b/src/core/repair/contextual-mode.tsindex 17f8477d9f..4cb9d9df52 100644--- a/src/core/repair/contextual-mode.ts+++ b/src/core/repair/contextual-mode.ts@@ -16,7 +16,7 @@*/import type { BrainEngine } from '../engine.ts';import { quoteIdentifier } from '../search/embedding-column.ts';-import { acceptedEmbeddingInputHashes, isContextualMode } from '../embedding-input-hash.ts';+import { acceptedEmbeddingInputHashes, embeddingInputHash, isContextualMode } from '../embedding-input-hash.ts';import { embeddingInputContext, embeddingWriteTarget } from '../page-state/projections.ts';import { resolveImportContextualMode } from '../import-contextual-mode.ts';import { embedStalePages } from '../embed-stale.ts';@@ -53,10 +53,17 @@ export const contextualModeRepair: RepairHandler = {'SELECT id,embedding_input_hash FROM content_chunks WHERE page_id=$1', [snapshot.page.id])).map(r => [Number(r.id), r.embedding_input_hash]));const stale = chunks.filter(chunk => !chunk.embedding_is_null).filter(chunk => {const hash = recorded.get(Number(chunk.id)) ?? null;- return hash === null ? isContextualMode(mode) : !acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);+ return hash === null ? isContextualMode(mode) || chunk.model !== target.provenanceModel+ : !acceptedEmbeddingInputHashes(provenance, mode, chunk).includes(hash);}).map(chunk => Number(chunk.id));if (stale.length) await tx.executeRaw(`UPDATE content_chunks SET ${quoteIdentifier(target.column.name)}=NULL,embedded_at=NULL,embedded_text_hash=NULL,embedding_input_hash=NULL WHERE page_id=$1 AND id=ANY($2::int[])`, [snapshot.page.id, stale]);+ const staleIds = new Set(stale);+ const raw = chunks.filter(chunk => !chunk.embedding_is_null && !staleIds.has(Number(chunk.id))+ && recorded.get(Number(chunk.id)) == null);+ if (raw.length) await tx.executeRaw(`UPDATE content_chunks c SET embedding_input_hash=proof.hash+ FROM unnest($2::int[],$3::text[]) AS proof(id,hash) WHERE c.page_id=$1 AND c.id=proof.id`,+ [snapshot.page.id, raw.map(chunk => Number(chunk.id)), raw.map(chunk => embeddingInputHash(provenance, 'none', chunk))]);return stale.length;});if (cleared === null) return false;diff --git a/test/page-projection-vector-preservation.test.ts b/test/page-projection-vector-preservation.test.tsindex c7b135379e..768f64d7fa 100644--- a/test/page-projection-vector-preservation.test.ts+++ b/test/page-projection-vector-preservation.test.ts@@ -26,6 +26,7 @@ interface StoredChunk {embedding: string | null;embedded_text_hash: string | null;embedded_at: string | null;+ embedding_input_hash: string | null;model: string;embedding_projection_test?: string | null;}@@ -169,7 +170,7 @@ for (const kind of backends) {await installPageProjection(engine, pending, (await preparePageProjection(pending)).chunks, preserve);const prepared = (await readProjectionSnapshot(engine, slug, sourceId))!;expect(await installPageEmbeddings(engine, prepared, prepared.chunks.map(c => ({- ...c, embedding: vector,+ chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source, embedding: vector,})))).toBe(true);const before = await storedChunks();expect(before.map(c => c.embedding_input_hash).every(Boolean)).toBe(true);diff --git a/test/repair-contextual-mode-5621.serial.test.ts b/test/repair-contextual-mode-5621.serial.test.tsindex 41b4542756..3a79bb6186 100644--- a/test/repair-contextual-mode-5621.serial.test.ts+++ b/test/repair-contextual-mode-5621.serial.test.ts@@ -26,6 +26,7 @@ import { titleTierCorpusGeneration } from '../src/core/contextual-retrieval-servimport { __setEmbedTransportForTests, configureGateway, resetGateway } from '../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';import { testBackends } from './helpers/test-backends.ts';+import { queuePageProjection, rebuildPendingPageProjections } from '../src/core/page-state/projections.ts';const DIMS = 1536;const MODEL = 'openai:text-embedding-3-large';@@ -79,6 +80,43 @@ for (const kind of testBackends()) describe(`#5621 gbrain repair contextual-modeconst run = async (apply: boolean, embed = true) => runRepair(ctx(), contextualModeRepair, await resolveRepairScope(engine),{ apply, embed, embeddingModel: MODEL });+ test('re-import does not turn an unverified title vector into verified raw provenance', async () => {+ const source = `transition-${kind}`, slug = 'notes/mode-transition';+ await engine.executeRaw('INSERT INTO sources(id,name,contextual_retrieval_mode) VALUES ($1,$1,$2)', [source, 'title']);+ const content = body('Mode Transition Example');+ await importFromContent(engine, slug, content, { sourceId: source });+ await engine.executeRaw(`UPDATE content_chunks SET embedding_input_hash=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id=$1 AND slug=$2)`, [source, slug]);+ await engine.executeRaw("UPDATE sources SET contextual_retrieval_mode='none' WHERE id=$1", [source]);+ inputs = [];+ await importFromContent(engine, slug, content.replace('type: note', 'type: note\ntags: [regression]'), { sourceId: source });+ const after = await vectors(source, slug);+ expect(inputs).toHaveLength(1);+ const chunks = await engine.getChunks(slug, { sourceId: source });+ expect(inputs[0]).toEqual(chunks.map(chunk => chunk.chunk_text));+ expect(after.every(row => row.v !== null && row.h !== null)).toBe(true);+ await queuePageProjection(engine, source, slug, 'regression');+ await rebuildPendingPageProjections(engine, 10);+ expect(await vectors(source, slug)).toEqual(after);+ });++ test('repair records proof for grandfathered raw vectors before an explicit none rebuild', async () => {+ const slug = 'notes/legacy-raw-repair';+ await legacyPage('off', slug, 'Legacy Raw Example');+ await engine.executeRaw(`UPDATE content_chunks SET embedding_input_hash=NULL WHERE page_id=(SELECT id FROM pages WHERE source_id='off' AND slug=$1)`, [slug]);+ const before = await vectors('off', slug);+ expect(before.every(row => row.v !== null && row.h === null)).toBe(true);+ inputs = [];+ await run(true, false);+ const stamped = await vectors('off', slug);+ expect((await page('off', slug)).mode).toBe('none');+ expect(stamped.map(row => row.v)).toEqual(before.map(row => row.v));+ expect(stamped.every(row => row.h !== null)).toBe(true);+ expect(inputs).toHaveLength(0);+ await queuePageProjection(engine, 'off', slug, 'regression');+ await rebuildPendingPageProjections(engine, 10);+ expect(await vectors('off', slug)).toEqual(stamped);+ });+test('stamps like a fresh import; unchanged inputs queue no re-embed, changed inputs re-embed once; a second run changes nothing', async () => {await legacyPage('plain', 'notes/raw-embedded', 'Raw Embedded Example');await legacyPage('off', 'notes/source-off', 'Source Off Example');