// 织忆 MemoryWeave — SQLite 知识图谱存储(CGO,实现 GraphStore 接口) // 设计要求: SQLite 仅存 graph_nodes / graph_edges / version_history // 不存 memories / episodes / tombstones(那属于 LanceDB 职责) package governance /* #cgo LDFLAGS: -lsqlite3 #include #include */ import "C" import ( "encoding/json" "fmt" "sync" "unsafe" "github.com/xiaoxue/memoryweave/internal/models" ) // SQLiteGraphStore CGO 直连 SQLite,独立于主存储的 LanceDB SQLite 文件 type SQLiteGraphStore struct { mu sync.RWMutex db *C.sqlite3 path string } func NewSQLiteGraphStore(dbPath string) (*SQLiteGraphStore, error) { if dbPath == "" { dbPath = "/var/lib/memoryweave/graph.db" } cPath := C.CString(dbPath) defer C.free(unsafe.Pointer(cPath)) var db *C.sqlite3 rc := C.sqlite3_open(cPath, &db) if rc != C.SQLITE_OK { msg := C.GoString(C.sqlite3_errmsg(db)) C.sqlite3_close(db) return nil, fmt.Errorf("sqlite open graph: %s", msg) } gs := &SQLiteGraphStore{db: db, path: dbPath} if err := gs.migrate(); err != nil { C.sqlite3_close(db) return nil, err } return gs, nil } func (gs *SQLiteGraphStore) migrate() error { sqls := []string{ `CREATE TABLE IF NOT EXISTS graph_nodes ( id TEXT PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, namespace TEXT NOT NULL DEFAULT '', properties TEXT DEFAULT '{}', pagerank REAL DEFAULT 1.0, created_at TEXT NOT NULL )`, `CREATE TABLE IF NOT EXISTS graph_edges ( id TEXT PRIMARY KEY, source TEXT NOT NULL, target TEXT NOT NULL, relation TEXT NOT NULL, weight REAL DEFAULT 1.0, evidence_count INTEGER DEFAULT 1, namespace TEXT NOT NULL DEFAULT '', created_at TEXT NOT NULL, FOREIGN KEY (source) REFERENCES graph_nodes(id), FOREIGN KEY (target) REFERENCES graph_nodes(id) )`, `CREATE TABLE IF NOT EXISTS version_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, memory_id TEXT NOT NULL, version INTEGER NOT NULL, content TEXT NOT NULL, updated_by TEXT DEFAULT '', source TEXT DEFAULT '', trigger TEXT DEFAULT '', reason TEXT DEFAULT '', timestamp TEXT NOT NULL )`, `CREATE INDEX IF NOT EXISTS idx_gn_namespace ON graph_nodes(namespace)`, `CREATE INDEX IF NOT EXISTS idx_ge_source ON graph_edges(source)`, `CREATE INDEX IF NOT EXISTS idx_ge_target ON graph_edges(target)`, `CREATE INDEX IF NOT EXISTS idx_ge_namespace ON graph_edges(namespace)`, `CREATE INDEX IF NOT EXISTS idx_vh_memory ON version_history(memory_id)`, } for _, s := range sqls { cSQL := C.CString(s) rc := C.sqlite3_exec(gs.db, cSQL, nil, nil, nil) C.free(unsafe.Pointer(cSQL)) if rc != C.SQLITE_OK { return fmt.Errorf("migrate graph: %s", C.GoString(C.sqlite3_errmsg(gs.db))) } } // 迁移:已有库可能缺少 pagerank 列(DESIGN.md 要求但原建表 SQL 漏了) gs.migrateAddColumn("graph_nodes", "pagerank", "REAL DEFAULT 1.0") // 修复孤儿边:自动补充缺失的节点 gs.repairOrphanEdges() return nil } func (gs *SQLiteGraphStore) repairOrphanEdges() { sql := `INSERT OR IGNORE INTO graph_nodes (id, name, type, namespace, created_at) SELECT DISTINCT source, source, 'entity', COALESCE(namespace,''), datetime('now') FROM graph_edges WHERE source NOT IN (SELECT id FROM graph_nodes); INSERT OR IGNORE INTO graph_nodes (id, name, type, namespace, created_at) SELECT DISTINCT target, target, 'entity', COALESCE(namespace,''), datetime('now') FROM graph_edges WHERE target NOT IN (SELECT id FROM graph_nodes);` cSQL := C.CString(sql) C.sqlite3_exec(gs.db, cSQL, nil, nil, nil) C.free(unsafe.Pointer(cSQL)) } // migrateAddColumn 幂等添加列(列存在时忽略错误) func (gs *SQLiteGraphStore) migrateAddColumn(table, column, def string) { sql := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column, def) cSQL := C.CString(sql) rc := C.sqlite3_exec(gs.db, cSQL, nil, nil, nil) C.free(unsafe.Pointer(cSQL)) // SQLITE_ERROR 表示列已存在,忽略即可 if rc != C.SQLITE_OK && rc != C.SQLITE_ERROR { // log but don't fail } } func (gs *SQLiteGraphStore) Close() error { if gs.db != nil { C.sqlite3_close(gs.db) gs.db = nil } return nil } // ─── GraphStore 接口实现 ──────────────────────────────── func (gs *SQLiteGraphStore) AddNode(id, name, nodeType, namespace string) error { gs.mu.Lock() defer gs.mu.Unlock() sql := fmt.Sprintf( "INSERT OR REPLACE INTO graph_nodes (id, name, type, namespace, created_at) VALUES ('%s', '%s', '%s', '%s', datetime('now'))", escape(id), escape(name), escape(nodeType), escape(namespace)) return execSQL(gs.db, sql) } func (gs *SQLiteGraphStore) AddEdge(id, source, target, relation, namespace string, weight float64) error { gs.mu.Lock() defer gs.mu.Unlock() // 自动创建缺失的源/目标节点;已存在的升级 namespace(default → 具体ns) for _, node := range []struct{ id, name string }{{source, source}, {target, target}} { // 先尝试 INSERT — 如果节点不存在就创建 sql := fmt.Sprintf( "INSERT OR IGNORE INTO graph_nodes (id, name, type, namespace, created_at) VALUES ('%s', '%s', 'entity', '%s', datetime('now'))", escape(node.id), escape(node.name), escape(namespace)) if err := execSQL(gs.db, sql); err != nil { return err } // 如果 namespace 非空非 default,顺手升级 default 节点 if namespace != "" && namespace != "default" { updateSQL := fmt.Sprintf( "UPDATE graph_nodes SET namespace='%s' WHERE id='%s' AND namespace='default'", escape(namespace), escape(node.id)) _ = execSQL(gs.db, updateSQL) // 忽略错误(节点不存在)不影响 } } sql := fmt.Sprintf( "INSERT OR REPLACE INTO graph_edges (id, source, target, relation, weight, namespace, created_at) VALUES ('%s', '%s', '%s', '%s', %f, '%s', datetime('now'))", escape(id), escape(source), escape(target), escape(relation), weight, escape(namespace)) return execSQL(gs.db, sql) } func (gs *SQLiteGraphStore) Navigate(entity string, maxHops int, namespace string) ([]map[string]interface{}, error) { // 双向 BFS gs.mu.RLock() defer gs.mu.RUnlock() // 命名空间兼容:shared/default 视为同一命名空间 nsClause := fmt.Sprintf("e.namespace IN ('%s', 'default')", escape(namespace)) if namespace == "" { nsClause = "1=1" // 通配所有命名空间 } visited := map[string]bool{entity: true} queue := []string{entity} var paths []map[string]interface{} for hop := 1; hop <= maxHops && len(queue) > 0; hop++ { var next []string for _, node := range queue { // 查询所有出边 sql := fmt.Sprintf( "SELECT e.id, e.target, e.relation, e.weight, n.name FROM graph_edges e JOIN graph_nodes n ON e.target = n.id WHERE e.source = '%s' AND %s", escape(node), nsClause) edges := queryRows(gs.db, sql) for _, edge := range edges { target := edge["target"].(string) if !visited[target] { visited[target] = true next = append(next, target) paths = append(paths, map[string]interface{}{ "from": node, "to": target, "relation": edge["relation"], "weight": edge["weight"], "hop": hop, }) } } } queue = next } return paths, nil } func (gs *SQLiteGraphStore) NavigateBiDir(source, target string, maxHops int, namespace string) ([]map[string]interface{}, error) { // 双向 BFS 直到相遇 forward, _ := gs.Navigate(source, maxHops, namespace) backward, _ := gs.Navigate(target, maxHops, namespace) return append(forward, backward...), nil } func (gs *SQLiteGraphStore) Query(entity, relation, namespace string) []map[string]interface{} { gs.mu.RLock() defer gs.mu.RUnlock() // 命名空间兼容 nsClause := fmt.Sprintf("e.namespace IN ('%s', 'default')", escape(namespace)) if namespace == "" { nsClause = "1=1" } sql := fmt.Sprintf( "SELECT e.source, e.target, e.relation, e.weight FROM graph_edges e WHERE e.relation = '%s' AND %s AND (e.source = '%s' OR e.target = '%s')", escape(relation), nsClause, escape(entity), escape(entity)) return queryRows(gs.db, sql) } func (gs *SQLiteGraphStore) Stats() (nodeCount, edgeCount int, density float64) { gs.mu.RLock() defer gs.mu.RUnlock() nodeCount = queryInt(gs.db, "SELECT COUNT(*) FROM graph_nodes") edgeCount = queryInt(gs.db, "SELECT COUNT(*) FROM graph_edges") if nodeCount > 0 { maxEdges := nodeCount * (nodeCount - 1) density = float64(edgeCount) / float64(maxEdges) if density > 1 { density = 1 } } return } func (gs *SQLiteGraphStore) Prune(minWeight float64) { gs.mu.Lock() defer gs.mu.Unlock() execSQL(gs.db, fmt.Sprintf("DELETE FROM graph_edges WHERE weight < %f", minWeight)) execSQL(gs.db, `DELETE FROM graph_nodes WHERE id NOT IN (SELECT DISTINCT source FROM graph_edges UNION SELECT DISTINCT target FROM graph_edges)`) } func (gs *SQLiteGraphStore) GetGraph(namespace string) ([]map[string]interface{}, []map[string]interface{}) { nodes := []map[string]interface{}{} edges := []map[string]interface{}{} var nodeSQL string if namespace == "" || namespace == "all" { nodeSQL = "SELECT id, name, type, namespace, properties FROM graph_nodes" } else { nodeSQL = "SELECT id, name, type, namespace, properties FROM graph_nodes WHERE namespace = '" + escape(namespace) + "'" } rows := queryRows(gs.db, nodeSQL) for _, n := range rows { props := n["properties"].(string) var properties map[string]interface{} if props != "" { json.Unmarshal([]byte(props), &properties) } nodes = append(nodes, map[string]interface{}{ "id": n["id"], "name": n["name"], "type": n["type"], "namespace": n["namespace"], "properties": properties, }) } var edgeSQL string if namespace == "" || namespace == "all" { edgeSQL = "SELECT id, source, target, relation, weight, namespace FROM graph_edges" } else { edgeSQL = "SELECT id, source, target, relation, weight, namespace FROM graph_edges WHERE namespace = '" + escape(namespace) + "'" } edgeRows := queryRows(gs.db, edgeSQL) for _, e := range edgeRows { edges = append(edges, map[string]interface{}{ "id": e["id"], "source": e["source"], "target": e["target"], "relation": e["relation"], "weight": e["weight"], "namespace": e["namespace"], }) } return nodes, edges } func (gs *SQLiteGraphStore) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult { // 从 recall 结果提取实体,展开图谱邻居 expanded := make([]models.RecallResult, len(results)) copy(expanded, results) for _, r := range results { paths, _ := gs.Navigate(r.Content, maxHops, namespace) for _, p := range paths { expanded = append(expanded, models.RecallResult{ Content: fmt.Sprintf("%v", p["to"]), Score: r.Score * 0.5, }) } } return expanded } // SearchNodes 按 label 模糊搜索节点(§2.5.4 match 格式兼容) func (gs *SQLiteGraphStore) SearchNodes(label, namespace string) []map[string]interface{} { gs.mu.RLock() defer gs.mu.RUnlock() nsClause := "1=1" if namespace != "" { nsClause = fmt.Sprintf("namespace = '%s'", escape(namespace)) } sql := fmt.Sprintf( "SELECT id, name, type, namespace, pagerank FROM graph_nodes WHERE name LIKE '%%%s%%' AND %s LIMIT 100", escape(label), nsClause) return queryRows(gs.db, sql) } // ListNodesByType 按 type 列出节点 func (gs *SQLiteGraphStore) ListNodesByType(nodeType, namespace string) []map[string]interface{} { gs.mu.RLock() defer gs.mu.RUnlock() nsClause := "1=1" if namespace != "" { nsClause = fmt.Sprintf("namespace = '%s'", escape(namespace)) } sql := fmt.Sprintf( "SELECT id, name, type, namespace, pagerank FROM graph_nodes WHERE type = '%s' AND %s ORDER BY pagerank DESC LIMIT 100", escape(nodeType), nsClause) return queryRows(gs.db, sql) } // ListNodes 列出所有节点 func (gs *SQLiteGraphStore) ListNodes(namespace string) []map[string]interface{} { gs.mu.RLock() defer gs.mu.RUnlock() nsClause := "1=1" if namespace != "" { nsClause = fmt.Sprintf("namespace = '%s'", escape(namespace)) } sql := fmt.Sprintf( "SELECT id, name, type, namespace, pagerank FROM graph_nodes WHERE %s ORDER BY pagerank DESC LIMIT 100", nsClause) return queryRows(gs.db, sql) } func (gs *SQLiteGraphStore) PageRank(damping float64, iterations int) map[string]float64 { gs.mu.RLock() defer gs.mu.RUnlock() // 获取所有节点 nodes := queryStrSlice(gs.db, "SELECT id FROM graph_nodes") n := float64(len(nodes)) if n == 0 { return nil } ranks := make(map[string]float64) base := (1.0 - damping) / n for _, id := range nodes { ranks[id] = 1.0 / n } outEdges := make(map[string][]struct { target string weight float64 }) for _, node := range nodes { sql := fmt.Sprintf("SELECT target, weight FROM graph_edges WHERE source = '%s'", escape(node)) rows := queryRows(gs.db, sql) for _, r := range rows { outEdges[node] = append(outEdges[node], struct { target string weight float64 }{r["target"].(string), r["weight"].(float64)}) } } for iter := 0; iter < iterations; iter++ { newRanks := make(map[string]float64) for _, node := range nodes { rank := base for src, edges := range outEdges { totalWt := 0.0 for _, e := range edges { totalWt += e.weight } for _, e := range edges { if e.target == node && totalWt > 0 { rank += damping * ranks[src] * e.weight / totalWt } } } newRanks[node] = rank } ranks = newRanks } return ranks } func (gs *SQLiteGraphStore) EvidenceCount(entity string) int { gs.mu.RLock() defer gs.mu.RUnlock() var sum int for _, r := range queryRows(gs.db, fmt.Sprintf("SELECT SUM(evidence_count) as s FROM graph_edges WHERE source = '%s' OR target = '%s'", escape(entity), escape(entity))) { if v, ok := r["s"]; ok { switch x := v.(type) { case int: sum += x case int64: sum += int(x) case float64: sum += int(x) } } } return sum } // ─── CGO 工具 ────────────────────────────────────────── func execSQL(db *C.sqlite3, sql string) error { cSQL := C.CString(sql) defer C.free(unsafe.Pointer(cSQL)) rc := C.sqlite3_exec(db, cSQL, nil, nil, nil) if rc != C.SQLITE_OK { return fmt.Errorf("sqlite: %s", C.GoString(C.sqlite3_errmsg(db))) } return nil } func queryInt(db *C.sqlite3, sql string) int { cSQL := C.CString(sql) defer C.free(unsafe.Pointer(cSQL)) var stmt *C.sqlite3_stmt rc := C.sqlite3_prepare_v2(db, cSQL, C.int(len(sql)), &stmt, nil) if rc != C.SQLITE_OK { return 0 } defer C.sqlite3_finalize(stmt) if C.sqlite3_step(stmt) == C.SQLITE_ROW { return int(C.sqlite3_column_int(stmt, 0)) } return 0 } func queryStrSlice(db *C.sqlite3, sql string) []string { var result []string cSQL := C.CString(sql) defer C.free(unsafe.Pointer(cSQL)) var stmt *C.sqlite3_stmt rc := C.sqlite3_prepare_v2(db, cSQL, C.int(len(sql)), &stmt, nil) if rc != C.SQLITE_OK { return result } defer C.sqlite3_finalize(stmt) for C.sqlite3_step(stmt) == C.SQLITE_ROW { result = append(result, C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, 0))))) } return result } func queryRows(db *C.sqlite3, sql string) []map[string]interface{} { var results []map[string]interface{} cSQL := C.CString(sql) defer C.free(unsafe.Pointer(cSQL)) var stmt *C.sqlite3_stmt rc := C.sqlite3_prepare_v2(db, cSQL, C.int(len(sql)), &stmt, nil) if rc != C.SQLITE_OK { return results } defer C.sqlite3_finalize(stmt) colCount := int(C.sqlite3_column_count(stmt)) for C.sqlite3_step(stmt) == C.SQLITE_ROW { row := make(map[string]interface{}) for i := 0; i < colCount; i++ { name := C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_name(stmt, C.int(i))))) switch C.sqlite3_column_type(stmt, C.int(i)) { case C.SQLITE_INTEGER: row[name] = int(C.sqlite3_column_int(stmt, C.int(i))) case C.SQLITE_FLOAT: row[name] = float64(C.sqlite3_column_double(stmt, C.int(i))) case C.SQLITE_TEXT: row[name] = C.GoString((*C.char)(unsafe.Pointer(C.sqlite3_column_text(stmt, C.int(i))))) default: row[name] = nil } } results = append(results, row) } return results } func escape(s string) string { result := "" for _, ch := range s { if ch == '\'' { result += "''" } else { result += string(ch) } } return result }