/** * graph-memory — 向量近重复检测(dry-run 报告模式)— Task 14 * * 移植自 PR #69 src/graph/dedup.ts @e3b87b0 的语义层。R1 裁决:本轮只产出 * 报告(对、相似度、建议胜者),不自动合并;用户经 Task 13 gm_merge 确认执行。 * * PR vs SQLite 适配: * - PR 用 Neo4j GDS 向量索引(db.index.vector.queryNodes('gm_node_embedding',5,vec)) * 做近邻搜索;SQLite 版替换为同社区内暴力 O(N²) 余弦——社区限制即 GDS 索引的 * 作用域等价(防跨社区误配)。 * - PR DuplicatePair 字段:{ nodeA, nodeB, nameA, nameB, similarity }; * brief 裁定本侧字段为 { nodeA, nodeB, similarity, suggestedWinner, reason }, * 对齐 PR 的 nodeA/nodeB/similarity 命名,以 suggestedWinner/reason 替代 * nameA/nameB + 自动合并(R1 dry-run)。 * - 阈值:PR 取 cfg.dedupThreshold(DEFAULT_CONFIG 默认 0.90);本侧 GmConfig * 暂无 dedupThreshold 字段(未随本任务开放),以模块常量 * DEFAULT_DEDUP_THRESHOLD 钉住,值 = 0.90(PR 对齐)。 * - suggestedWinner:PR 主判 validatedCount 高者 → tie updatedAt 新者; * brief 裁定"validatedCount 高者(不移植内容更长启发式)",本侧照搬 PR 的 * validatedCount 主判 + updatedAt tiebreak,不引入内容长度。 * * 纯读函数:detectDuplicates 不写库(零 INSERT/UPDATE/DELETE)。 */ import type { DatabaseSyncInstance } from "../store/sqlite.ts"; /** 余弦相似度下限;低于此值的配对不报告。对齐 PR DEFAULT_CONFIG.dedupThreshold = 0.90。 */ export const DEFAULT_DEDUP_THRESHOLD = 0.90; /** * dedup 运行时配置。threshold 缺省时取 DEFAULT_DEDUP_THRESHOLD。 * GmConfig 结构兼容本类型(无 threshold 字段时取默认),故 maintenance 可直传 GmConfig。 */ export interface DedupConfig { /** 余弦相似度下限;低于此值的配对不报告。默认 DEFAULT_DEDUP_THRESHOLD (0.90)。 */ threshold?: number; } /** * 一对近重复节点(dry-run 报告条目)。 * nodeA / nodeB / similarity 命名对齐 PR DuplicatePair; * suggestedWinner / reason 为本侧新增(R1:只报告,不自动合并)。 */ export interface DuplicatePair { /** 配对节点 A 的 id(社区内 i b.validated_count) { return [a.id, `validatedCount: ${a.id}=${a.validated_count} > ${b.id}=${b.validated_count}`]; } if (b.validated_count > a.validated_count) { return [b.id, `validatedCount: ${b.id}=${b.validated_count} > ${a.id}=${a.validated_count}`]; } // tie → updatedAt 新者(PR dedup() tiebreak 对齐) const winner = a.updated_at >= b.updated_at ? a : b; return [ winner.id, `validatedCount 相等(${a.validated_count}=${b.validated_count}),updatedAt 新者胜出`, ]; } /** * 检测近重复节点对 — dry-run 报告模式(纯读,零写库)。 * * 对每个有 embedding 且 community_id 非空的 active 节点,在同社区内做暴力 * O(N²) 余弦配对,相似度 ≥ threshold 的入报告;每对仅出现一次(i(); for (const row of rows) { let group = byCommunity.get(row.community_id); if (!group) { group = []; byCommunity.set(row.community_id, group); } group.push(row); } const pairs: DuplicatePair[] = []; for (const group of byCommunity.values()) { if (group.length < 2) continue; // 预解码向量(避免重复解码) const vectors = group.map((row) => decodeEmbedding(row.embedding)); // 暴力 O(N²) 配对,i= threshold) { const [winnerId, reason] = pickWinner(group[i]!, group[j]!); pairs.push({ nodeA: group[i]!.id, nodeB: group[j]!.id, similarity: sim, suggestedWinner: winnerId, reason, }); } } } } // 按相似度降序(PR detectDuplicates 返回前已 sort) pairs.sort((a, b) => b.similarity - a.similarity); return pairs; }