/** * graph-memory — 跨对话召回 * * By: adoresever * Email: Wywelljob@gmail.com * * Query recall is deliberately relevance-first: vector ranking is preserved, * with FTS5 as an exact-term/failure fallback. Graph centrality is useful for * offline graph inspection, but must not displace the memories most similar * to the current user question. */ import { type DatabaseSyncInstance } from "../store/sqlite.ts"; import { createHash } from "crypto"; import type { GmConfig, RecallResult, GmNode, GmTurnMemory } from "../types.ts"; import type { EmbedBatchFn, EmbedFn } from "../engine/embed.ts"; import { searchNodes, vectorSearchWithScore, graphWalk, saveVector, getVectorHash, allActiveNodes, searchTurnMemories, turnMemoryVectorSearchWithScore, nodesForTurnMemories, saveTurnVector, getTurnVectorHash, getNavigationTriplesForMemories, findNavigationSeedTermIds, navigationCandidateTermIds, rankTurnMemoryIdsByNavigation, getTurnMemoriesByIds, hasTurnMemories, } from "../store/store.ts"; import { personalizedNavigationPageRank } from "../graph/pagerank.ts"; import { QueryVecCache } from "./query-cache.ts"; export class Recaller { private embed: EmbedFn | null = null; private embedBatch: EmbedBatchFn | null = null; private embeddingFingerprint = ""; /** 查询向量 LRU:同会话重复查询省一次 embedding 调用(db 模式不入缓存)。 */ private queryVecCache = new QueryVecCache(); constructor(private db: DatabaseSyncInstance, private cfg: GmConfig) {} setEmbedFn(fn: EmbedFn, fingerprint = ""): void { this.embed = fn; this.embeddingFingerprint = fingerprint; } /** 注入批量 embed 函数(createEmbedBatchFn 产出)。 */ setEmbedBatchFn(fn: EmbedBatchFn): void { this.embedBatch = fn; } async recall(query: string): Promise { const limit = this.cfg.recallMaxNodes; let queryVector: number[] | undefined; if (this.embed) { // 局部化 fingerprint:await 前后读取同一个快照,防止并发 setEmbedFn 串台 const fp = this.embeddingFingerprint; // LRU 命中时零 API 调用;fingerprint 变化天然 miss(旧模型向量不可复用) const cached = this.queryVecCache.get(query, fp); if (cached) { queryVector = cached; } else { try { queryVector = await this.embed(query, "query"); // embed 成功才入缓存:抛错走 catch,失败结果不占据缓存槽位 this.queryVecCache.set(query, fp, queryVector); } catch { // The lexical path remains available when the embedding provider is // temporarily unavailable. } } } const directMemories = this.recallTurnMemories(query, limit, queryVector); const seedIds = findNavigationSeedTermIds( this.db, query, directMemories.map(memory => memory.id), ); let graphMemories: GmTurnMemory[] = []; let navigationScores = new Map(); if (seedIds.length) { const candidateTermIds = navigationCandidateTermIds(this.db, seedIds); navigationScores = personalizedNavigationPageRank( this.db, seedIds, candidateTermIds, this.cfg, ).scores; graphMemories = getTurnMemoriesByIds( this.db, rankTurnMemoryIdsByNavigation(this.db, navigationScores), ); } const turnMemories = this.mergeTurnMemoryRanks(directMemories, graphMemories, limit); if (turnMemories.length) { const memoryIds = turnMemories.map(memory => memory.id); const nodes = nodesForTurnMemories( this.db, memoryIds, limit, ); const { edges } = graphWalk(this.db, nodes.map(node => node.id), 0); return { nodes, edges, turnMemories, triples: getNavigationTriplesForMemories(this.db, memoryIds, navigationScores), }; } // Databases created before the turn-memory migration remain searchable. // The same confidence rule applies; a legacy node match cannot bypass it. return this.recallPrecise(query, limit, queryVector, hasTurnMemories(this.db)); } /** * Fuse independent summary and graph ranks without mixing incomparable * cosine and PageRank score scales. A memory supported by both routes rises; * exact summary matches keep tie priority over graph-only expansion. */ private mergeTurnMemoryRanks( direct: GmTurnMemory[], graph: GmTurnMemory[], limit: number, ): GmTurnMemory[] { const candidates = new Map(); direct.forEach((memory, index) => { candidates.set(memory.id, { memory, score: 1 / (index + 1), directRank: index, }); }); graph.forEach((memory, index) => { const existing = candidates.get(memory.id); if (existing) { existing.score += 1 / (index + 1); } else { candidates.set(memory.id, { memory, score: 1 / (index + 1), directRank: Number.POSITIVE_INFINITY, }); } }); return Array.from(candidates.values()) .sort((left, right) => right.score - left.score || left.directRank - right.directRank || right.memory.updatedAt - left.memory.updatedAt || left.memory.id.localeCompare(right.memory.id) ) .slice(0, limit) .map(candidate => candidate.memory); } private recallTurnMemories( query: string, limit: number, queryVector?: number[], ): GmTurnMemory[] { const lexical = searchTurnMemories(this.db, query, limit); const threshold = this.cfg.semanticScoreThreshold; const semantic = queryVector && threshold !== undefined ? turnMemoryVectorSearchWithScore(this.db, queryVector, limit, threshold) : []; const selected: GmTurnMemory[] = []; const seen = new Set(); const append = (memory: GmTurnMemory) => { if (selected.length >= limit || seen.has(memory.id)) return; seen.add(memory.id); selected.push(memory); }; for (const { memory } of semantic) append(memory); for (const memory of lexical) append(memory); return selected; } /** * Preserve semantic rank. FTS5 contributes exact terms and is the complete * fallback when the embedding provider is absent or temporarily fails. */ private async recallPrecise( query: string, limit: number, queryVector?: number[], legacyOnly = false, ): Promise { const lexical = searchNodes(this.db, query, limit, legacyOnly); const threshold = this.cfg.semanticScoreThreshold; const semantic = queryVector && threshold !== undefined ? vectorSearchWithScore( this.db, queryVector, limit, threshold, legacyOnly, ) : []; const selected: GmNode[] = []; const selectedIds = new Set(); const append = (node: GmNode) => { if (selected.length >= limit || selectedIds.has(node.id)) return; selected.push(node); selectedIds.add(node.id); }; for (const { node } of semantic) append(node); for (const node of lexical) append(node); if (!selected.length) return { nodes: [], edges: [], turnMemories: [], triples: [] }; // Depth zero asks the store only for edges whose two endpoints are direct // query matches. No unrelated graph hub is allowed to enter the prompt. const { edges } = graphWalk(this.db, selected.map(node => node.id), 0); return { nodes: selected, edges, turnMemories: [], triples: [] }; } /** 异步同步 embedding,不阻塞主流程 */ async syncEmbed(node: GmNode): Promise { if (!this.embed) return; const fp = this.embeddingFingerprint; const temporal = Object.keys(node.temporal).length ? `\n时间语义: ${JSON.stringify(node.temporal)}` : ""; const text = `${node.name}: ${node.description}\n${node.content}${temporal}`; const hashInput = fp ? `${fp}\0${text}` : text; const hash = createHash("md5").update(hashInput).digest("hex"); if (getVectorHash(this.db, node.id) === hash) return; try { const vec = await this.embed(text, "db"); if (vec.length) saveVector(this.db, node.id, hashInput, vec); } catch { /* 不影响主流程 */ } } /** * 批量同步节点向量:N 个节点 → 1 次 /embeddings 调用(N→1 成本)。 * per-node hash 短路(同 syncEmbed 语义);单事务批 upsert; * 批量 API 失败整批抛错(不移植 PR 的 catch{} 静默)。 */ async syncEmbedBatch(nodes: GmNode[]): Promise { if (!nodes.length) return; if (!this.embed && !this.embedBatch) return; const fp = this.embeddingFingerprint; // 构建每个节点的 text + hashInput + hash(与 syncEmbed :220-227 一致) const targets = nodes.map(node => { const temporal = Object.keys(node.temporal).length ? `\n时间语义: ${JSON.stringify(node.temporal)}` : ""; const text = `${node.name}: ${node.description}\n${node.content}${temporal}`; const hashInput = fp ? `${fp}\0${text}` : text; const hash = createHash("md5").update(hashInput).digest("hex"); return { node, text, hashInput, hash }; }); // hash 短路:跳过未变节点 const pending = targets.filter(t => getVectorHash(this.db, t.node.id) !== t.hash); if (!pending.length) return; if (!this.embedBatch) { // 无批量能力(仅 setEmbedFn 的旧接线):退回逐节点单发 for (const t of pending) { try { const vec = await this.embed!(t.text, "db"); if (vec.length) saveVector(this.db, t.node.id, t.hashInput, vec); } catch { /* 不影响主流程 */ } } return; } // 批量嵌入:一次 API 调用;失败整批抛错(不 catch{}) const vecs = await this.embedBatch(pending.map(t => t.text), "db"); // 单事务批 upsert this.db.exec("BEGIN"); try { for (let i = 0; i < pending.length; i++) { saveVector(this.db, pending[i].node.id, pending[i].hashInput, vecs[i]); } this.db.exec("COMMIT"); } catch (err) { this.db.exec("ROLLBACK"); throw err; } } /** Keep the compact episodic layer independently searchable. */ async syncTurnMemoryEmbed(memory: GmTurnMemory): Promise { if (!this.embed) return; const fp = this.embeddingFingerprint; const text = `${memory.outcome}: ${memory.summary}`; const hashInput = fp ? `${fp}\0${text}` : text; const hash = createHash("md5").update(hashInput).digest("hex"); if (getTurnVectorHash(this.db, memory.id) === hash) return; try { const vec = await this.embed(text, "db"); if (vec.length) saveTurnVector(this.db, memory.id, hashInput, vec); } catch { /* 不影响主流程 */ } } /** * 增量重建向量:换嵌入模型后,fingerprint 变了 → hash 不匹配 → 重嵌入。 * hash 短路:fingerprint 没变的节点跳过。**绝不 clearAllEmbeddings**。 * * scope 语义:missing=只补缺向量、stale=hash 不匹配、all=全量。 * dryRun=true 只返回统计(各 scope 计数 + 预计批数),不改库。 * 执行=分批 syncEmbedBatch + 逐批进度。 */ async reembed(opts: { dryRun?: boolean; batchSize?: number; scope?: "missing" | "stale" | "all"; } = {}): Promise<{ dryRun: boolean; scope: "missing" | "stale" | "all"; batchSize: number; stats: { missing: number; stale: number; all: number }; selected: number; pending: number; estimatedBatches: number; batches: number; embedded: number; }> { const dryRun = opts.dryRun ?? true; // `??` 不拦截 0(0 ?? 50 === 0);batchSize<=0 会让执行循环 i += batchSize 永不前进 → 无限循环。 // 钳到 >=1:dry-run 计数、执行循环与返回值共用同一安全值。 const batchSize = Math.max(1, opts.batchSize ?? 50); const scope = opts.scope ?? "stale"; // 分类节点:missing(无向量行)、stale(有向量但 hash 不匹配)、all const allNodes = allActiveNodes(this.db); const missingNodes = allNodes.filter(n => getVectorHash(this.db, n.id) === null); const withVecNodes = allNodes.filter(n => getVectorHash(this.db, n.id) !== null); const staleNodes = this.pendingReembed(withVecNodes); const stats = { missing: missingNodes.length, stale: staleNodes.length, all: allNodes.length }; // 选定 scope 的候选节点集(执行用)+ 语义计数(报告用) const scopeNodes = scope === "missing" ? missingNodes : scope === "stale" ? withVecNodes : allNodes; const scopeCount = scope === "missing" ? stats.missing : scope === "stale" ? stats.stale : stats.all; // hash 短路:只保留需要(重)嵌入的节点 const pendingNodes = this.pendingReembed(scopeNodes); const pending = pendingNodes.length; const estimatedBatches = batchSize > 0 ? Math.ceil(pending / batchSize) : 0; if (dryRun) { return { dryRun: true, scope, batchSize, stats, selected: scopeCount, pending, estimatedBatches, batches: 0, embedded: 0, }; } // 执行:分批 syncEmbedBatch(pending 已短路,每批全待嵌入) let batches = 0; let embedded = 0; for (let i = 0; i < pendingNodes.length; i += batchSize) { const chunk = pendingNodes.slice(i, i + batchSize); await this.syncEmbedBatch(chunk); batches += 1; embedded += chunk.length; } return { dryRun: false, scope, batchSize, stats, selected: scopeCount, pending, estimatedBatches, batches, embedded, }; } /** * nodes 中 hash 不匹配(需要重嵌入)的子集——dry-run 统计 + 执行前短路用,只读不改库。 * 与 syncEmbedBatch 共享 hash 短路逻辑(同 text/fingerprint → md5),确保 dry-run 计数与实际执行一致。 */ private pendingReembed(nodes: GmNode[]): GmNode[] { if (!this.embed && !this.embedBatch) return []; const fp = this.embeddingFingerprint; return nodes.filter(node => { const temporal = Object.keys(node.temporal).length ? `\n时间语义: ${JSON.stringify(node.temporal)}` : ""; const text = `${node.name}: ${node.description}\n${node.content}${temporal}`; const hashInput = fp ? `${fp}\0${text}` : text; const hash = createHash("md5").update(hashInput).digest("hex"); return getVectorHash(this.db, node.id) !== hash; }); } }