Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(embed): preserve code-chunk metadata across re-embed (#769) (#1232)
Ryan Ayers64920f83c90e
diff --git a/src/commands/embed.ts b/src/commands/embed.tsindex 6d8816a6eb..348d76812c 100644--- a/src/commands/embed.ts+++ b/src/commands/embed.ts@@ -581,7 +581,7 @@ async function embedPage(for (let j = 0; j < toEmbed.length; j++) {embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);}- const updated: ChunkInput[] = chunks.map(c => ({+ const updated: ChunkInput[] = chunks.map(c => preserveCodeMetadata(c, {chunk_index: c.chunk_index,chunk_text: c.chunk_text,chunk_source: c.chunk_source,@@ -605,6 +605,31 @@ async function embedPage(slog(`${slug}: embedded ${toEmbed.length} chunks`);}+/**+ * Carry code-chunk metadata (language, symbol_name, symbol_type, line range,+ * parent scope, doc comment, qualified name) from a loaded Chunk back into a+ * ChunkInput destined for upsertChunks.+ *+ * Issue #769: every re-embed used to strip these fields, and upsertChunks+ * overwrites (does not COALESCE) the metadata columns from EXCLUDED, so+ * each pass clobbered code-def's primary index to NULL. Pulling the+ * preservation into one helper keeps the three re-embed call sites+ * (embedPage, embedAll non-stale, embedAllStale) in lock-step.+ */+function preserveCodeMetadata(loaded: any, base: ChunkInput): ChunkInput {+ return {+ ...base,+ language: loaded.language ?? undefined,+ symbol_name: loaded.symbol_name ?? undefined,+ symbol_type: loaded.symbol_type ?? undefined,+ start_line: loaded.start_line ?? undefined,+ end_line: loaded.end_line ?? undefined,+ parent_symbol_path: loaded.parent_symbol_path ?? undefined,+ doc_comment: loaded.doc_comment ?? undefined,+ symbol_name_qualified: loaded.symbol_name_qualified ?? undefined,+ };+}+async function embedAll(engine: BrainEngine,staleOnly: boolean,@@ -717,8 +742,10 @@ async function embedAll(for (let j = 0; j < toEmbed.length; j++) {embeddingMap.set(toEmbed[j].chunk_index, embeddings[j]);}- // Preserve ALL chunks, only update embeddings for stale ones- const updated: ChunkInput[] = chunks.map(c => ({+ // Preserve ALL chunks, only update embeddings for stale ones.+ // preserveCodeMetadata threads code-chunk metadata (#769) so re-embed+ // doesn't clobber language/symbol_name/symbol_type to NULL.+ const updated: ChunkInput[] = chunks.map(c => preserveCodeMetadata(c, {chunk_index: c.chunk_index,chunk_text: c.chunk_text,chunk_source: c.chunk_source,@@ -1012,7 +1039,10 @@ async function embedAllStale(for (let j = 0; j < stale.length; j++) {staleIdxToEmbedding.set(stale[j].chunk_index, embeddings[j]);}- const merged: ChunkInput[] = existing.map(c => ({+ // preserveCodeMetadata threads code-chunk metadata (#769) so the+ // autopilot --stale path doesn't clobber language/symbol_name/etc+ // to NULL on every cycle.+ const merged: ChunkInput[] = existing.map(c => preserveCodeMetadata(c, {chunk_index: c.chunk_index,chunk_text: c.chunk_text,chunk_source: c.chunk_source,diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 54efd08732..6eff067b6d 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -2322,6 +2322,10 @@ export class PGLiteEngine implements BrainEngine {// v0.40.3.0 D24 NULL→non-NULL race fix mirrors postgres-engine.ts. Two writers// racing on the same chunk previously raced last-write-wins; the fix lets the// fresher `embedded_at` win in the text-unchanged branch.+ //+ // Code-chunk metadata columns follow the same chunk_text-gated CASE pattern as `embedding`+ // (#769). Re-chunk trusts EXCLUDED outright; pure re-embed COALESCEs so a caller carrying+ // only embedding-shaped fields doesn't clobber metadata to NULL.await this.db.query(`INSERT INTO content_chunks ${cols} VALUES ${rowParts.join(', ')}ON CONFLICT (page_id, chunk_index) DO UPDATE SET@@ -2345,14 +2349,14 @@ export class PGLiteEngine implements BrainEngine {THEN EXCLUDED.embedded_atELSE content_chunks.embedded_atEND,- language = EXCLUDED.language,- symbol_name = EXCLUDED.symbol_name,- symbol_type = EXCLUDED.symbol_type,- start_line = EXCLUDED.start_line,- end_line = EXCLUDED.end_line,- parent_symbol_path = EXCLUDED.parent_symbol_path,- doc_comment = EXCLUDED.doc_comment,- symbol_name_qualified = EXCLUDED.symbol_name_qualified,+ language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END,+ symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END,+ symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END,+ start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END,+ end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END,+ 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,modality = EXCLUDED.modality,embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`,paramsdiff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex b42f2a9092..24a7f7d6a8 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -2473,6 +2473,13 @@ export class PostgresEngine implements BrainEngine {// - new is fresher (embedded_at > existing.embedded_at) → take new// - otherwise → keep existing (slower writer with stale embedding loses)// Mirrored in pglite-engine.ts; pinned by test/e2e/concurrent-embed-race.test.ts.+ //+ // Code-chunk metadata columns (language / symbol_name / symbol_type / line range /+ // parent_symbol_path / doc_comment / symbol_name_qualified) follow the SAME chunk_text-gated+ // CASE pattern as `embedding` (#769). Re-chunk (chunk_text changed) trusts EXCLUDED outright;+ // pure re-embed (chunk_text unchanged) COALESCEs so a caller that only carries embedding+ // doesn't clobber metadata to NULL. Without this, every embed --stale pass nuked code-def's+ // primary index for thousands of chunks at once.await sql.unsafe(`INSERT INTO content_chunks ${cols} VALUES ${rows.join(', ')}ON CONFLICT (page_id, chunk_index) DO UPDATE SET@@ -2496,14 +2503,14 @@ export class PostgresEngine implements BrainEngine {THEN EXCLUDED.embedded_atELSE content_chunks.embedded_atEND,- language = EXCLUDED.language,- symbol_name = EXCLUDED.symbol_name,- symbol_type = EXCLUDED.symbol_type,- start_line = EXCLUDED.start_line,- end_line = EXCLUDED.end_line,- parent_symbol_path = EXCLUDED.parent_symbol_path,- doc_comment = EXCLUDED.doc_comment,- symbol_name_qualified = EXCLUDED.symbol_name_qualified,+ language = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.language ELSE COALESCE(EXCLUDED.language, content_chunks.language) END,+ symbol_name = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_name ELSE COALESCE(EXCLUDED.symbol_name, content_chunks.symbol_name) END,+ symbol_type = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.symbol_type ELSE COALESCE(EXCLUDED.symbol_type, content_chunks.symbol_type) END,+ start_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.start_line ELSE COALESCE(EXCLUDED.start_line, content_chunks.start_line) END,+ end_line = CASE WHEN EXCLUDED.chunk_text != content_chunks.chunk_text THEN EXCLUDED.end_line ELSE COALESCE(EXCLUDED.end_line, content_chunks.end_line) END,+ 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,modality = EXCLUDED.modality,embedding_image = COALESCE(EXCLUDED.embedding_image, content_chunks.embedding_image)`,params as Parameters<typeof sql.unsafe>[1],diff --git a/test/embed.serial.test.ts b/test/embed.serial.test.tsindex b4db83beb9..a0bf89beac 100644--- a/test/embed.serial.test.ts+++ b/test/embed.serial.test.ts@@ -803,3 +803,107 @@ describe('embedAllStale --source threading (D7)', () => {expect((firstCallOpts as { sourceId?: string }).sourceId).toBe('media-corpus');});});++// ────────────────────────────────────────────────────────────────+// Code metadata preservation across re-embed (regression for #769)+// ────────────────────────────────────────────────────────────────+//+// gbrain v0.30.1 and earlier silently clobbered code-chunk metadata+// (language, symbol_name, symbol_type, start_line, end_line,+// parent_symbol_path, doc_comment, symbol_name_qualified) on every+// re-embed pass. The chunker populated those columns at import time,+// but embed.ts loaded chunks via getChunks then mapped them to a+// stripped ChunkInput carrying only 5 fields. upsertChunks then+// OVERWROTE (not COALESCEd) the metadata columns from EXCLUDED, so+// re-embed wiped them to NULL. End result on a real brain: 4875 code+// pages, 47866 chunks, all with NULL language/symbol_name/symbol_type;+// code-def returned 0 hits across every indexed repo.+//+// All three runEmbed paths (--stale autopilot, --all, --slugs) must+// thread metadata through the re-upsert. Tests below assert that the+// engine.upsertChunks call carries the same metadata it loaded.++describe('runEmbed preserves code-chunk metadata across re-embed (regression for #769)', () => {+ const fullCodeChunk = {+ chunk_index: 0,+ chunk_text: '[Java] foo/Bar.java:10-20 method baz',+ chunk_source: 'compiled_truth' as const,+ embedded_at: null,+ token_count: 12,+ language: 'java',+ symbol_name: 'baz',+ symbol_type: 'function',+ start_line: 10,+ end_line: 20,+ parent_symbol_path: ['Bar'],+ doc_comment: 'does the thing',+ symbol_name_qualified: 'Bar.baz',+ };++ function metadataOf(chunk: any) {+ return {+ language: chunk.language,+ symbol_name: chunk.symbol_name,+ symbol_type: chunk.symbol_type,+ start_line: chunk.start_line,+ end_line: chunk.end_line,+ parent_symbol_path: chunk.parent_symbol_path,+ doc_comment: chunk.doc_comment,+ symbol_name_qualified: chunk.symbol_name_qualified,+ };+ }++ test('--stale (autopilot path) carries code metadata into upsertChunks', async () => {+ const stale = [{+ slug: 'code-page',+ chunk_index: 0,+ chunk_text: fullCodeChunk.chunk_text,+ chunk_source: 'compiled_truth',+ model: null,+ token_count: 12,+ }];+ let upsertChunkArgs: any[] | null = null;+ const engine = mockEngine({+ countStaleChunks: async () => 1,+ listStaleChunks: async () => stale,+ getChunks: async () => [fullCodeChunk],+ upsertChunks: async (_slug: string, chunks: any[]) => { upsertChunkArgs = chunks; },+ });++ await runEmbed(engine, ['--stale']);++ expect(upsertChunkArgs).not.toBeNull();+ expect(upsertChunkArgs!).toHaveLength(1);+ expect(metadataOf(upsertChunkArgs![0])).toEqual(metadataOf(fullCodeChunk));+ });++ test('--all (full re-embed) carries code metadata into upsertChunks', async () => {+ let upsertChunkArgs: any[] | null = null;+ const engine = mockEngine({+ listPages: async () => [{ slug: 'code-page' }],+ getChunks: async () => [fullCodeChunk],+ upsertChunks: async (_slug: string, chunks: any[]) => { upsertChunkArgs = chunks; },+ });++ await runEmbed(engine, ['--all']);++ expect(upsertChunkArgs).not.toBeNull();+ expect(upsertChunkArgs!).toHaveLength(1);+ expect(metadataOf(upsertChunkArgs![0])).toEqual(metadataOf(fullCodeChunk));+ });++ test('--slugs (per-page embed) carries code metadata into upsertChunks', async () => {+ let upsertChunkArgs: any[] | null = null;+ const engine = mockEngine({+ getPage: async () => ({ slug: 'code-page', compiled_truth: 'x', timeline: '' }),+ getChunks: async () => [fullCodeChunk],+ upsertChunks: async (_slug: string, chunks: any[]) => { upsertChunkArgs = chunks; },+ });++ await runEmbed(engine, ['--slugs', 'code-page']);++ expect(upsertChunkArgs).not.toBeNull();+ expect(upsertChunkArgs!).toHaveLength(1);+ expect(metadataOf(upsertChunkArgs![0])).toEqual(metadataOf(fullCodeChunk));+ });+});