/** * graph-memory * * By: adoresever * Email: Wywelljob@gmail.com */ import { DatabaseSync, type DatabaseSyncInstance } from "./sqlite.ts"; import { createHash } from "crypto"; import type { GmNode, GmEdge, GmNavigationTriple, GmTurnMemory, EdgeType, NodeTemporal, NodeType, TurnOutcome, } from "../types.ts"; // ─── 工具 ───────────────────────────────────────────────────── function uid(p: string): string { return `${p}-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; } function embeddingBlob(vector: number[]): Uint8Array { const values = new Float32Array(vector); return new Uint8Array(values.buffer, values.byteOffset, values.byteLength); } function vectorNorm(vector: Float32Array): number { return Math.sqrt(vector.reduce((sum, value) => sum + value * value, 0)); } function cosineSimilarity(query: Float32Array, queryNorm: number, raw: Uint8Array): number { const vector = new Float32Array(raw.buffer, raw.byteOffset, raw.byteLength / 4); if (vector.length !== query.length) return Number.NEGATIVE_INFINITY; let dot = 0; let candidateSquaredNorm = 0; for (let index = 0; index < query.length; index += 1) { dot += vector[index] * query[index]; candidateSquaredNorm += vector[index] * vector[index]; } return dot / (Math.sqrt(candidateSquaredNorm) * queryNorm + 1e-9); } function toNode(r: any): GmNode { return { id: r.id, type: r.type, name: r.name, description: r.description ?? "", content: r.content, temporal: JSON.parse(r.temporal_json ?? "{}"), status: r.status, validatedCount: r.validated_count, sourceSessions: JSON.parse(r.source_sessions ?? "[]"), communityId: r.community_id ?? null, pagerank: r.pagerank ?? 0, createdAt: r.created_at, updatedAt: r.updated_at, }; } function toEdge(r: any): GmEdge { return { id: r.id, fromId: r.from_id, toId: r.to_id, type: r.type, instruction: r.instruction, condition: r.condition ?? undefined, sessionId: r.session_id, createdAt: r.created_at, }; } /** 标准化 name:全小写,空格转连字符,保留中文 */ function normalizeName(name: string): string { return name.trim().toLowerCase() .replace(/[\s_]+/g, "-") .replace(/[^a-z0-9\u4e00-\u9fff\-]/g, "") .replace(/-{2,}/g, "-") .replace(/^-|-$/g, ""); } // ─── 节点 CRUD ─────────────────────────────────────────────── export function findByName(db: DatabaseSyncInstance, name: string): GmNode | null { const r = db.prepare("SELECT * FROM gm_nodes WHERE name = ?").get(normalizeName(name)) as any; return r ? toNode(r) : null; } export function findById(db: DatabaseSyncInstance, id: string): GmNode | null { const r = db.prepare("SELECT * FROM gm_nodes WHERE id = ?").get(id) as any; return r ? toNode(r) : null; } export function allActiveNodes(db: DatabaseSyncInstance): GmNode[] { return (db.prepare("SELECT * FROM gm_nodes WHERE status='active'").all() as any[]).map(toNode); } export function allEdges(db: DatabaseSyncInstance): GmEdge[] { return (db.prepare("SELECT * FROM gm_edges").all() as any[]).map(toEdge); } export function upsertNode( db: DatabaseSyncInstance, c: { type: NodeType; name: string; description: string; content: string; operation?: "create" | "confirm" | "revise"; temporal?: NodeTemporal; }, sessionId: string, sources: Array<{ messageId: string; turnIndex: number }> = [], ): { node: GmNode; isNew: boolean } { const name = normalizeName(c.name); const ex = findByName(db, name); if (ex) { const sessions = JSON.stringify(Array.from(new Set([...ex.sourceSessions, sessionId]))); // The extractor owns the claim operation. Content length is not evidence // of correctness, so the store must never use it to choose a version. // Only an explicit confirmation preserves the current claim; create and // revise both publish the model's current structured claim as a revision. const replace = c.operation !== "confirm"; const content = replace ? c.content : ex.content; const desc = replace ? c.description : ex.description; const temporal = replace ? (c.temporal ?? {}) : c.temporal && Object.keys(c.temporal).length ? c.temporal : ex.temporal; // A correction is a new claim version, not another validation of the old // claim. Confirmation alone increases confidence. const count = replace ? 1 : ex.validatedCount + 1; if (replace) { const previousSourceRefs = db.prepare(` SELECT session_id, message_id, turn_index FROM gm_node_sources WHERE node_id=? ORDER BY turn_index, message_id `).all(ex.id); db.prepare(`INSERT INTO gm_node_revisions (node_id, previous_description, previous_content, previous_temporal_json, previous_validated_count, previous_source_refs, replacement_session_id, replaced_at) VALUES (?,?,?,?,?,?,?,?)`) .run( ex.id, ex.description, ex.content, JSON.stringify(ex.temporal), ex.validatedCount, JSON.stringify(previousSourceRefs), sessionId, Date.now(), ); // The active node must cite only evidence for its current claim. Older // provenance remains auditable in gm_node_revisions. db.prepare("DELETE FROM gm_node_sources WHERE node_id=?").run(ex.id); } // 重提取成功 = decay 自动弃用节点的复活信号(manual/merge 弃用保留给用户, // revive 守卫只认 deprecated_by='decay')。必须在下面的 UPDATE 之前调用: // UPDATE 无条件把 status 拉回 'active'(既有行为),而 revive 的守卫只匹配 // 仍是 'deprecated' 的 decay 弃用行。 reviveIfDecayDeprecated(db, ex.id); db.prepare(`UPDATE gm_nodes SET content=?, description=?, temporal_json=?, status='active', validated_count=?, source_sessions=?, updated_at=? WHERE id=?`) .run(content, desc, JSON.stringify(temporal), count, sessions, Date.now(), ex.id); saveNodeSources(db, ex.id, sessionId, sources); return { node: { ...ex, content, description: desc, temporal, status: "active", validatedCount: count }, isNew: false }; } const id = uid("n"); db.prepare(`INSERT INTO gm_nodes (id, type, name, description, content, temporal_json, status, validated_count, source_sessions, created_at, updated_at) VALUES (?,?,?,?,?,?,'active',1,?,?,?)`) .run(id, c.type, name, c.description, c.content, JSON.stringify(c.temporal ?? {}), JSON.stringify([sessionId]), Date.now(), Date.now()); const node = findByName(db, name)!; saveNodeSources(db, node.id, sessionId, sources); return { node, isNew: true }; } /** Link one graph node to durable message rows that actually exist. */ export function saveNodeSources( db: DatabaseSyncInstance, nodeId: string, sessionId: string, sources: Array<{ messageId: string; turnIndex: number }>, ): void { const insert = db.prepare(` INSERT OR IGNORE INTO gm_node_sources (node_id, session_id, message_id, turn_index) SELECT ?, ?, id, turn_index FROM gm_messages WHERE id=? `); for (const source of sources) { insert.run(nodeId, sessionId, source.messageId); } } export interface GmNodeSource { nodeId: string; sessionId: string; messageId: string; turnIndex: number; } /** Read exact provenance refs without loading or truncating message content. */ export function getNodeSources( db: DatabaseSyncInstance, nodeIds: string[], ): GmNodeSource[] { if (!nodeIds.length) return []; const placeholders = nodeIds.map(() => "?").join(","); return (db.prepare(` SELECT node_id, session_id, message_id, turn_index FROM gm_node_sources WHERE node_id IN (${placeholders}) ORDER BY node_id, turn_index, message_id `).all(...nodeIds) as any[]).map(row => ({ nodeId: String(row.node_id), sessionId: String(row.session_id), messageId: String(row.message_id), turnIndex: Number(row.turn_index), })); } /** 按 name 精确更新 description / content;找不到返回 null(调用方决定报错语义) */ export function updateNode( db: DatabaseSyncInstance, name: string, patch: { description?: string; content?: string }, ): GmNode | null { const ex = findByName(db, name); if (!ex) return null; const now = Date.now(); const description = patch.description ?? ex.description; const content = patch.content ?? ex.content; db.prepare("UPDATE gm_nodes SET description=?, content=?, updated_at=? WHERE id=?") .run(description, content, now, ex.id); return { ...ex, description, content, updatedAt: now }; } export function deprecate( db: DatabaseSyncInstance, nodeId: string, temporalState: "historical" | "superseded" = "historical", ): void { const node = findById(db, nodeId); if (!node) return; const temporal = { ...node.temporal, state: temporalState }; db.prepare("UPDATE gm_nodes SET status='deprecated', temporal_json=?, updated_at=? WHERE id=?") .run(JSON.stringify(temporal), Date.now(), nodeId); } /** 批量更新 PageRank 分数 */ export function updatePageranks(db: DatabaseSyncInstance, scores: Map): void { const stmt = db.prepare("UPDATE gm_nodes SET pagerank=? WHERE id=?"); db.exec("BEGIN"); try { for (const [id, score] of scores) { stmt.run(score, id); } db.exec("COMMIT"); } catch (e) { db.exec("ROLLBACK"); throw e; } } /** 批量更新社区 ID */ export function updateCommunities(db: DatabaseSyncInstance, labels: Map): void { const stmt = db.prepare("UPDATE gm_nodes SET community_id=? WHERE id=?"); db.exec("BEGIN"); try { for (const [id, cid] of labels) { stmt.run(cid, id); } db.exec("COMMIT"); } catch (e) { db.exec("ROLLBACK"); throw e; } } // ─── 边 CRUD ───────────────────────────────────────────────── export function upsertEdge( db: DatabaseSyncInstance, e: { fromId: string; toId: string; type: EdgeType; instruction: string; condition?: string; sessionId: string }, ): void { const ex = db.prepare("SELECT id FROM gm_edges WHERE from_id=? AND to_id=? AND type=?") .get(e.fromId, e.toId, e.type) as any; if (ex) { db.prepare("UPDATE gm_edges SET instruction=?, condition=?, session_id=? WHERE id=?") .run(e.instruction, e.condition ?? null, e.sessionId, ex.id); return; } db.prepare(`INSERT INTO gm_edges (id, from_id, to_id, type, instruction, condition, session_id, created_at) VALUES (?,?,?,?,?,?,?,?)`) .run(uid("e"), e.fromId, e.toId, e.type, e.instruction, e.condition ?? null, e.sessionId, Date.now()); // 新边写入路径:两端节点发生相关性活动(touch 刷新 last_accessed_at), // decay 自动弃用的端点借此复活(manual/merge 弃用不复活——守卫只认 'decay')。 // 仅 INSERT 分支接线:既有边的 UPDATE 是重申而非新提及,且 decay 弃用节点 // 已被断联,不存在"既有边触达 decay 弃用端点"的路径。 touchNodes(db, [e.fromId, e.toId]); reviveIfDecayDeprecated(db, e.fromId); reviveIfDecayDeprecated(db, e.toId); } export function edgesFrom(db: DatabaseSyncInstance, id: string): GmEdge[] { return (db.prepare("SELECT * FROM gm_edges WHERE from_id=?").all(id) as any[]).map(toEdge); } export function edgesTo(db: DatabaseSyncInstance, id: string): GmEdge[] { return (db.prepare("SELECT * FROM gm_edges WHERE to_id=?").all(id) as any[]).map(toEdge); } // ─── FTS5 搜索 ─────────────────────────────────────────────── // FTS support belongs to a concrete connection. A process-global boolean is // incorrect when multiple host profiles use different SQLite builds or when // tests/DSH fibers own independent databases. const fts5Availability = new WeakMap(); function fts5Available(db: DatabaseSyncInstance): boolean { const cached = fts5Availability.get(db as object); if (cached !== undefined) return cached; try { db.prepare("SELECT * FROM gm_nodes_fts LIMIT 0").all(); fts5Availability.set(db as object, true); return true; } catch { fts5Availability.set(db as object, false); return false; } } export function searchNodes( db: DatabaseSyncInstance, query: string, limit = 6, withoutTurnMemory = false, ): GmNode[] { const terms = Array.from(new Set(query.trim().split(/\s+/).filter(Boolean))); if (!terms.length) { // 召回命中 touch:空查询的 topNodes 兜底命中同样是相关性活动。 const results = topNodes(db, limit); touchNodes(db, results.map(node => node.id)); return results; } if (fts5Available(db)) { try { const ftsQuery = terms.map(t => `"${t.replace(/"/g, "")}"`).join(" OR "); const rows = db.prepare(` SELECT n.*, rank FROM gm_nodes_fts fts JOIN gm_nodes n ON n.rowid = fts.rowid WHERE gm_nodes_fts MATCH ? AND n.status = 'active' ${withoutTurnMemory ? `AND NOT EXISTS ( SELECT 1 FROM gm_node_sources node_source JOIN gm_turn_memory_sources memory_source ON memory_source.message_id=node_source.message_id WHERE node_source.node_id=n.id )` : ""} ORDER BY rank LIMIT ? `).all(ftsQuery, limit) as any[]; if (rows.length > 0) { const results = rows.map(toNode); touchNodes(db, results.map(node => node.id)); return results; } } catch { /* FTS 查询失败,降级 */ } } const where = terms.map(() => "(name LIKE ? OR description LIKE ? OR content LIKE ?)").join(" OR "); const likes = terms.flatMap(t => [`%${t}%`, `%${t}%`, `%${t}%`]); const results = (db.prepare(` SELECT * FROM gm_nodes n WHERE status='active' AND (${where}) ${withoutTurnMemory ? `AND NOT EXISTS ( SELECT 1 FROM gm_node_sources node_source JOIN gm_turn_memory_sources memory_source ON memory_source.message_id=node_source.message_id WHERE node_source.node_id=n.id )` : ""} ORDER BY pagerank DESC, validated_count DESC, updated_at DESC LIMIT ? `).all(...likes, limit) as any[]).map(toNode); touchNodes(db, results.map(node => node.id)); return results; } /** 热门节点:综合 pagerank + validatedCount 排序 */ export function topNodes(db: DatabaseSyncInstance, limit = 6): GmNode[] { return (db.prepare(` SELECT * FROM gm_nodes WHERE status='active' ORDER BY pagerank DESC, validated_count DESC, updated_at DESC LIMIT ? `).all(limit) as any[]).map(toNode); } // ─── 递归 CTE 图遍历 ──────────────────────────────────────── export function graphWalk( db: DatabaseSyncInstance, seedIds: string[], maxDepth: number, ): { nodes: GmNode[]; edges: GmEdge[] } { if (!seedIds.length) return { nodes: [], edges: [] }; const placeholders = seedIds.map(() => "?").join(","); const walkRows = db.prepare(` WITH RECURSIVE walk(node_id, depth) AS ( SELECT id, 0 FROM gm_nodes WHERE id IN (${placeholders}) AND status='active' UNION SELECT CASE WHEN e.from_id = w.node_id THEN e.to_id ELSE e.from_id END, w.depth + 1 FROM walk w JOIN gm_edges e ON (e.from_id = w.node_id OR e.to_id = w.node_id) WHERE w.depth < ? ) SELECT DISTINCT node_id FROM walk `).all(...seedIds, maxDepth) as any[]; const nodeIds = walkRows.map((r: any) => r.node_id); if (!nodeIds.length) return { nodes: [], edges: [] }; const np = nodeIds.map(() => "?").join(","); const nodes = (db.prepare(` SELECT * FROM gm_nodes WHERE id IN (${np}) AND status='active' `).all(...nodeIds) as any[]).map(toNode); const edges = (db.prepare(` SELECT * FROM gm_edges WHERE from_id IN (${np}) AND to_id IN (${np}) `).all(...nodeIds, ...nodeIds) as any[]).map(toEdge); return { nodes, edges }; } // ─── 按 session 查询 ──────────────────────────────────────── export function getBySession(db: DatabaseSyncInstance, sessionId: string): GmNode[] { return (db.prepare(` SELECT DISTINCT n.* FROM gm_nodes n, json_each(n.source_sessions) j WHERE j.value = ? AND n.status = 'active' `).all(sessionId) as any[]).map(toNode); } /** * Nodes supported by the current session's recent completed turns. * The turn window follows the host's visible-history policy; it is not a * second node-count cap and therefore keeps every concept extracted per turn. */ export function getRecentBySession( db: DatabaseSyncInstance, sessionId: string, currentTurn: number, turnCount: number, ): GmNode[] { const firstTurn = Math.max(0, currentTurn - turnCount); return (db.prepare(` SELECT DISTINCT n.* FROM gm_nodes n JOIN gm_node_sources s ON s.node_id=n.id WHERE n.status='active' AND s.session_id=? AND s.turn_index>=? AND s.turn_index 0; } /** * Read the oldest pending completed turn as one semantic extraction job. * No character/message batching is involved: the DSH adapter persists exactly * one user question and one final assistant answer for each completed turn. */ export function getNextUnextractedTurn( db: DatabaseSyncInstance, sid: string, completedTurn: number, ): any[] { const next = db.prepare(` SELECT MIN(turn_index) AS turn_index FROM gm_messages WHERE session_id=? AND extracted=0 AND extraction_state='pending' AND turn_index<=? `).get(sid, completedTurn) as { turn_index?: number | null } | undefined; if (next?.turn_index === null || next?.turn_index === undefined) return []; return db.prepare(` SELECT * FROM gm_messages WHERE session_id=? AND turn_index=? AND extracted=0 AND extraction_state='pending' ORDER BY rowid `).all(sid, Number(next.turn_index)) as any[]; } /** * Read one exact completed turn. Live DSH extraction uses this path so an * unrelated legacy backlog can never be pulled into a foreground session. * Historical retries deliberately use getNextUnextractedTurn instead. */ export function getUnextractedTurn( db: DatabaseSyncInstance, sid: string, turn: number, ): any[] { if (!Number.isInteger(turn) || turn < 1) return []; return db.prepare(` SELECT * FROM gm_messages WHERE session_id=? AND turn_index=? AND extracted=0 AND extraction_state='pending' ORDER BY rowid `).all(sid, turn) as any[]; } /** Persist the highest DSH/OpenClaw turn known to be complete. */ export function markExtractionTurnCompleted( db: DatabaseSyncInstance, sid: string, completedTurn: number, ): void { if (!Number.isFinite(completedTurn)) return; db.prepare(` INSERT INTO gm_extraction_sessions (session_id, completed_turn, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET completed_turn=MAX(completed_turn, excluded.completed_turn), updated_at=excluded.updated_at `).run(sid, completedTurn, Date.now()); } export function getExtractionCompletedTurn( db: DatabaseSyncInstance, sid: string, ): number | null { const row = db.prepare(` SELECT completed_turn FROM gm_extraction_sessions WHERE session_id=? `).get(sid) as { completed_turn?: number } | undefined; return row?.completed_turn === undefined ? null : Number(row.completed_turn); } function messageIdPlaceholders(ids: string[]): string { return ids.map(() => "?").join(","); } /** * Mark only the source rows actually accepted by the extractor. * * producedKnowledge:该轮提取是否实际固化导航三元组(本地"产出"= 三元组落库)。 * LLM 成功返回但零三元组时传 false——原始消息是将来补偿重挖的唯一原料, * retention 的 referenced 模式只退役 produced_knowledge=1 的行;recent 模式 * 不受此标记约束。默认 true 保持既有调用方的 legacy 语义不变。 */ export function markMessagesExtracted( db: DatabaseSyncInstance, ids: string[], producedKnowledge: boolean = true, ): number { if (!ids.length) return 0; const result = db.prepare(` UPDATE gm_messages SET extracted=1, extraction_state='succeeded', extraction_error=NULL, extraction_next_retry_at=NULL, extraction_updated_at=?, produced_knowledge=? WHERE id IN (${messageIdPlaceholders(ids)}) AND extraction_state='pending' `).run(Date.now(), producedKnowledge ? 1 : 0, ...ids); return Number(result.changes); } export function recordExtractionFailure( db: DatabaseSyncInstance, ids: string[], error: string, nextRetryAt: number | null, ): number { if (!ids.length) return 0; const result = db.prepare(` UPDATE gm_messages SET extraction_attempts=extraction_attempts+1, extraction_error=?, extraction_next_retry_at=?, extraction_updated_at=? WHERE id IN (${messageIdPlaceholders(ids)}) AND extraction_state='pending' `).run(error.slice(0, 2_000), nextRetryAt, Date.now(), ...ids); return Number(result.changes); } /** A poison message remains durable and explicitly unlearned until retried. */ export function quarantineMessages(db: DatabaseSyncInstance, ids: string[], error: string): number { if (!ids.length) return 0; const result = db.prepare(` UPDATE gm_messages SET extracted=0, extraction_state='quarantined', extraction_error=?, extraction_next_retry_at=NULL, extraction_updated_at=? WHERE id IN (${messageIdPlaceholders(ids)}) AND extraction_state='pending' `).run(error.slice(0, 2_000), Date.now(), ...ids); return Number(result.changes); } export function requeueQuarantined(db: DatabaseSyncInstance, sid?: string): number { const result = sid ? db.prepare(` UPDATE gm_messages SET extraction_state='pending', extraction_attempts=0, extraction_error=NULL, extraction_next_retry_at=NULL, extraction_updated_at=? WHERE extraction_state='quarantined' AND session_id=? `).run(Date.now(), sid) : db.prepare(` UPDATE gm_messages SET extraction_state='pending', extraction_attempts=0, extraction_error=NULL, extraction_next_retry_at=NULL, extraction_updated_at=? WHERE extraction_state='quarantined' `).run(Date.now()); return Number(result.changes); } export function getExtractionStats(db: DatabaseSyncInstance): { pending: number; succeeded: number; quarantined: number; } { const rows = db.prepare(` SELECT extraction_state AS state, COUNT(*) AS count FROM gm_messages GROUP BY extraction_state `).all() as Array<{ state: string; count: number }>; const result = { pending: 0, succeeded: 0, quarantined: 0 }; for (const row of rows) { if (row.state in result) (result as any)[row.state] = Number(row.count); } return result; } export function getPendingSessionIds(db: DatabaseSyncInstance, limit: number = 100): string[] { return (db.prepare(` SELECT session_id, MIN(turn_index) AS first_turn FROM gm_messages WHERE extracted=0 AND extraction_state='pending' AND (extraction_next_retry_at IS NULL OR extraction_next_retry_at<=?) GROUP BY session_id ORDER BY first_turn, session_id LIMIT ? `).all(Date.now(), limit) as Array<{ session_id: string }>).map(row => row.session_id); } /** Read exact durable message evidence for one node, in source order. */ export function getNodeSourceMessages( db: DatabaseSyncInstance, nodeId: string, excludedMessageIds: ReadonlySet = new Set(), ): Array<{ sessionId: string; turnIndex: number; role: string; text: string; createdAt: number }> { const rows = db.prepare(` SELECT s.message_id, s.session_id, s.turn_index, m.role, m.content, m.created_at FROM gm_node_sources s JOIN gm_messages m ON m.id=s.message_id WHERE s.node_id=? ORDER BY s.turn_index, m.created_at `).all(nodeId) as any[]; const results: Array<{ sessionId: string; turnIndex: number; role: string; text: string; createdAt: number }> = []; for (const row of rows) { if (excludedMessageIds.has(String(row.message_id))) continue; let text = ""; try { text = extractStoredText(JSON.parse(row.content)); } catch { text = String(row.content); } if (!text.trim()) continue; results.push({ sessionId: row.session_id, turnIndex: row.turn_index, role: row.role, text, createdAt: row.created_at, }); } return results; } /** Read text from legacy OpenClaw payloads and DSH block-based messages. */ export function extractStoredText(value: unknown): string { if (typeof value === "string") return value; if (Array.isArray(value)) return value.map(extractStoredText).filter(Boolean).join("\n"); if (!value || typeof value !== "object") return ""; const record = value as Record; if (record.type === "text" && typeof record.text === "string") { return record.text; } // Typed non-text blocks are reasoning/tool protocol data, not user-visible // evidence. Do not recurse into their payloads. if (typeof record.type === "string") return ""; if (record.content !== undefined) return extractStoredText(record.content); if (record.message !== undefined) return extractStoredText(record.message); return ""; } // ─── 分层轮次记忆 ────────────────────────────────────────── function toTurnMemory(db: DatabaseSyncInstance, row: any): GmTurnMemory { const sources = (db.prepare(` SELECT message_id, turn_index FROM gm_turn_memory_sources WHERE memory_id=? ORDER BY source_order `).all(row.id) as any[]).map(source => ({ messageId: String(source.message_id), turnIndex: Number(source.turn_index), })); return { id: String(row.id), sessionId: String(row.session_id), summary: String(row.summary), outcome: row.outcome as TurnOutcome, sources, createdAt: Number(row.created_at), updatedAt: Number(row.updated_at), }; } function turnMemoryId(sessionId: string, sources: Array<{ messageId: string }>): string { const sourceKey = sources.map(source => source.messageId).sort().join("\0"); const digest = createHash("sha256").update(`${sessionId}\0${sourceKey}`).digest("hex"); return `tm-${digest.slice(0, 32)}`; } function normalizedNavigationTerm(text: string): string { return text.trim().replace(/\s+/g, " ").toLocaleLowerCase(); } function navigationTermId(normalized: string): string { return `nt-${createHash("sha256").update(normalized).digest("hex").slice(0, 32)}`; } function navigationTripleId(memoryId: string, subjectId: string, predicate: string, objectId: string): string { const key = `${memoryId}\0${subjectId}\0${predicate.trim()}\0${objectId}`; return `tr-${createHash("sha256").update(key).digest("hex").slice(0, 32)}`; } /** Store one compact index while retaining exact message provenance. */ export function upsertTurnMemory( db: DatabaseSyncInstance, input: { sessionId: string; summary: string; outcome: TurnOutcome; sources: Array<{ messageId: string; turnIndex: number }>; }, ): GmTurnMemory { if (!input.sources.length) throw new Error("turn memory requires at least one durable source message"); const id = turnMemoryId(input.sessionId, input.sources); const now = Date.now(); db.prepare(` INSERT INTO gm_turn_memories (id, session_id, summary, outcome, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET summary=excluded.summary, outcome=excluded.outcome, updated_at=excluded.updated_at `).run(id, input.sessionId, input.summary, input.outcome, now, now); const link = db.prepare(` INSERT OR IGNORE INTO gm_turn_memory_sources (memory_id, message_id, turn_index, source_order) SELECT ?, id, turn_index, ? FROM gm_messages WHERE id=? `); input.sources.forEach((source, index) => link.run(id, index, source.messageId)); const row = db.prepare("SELECT * FROM gm_turn_memories WHERE id=?").get(id); return toTurnMemory(db, row); } export function getTurnMemoriesByIds( db: DatabaseSyncInstance, ids: string[], ): GmTurnMemory[] { const memories: GmTurnMemory[] = []; const statement = db.prepare("SELECT * FROM gm_turn_memories WHERE id=?"); for (const id of ids) { const row = statement.get(id); if (row) memories.push(toTurnMemory(db, row)); } return memories; } /** * Recent summaries are reference-resolution context, not extraction evidence. * `beforeTurn` prevents the current Q/A pair from feeding itself on retries. */ export function getRecentTurnMemoriesBySession( db: DatabaseSyncInstance, sessionId: string, beforeTurn: number, limit: number, ): GmTurnMemory[] { if (!Number.isFinite(beforeTurn) || limit <= 0) return []; const rows = db.prepare(` SELECT tm.* FROM gm_turn_memories tm WHERE tm.session_id=? AND NOT EXISTS ( SELECT 1 FROM gm_turn_memory_sources source WHERE source.memory_id=tm.id AND source.turn_index>=? ) ORDER BY ( SELECT MAX(source.turn_index) FROM gm_turn_memory_sources source WHERE source.memory_id=tm.id ) DESC, tm.updated_at DESC, tm.id LIMIT ? `).all(sessionId, beforeTurn, limit) as any[]; return rows.map(row => toTurnMemory(db, row)).reverse(); } function upsertNavigationTerm(db: DatabaseSyncInstance, text: string): string { const display = text.trim().replace(/\s+/g, " "); const normalized = normalizedNavigationTerm(display); if (!normalized) throw new TypeError("navigation term must not be empty"); const id = navigationTermId(normalized); const now = Date.now(); db.prepare(` INSERT INTO gm_navigation_terms (id, normalized, display_text, community_id, created_at, updated_at) VALUES (?, ?, ?, NULL, ?, ?) ON CONFLICT(normalized) DO UPDATE SET display_text=excluded.display_text, updated_at=excluded.updated_at `).run(id, normalized, display, now, now); return id; } /** * Atomically replace the navigation generated for one compact turn. The * model's subject/predicate/object values are stored verbatim after whitespace * normalization; the host applies no semantic gate or inferred relation. */ export function replaceNavigationTriples( db: DatabaseSyncInstance, memory: GmTurnMemory, triples: Array<{ subject: string; predicate: string; object: string }>, ): void { db.exec("BEGIN"); try { db.prepare("DELETE FROM gm_navigation_triples WHERE memory_id=?").run(memory.id); const insert = db.prepare(` INSERT OR IGNORE INTO gm_navigation_triples (id, memory_id, session_id, subject_id, predicate, object_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) `); for (const triple of triples) { const subjectId = upsertNavigationTerm(db, triple.subject); const objectId = upsertNavigationTerm(db, triple.object); const predicate = triple.predicate.trim().replace(/\s+/g, " "); if (!predicate) throw new TypeError("navigation predicate must not be empty"); insert.run( navigationTripleId(memory.id, subjectId, predicate, objectId), memory.id, memory.sessionId, subjectId, predicate, objectId, Date.now(), ); } db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } /** Return navigation in the same memory-relevance order supplied by recall. */ export function getNavigationTriplesForMemories( db: DatabaseSyncInstance, memoryIds: string[], termScores?: ReadonlyMap, ): GmNavigationTriple[] { if (!memoryIds.length) return []; const query = db.prepare(` SELECT triple.*, subject.display_text AS subject, subject.community_id AS subject_community_id, object.display_text AS object, object.community_id AS object_community_id FROM gm_navigation_triples triple JOIN gm_navigation_terms subject ON subject.id=triple.subject_id JOIN gm_navigation_terms object ON object.id=triple.object_id WHERE triple.memory_id=? ORDER BY triple.created_at, triple.id `); return memoryIds.flatMap(memoryId => { const triples = (query.all(memoryId) as any[]).map(row => ({ id: String(row.id), memoryId: String(row.memory_id), sessionId: String(row.session_id), subjectId: String(row.subject_id), subject: String(row.subject), predicate: String(row.predicate), objectId: String(row.object_id), object: String(row.object), subjectCommunityId: row.subject_community_id ? String(row.subject_community_id) : null, objectCommunityId: row.object_community_id ? String(row.object_community_id) : null, createdAt: Number(row.created_at), } satisfies GmNavigationTriple)); if (!termScores?.size || triples.length < 2) return triples; // A selected source memory may contain many facts. Send only the edge(s) // that best explain this query-time graph route; the complete original Q/A // remains the factual evidence and is never shortened here. const relevance = triples.map(triple => { const subject = termScores.get(triple.subjectId) ?? 0; const object = termScores.get(triple.objectId) ?? 0; return { triple, connected: subject > 0 && object > 0, score: subject > 0 && object > 0 ? Math.sqrt(subject * object) : Math.max(subject, object), }; }); const connected = relevance.some(candidate => candidate.connected); const eligible = connected ? relevance.filter(candidate => candidate.connected) : relevance; const best = Math.max(...eligible.map(candidate => candidate.score)); return eligible .filter(candidate => candidate.score === best) .map(candidate => candidate.triple); }); } /** * Resolve query seeds from the compact SPO index without another model call. * Summary vectors handle paraphrases; this path deliberately handles literal * entity/attribute mentions and preserves the graph's exact vocabulary. */ export function findNavigationSeedTermIds( db: DatabaseSyncInstance, query: string, memoryIds: string[] = [], ): string[] { const normalizedQuery = normalizedNavigationTerm(query); const seeds: string[] = []; const seen = new Set(); const append = (id: string) => { if (seen.has(id)) return; seen.add(id); seeds.push(id); }; if (normalizedQuery) { const rows = db.prepare( "SELECT id, normalized FROM gm_navigation_terms ORDER BY updated_at DESC, id", ).all() as Array<{ id: string; normalized: string }>; const literalMatches = rows.filter(row => normalizedQuery.includes(row.normalized) || row.normalized.includes(normalizedQuery) ); // Prefer the most specific stored phrase. If both "ReleaseOrchestrator" // and "ReleaseOrchestrator addService" match, the shorter hub must not // expand unrelated memories. Independent terms remain separate seeds. for (const row of literalMatches) { const isContainedByMoreSpecificMatch = literalMatches.some(other => other.id !== row.id && other.normalized.length > row.normalized.length && other.normalized.includes(row.normalized) ); if (!isContainedByMoreSpecificMatch) append(String(row.id)); } } // Literal entity/attribute evidence is the strongest routing signal. Only // fall back to endpoints from semantically matched summaries when the user // phrased the question differently from every stored navigation term. if (!seeds.length && memoryIds.length) { const statement = db.prepare(` SELECT subject_id, object_id FROM gm_navigation_triples WHERE memory_id=? ORDER BY created_at, id `); for (const memoryId of memoryIds) { for (const row of statement.all(memoryId) as any[]) { append(String(row.subject_id)); append(String(row.object_id)); } } } return seeds; } /** * A community is a local candidate scope, never prompt content by itself. * When fresh terms have not been assigned yet, the complete compact graph is * still cheap enough for query-time PPR and avoids a false negative. */ export function navigationCandidateTermIds( db: DatabaseSyncInstance, seedIds: string[], ): string[] { if (!seedIds.length) return []; const communityStatement = db.prepare( "SELECT community_id FROM gm_navigation_terms WHERE id=?", ); const communities = new Set(); for (const seedId of seedIds) { const row = communityStatement.get(seedId) as { community_id?: string | null } | undefined; if (row?.community_id) communities.add(String(row.community_id)); } if (!communities.size) { return (db.prepare("SELECT id FROM gm_navigation_terms ORDER BY id").all() as any[]) .map(row => String(row.id)); } const candidates = new Set(seedIds); const statement = db.prepare( "SELECT id FROM gm_navigation_terms WHERE community_id=? ORDER BY id", ); for (const community of communities) { for (const row of statement.all(community) as any[]) candidates.add(String(row.id)); } return Array.from(candidates); } /** Map query-local graph relevance back to the exact dialogue evidence. */ export function rankTurnMemoryIdsByNavigation( db: DatabaseSyncInstance, termScores: ReadonlyMap, ): string[] { if (!termScores.size) return []; const scores = new Map(); const rows = db.prepare(` SELECT memory_id, subject_id, object_id FROM gm_navigation_triples ORDER BY created_at, id `).all() as Array<{ memory_id: string; subject_id: string; object_id: string }>; for (const row of rows) { // Max endpoint relevance prevents a verbose turn with many triples from // outranking a concise turn solely because it emitted more graph edges. const score = Math.max( termScores.get(String(row.subject_id)) ?? 0, termScores.get(String(row.object_id)) ?? 0, ); const memoryId = String(row.memory_id); if (score > (scores.get(memoryId) ?? 0)) scores.set(memoryId, score); } return Array.from(scores) .filter(([, score]) => score > 0) .sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0])) .map(([memoryId]) => memoryId); } export function updateNavigationCommunities( db: DatabaseSyncInstance, labels: Map, ): void { const statement = db.prepare("UPDATE gm_navigation_terms SET community_id=? WHERE id=?"); db.exec("BEGIN"); try { for (const [id, communityId] of labels) statement.run(communityId, id); db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } export function hasTurnMemories(db: DatabaseSyncInstance): boolean { return Number((db.prepare("SELECT COUNT(*) AS count FROM gm_turn_memories").get() as any)?.count ?? 0) > 0; } /** Lexical fallback for hosts without a working embedding provider. */ export function searchTurnMemories( db: DatabaseSyncInstance, query: string, limit: number, ): GmTurnMemory[] { const phrase = query.trim().replace(/\s+/g, " "); if (!phrase) return []; // Semantic search handles paraphrases. The lexical fallback deliberately // requires the complete phrase; OR-ing common words such as "is"/"the" // turns a fallback into another source of unrelated prompt injection. const rows = db.prepare(` SELECT * FROM gm_turn_memories WHERE summary LIKE ? ORDER BY updated_at DESC LIMIT ? `).all(`%${phrase}%`, limit) as any[]; return rows.map(row => toTurnMemory(db, row)); } export function saveTurnVector( db: DatabaseSyncInstance, memoryId: string, content: string, vec: number[], ): void { const hash = createHash("md5").update(content).digest("hex"); db.prepare(` INSERT INTO gm_turn_vectors (memory_id, content_hash, embedding) VALUES (?, ?, ?) ON CONFLICT(memory_id) DO UPDATE SET content_hash=excluded.content_hash, embedding=excluded.embedding `).run(memoryId, hash, embeddingBlob(vec)); } export function getTurnVectorHash(db: DatabaseSyncInstance, memoryId: string): string | null { return (db.prepare("SELECT content_hash FROM gm_turn_vectors WHERE memory_id=?").get(memoryId) as any) ?.content_hash ?? null; } export type ScoredTurnMemory = { memory: GmTurnMemory; score: number }; export function turnMemoryVectorSearchWithScore( db: DatabaseSyncInstance, queryVec: number[], limit: number, minScore: number, ): ScoredTurnMemory[] { const rows = db.prepare(` SELECT v.embedding, m.* FROM gm_turn_vectors v JOIN gm_turn_memories m ON m.id=v.memory_id `).all() as any[]; if (!rows.length) return []; const query = new Float32Array(queryVec); const queryNorm = vectorNorm(query); if (queryNorm === 0) return []; return rows.map(row => ({ memory: toTurnMemory(db, row), score: cosineSimilarity(query, queryNorm, row.embedding as Uint8Array), })).filter(result => result.score >= minScore) .sort((left, right) => right.score - left.score) .slice(0, limit); } /** Resolve graph navigation nodes whose evidence belongs to matched turns. */ export function nodesForTurnMemories( db: DatabaseSyncInstance, memoryIds: string[], limit: number, ): GmNode[] { const results: GmNode[] = []; const seen = new Set(); const statement = db.prepare(` SELECT DISTINCT n.* FROM gm_turn_memory_sources memory_source JOIN gm_node_sources node_source ON node_source.message_id=memory_source.message_id JOIN gm_nodes n ON n.id=node_source.node_id WHERE memory_source.memory_id=? AND n.status='active' ORDER BY n.updated_at DESC `); for (const memoryId of memoryIds) { for (const row of statement.all(memoryId) as any[]) { if (seen.has(row.id)) continue; seen.add(row.id); results.push(toNode(row)); if (results.length >= limit) return results; } } return results; } /** Read exact Q/A evidence for matched compact memories. */ export function getTurnMemorySourceMessages( db: DatabaseSyncInstance, memoryId: string, excludedMessageIds: ReadonlySet = new Set(), ): Array<{ sessionId: string; turnIndex: number; role: string; text: string; createdAt: number }> { const rows = db.prepare(` SELECT m.id, tm.session_id, source.turn_index, m.role, m.content, m.created_at FROM gm_turn_memory_sources source JOIN gm_turn_memories tm ON tm.id=source.memory_id JOIN gm_messages m ON m.id=source.message_id WHERE source.memory_id=? ORDER BY source.source_order `).all(memoryId) as any[]; return rows.flatMap(row => { if (excludedMessageIds.has(String(row.id))) return []; let text = ""; try { text = extractStoredText(JSON.parse(row.content)); } catch { text = String(row.content); } return text.trim() ? [{ sessionId: String(row.session_id), turnIndex: Number(row.turn_index), role: String(row.role), text, createdAt: Number(row.created_at), }] : []; }); } // ─── 统计 ──────────────────────────────────────────────────── export function getStats(db: DatabaseSyncInstance): { totalNodes: number; byType: Record; totalEdges: number; byEdgeType: Record; communities: number; turnMemories: number; navigationTerms: number; navigationTriples: number; navigationCommunities: number; } { const totalNodes = (db.prepare("SELECT COUNT(*) as c FROM gm_nodes WHERE status='active'").get() as any).c; const byType: Record = {}; for (const r of db.prepare("SELECT type, COUNT(*) as c FROM gm_nodes WHERE status='active' GROUP BY type").all() as any[]) { byType[r.type] = r.c; } const totalEdges = (db.prepare("SELECT COUNT(*) as c FROM gm_edges").get() as any).c; const byEdgeType: Record = {}; for (const r of db.prepare("SELECT type, COUNT(*) as c FROM gm_edges GROUP BY type").all() as any[]) { byEdgeType[r.type] = r.c; } const communities = (db.prepare( "SELECT COUNT(DISTINCT community_id) as c FROM gm_nodes WHERE status='active' AND community_id IS NOT NULL" ).get() as any).c; const turnMemories = Number((db.prepare("SELECT COUNT(*) AS c FROM gm_turn_memories").get() as any).c); const navigationTerms = Number((db.prepare("SELECT COUNT(*) AS c FROM gm_navigation_terms").get() as any).c); const navigationTriples = Number((db.prepare("SELECT COUNT(*) AS c FROM gm_navigation_triples").get() as any).c); const navigationCommunities = Number((db.prepare( "SELECT COUNT(DISTINCT community_id) AS c FROM gm_navigation_terms WHERE community_id IS NOT NULL", ).get() as any).c); return { totalNodes, byType, totalEdges, byEdgeType, communities, turnMemories, navigationTerms, navigationTriples, navigationCommunities, }; } // ─── 向量存储 + 搜索 ──────────────────────────────────────── export function saveVector(db: DatabaseSyncInstance, nodeId: string, content: string, vec: number[]): void { const hash = createHash("md5").update(content).digest("hex"); db.prepare(`INSERT INTO gm_vectors (node_id, content_hash, embedding) VALUES (?,?,?) ON CONFLICT(node_id) DO UPDATE SET content_hash=excluded.content_hash, embedding=excluded.embedding`) .run(nodeId, hash, embeddingBlob(vec)); } export function getVectorHash(db: DatabaseSyncInstance, nodeId: string): string | null { return (db.prepare("SELECT content_hash FROM gm_vectors WHERE node_id=?").get(nodeId) as any)?.content_hash ?? null; } export function getVectorStats(db: DatabaseSyncInstance): { count: number; dimensions: number[] } { const count = Number((db.prepare("SELECT COUNT(*) AS c FROM gm_vectors").get() as any)?.c ?? 0); const rows = db.prepare("SELECT embedding FROM gm_vectors").all() as Array<{ embedding: Uint8Array }>; const dimensions = [...new Set(rows.map((row) => row.embedding.byteLength / 4))].sort((a, b) => a - b); return { count, dimensions }; } export type ScoredNode = { node: GmNode; score: number }; export function vectorSearchWithScore( db: DatabaseSyncInstance, queryVec: number[], limit: number, minScore?: number, withoutTurnMemory = false, ): ScoredNode[] { const rows = db.prepare(` SELECT v.node_id, v.embedding, n.* FROM gm_vectors v JOIN gm_nodes n ON n.id = v.node_id WHERE n.status = 'active' ${withoutTurnMemory ? `AND NOT EXISTS ( SELECT 1 FROM gm_node_sources node_source JOIN gm_turn_memory_sources memory_source ON memory_source.message_id=node_source.message_id WHERE node_source.node_id=n.id )` : ""} `).all() as any[]; if (!rows.length) return []; const q = new Float32Array(queryVec); const qNorm = vectorNorm(q); if (qNorm === 0) return []; const scored = rows .map(row => ({ score: cosineSimilarity(q, qNorm, row.embedding as Uint8Array), node: toNode(row), })) .filter(s => minScore === undefined || s.score >= minScore) .sort((a, b) => b.score - a.score) .slice(0, limit); // 召回命中 touch:向量召回命中的节点同样记录相关性活动。 touchNodes(db, scored.map(entry => entry.node.id)); return scored; } /** 兼容旧接口 */ export function vectorSearch(db: DatabaseSyncInstance, queryVec: number[], limit: number, minScore?: number): GmNode[] { return vectorSearchWithScore(db, queryVec, limit, minScore).map(s => s.node); } /** * 社区种子总数护栏(PR #69 totalLimit 语义的本地默认值): * 社区很多时每社区 perCommunity 个代表会被放大成无界种子集, * graphWalk 复杂度随之失控。生产调用方应传本常量作为 totalLimit; * 不传 totalLimit 时行为与历史版本完全一致(不截断)。 */ export const DEFAULT_COMMUNITY_SEED_LIMIT = 64; /** * 社区代表节点:每个社区取最近更新的 topN 个节点 * 用于泛化召回 —— 用户问"做了哪些工作"时按领域返回概览 * totalLimit:按社区顺序(新→旧)与社区内 rank 截断总种子数(PR #69 移植), * 防社区很多时种子无上限放大把 graphWalk 拖成准全图扫描; * 不传时行为与历史版本完全一致(不截断)。 */ export function communityRepresentatives(db: DatabaseSyncInstance, perCommunity = 2, totalLimit?: number): GmNode[] { const rows = db.prepare(` SELECT * FROM gm_nodes WHERE status = 'active' AND community_id IS NOT NULL ORDER BY community_id, updated_at DESC `).all() as any[]; const byCommunity = new Map(); for (const r of rows) { const node = toNode(r); const cid = r.community_id as string; if (!byCommunity.has(cid)) byCommunity.set(cid, []); const list = byCommunity.get(cid)!; if (list.length < perCommunity) list.push(node); } // 社区按最新更新时间排序 const communities = Array.from(byCommunity.entries()) .sort((a, b) => { const aTime = Math.max(...a[1].map(n => n.updatedAt)); const bTime = Math.max(...b[1].map(n => n.updatedAt)); return bTime - aTime; }); const result: GmNode[] = []; for (const [, nodes] of communities) { result.push(...nodes); } // 负值按 0 处理(Cypher LIMIT 负数=不限制属边角语义,不移植)。 return totalLimit === undefined ? result : result.slice(0, Math.max(0, totalLimit)); } // ─── 柔性衰减存储(PR #69 decay 三连 · 存储层)─────────────── /** * decay 候选读取与批量写回的默认分片大小。node:sqlite 同步执行:批量 UPDATE * 不分片会让大图的单个巨型事务长时间占住事件循环(Review Focus #5), * 500 条/片的独立事务把单轮停顿压到可接受水位。 */ export const DECAY_BATCH_SIZE = 500; /** * 遗忘曲线评分的存储侧输入 DTO。字段与 Task 8 纯函数层(src/graph/decay.ts 的 * DecayNode / scoreNode 输入)逐名对齐,编排层(runMaintenance decay 步骤)可 * 直接展开送入 scoreNode;tier 保持宽松的 string 而非 NodeTier——读取时已把 * 哨兵值归一为合法三值,但写回(applyDecayBatch)不引入对 decay.ts 的类型 * 依赖,存储层与纯函数层保持单向(decay.ts ← types.ts,store 独立)。 */ export interface DecayCandidate { id: string; tier: string; lastAccessedAt: number; decayScore: number; decayComputedAt: number; validatedCount: number; pagerank: number; createdAt: number; updatedAt: number; } /** 按 size 切片(size<=0 按 1 处理),分片遍历的公共实现。 */ function chunk(items: T[], size: number): T[][] { const safe = Math.max(1, Math.floor(size) || 1); const chunks: T[][] = []; for (let i = 0; i < items.length; i += safe) chunks.push(items.slice(i, i + safe)); return chunks; } /** * 批量刷新节点的最近相关性活动时间(召回命中 / 新边写入路径)。 * 同一节点重复 touch 幂等;逐条执行,天然不受 SQL 变量上限约束。 */ function touchNodes(db: DatabaseSyncInstance, ids: string[], now: number = Date.now()): void { const stmt = db.prepare("UPDATE gm_nodes SET last_accessed_at=? WHERE id=?"); for (const id of ids) stmt.run(now, id); } /** * 读取非 deprecated 节点作为遗忘曲线评分候选,按 id 升序 LIMIT/OFFSET 分页。 * PR 参考实现是 Cypher 全量扫描(无分页先例);SQLite 侧分页供编排层逐批 * "评分 + 写回",避免大图单轮全载。tier 归一沿用 PR toNode 先例:迁移默认的 * 哨兵 'active'(及任何历史脏值)归一为 working,防评分层拿到非法 tier 后 * computeBeta 返回 undefined 使 recency 变 NaN。 */ export function getAllDecayCandidates( db: DatabaseSyncInstance, opts?: { limit?: number; offset?: number }, ): DecayCandidate[] { const limit = Math.max(1, opts?.limit ?? DECAY_BATCH_SIZE); const offset = Math.max(0, opts?.offset ?? 0); const rows = db.prepare(` SELECT id, tier, last_accessed_at, decay_score, decay_computed_at, validated_count, pagerank, created_at, updated_at FROM gm_nodes WHERE status='active' ORDER BY id LIMIT ? OFFSET ? `).all(limit, offset) as any[]; return rows.map(row => ({ id: String(row.id), tier: row.tier === "core" || row.tier === "working" || row.tier === "peripheral" ? String(row.tier) : "working", lastAccessedAt: Number(row.last_accessed_at), decayScore: Number(row.decay_score), decayComputedAt: Number(row.decay_computed_at), validatedCount: Number(row.validated_count), pagerank: Number(row.pagerank), createdAt: Number(row.created_at), updatedAt: Number(row.updated_at), })); } /** * 批量写回遗忘曲线评分结果(tier / decay_score / decay_computed_at)。 * 单事务分片提交:每 batchSize 条独立 BEGIN/COMMIT,中途失败只回滚出错分片、 * 已提交分片保留(fail-forward,维护链下一周期重扫未写回部分)。 * tier 由调用方先经 decideTierTransition 得出(转换后 tier),本方法只写回 * 不决策——与 markDeprecatedByDecay 两步分离,供编排层在两步之间计数 * tierTransitions 并以 {...node, tier: finalTier} 判定 shouldAutoDeprecate。 * PR 语义移植:tier 实际变化(旧值≠新值)才 bump updated_at,防止每轮评分都 * 刷新活跃度时钟;bump 时刻与该条 decayComputedAt 对齐(PR 用同一 now)。 */ export function applyDecayBatch( db: DatabaseSyncInstance, updates: Array<{ id: string; tier: string; decayScore: number; decayComputedAt: number }>, batchSize: number = DECAY_BATCH_SIZE, ): void { if (!updates.length) return; // SQLite UPDATE 的 SET 表达式全部基于行旧值计算:CASE 里的 tier 是更新前的值。 const stmt = db.prepare(` UPDATE gm_nodes SET updated_at = CASE WHEN tier <> ? THEN ? ELSE updated_at END, tier=?, decay_score=?, decay_computed_at=? WHERE id=? `); for (const slice of chunk(updates, batchSize)) { db.exec("BEGIN"); try { for (const update of slice) { stmt.run(update.tier, update.decayComputedAt, update.tier, update.decayScore, update.decayComputedAt, update.id); } db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } } /** * 遗忘曲线自动弃用(两阶段生命周期·阶段一):批量标记 status='deprecated' + * deprecated_at=now + deprecated_by='decay',并切断该节点全部两向边(from 命中、 * to 命中皆删 = 断联)。PR 状态守卫语义:ids 来自 decay 扫描快照,评分与批量 * 写入之间存在时间窗——窗口内已被手动弃用/复活的节点不覆盖为 decay(守卫未 * 通过者整体不动,标记与边均保留)。分片独立提交,同 applyDecayBatch。 */ export function markDeprecatedByDecay( db: DatabaseSyncInstance, ids: string[], now: number = Date.now(), ): void { if (!ids.length) return; for (const slice of chunk(ids, DECAY_BATCH_SIZE)) { db.exec("BEGIN"); try { const placeholders = slice.map(() => "?").join(","); const activeIds = (db.prepare( `SELECT id FROM gm_nodes WHERE id IN (${placeholders}) AND status='active'`, ).all(...slice) as Array<{ id: string }>).map(row => String(row.id)); if (activeIds.length) { const activePlaceholders = activeIds.map(() => "?").join(","); db.prepare(` UPDATE gm_nodes SET status='deprecated', deprecated_at=?, deprecated_by='decay', updated_at=? WHERE id IN (${activePlaceholders}) `).run(now, now, ...activeIds); // from/to 两个 IN 子句各占一份占位符:参数必须传两份, // 否则未绑定占位符按 NULL 处理,to 向的边永远删不掉。 db.prepare(` DELETE FROM gm_edges WHERE from_id IN (${activePlaceholders}) OR to_id IN (${activePlaceholders}) `).run(...activeIds, ...activeIds); } db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } } /** * 两阶段生命周期·阶段二:硬删到期的 decay 弃用节点(两向边、向量、节点行一并 * 移除;gm_node_sources / gm_node_revisions 依赖 ON DELETE CASCADE 随行清理)。 * 只删 deprecated_by='decay':manual/merge 与 NULL(存量废弃行)一律留给用户, * 时钟严格按 deprecated_at(cutoff 为严格下界,NULL 不命中),不受 upsertNode * 对 updated_at 的常规刷新影响。返回删除的节点数。 */ export function purgeDeprecatedBefore(db: DatabaseSyncInstance, cutoffMs: number): number { const dueIds = (db.prepare(` SELECT id FROM gm_nodes WHERE status='deprecated' AND deprecated_by='decay' AND deprecated_at IS NOT NULL AND deprecated_at < ? ORDER BY id `).all(cutoffMs) as Array<{ id: string }>).map(row => String(row.id)); let purged = 0; for (const slice of chunk(dueIds, DECAY_BATCH_SIZE)) { db.exec("BEGIN"); try { const placeholders = slice.map(() => "?").join(","); // 同 markDeprecatedByDecay:from/to 双 IN 各占一份占位符,参数传两份。 db.prepare(`DELETE FROM gm_edges WHERE from_id IN (${placeholders}) OR to_id IN (${placeholders})`) .run(...slice, ...slice); db.prepare(`DELETE FROM gm_vectors WHERE node_id IN (${placeholders})`).run(...slice); const result = db.prepare(`DELETE FROM gm_nodes WHERE id IN (${placeholders})`).run(...slice); purged += Number(result.changes); db.exec("COMMIT"); } catch (error) { db.exec("ROLLBACK"); throw error; } } return purged; } /** * 复活 decay 自动弃用的节点:清 deprecated_at/deprecated_by、status 回 active * (召回各路径只读 active,只清标记不回 status 会留下"不可见也不可删"的 * 僵尸态),并把 last_accessed_at 续到复活时刻——复活即一次相关性活动,否则 * 陈旧的访问时间会让节点在下一轮 decay 判定中立即再弃用,复活形同虚设 * (PR 的 upsertNode 在重新提及路径同样写 lastAccessedAt)。 * 仅 decay 弃用复活:manual/merge 是用户的显式决策,返回 false 且行不动。 */ export function reviveIfDecayDeprecated( db: DatabaseSyncInstance, nodeId: string, now: number = Date.now(), ): boolean { const result = db.prepare(` UPDATE gm_nodes SET status='active', deprecated_at=NULL, deprecated_by=NULL, last_accessed_at=?, updated_at=? WHERE id=? AND status='deprecated' AND deprecated_by='decay' `).run(now, now, nodeId); return Number(result.changes) > 0; }