Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
refactor(import): A13 chunk reuse in its own module; engine scope loaders on one line
time-attacka765292ef407
diff --git a/src/core/import-chunk-reuse.ts b/src/core/import-chunk-reuse.tsnew file mode 100644index 0000000000..c8a1a72a52--- /dev/null+++ b/src/core/import-chunk-reuse.ts@@ -0,0 +1,51 @@+/**+ * A13 vector reuse for one Markdown page import, shared by the inline import+ * (before its transaction, onto the chunks it will embed) and the prepared+ * publish (inside its publication transaction, under the page guard).+ */+import type { BrainEngine } from './engine.ts';+import type { Chunk, ChunkInput } from './types.ts';+import { embeddingWriteTarget, embeddingInputContext } from './page-state/projections.ts';+import { canReuseMarkdownVector, planEmbeddingReuse } from './embed-reuse.ts';++/**+ * A13 reuse for one page import: copies each stored vector the reuse gate+ * admits onto its matching new chunk in `into`, and maps the chunk's index to+ * the stored row id when that row already holds exactly what the chunk would+ * insert (so a prepared import can keep it in place), else to null.+ */+export async function reuseStoredChunkVectors(+ exec: BrainEngine,+ into: ChunkInput[],+ { slug, sourceId, title, corpusGeneration, tier }: { slug: string; sourceId: string; title: string; corpusGeneration: string | null; tier: 'title' | 'none' },+): Promise<Map<number, number | null>> {+ const reused = new Map<number, number | null>();+ const target = await embeddingWriteTarget(exec);+ const provenance = embeddingInputContext(target, title, corpusGeneration, into);+ const rows = await exec.executeRaw<{ chunk_index: number; embedding_input_hash: string | null; contextual_retrieval_mode: string | null; text_only: boolean }>(+ `SELECT c.chunk_index, c.embedding_input_hash, p.contextual_retrieval_mode,+ c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedded_text_hash = md5(c.chunk_text) AS text_only+ FROM content_chunks c JOIN pages p ON p.id = c.page_id+ WHERE p.source_id = $1 AND p.slug = $2`, [sourceId, slug]);+ if (rows.length === 0) return reused;+ const recorded = new Map(rows.map(row => [Number(row.chunk_index), row.embedding_input_hash]));+ const textOnly = new Set(rows.filter(row => row.text_only).map(row => Number(row.chunk_index)));+ // 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 exec.getChunks(slug, { sourceId, includeEmbedding: true, requireSafeChunks: true }))+ .filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), rows[0]!.contextual_retrieval_mode, tier, provenance, chunk));+ const identity = (chunk: ChunkInput | Chunk) => JSON.stringify([chunk.chunk_index, chunk.chunk_text, chunk.chunk_source,+ chunk.language ?? null, chunk.symbol_name ?? null, chunk.symbol_type ?? null, chunk.start_line ?? null, chunk.end_line ?? null,+ chunk.parent_symbol_path ?? null, chunk.doc_comment ?? null, chunk.symbol_name_qualified ?? null, chunk.modality ?? 'text']);+ for (const [i, matched] of planEmbeddingReuse(stored, into, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {+ into[i].embedding = matched.embedding as Float32Array;+ into[i].token_count = matched.token_count ?? undefined;+ if (matched.model) into[i].model = matched.model;+ // The stored row already holds exactly what this chunk would insert (same+ // index, identity, vector, recorded input and text hash, no image or+ // multimodal vector the insert would drop), so it can stay in place.+ const row = matched as Chunk;+ reused.set(i, recorded.get(row.chunk_index) != null && textOnly.has(row.chunk_index) && identity(row) === identity(into[i]) ? row.id : null);+ }+ return reused;+}diff --git a/src/core/import-file.ts b/src/core/import-file.tsindex 88ca6277f3..0d163c0590 100644--- a/src/core/import-file.ts+++ b/src/core/import-file.ts@@ -21,11 +21,12 @@ import { prepareCodeChunks, installCodeChunkEdges } from './code-chunks.ts';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';+ sealPageTextProjection, stampEmbeddingInputs, type ProjectionSnapshot } from './page-state/projections.ts';import { sanitizeText } from './batch-rows.ts';import { hasProtectedBody, safeChunksFilter } from './search/safe-chunks.ts';import { findChunkForOffset } from './chunkers/edge-extractor.ts';-import { canReuseMarkdownVector, planEmbeddingReuse } from './embed-reuse.ts';+import { planEmbeddingReuse } from './embed-reuse.ts';+import { reuseStoredChunkVectors } from './import-chunk-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 +@@ -35,7 +36,7 @@ import { embedMultimodal, currentEmbeddingSignature } from './embedding.ts';import { embedBatchKeepingUsable, embedBatchWithBackoff } from './embed-retry.ts';import { isEmbeddingZeroNormError, type EmbeddingZeroNormError } from './ai/embedding-guard.ts';import { slugifyPath, slugifyCodePath, isCodeFilePath, hasMalformedPathSegment } from './sync.ts';-import type { Chunk, ChunkInput, Page, PageInput, PageType } from './types.ts';+import type { ChunkInput, Page, PageInput, PageType } from './types.ts';import type { PageSnapshot } from './page-state/types.ts';import { pipelined } from './page-state/transactions.ts';import { addPageTags } from './page-state/tags.ts';@@ -765,38 +766,8 @@ export async function importFromContent(// reach the provider.const reusable = !!existing && !existing.deleted_at && !opts.forceRechunk && !opts.onPostCommitEmbedding && chunks.length > 0&& !(opts.prepare && modeRequiresSynopsis(effectiveCRMode)) && !hasProtectedBody(`${existing.compiled_truth}\n${existing.timeline ?? ''}`) && !hasProtectedBody(`${parsed.compiled_truth}\n${parsed.timeline ?? ''}`);- const reuseStoredVectors = async (exec: BrainEngine, into: ChunkInput[]): Promise<Map<number, number | null>> => {- const reused = new Map<number, number | null>();- const target = await embeddingWriteTarget(exec);- const provenance = embeddingInputContext(target, parsed.title, corpusGeneration, into);- const tier = effectiveCRMode === 'title' ? 'title' : 'none';- const rows = await exec.executeRaw<{ chunk_index: number; embedding_input_hash: string | null; contextual_retrieval_mode: string | null; text_only: boolean }>(- `SELECT c.chunk_index, c.embedding_input_hash, p.contextual_retrieval_mode,- c.embedding_image IS NULL AND c.embedding_multimodal IS NULL AND c.embedded_text_hash = md5(c.chunk_text) AS text_only- FROM content_chunks c JOIN pages p ON p.id = c.page_id- WHERE p.source_id = $1 AND p.slug = $2`, [sourceId ?? 'default', slug]);- if (rows.length === 0) return reused;- const recorded = new Map(rows.map(row => [Number(row.chunk_index), row.embedding_input_hash]));- const textOnly = new Set(rows.filter(row => row.text_only).map(row => Number(row.chunk_index)));- // 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 exec.getChunks(slug, { sourceId: sourceId ?? 'default', includeEmbedding: true, requireSafeChunks: true }))- .filter(chunk => canReuseMarkdownVector(recorded.get(chunk.chunk_index), rows[0]!.contextual_retrieval_mode, tier, provenance, chunk));- const identity = (chunk: ChunkInput | Chunk) => JSON.stringify([chunk.chunk_index, chunk.chunk_text, chunk.chunk_source,- chunk.language ?? null, chunk.symbol_name ?? null, chunk.symbol_type ?? null, chunk.start_line ?? null, chunk.end_line ?? null,- chunk.parent_symbol_path ?? null, chunk.doc_comment ?? null, chunk.symbol_name_qualified ?? null, chunk.modality ?? 'text']);- for (const [i, matched] of planEmbeddingReuse(stored, into, c => `${c.chunk_source}\0${c.chunk_text}`).reuse) {- into[i].embedding = matched.embedding as Float32Array;- into[i].token_count = matched.token_count ?? undefined;- if (matched.model) into[i].model = matched.model;- // The stored row already holds exactly what this chunk would insert (same- // index, identity, vector, recorded input and text hash, no image or- // multimodal vector the insert would drop), so it can stay in place.- const row = matched as Chunk;- reused.set(i, recorded.get(row.chunk_index) != null && textOnly.has(row.chunk_index) && identity(row) === identity(into[i]) ? row.id : null);- }- return reused;- };+ const reuseCtx = { slug, sourceId: sourceId ?? 'default', title: parsed.title, corpusGeneration, tier: effectiveCRMode === 'title' ? 'title' as const : 'none' as const };+ const reuseStoredVectors = (exec: BrainEngine, into: ChunkInput[]) => reuseStoredChunkVectors(exec, into, reuseCtx);const reused = reusable && !opts.noEmbed && !opts.prepare ? await reuseStoredVectors(engine, chunks) : new Map<number, number | null>();let embeddingPartial: EmbeddingZeroNormError | undefined;diff --git a/src/core/pglite-engine.ts b/src/core/pglite-engine.tsindex 6f54c4a7f5..4d45673fea 100644--- a/src/core/pglite-engine.ts+++ b/src/core/pglite-engine.ts@@ -705,10 +705,7 @@ export async function probePgliteScratchStore(export class PGLiteEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;- private readonly vectorScope = vectorScopeLoader(- () => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL),- ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]),- );+ private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL), ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]));/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;private _checkpointGuard: PgliteCheckpointGuard | undefined;diff --git a/src/core/postgres-engine.ts b/src/core/postgres-engine.tsindex 79b699f265..86185853ec 100644--- a/src/core/postgres-engine.ts+++ b/src/core/postgres-engine.ts@@ -179,10 +179,7 @@ export function getPostgresSchema(export class PostgresEngine implements BrainEngine {private vectorIterativeScan?: Promise<boolean>;- private readonly vectorScope = vectorScopeLoader(- () => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL),- ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]),- );+ private readonly vectorScope = vectorScopeLoader(() => this.executeRaw<PageSourceStats>(PAGE_SOURCE_STATS_SQL), ids => this.executeRaw<ScopeChunkCount>(SCOPE_CHUNKS_SQL, [ids]));/** Transaction clones keep chunk invalidation and replacement atomic. */private _chunkWritesInTransaction = false;readonly kind = 'postgres' as const;