2.4 KiB
2.4 KiB
P2: 信任评分 — 织忆 Go daemon
目标
给 graph.db 的 edges 表加信任评分字段,新增反馈 API 端点。
修改文件
1. /tmp/memoryweave/go/internal/governance/graph_sqlite.go
a) Upgrade SQL 迁移(在 migrate() 中追加)
ALTER TABLE graph_edges ADD COLUMN trust_score REAL DEFAULT 0.5;
ALTER TABLE graph_edges ADD COLUMN retrieval_count INTEGER DEFAULT 0;
ALTER TABLE graph_edges ADD COLUMN helpful_count INTEGER DEFAULT 0;
注意:ALTER TABLE ADD COLUMN 要先检查列是否存在,用 sqlite3 的 PRAGMA table_info(graph_edges) 检查。
b) 新增方法
// AddEdgeFeedback 记录边反馈
func (gs *SQLiteGraphStore) AddEdgeFeedback(edgeID string, helpful bool) error
// 实现:UPDATE graph_edges SET helpful_count = helpful_count + 1 WHERE id = ?
// 如果不是 helpful: UPDATE graph_edges SET retrieval_count = retrieval_count + 1 WHERE id = ?
// UpdateEdgeTrustScores 批量更新信任评分(定时或触发)
func (gs *SQLiteGraphStore) UpdateEdgeTrustScores() error
// 实现:UPDATE graph_edges SET trust_score =
// CASE
// WHEN retrieval_count > 0 THEN CAST(helpful_count AS REAL) / retrieval_count
// ELSE 0.5
// END
// IncrementEdgeRetrieval 递增边的检索计数(在 ExpandFromResults 里调用)
func (gs *SQLiteGraphStore) IncrementEdgeRetrieval(edgeID string) error
c) 在 ExpandFromResults(行 679-733)中,每条被检索的边调用 IncrementEdgeRetrieval
2. /tmp/memoryweave/go/internal/api/routes/core.go
新增端点:
// POST /api/v1/graph/edge/feedback
func (a *API) EdgeFeedback(w http.ResponseWriter, r *http.Request) {
// body: { edge_id: string, helpful: bool }
// 调用 a.GraphStore.AddEdgeFeedback(edgeID, helpful)
}
3. /tmp/memoryweave/go/internal/api/server.go
注册新路由:
mux.HandleFunc("/api/v1/graph/edge/feedback", api.EdgeFeedback)
4. /tmp/memoryweave/go/internal/api/routes/core.go
在 Recall handler 中,当结果返回时(行 292),遍历每条结果的 edge ID,递增 retrieval_count。
验证方法
# 提交反馈
curl -s -X POST -H "X-API-Key: zhiyi-dev-key-2026" \
-H "Content-Type: application/json" \
-d '{"edge_id":"e_xxx","helpful":true}' \
http://localhost:7821/api/v1/graph/edge/feedback
# 验证 trust_score 更新
sqlite3 /var/lib/memoryweave/graph.db "SELECT id, trust_score, retrieval_count, helpful_count FROM graph_edges LIMIT 5"