Files
memoryweave/go/internal/api/routes/peer.go
T

336 lines
11 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 — P3 Peer Representation API(t_f8fc97e6,设计 §6.1)
//
// 端点:
//
// POST /api/v1/peer/{id}/refresh 手动刷新某实体的四层推理画像(显式触发)
// GET /api/v1/peer/{id}/explain 解释为何这样理解该实体(可审计:画像 + 来源记忆)
// POST /api/v1/recall/peer?peer_id=… 召回某 peer 的推理画像(env 门控 ZHIYI_PEER_RECALL)
//
// 设计约束(与 L2 pattern / L3 skillgen 同源):
//
// · refresh/explain 是显式 API,不挂 cron ⇒ 默认零行为变化。
// · 召回注入走独立端点 + env 门控 ZHIYI_PEER_RECALL,默认 0 ⇒ 主召回管线逐条不变(AC2)。
// · peers 表在 graph.db(短命 modernc),不碰 state.db。
package routes
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"github.com/xiaoxue/memoryweave/internal/governance"
"github.com/xiaoxue/memoryweave/internal/models"
"github.com/xiaoxue/memoryweave/internal/peer"
"github.com/xiaoxue/memoryweave/internal/storage"
)
// PeerAPI P3 peer 表示端点。
type PeerAPI struct {
Store *peer.Store
Reasoner peer.Reasoner
LDB func() storage.LanceDB // 扫 L1 记忆(explicit 层来源)
GraphStore governance.GraphStore // 图谱上下文(推理输入)
}
// NewPeerAPI 构造。
func NewPeerAPI(store *peer.Store, reasoner peer.Reasoner, ldb func() storage.LanceDB, g governance.GraphStore) *PeerAPI {
return &PeerAPI{Store: store, Reasoner: reasoner, LDB: ldb, GraphStore: g}
}
// peerSubPath 解析 /api/v1/peer/{id}/{action} 子路径。
func peerSubPath(path string) (id, action string) {
const prefix = "/api/v1/peer/"
if !strings.HasPrefix(path, prefix) {
return "", ""
}
rest := strings.TrimPrefix(path, prefix) // <id>/refresh 或 <id>/explain
parts := strings.Split(rest, "/")
if len(parts) != 2 || parts[0] == "" {
return "", ""
}
dec, err := url.PathUnescape(parts[0])
if err != nil {
return "", ""
}
return dec, parts[1]
}
// Sub 分发 /api/v1/peer/{id}/refresh 与 /api/v1/peer/{id}/explain。
func (pa *PeerAPI) Sub(w http.ResponseWriter, r *http.Request) {
id, action := peerSubPath(r.URL.Path)
if id == "" {
respondError(w, 404, "peer id required")
return
}
switch action {
case "refresh":
if r.Method != http.MethodPost {
http.Error(w, "POST only", http.StatusMethodNotAllowed)
return
}
pa.Refresh(w, r, id)
case "explain":
if r.Method != http.MethodGet {
http.Error(w, "GET only", http.StatusMethodNotAllowed)
return
}
pa.Explain(w, r, id)
default:
respondError(w, 404, "unknown action: "+action)
}
}
// RefreshAsync 异步刷新某实体的四层画像(推理不阻塞主流程,AC4)。
// 返回一个 done channel,调用方可不等待(非阻塞);推理在后台 goroutine 完成。
// 任何错误只记日志,不影响调用方。
func (pa *PeerAPI) RefreshAsync(id, namespace string) chan error {
done := make(chan error, 1)
if pa == nil || pa.Store == nil || pa.Reasoner == nil {
done <- fmt.Errorf("peer 未装配")
return done
}
go func() {
done <- pa.refresh(id, namespace, 2000)
}()
return done
}
// RefreshFromContent 提交新记忆后异步刷新内容里出现的已知实体(设计「新记忆进入 → 不阻塞主流程
// → 更新该 peer 表示」)。匹配:content 含某 peer_id 子串即触发。全部 goroutine 内执行,立即返回。
// 由 server.go 在 commit 处理器里以 ZHIYI_PEER_RECALL=1 门控调用;默认关 ⇒ 不触发。
func (pa *PeerAPI) RefreshFromContent(content, namespace string) {
if pa == nil || pa.Store == nil || content == "" {
return
}
peers, err := pa.Store.List(200)
if err != nil || len(peers) == 0 {
return
}
for _, p := range peers {
if p.PeerID != "" && strings.Contains(content, p.PeerID) {
go pa.refresh(p.PeerID, namespace, 2000)
}
}
}
// refresh 实际刷新编排(同步执行体;由 RefreshAsync / RefreshFromContent 包 goroutine)。
func (pa *PeerAPI) refresh(id, namespace string, limit int) error {
explicit, _, scanErr := pa.collectExplicit(id, namespace, limit)
if scanErr != nil {
return scanErr
}
graphCtx := pa.collectGraphContext(id)
if _, err := peer.BuildPeer(pa.Store, pa.Reasoner, id, explicit.facts, explicit.prefs, explicit.skills, graphCtx); err != nil {
return err
}
return nil
}
// Refresh POST /api/v1/peer/{id}/refresh — 扫 L1 记忆 + 图谱上下文 → 四层推理 → 写 peers 表。
// body 可选 {"namespace": "...", "limit": N}(namespace 空 = 全库)。
func (pa *PeerAPI) Refresh(w http.ResponseWriter, r *http.Request, id string) {
if pa.Store == nil || pa.Reasoner == nil {
respondError(w, 503, "peer 未装配(Store/Reasoner 为空)")
return
}
var req struct {
Namespace string `json:"namespace"`
Limit int `json:"limit"`
}
if r.Body != nil {
_ = json.NewDecoder(r.Body).Decode(&req)
}
if req.Limit <= 0 {
req.Limit = 2000
}
// 1. 扫 L1 记忆(LanceDB),提取 explicit 层
explicit, matched, scanErr := pa.collectExplicit(id, req.Namespace, req.Limit)
if scanErr != nil {
respondError(w, 500, "scan memories: "+scanErr.Error())
return
}
// 2. 图谱上下文(实体 1 跳邻居名)
graphCtx := pa.collectGraphContext(id)
// 3. 四层推理 + 写库
p, perr := peer.BuildPeer(pa.Store, pa.Reasoner, id, explicit.facts, explicit.prefs, explicit.skills, graphCtx)
if perr != nil {
respondError(w, 400, "build peer: "+perr.Error())
return
}
respond(w, 200, map[string]interface{}{
"peer": p,
"matched": matched,
"scanned": req.Limit,
"graph_ctx": graphCtx,
"has_reason": len(p.InferredTraits) > 0 || len(p.InferredGoals) > 0 || p.HypothesizedContext != "",
})
}
// Explain GET /api/v1/peer/{id}/explain — 可审计解释:画像 + 来源记忆。
func (pa *PeerAPI) Explain(w http.ResponseWriter, r *http.Request, id string) {
if pa.Store == nil {
respondError(w, 503, "peer 未装配(Store 为空)")
return
}
p, err := pa.Store.Get(id)
if err != nil {
if err == sql.ErrNoRows {
respondError(w, 404, "peer not found: "+id+"(先 POST /peer/{id}/refresh 生成画像)")
} else {
respondError(w, 500, "get peer: "+err.Error())
}
return
}
// 来源记忆:扫 L1 里含该实体的记忆(仅读,不改库)
src := []string{}
if pa.LDB != nil {
if ldb := pa.LDB(); ldb != nil {
if recs, serr := ldb.Scan(2000, ""); serr == nil {
for _, m := range recs {
if strings.Contains(m.Content, id) {
src = append(src, m.Content)
}
}
}
}
}
respond(w, 200, map[string]interface{}{"peer": p, "source_memories": src})
}
// RecallPeer POST /api/v1/recall/peer?peer_id=… — 召回某 peer 的四层推理画像。
// env 门控 ZHIYI_PEER_RECALL:默认 0 → 404(零变化);=1 → 返回画像 JSON(AC3 判据)。
func (pa *PeerAPI) RecallPeer(w http.ResponseWriter, r *http.Request) {
if !peerRecallEnabled() {
respondError(w, 404, "peer recall 默认关(ZHIYI_PEER_RECALL 未设/≠1)")
return
}
pid := r.URL.Query().Get("peer_id")
if pid == "" {
respondError(w, 400, "peer_id required")
return
}
if pa.Store == nil {
respondError(w, 503, "peer 未装配(Store 为空)")
return
}
p, err := pa.Store.Get(pid)
if err != nil {
if err == sql.ErrNoRows {
respondError(w, 404, "peer not found: "+pid)
} else {
respondError(w, 500, "get peer: "+err.Error())
}
return
}
respond(w, 200, map[string]interface{}{
"peer_id": p.PeerID,
"portrait": map[string]interface{}{
"explicit": map[string]interface{}{"facts": p.Facts, "preferences": p.Preferences, "skills": p.Skills},
"deductive": map[string]interface{}{"traits": p.InferredTraits, "goals": p.InferredGoals},
"inductive": map[string]interface{}{"patterns": p.Patterns},
"abductive": map[string]interface{}{"hypothesized_context": p.HypothesizedContext},
},
"updated_at": p.UpdatedAt,
})
}
// explicitResult explicit 层收集结果。
type explicitResult struct {
facts, prefs, skills []string
}
// collectExplicit 扫 L1 记忆并提取 explicit 层。namespace 空 = 全库。
func (pa *PeerAPI) collectExplicit(id, namespace string, limit int) (explicitResult, int, error) {
var res explicitResult
if pa.LDB == nil {
return res, 0, nil
}
ldb := pa.LDB()
if ldb == nil {
return res, 0, nil
}
recs, err := ldb.Scan(limit, namespace)
if err != nil {
return res, 0, err
}
facts, prefs, skills, matched := peer.CollectFacts(recs, id)
return explicitResult{facts: facts, prefs: prefs, skills: skills}, matched, nil
}
// collectGraphContext 取实体图谱 1 跳邻居名作为推理上下文(读图,只读不改)。
func (pa *PeerAPI) collectGraphContext(id string) []string {
if pa.GraphStore == nil {
return nil
}
paths, err := pa.GraphStore.Navigate(id, 1, "", nil)
if err != nil || len(paths) == 0 {
return nil
}
seen := map[string]bool{}
var out []string
for _, p := range paths {
for _, k := range []string{"to", "target"} {
if v, ok := p[k].(string); ok && v != "" && !seen[v] && v != id {
seen[v] = true
out = append(out, v)
}
}
}
if len(out) > 10 {
out = out[:10]
}
return out
}
// peerRecallEnabled 每次调用读 env(默认关,零行为变化)。
func peerRecallEnabled() bool {
switch strings.ToLower(os.Getenv("ZHIYI_PEER_RECALL")) {
case "1", "true", "on":
return true
}
return false
}
// GetRecallResults 供 storage.PeerRecallProvider 装配(server.go 在 ZHIYI_PEER_RECALL=1
// 时注册)。query 命中某实体 → 返回该 peer 的四层画像(Category="peer")。
// 命中判定:query 里含 peer_id 子串(大小写不敏感);取最多 topK 个。无命中 → 空。
func (pa *PeerAPI) GetRecallResults(query, namespace string, topK int) []models.RecallResult {
if pa == nil || pa.Store == nil || topK <= 0 {
return nil
}
peers, err := pa.Store.List(200)
if err != nil || len(peers) == 0 {
return nil
}
q := strings.ToLower(strings.TrimSpace(query))
var out []models.RecallResult
for _, p := range peers {
if p.PeerID != "" && q != "" && strings.Contains(q, strings.ToLower(p.PeerID)) {
content := "peer 画像: " + p.PeerID +
" | 事实: " + strings.Join(p.Facts, "; ") +
" | 偏好: " + strings.Join(p.Preferences, "; ") +
" | 技能: " + strings.Join(p.Skills, "; ") +
" | 演绎特质: " + strings.Join(p.InferredTraits, "; ") +
" | 演绎目标: " + strings.Join(p.InferredGoals, "; ") +
" | 归纳模式: " + strings.Join(p.Patterns, "; ") +
" | 最佳解释: " + p.HypothesizedContext
out = append(out, models.RecallResult{
ID: "peer:" + p.PeerID,
Content: content,
Category: "peer",
Score: 1.0,
Namespace: namespace,
Source: "peer_representation",
})
if len(out) >= topK {
break
}
}
}
return out
}