535 lines
13 KiB
Go
535 lines
13 KiB
Go
// 织忆 MemoryWeave — 内存知识图谱(零外部依赖)
|
||
package governance
|
||
|
||
import (
|
||
"fmt"
|
||
"sync"
|
||
)
|
||
|
||
// InMemoryGraph 纯内存知识图谱,替代 SQLite 依赖
|
||
type InMemoryGraph struct {
|
||
mu sync.RWMutex
|
||
nodes map[string]*GraphNode
|
||
edges []*GraphEdge
|
||
}
|
||
|
||
type GraphNode struct {
|
||
ID string `json:"id"`
|
||
Name string `json:"name"`
|
||
Type string `json:"type"`
|
||
Namespace string `json:"namespace"`
|
||
}
|
||
|
||
type GraphEdge struct {
|
||
ID string `json:"id"`
|
||
Source string `json:"source"`
|
||
Target string `json:"target"`
|
||
Relation string `json:"relation"`
|
||
Weight float64 `json:"weight"`
|
||
Namespace string `json:"namespace"`
|
||
}
|
||
|
||
func NewInMemoryGraph() *InMemoryGraph {
|
||
return &InMemoryGraph{
|
||
nodes: make(map[string]*GraphNode),
|
||
}
|
||
}
|
||
|
||
func (g *InMemoryGraph) AddNode(id, name, nodeType, namespace string) error {
|
||
g.mu.Lock()
|
||
defer g.mu.Unlock()
|
||
g.nodes[id] = &GraphNode{ID: id, Name: name, Type: nodeType, Namespace: namespace}
|
||
return nil
|
||
}
|
||
|
||
func (g *InMemoryGraph) AddEdge(id, source, target, relation, namespace string, weight float64) error {
|
||
g.mu.Lock()
|
||
defer g.mu.Unlock()
|
||
g.edges = append(g.edges, &GraphEdge{
|
||
ID: id, Source: source, Target: target,
|
||
Relation: relation, Weight: weight, Namespace: namespace,
|
||
})
|
||
return nil
|
||
}
|
||
|
||
// relFilterOK 检查关系类型是否在白名单中(nil=全部通过)
|
||
func relFilterOK(rel string, relFilter []string) bool {
|
||
if relFilter == nil {
|
||
return true
|
||
}
|
||
for _, r := range relFilter {
|
||
if r == rel {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// Navigate 多跳 BFS 导航(E1.4: relationFilter 支持, E1.7: 环路检测)
|
||
func (g *InMemoryGraph) Navigate(entity string, maxHops int, namespace string, relFilter []string) ([]map[string]interface{}, error) {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
|
||
visited := map[string]bool{entity: true}
|
||
// E1.7: 环路检测 — 同一条边在单次 BFS 中不应被重复访问
|
||
seenEdges := map[string]bool{}
|
||
queue := []string{entity}
|
||
var paths []map[string]interface{}
|
||
|
||
for hop := 1; hop <= maxHops && len(queue) > 0; hop++ {
|
||
var nextQueue []string
|
||
for _, current := range queue {
|
||
for _, e := range g.edges {
|
||
if e.Namespace != namespace || !relFilterOK(e.Relation, relFilter) {
|
||
continue
|
||
}
|
||
// E1.7: 环路检测 — 跳过已访问边
|
||
if seenEdges[e.ID] {
|
||
continue
|
||
}
|
||
neighbor := ""
|
||
if e.Source == current {
|
||
neighbor = e.Target
|
||
} else if e.Target == current {
|
||
neighbor = e.Source
|
||
}
|
||
if neighbor == "" || visited[neighbor] {
|
||
continue
|
||
}
|
||
seenEdges[e.ID] = true // 标记边为已访问(环路检测)
|
||
visited[neighbor] = true
|
||
nextQueue = append(nextQueue, neighbor)
|
||
paths = append(paths, map[string]interface{}{
|
||
"edge_id": e.ID,
|
||
"source": current,
|
||
"target": neighbor,
|
||
"relation": e.Relation,
|
||
"weight": e.Weight,
|
||
"hop": hop,
|
||
})
|
||
}
|
||
}
|
||
queue = nextQueue
|
||
}
|
||
return paths, nil
|
||
}
|
||
|
||
// NavigateBiDir 真正双向 BFS(E1.1 修复:对齐 SQLite 算法)
|
||
// E1.2: 无相遇节点时返回 {unreachable:true} 而非降级为单向邻居
|
||
func (g *InMemoryGraph) NavigateBiDir(source, target string, maxHops int, namespace string, relFilter []string) ([]map[string]interface{}, error) {
|
||
if target == "" || target == source {
|
||
return g.Navigate(source, maxHops, namespace, relFilter)
|
||
}
|
||
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
|
||
// 构建邻接表(按 relationFilter 过滤)
|
||
adj := make(map[string][][2]string) // node -> []{neighbor, edge_id}
|
||
edgeInfo := make(map[string][2]string) // edge_id -> [relation, weight_str]
|
||
for _, e := range g.edges {
|
||
if e.Namespace != namespace || !relFilterOK(e.Relation, relFilter) {
|
||
continue
|
||
}
|
||
adj[e.Source] = append(adj[e.Source], [2]string{e.Target, e.ID})
|
||
adj[e.Target] = append(adj[e.Target], [2]string{e.Source, e.ID})
|
||
edgeInfo[e.ID] = [2]string{e.Relation, fmt.Sprintf("%f", e.Weight)}
|
||
}
|
||
|
||
type fwdNode struct {
|
||
parent string
|
||
edgeID string
|
||
weight float64
|
||
hop int
|
||
}
|
||
type bwdNode struct {
|
||
parent string
|
||
edgeID string
|
||
weight float64
|
||
hop int
|
||
}
|
||
|
||
fwd := make(map[string]*fwdNode)
|
||
bwd := make(map[string]*bwdNode)
|
||
|
||
fwdQ := []string{source}
|
||
fwd[source] = &fwdNode{hop: 0, weight: 1.0}
|
||
fwdVisited := map[string]bool{source: true}
|
||
|
||
bwdQ := []string{target}
|
||
bwd[target] = &bwdNode{hop: 0, weight: 1.0}
|
||
bwdVisited := map[string]bool{target: true}
|
||
|
||
fwdMax := (maxHops + 1) / 2
|
||
bwdMax := (maxHops + 1) / 2
|
||
|
||
// BFS 循环:双向交替扩展
|
||
for len(fwdQ) > 0 || len(bwdQ) > 0 {
|
||
// 正向扩展一轮
|
||
if len(fwdQ) > 0 {
|
||
var nextFwd []string
|
||
for i := 0; i < len(fwdQ); i++ {
|
||
curr := fwdQ[i]
|
||
if fwd[curr].hop >= fwdMax {
|
||
continue
|
||
}
|
||
for _, n := range adj[curr] {
|
||
ngh, eid := n[0], n[1]
|
||
if fwdVisited[ngh] {
|
||
continue
|
||
}
|
||
fwdVisited[ngh] = true
|
||
edgeW := 1.0
|
||
if info, ok := edgeInfo[eid]; ok {
|
||
fmt.Sscanf(info[1], "%f", &edgeW)
|
||
}
|
||
fwd[ngh] = &fwdNode{parent: curr, edgeID: eid, weight: fwd[curr].weight * edgeW, hop: fwd[curr].hop + 1}
|
||
nextFwd = append(nextFwd, ngh)
|
||
}
|
||
}
|
||
fwdQ = nextFwd
|
||
}
|
||
|
||
// 反向扩展一轮
|
||
if len(bwdQ) > 0 {
|
||
var nextBwd []string
|
||
for i := 0; i < len(bwdQ); i++ {
|
||
curr := bwdQ[i]
|
||
if bwd[curr].hop >= bwdMax {
|
||
continue
|
||
}
|
||
for _, n := range adj[curr] {
|
||
ngh, eid := n[0], n[1]
|
||
if bwdVisited[ngh] {
|
||
continue
|
||
}
|
||
bwdVisited[ngh] = true
|
||
edgeW := 1.0
|
||
if info, ok := edgeInfo[eid]; ok {
|
||
fmt.Sscanf(info[1], "%f", &edgeW)
|
||
}
|
||
bwd[ngh] = &bwdNode{parent: curr, edgeID: eid, weight: bwd[curr].weight * edgeW, hop: bwd[curr].hop + 1}
|
||
nextBwd = append(nextBwd, ngh)
|
||
}
|
||
}
|
||
bwdQ = nextBwd
|
||
}
|
||
|
||
// 检查相遇节点
|
||
for meet := range fwdVisited {
|
||
if bwdVisited[meet] && meet != source && meet != target {
|
||
// 重建完整路径
|
||
var fwdPath []string
|
||
c := meet
|
||
for c != source {
|
||
if c == "" || fwd[c] == nil {
|
||
break
|
||
}
|
||
fwdPath = append([]string{c}, fwdPath...)
|
||
c = fwd[c].parent
|
||
}
|
||
fwdPath = append([]string{source}, fwdPath...)
|
||
|
||
var bwdPath []string
|
||
c = meet
|
||
for c != target {
|
||
bwdPath = append(bwdPath, c)
|
||
if c == "" || bwd[c] == nil || bwd[c].parent == "" {
|
||
break
|
||
}
|
||
c = bwd[c].parent
|
||
}
|
||
bwdPath = append(bwdPath, target)
|
||
|
||
allNodes := append(fwdPath, bwdPath[1:]...)
|
||
score := fwd[meet].weight * bwd[meet].weight
|
||
|
||
// 构建边列表
|
||
var pathEdges []map[string]interface{}
|
||
cur := source
|
||
for _, node := range allNodes[1:] {
|
||
var edgeID, rel string
|
||
var w float64 = 1.0
|
||
if fn, ok := fwd[node]; ok && fn.parent != "" {
|
||
if info, ok2 := edgeInfo[fn.edgeID]; ok2 {
|
||
edgeID = fn.edgeID
|
||
rel = info[0]
|
||
fmt.Sscanf(info[1], "%f", &w)
|
||
}
|
||
}
|
||
pathEdges = append(pathEdges, map[string]interface{}{
|
||
"source": cur, "target": node,
|
||
"relation": rel, "weight": w, "edge_id": edgeID,
|
||
})
|
||
cur = node
|
||
}
|
||
|
||
return []map[string]interface{}{{
|
||
"nodes": allNodes,
|
||
"edges": pathEdges,
|
||
"score": score,
|
||
}}, nil
|
||
}
|
||
}
|
||
}
|
||
|
||
// E1.2: 无相遇节点时返回 unreachable,而非降级为单向邻居
|
||
return []map[string]interface{}{{
|
||
"unreachable": true,
|
||
"source": source,
|
||
"target": target,
|
||
"max_hops": maxHops,
|
||
}}, nil
|
||
}
|
||
|
||
// AllEdges 列出所有边(指定 namespace)
|
||
func (g *InMemoryGraph) AllEdges(namespace string) []GraphEdge {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
var out []GraphEdge
|
||
for _, e := range g.edges {
|
||
if namespace == "" || e.Namespace == namespace {
|
||
out = append(out, *e)
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
// Stats 返回图谱统计
|
||
func (g *InMemoryGraph) Stats() (nodeCount, edgeCount int, density float64) {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
|
||
nodeCount = len(g.nodes)
|
||
edgeCount = len(g.edges)
|
||
if nodeCount > 1 {
|
||
density = float64(edgeCount) / float64(nodeCount*(nodeCount-1))
|
||
}
|
||
return
|
||
}
|
||
|
||
// Prune 删除低权重边和孤立节点
|
||
func (g *InMemoryGraph) Prune(minWeight float64) {
|
||
g.mu.Lock()
|
||
defer g.mu.Unlock()
|
||
|
||
// 删除低权重边
|
||
var kept []*GraphEdge
|
||
for _, e := range g.edges {
|
||
if e.Weight >= minWeight {
|
||
kept = append(kept, e)
|
||
}
|
||
}
|
||
g.edges = kept
|
||
|
||
// 删除孤立节点
|
||
connected := make(map[string]bool)
|
||
for _, e := range g.edges {
|
||
connected[e.Source] = true
|
||
connected[e.Target] = true
|
||
}
|
||
for id := range g.nodes {
|
||
if !connected[id] {
|
||
delete(g.nodes, id)
|
||
}
|
||
}
|
||
}
|
||
|
||
func (g *InMemoryGraph) CleanupNoiseNodes(dryRun bool) (int, []string, error) {
|
||
g.mu.Lock()
|
||
defer g.mu.Unlock()
|
||
// InMemoryGraph 不需要脏数据清理(测试用)
|
||
return 0, nil, nil
|
||
}
|
||
|
||
// Query 按实体和关系查询
|
||
func (g *InMemoryGraph) Query(entity, relation, namespace string) []map[string]interface{} {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
|
||
var results []map[string]interface{}
|
||
for _, e := range g.edges {
|
||
if e.Namespace != namespace {
|
||
continue
|
||
}
|
||
if e.Source == entity || e.Target == entity {
|
||
if relation == "" || containsRelation(e.Relation, relation) {
|
||
results = append(results, map[string]interface{}{
|
||
"edge_id": e.ID,
|
||
"source": e.Source,
|
||
"target": e.Target,
|
||
"relation": e.Relation,
|
||
"weight": e.Weight,
|
||
})
|
||
}
|
||
}
|
||
}
|
||
return results
|
||
}
|
||
|
||
// PageRank 计算节点重要性(多 Agent 引用加权)
|
||
func (g *InMemoryGraph) PageRank(damping float64, iterations int) map[string]float64 {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
|
||
if damping <= 0 {
|
||
damping = 0.85
|
||
}
|
||
if iterations <= 0 {
|
||
iterations = 20
|
||
}
|
||
|
||
N := float64(len(g.nodes))
|
||
if N == 0 {
|
||
return nil
|
||
}
|
||
|
||
rank := make(map[string]float64)
|
||
for id := range g.nodes {
|
||
rank[id] = 1.0 / N
|
||
}
|
||
|
||
outDegree := make(map[string]int)
|
||
for _, e := range g.edges {
|
||
outDegree[e.Source]++
|
||
}
|
||
|
||
for iter := 0; iter < iterations; iter++ {
|
||
newRank := make(map[string]float64)
|
||
var sinkRank float64
|
||
for id := range g.nodes {
|
||
if outDegree[id] == 0 {
|
||
sinkRank += rank[id]
|
||
}
|
||
}
|
||
sinkContrib := sinkRank / N
|
||
|
||
for id := range g.nodes {
|
||
newRank[id] = (1.0 - damping) / N
|
||
newRank[id] += damping * sinkContrib
|
||
}
|
||
|
||
for _, e := range g.edges {
|
||
if outDegree[e.Source] > 0 {
|
||
contrib := damping * rank[e.Source] / float64(outDegree[e.Source])
|
||
newRank[e.Target] += contrib
|
||
}
|
||
}
|
||
rank = newRank
|
||
}
|
||
return rank
|
||
}
|
||
|
||
// EvidenceCount 返回实体引用证据数
|
||
func (g *InMemoryGraph) EvidenceCount(entity string) int {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
count := 0
|
||
for _, e := range g.edges {
|
||
if e.Source == entity || e.Target == entity {
|
||
count++
|
||
}
|
||
}
|
||
return count
|
||
}
|
||
|
||
// GetEntityDegree E4.3: 返回实体的图谱度(入度+出度),度越高越优先保留
|
||
func (g *InMemoryGraph) GetEntityDegree(entity string) int {
|
||
return g.EvidenceCount(entity)
|
||
}
|
||
|
||
func containsRelation(rel, substr string) bool {
|
||
if len(substr) == 0 {
|
||
return true
|
||
}
|
||
return rel == substr
|
||
}
|
||
|
||
// GetGraph 内存图谱的导出
|
||
func (g *InMemoryGraph) GetGraph(namespace string, limit int) ([]map[string]interface{}, []map[string]interface{}) {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
var nodes []map[string]interface{}
|
||
var edges []map[string]interface{}
|
||
for _, n := range g.nodes {
|
||
if namespace == "" || n.Namespace == namespace {
|
||
nodes = append(nodes, map[string]interface{}{
|
||
"id": n.ID, "name": n.Name, "type": n.Type, "namespace": n.Namespace,
|
||
})
|
||
if limit > 0 && len(nodes) >= limit {
|
||
break
|
||
}
|
||
}
|
||
}
|
||
for _, e := range g.edges {
|
||
if namespace == "" || e.Namespace == namespace {
|
||
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
|
||
}
|
||
|
||
// SearchNodes 按 label 模糊搜索节点
|
||
func (g *InMemoryGraph) SearchNodes(label, namespace string) []map[string]interface{} {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
var out []map[string]interface{}
|
||
for _, n := range g.nodes {
|
||
if namespace != "" && n.Namespace != namespace {
|
||
continue
|
||
}
|
||
if searchSubstring(n.Name, label) {
|
||
out = append(out, map[string]interface{}{
|
||
"id": n.ID, "name": n.Name, "type": n.Type, "namespace": n.Namespace,
|
||
})
|
||
}
|
||
}
|
||
return out
|
||
}
|
||
|
||
// ListNodesByType 按 type 列出节点
|
||
func (g *InMemoryGraph) ListNodesByType(nodeType, namespace string) []map[string]interface{} {
|
||
g.mu.RLock()
|
||
defer g.mu.RUnlock()
|
||
var out []map[string]interface{}
|
||
for _, n := range g.nodes {
|
||
if namespace != "" && n.Namespace != namespace {
|
||
continue
|
||
}
|
||
if nodeType != "" && n.Type != nodeType {
|
||
continue
|
||
}
|
||
out = append(out, map[string]interface{}{
|
||
"id": n.ID, "name": n.Name, "type": n.Type, "namespace": n.Namespace,
|
||
})
|
||
}
|
||
return out
|
||
}
|
||
|
||
// ListNodes 列出所有节点
|
||
func (g *InMemoryGraph) ListNodes(namespace string) []map[string]interface{} {
|
||
return g.ListNodesByType("", namespace)
|
||
}
|
||
|
||
// P0: FallbackTextSearch 内存版 stub
|
||
func (g *InMemoryGraph) FallbackTextSearch(query, namespace string, limit int) []map[string]interface{} {
|
||
// InMemoryGraph 不支持 SQL LIKE,降级到 SearchNodes
|
||
return g.SearchNodes(query, namespace)
|
||
}
|
||
|
||
// P2: 信任评分 stub(InMemoryGraph 不持久化)
|
||
func (g *InMemoryGraph) AddEdgeFeedback(edgeID string, helpful bool) error { return nil }
|
||
func (g *InMemoryGraph) IncrementEdgeRetrieval(edgeID string) error { return nil }
|
||
func (g *InMemoryGraph) UpdateEdgeTrustScores() error { return nil }
|
||
|
||
func searchSubstring(s, substr string) bool {
|
||
for i := 0; i <= len(s)-len(substr); i++ {
|
||
if s[i:i+len(substr)] == substr {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
} |