Files
memoryweave/go/internal/api/routes/graph.go
T
xiaoyi 092535cfc5 feat(graph): 图谱复活第一步 —— 读侧埋点 + 知识形态影子门(零行为变化)
背景(实测):graph_nodes MAX(created_at) 停在 11-16,24h 内 [graph] skip-entity
59 次(worklog-note 43 / 空 source 15)全部被来源分档挡掉 ⇒ 图谱 2 天零新增;
navigate/query 此前完全无日志,'图有没有被读' 无观测(retrieval_count 只由
AddEdgeFeedback 显式 +1,navigate 不更新 —— 拿它当读计数是判据错误)。

本提交只做两件事,均可关(默认零行为变化):
1. [graph][read] 读侧埋点:/graph/navigate|query 每次打 op/entity/hops/paths。
2. ZHIYI_GRAPH_KNOWLEDGE_GATE=shadow|on:知识形态门(判据 = 蒸馏 facts 至少一条过
   distill.DensityKeep 信息密度≥2 项,零 LLM)。shadow 只记 [graph][kg-shadow]
   '若开闸会写多少实体';on 才放行来源分档,§2 合成边仍由 GRAPH_AUTO_SYNTH 独立控制。

为什么不按 tier=core:蒸馏直写记忆 Tier 恒为 normal(api/server.go),全仓无写者置
core,现存 1926 条 core 全是历史 recovery 导入 ⇒ 按 tier 门等于零增量。

go build ./... ok;go test ./internal/governance ./internal/api/routes -run Graph ok;
生产已切 zhiyid-kgraph-20261118(shadow),回滚=删
zhiyid.service.d/zzzzzzzzzzzzzzz-kgraph-20261118.conf。
2026-11-18 02:40:48 +08:00

226 lines
7.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 织忆 MemoryWeave — 知识图谱 API
package routes
import (
"encoding/json"
"log"
"net/http"
"strings"
"unicode"
"github.com/xiaoxue/memoryweave/internal/governance"
)
// graphReadLog 读侧埋点(2026-11-18):此前 Navigate/Query 完全无日志,
// 导致「图谱有没有被读」只能靠猜(retrieval_count 只由 AddEdgeFeedback 显式+1,
// navigate 不更新它 —— 拿它当读计数是判据错误)。埋这一行是为了让
// 「消费者是否存在」变成可证伪的数字,而非脑补。
func graphReadLog(op, entity string, hops int, count int) {
log.Printf("[graph][read] op=%s entity=%q hops=%d paths=%d", op, entity, hops, count)
}
type GraphAPI struct {
Graph governance.GraphStore
}
func NewGraphAPI(g governance.GraphStore) *GraphAPI {
return &GraphAPI{Graph: g}
}
// GET /api/v1/graph/stats
func (ga *GraphAPI) Stats(w http.ResponseWriter, r *http.Request) {
nodeCount, edgeCount, density := ga.Graph.Stats()
respond(w, 200, map[string]interface{}{
"node_count": nodeCount,
"edge_count": edgeCount,
"density": density,
})
}
// POST /api/v1/graph/query
// 设计文档 §2.5.4: match 格式兼容; 同时保留 entity+relation 简洁格式
func (ga *GraphAPI) Query(w http.ResponseWriter, r *http.Request) {
var req struct {
Entity string `json:"entity"`
Relation string `json:"relation"`
Namespace string `json:"namespace"`
// 设计文档兼容格式: {"match": {"type": "entity", "label": "..."}}
Match *struct {
Type string `json:"type"`
Label string `json:"label"`
} `json:"match"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
// 兼容设计文档 match 格式
if req.Match != nil && req.Entity == "" {
// match.type 过滤 node type, match.label 做 name 模糊搜索
var nodes []map[string]interface{}
if req.Match.Label != "" {
nodes = ga.Graph.SearchNodes(req.Match.Label, req.Namespace)
} else if req.Match.Type != "" {
nodes = ga.Graph.ListNodesByType(req.Match.Type, req.Namespace)
} else {
nodes = ga.Graph.ListNodes(req.Namespace)
}
respond(w, 200, map[string]interface{}{"nodes": nodes, "count": len(nodes)})
return
}
// 默认跨 namespace 搜索(空 = 匹配所有,§2.5.6)
results := ga.Graph.Query(NormalizeEntity(req.Entity), req.Relation, req.Namespace)
graphReadLog("query", req.Entity, 0, len(results))
respond(w, 200, map[string]interface{}{"results": results, "count": len(results)})
}
// POST /api/v1/graph/navigate
// 支持三种模式:
// 1. 单实体 BFS: {"entity": "...", "max_hops": 2}
// 2. 双向 BFS: {"source": "...", "target": "...", "max_hops": 3}
// 3. 关系过滤 BFS: {"entity": "...", "max_hops": 2, "relation_filter": ["related_to", "uses"]}(E1.5)
//
// 返回新增 grouped_by_relation 字段,按关系类型分组,便于阅读
func (ga *GraphAPI) Navigate(w http.ResponseWriter, r *http.Request) {
var req struct {
Entity string `json:"entity"`
Source string `json:"source"`
Target string `json:"target"`
MaxHops int `json:"max_hops"`
Namespace string `json:"namespace"`
RelationFilter []string `json:"relation_filter"` // E1.5: 关系类型白名单
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondError(w, 400, "invalid body")
return
}
if req.MaxHops <= 0 {
req.MaxHops = 2
}
// 响应体积上限:与 /graph/notes 同因同治(2026-09-27 小怡)。
// 实测 navigate("牧尘", 2) 服务端吐 34,465 条 ≈3.4MB,再加 grouped_by_relation 同量级复制
// ⇒ 单次响应 ~7MB。全仓调用点核对(3 处)都只读样本,paths 全量无人消费:
// - hermes 插件 plugins/zhiyi/__init__.py:911 → for p in paths[:50]
// - web-ui/index.html → 只读 d.count(不渲染 paths)
// - openclaw 客户端 → 已退役
// ⇒ paths 截断为可观测样本;count 仍报真实总数(调用方用它显示 "Found N paths")。
const maxNavigatePaths = 200
// 模式 2: 双向 BFS(source + target)
if req.Source != "" && req.Target != "" {
source := NormalizeEntity(req.Source)
target := NormalizeEntity(req.Target)
paths, err := ga.Graph.NavigateBiDir(source, target, req.MaxHops, req.Namespace, req.RelationFilter)
if err != nil {
respondError(w, 500, "navigate failed: "+err.Error())
return
}
totalPaths := len(paths)
if totalPaths > maxNavigatePaths {
paths = paths[:maxNavigatePaths]
}
graphReadLog("navigate-bidir", req.Source+"->"+req.Target, req.MaxHops, totalPaths)
respond(w, 200, map[string]interface{}{
"paths": paths, "source": req.Source, "target": req.Target,
"bidirectional": true, "count": totalPaths,
"returned": len(paths), "truncated": totalPaths > len(paths),
"relation_filter": req.RelationFilter,
})
return
}
// 模式 1: 单实体 BFS(兼容旧格式)
if req.Entity == "" {
respondError(w, 400, "entity (or source+target) required")
return
}
entity := NormalizeEntity(req.Entity)
paths, err := ga.Graph.Navigate(entity, req.MaxHops, req.Namespace, req.RelationFilter)
if err != nil {
respondError(w, 500, "navigate failed: "+err.Error())
return
}
// paths 截断(见函数开头 maxNavigatePaths 说明);grouped/suggestions 基于截断后样本构建。
totalPaths := len(paths)
if totalPaths > maxNavigatePaths {
paths = paths[:maxNavigatePaths]
}
graphReadLog("navigate", req.Entity, req.MaxHops, totalPaths)
// 新增:按 relation 分组,更直观
grouped := make(map[string][]map[string]interface{})
for _, p := range paths {
rel := p["relation"].(string)
if rel == "" {
rel = "_unknown"
}
grouped[rel] = append(grouped[rel], map[string]interface{}{
"from": stripPrefix(p["from"].(string)),
"to": stripPrefix(p["to"].(string)),
"weight": p["weight"],
"hop": p["hop"],
})
}
// 新增:相关实体建议(从 path 提取去重的 to 节点,跳过 ep_ 开头的)
suggestions := []string{}
seen := make(map[string]bool)
for _, p := range paths {
to := stripPrefix(p["to"].(string))
if !seen[to] && !strings.HasPrefix(p["to"].(string), "ep_") {
seen[to] = true
suggestions = append(suggestions, to)
}
}
if len(suggestions) > 20 {
suggestions = suggestions[:20]
}
respond(w, 200, map[string]interface{}{
"paths": paths,
"grouped_by_relation": grouped,
"entity": req.Entity,
"normalized_entity": entity,
"count": totalPaths,
"returned": len(paths),
"truncated": totalPaths > len(paths),
"relation_count": len(grouped),
"suggestions": suggestions,
"relation_filter": req.RelationFilter,
})
}
// stripPrefix 去掉节点 ID 的 n_ 前缀,用于可读展示
func stripPrefix(id string) string {
return strings.TrimPrefix(id, "n_")
}
// NormalizeEntity 规整实体名:去特殊字符 + n_前缀,保留中文和 Unicode 字符
func NormalizeEntity(entity string) string {
if strings.HasPrefix(entity, "n_") {
entity = entity[2:]
}
// 过滤特殊字符,保留 Unicode 字母、数字、下划线、中横线
clean := strings.Map(func(r rune) rune {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '_' || r == '-' || r == ' ' {
return r
}
// 保留中文和其他 Unicode 字母(如韩文、日文等)
if unicode.IsLetter(r) {
return r
}
return '_'
}, strings.ToLower(strings.TrimSpace(entity)))
// 合并连续下划线
for strings.Contains(clean, "__") {
clean = strings.ReplaceAll(clean, "__", "_")
}
clean = strings.Trim(clean, "_ ")
if clean == "" {
return "n_unknown"
}
return "n_" + clean
}