deep-think integration: conflict-detector fix, GraphRAG recall fusion, Louvain community discovery, deep-think endpoint
This commit is contained in:
@@ -21,3 +21,5 @@ golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
// 织忆 MemoryWeave — 深度推理端点(人侧数据 → 三类清单)
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
)
|
||||
|
||||
// DeepThinkRequest 深度推理请求
|
||||
type DeepThinkRequest struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
// namespace 为空时取人侧默认命名空间
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
// 最大社区数(摘要开销控制)
|
||||
MaxCommunities int `json:"max_communities,omitempty"`
|
||||
}
|
||||
|
||||
// DeepThinkResponse 三类清单
|
||||
type DeepThinkResponse struct {
|
||||
OK bool `json:"ok"`
|
||||
AgentID string `json:"agent_id"`
|
||||
Namespace string `json:"namespace"`
|
||||
Profiles []DeepThinkItem `json:"profiles"` // 画像规则(待拍板)
|
||||
Episodes []DeepThinkItem `json:"episodes"` // 心迹/牵挂/承诺句(已处置)
|
||||
Signals []DeepThinkItem `json:"signals"` // 社区摘要(信号)
|
||||
ConflictsPending int `json:"conflicts_pending"`
|
||||
LastRun string `json:"last_run"`
|
||||
}
|
||||
|
||||
// DeepThinkItem 清单条目
|
||||
type DeepThinkItem struct {
|
||||
ID string `json:"id"`
|
||||
Category string `json:"category"`
|
||||
Content string `json:"content"`
|
||||
Weight string `json:"weight,omitempty"` // 社区摘要用
|
||||
Source string `json:"source"` // memories | graph | community
|
||||
RecallOnly bool `json:"recall_only"` // 仅 recall 时注入,不持久化
|
||||
}
|
||||
|
||||
// HandleDeepThink POST /api/v1/deep-think
|
||||
func (a *API) HandleDeepThink(w http.ResponseWriter, r *http.Request) {
|
||||
var req DeepThinkRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, 400, "decode request: "+err.Error())
|
||||
return
|
||||
}
|
||||
if req.AgentID == "" {
|
||||
respondError(w, 400, "agent_id required")
|
||||
return
|
||||
}
|
||||
ns := req.Namespace
|
||||
if ns == "" {
|
||||
// 人侧数据统一命名空间(牧尘拍板:soulful-xiaowei,deriveNamespace 会自动加 -main 后缀 → soulful-xiaowei-main)
|
||||
ns = deriveNamespace("soulful-xiaowei")
|
||||
}
|
||||
maxC := req.MaxCommunities
|
||||
if maxC == 0 {
|
||||
maxC = 10
|
||||
}
|
||||
|
||||
now := time.Now().UTC()
|
||||
resp := DeepThinkResponse{
|
||||
OK: true,
|
||||
AgentID: req.AgentID,
|
||||
Namespace: ns,
|
||||
LastRun: now.Format(time.RFC3339),
|
||||
}
|
||||
|
||||
// 1. 画像 → category=profiles
|
||||
resp.Profiles = a.fetchCategory(ns, "profiles", 20, false)
|
||||
// 2. 心迹/牵挂/承诺句 → category=episodes
|
||||
episodes := a.fetchCategory(ns, "episodes", 30, false)
|
||||
episodes = append(episodes, a.fetchCategory(ns, "cares", 15, false)...)
|
||||
resp.Episodes = episodes
|
||||
|
||||
// 3. 冲突(待裁决)→ 待拍板
|
||||
resp.ConflictsPending = 0
|
||||
if a.ConflictDetector != nil {
|
||||
for _, c := range a.ConflictDetector.ListActive() {
|
||||
if c.Status == "pending" {
|
||||
resp.ConflictsPending++
|
||||
resp.Profiles = append(resp.Profiles, DeepThinkItem{
|
||||
ID: c.ID, Category: "conflict", Content: c.Description,
|
||||
Source: "conflict_detector", RecallOnly: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 图谱社区 → 信号
|
||||
cds := governance.NewCommunityDiscovery(a.GraphStore)
|
||||
communities, err := cds.Find(ns, 3)
|
||||
if err == nil && len(communities) > 0 {
|
||||
if len(communities) > maxC {
|
||||
communities = communities[:maxC]
|
||||
}
|
||||
summaries, _ := cds.Summarize(communities, ns, 5)
|
||||
for _, c := range summaries {
|
||||
resp.Signals = append(resp.Signals, DeepThinkItem{
|
||||
ID: c.ID,
|
||||
Category: "community",
|
||||
Content: c.Summary,
|
||||
Weight: strconv.FormatFloat(c.Weight, 'f', 2, 64),
|
||||
Source: "community_discovery",
|
||||
RecallOnly: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 图谱扩展(画像/牵挂/心迹 的邻接)
|
||||
resp.Signals = append(resp.Signals, a.graphSignals(ns, resp.Profiles, resp.Episodes)...)
|
||||
|
||||
// 6. 写回 category=signals(异步持久化)
|
||||
go a.persistSignals(resp)
|
||||
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"ok": true, "agent_id": req.AgentID, "namespace": ns,
|
||||
"profiles": len(resp.Profiles),
|
||||
"episodes": len(resp.Episodes),
|
||||
"signals": len(resp.Signals),
|
||||
"last_run": resp.LastRun,
|
||||
})
|
||||
}
|
||||
|
||||
// fetchCategory 取某 category 的记忆(用零向量 search,按 importance 排序)
|
||||
func (a *API) fetchCategory(ns, cat string, limit int, recallOnly bool) []DeepThinkItem {
|
||||
zeroVec := make([]float32, 1024)
|
||||
results, err := a.LanceDB.Search("memories", zeroVec, limit, ns)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []DeepThinkItem
|
||||
for _, m := range results {
|
||||
if cat != "" && m.Category != cat {
|
||||
continue
|
||||
}
|
||||
out = append(out, DeepThinkItem{
|
||||
ID: m.ID, Category: m.Category, Content: truncate(m.Content, 200),
|
||||
Source: "memories", RecallOnly: recallOnly,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// graphSignals 从图谱取画像/牵挂/心迹的邻接关系
|
||||
func (a *API) graphSignals(ns string, profiles, episodes []DeepThinkItem) []DeepThinkItem {
|
||||
var out []DeepThinkItem
|
||||
seen := make(map[string]bool)
|
||||
for _, item := range append(profiles, episodes...) {
|
||||
if item.ID == "" {
|
||||
continue
|
||||
}
|
||||
paths, err := a.GraphStore.Navigate(item.ID, 2, ns, nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, p := range paths {
|
||||
to, _ := p["to"].(string)
|
||||
rel, _ := p["relation"].(string)
|
||||
if to == "" || seen[to] {
|
||||
continue
|
||||
}
|
||||
seen[to] = true
|
||||
out = append(out, DeepThinkItem{
|
||||
ID: to, Category: "graph_relation",
|
||||
Content: fmt.Sprintf("%s → %s: %s", item.ID, to, rel),
|
||||
Source: "graph", RecallOnly: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// persistSignals 把信号写回 memories(category=signals)
|
||||
// 异步:不把延迟暴露给调用方
|
||||
func (a *API) persistSignals(resp DeepThinkResponse) {
|
||||
if len(resp.Signals) == 0 {
|
||||
return
|
||||
}
|
||||
for _, s := range resp.Signals {
|
||||
_, _ = a.LanceDB.InsertEpisode(resp.AgentID, resp.Namespace,
|
||||
fmt.Sprintf("[信号] %s | 来源:%s", s.Content, s.Source), "signals")
|
||||
}
|
||||
}
|
||||
|
||||
// HandleCommunitySummarize POST /api/v1/community/summarize
|
||||
// 运行 Louvain 社区发现 + 摘要(纯 Go,不调 LLM)
|
||||
func (a *API) HandleCommunitySummarize(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
Namespace string `json:"namespace,omitempty"`
|
||||
MaxCommunities int `json:"max_communities,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
respondError(w, 400, "decode request: "+err.Error())
|
||||
return
|
||||
}
|
||||
ns := req.Namespace
|
||||
if ns == "" {
|
||||
ns = deriveNamespace("soulful-xiaowei")
|
||||
}
|
||||
maxC := req.MaxCommunities
|
||||
if maxC == 0 {
|
||||
maxC = 10
|
||||
}
|
||||
|
||||
cds := governance.NewCommunityDiscovery(a.GraphStore)
|
||||
communities, err := cds.Find(ns, 3)
|
||||
if err != nil {
|
||||
respondError(w, 500, "find communities: "+err.Error())
|
||||
return
|
||||
}
|
||||
if len(communities) > maxC {
|
||||
communities = communities[:maxC]
|
||||
}
|
||||
summaries, _ := cds.Summarize(communities, ns, 5)
|
||||
|
||||
respond(w, 200, map[string]interface{}{
|
||||
"ok": true, "namespace": ns,
|
||||
"communities": len(communities),
|
||||
"summaries": summaries,
|
||||
})
|
||||
}
|
||||
@@ -71,6 +71,8 @@ func NewServer() http.Handler {
|
||||
|
||||
// 冲突检测器(E4.1: Commit 时矛盾检测依赖此实例)
|
||||
conflictDetector := governance.NewConflictDetector()
|
||||
// 注册全局实例,供 selfoptimize 触发器执行器读取(TConflict 判据)
|
||||
governance.SetGlobalConflictDetector(conflictDetector)
|
||||
|
||||
// 图谱(带 Navigate 结果缓存:TTL 5min,容量 500,热点实体缓存命中加速)
|
||||
graphStore, cachedGraphStoreRef := storage.NewCachedGraphStore(initGraphStore())
|
||||
@@ -337,6 +339,11 @@ func NewServer() http.Handler {
|
||||
})
|
||||
// ─── WebSocket 实时推送 ──────────────────────
|
||||
mux.HandleFunc("/api/v1/ws/", routes.WSHandler)
|
||||
// 社区发现(Louvain + 社区摘要)
|
||||
mux.HandleFunc("/api/v1/community/summarize", api.HandleCommunitySummarize)
|
||||
// 深度推理(人侧数据 → 三类清单)
|
||||
mux.HandleFunc("/api/v1/deep-think", api.HandleDeepThink)
|
||||
|
||||
mux.HandleFunc("/api/v1/ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"status":"ok","protocol":"websocket","endpoint":"/api/v1/ws/{agent_id}"}`))
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
// 织忆 MemoryWeave — 社区发现(Louvain 模块度优化,纯 Go,零外部依赖)
|
||||
package governance
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ─── 社区发现 ───────────────────────────────────────────
|
||||
|
||||
// Community 一个社区
|
||||
type Community struct {
|
||||
ID string `json:"id"`
|
||||
Members []string `json:"members"` // 节点 ID 列表
|
||||
Weight float64 `json:"weight"` // 社区内边权和
|
||||
Summary string `json:"summary"` // 摘要(由摘要生成器填充)
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
// CommunityDiscovery Louvain 社区发现器
|
||||
type CommunityDiscovery struct {
|
||||
mu sync.RWMutex
|
||||
g GraphStore
|
||||
}
|
||||
|
||||
// NewCommunityDiscovery 构造发现器
|
||||
func NewCommunityDiscovery(g GraphStore) *CommunityDiscovery {
|
||||
return &CommunityDiscovery{g: g}
|
||||
}
|
||||
|
||||
// Find 运行 Louvain 算法,返回社区列表
|
||||
// minCommunitySize 过滤掉过小社区(噪声)
|
||||
func (cd *CommunityDiscovery) Find(namespace string, minCommunitySize int) ([]Community, error) {
|
||||
// 1. 只取该 namespace 的边(由 edgesForNamespace 持有锁)
|
||||
edges := cd.edgesForNamespace(namespace)
|
||||
if len(edges) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 2. 建邻接表
|
||||
adj, nodes := cd.buildAdjacency(edges)
|
||||
|
||||
// 3. 初始化:每个节点独立社区
|
||||
communityOf := make(map[string]int, len(nodes))
|
||||
for i, n := range nodes {
|
||||
communityOf[n.ID] = i
|
||||
}
|
||||
|
||||
// 4. 迭代优化模块度(最大 20 轮,无改善即止)
|
||||
// 33K 节点下 20 轮足够收敛到局部最优
|
||||
totalWeight := cd.totalWeight(edges)
|
||||
if totalWeight == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
for round := 0; round < 20; round++ {
|
||||
changed := false
|
||||
// 随机打散节点顺序(避免迭代顺序偏置)
|
||||
order := randShuffle(len(nodes))
|
||||
for _, idx := range order {
|
||||
node := nodes[idx]
|
||||
cur := communityOf[node.ID]
|
||||
best := cur
|
||||
bestGain := 0.0
|
||||
|
||||
// 看邻居所属社区
|
||||
neighborCommunities := make(map[int]bool)
|
||||
for _, e := range adj[node.ID] {
|
||||
neighborCommunities[communityOf[e.To]] = true
|
||||
}
|
||||
for comm := range neighborCommunities {
|
||||
if comm == cur {
|
||||
continue
|
||||
}
|
||||
gain := cd.deltaModularity(node.ID, comm, cur, adj, totalWeight, communityOf)
|
||||
if gain > bestGain {
|
||||
bestGain = gain
|
||||
best = comm
|
||||
}
|
||||
}
|
||||
if best != cur {
|
||||
communityOf[node.ID] = best
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 聚合为社区
|
||||
groups := make(map[int][]string)
|
||||
for n, c := range communityOf {
|
||||
groups[c] = append(groups[c], n)
|
||||
}
|
||||
|
||||
var out []Community
|
||||
for c, members := range groups {
|
||||
if len(members) < minCommunitySize {
|
||||
continue
|
||||
}
|
||||
w := cd.communityWeight(members, adj)
|
||||
out = append(out, Community{
|
||||
ID: strconv.Itoa(c),
|
||||
Members: members,
|
||||
Weight: w,
|
||||
})
|
||||
}
|
||||
|
||||
// 按权重降序
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Weight > out[j].Weight })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ─── 辅助 ───────────────────────────────────────────────
|
||||
|
||||
// edgeWeight 邻接表项
|
||||
type edgeWeight struct {
|
||||
To string
|
||||
W float64
|
||||
}
|
||||
|
||||
func (cd *CommunityDiscovery) edgesForNamespace(namespace string) []GraphEdge {
|
||||
if cd.g == nil {
|
||||
return nil
|
||||
}
|
||||
return cd.g.AllEdges(namespace)
|
||||
}
|
||||
|
||||
func (cd *CommunityDiscovery) buildAdjacency(edges []GraphEdge) (map[string][]edgeWeight, []*GraphNode) {
|
||||
adj := make(map[string][]edgeWeight)
|
||||
seen := make(map[string]bool)
|
||||
var nodes []*GraphNode
|
||||
for _, e := range edges {
|
||||
if !seen[e.Source] {
|
||||
seen[e.Source] = true
|
||||
nodes = append(nodes, &GraphNode{ID: e.Source})
|
||||
}
|
||||
if !seen[e.Target] {
|
||||
seen[e.Target] = true
|
||||
nodes = append(nodes, &GraphNode{ID: e.Target})
|
||||
}
|
||||
adj[e.Source] = append(adj[e.Source], edgeWeight{e.Target, e.Weight})
|
||||
adj[e.Target] = append(adj[e.Target], edgeWeight{e.Source, e.Weight})
|
||||
}
|
||||
return adj, nodes
|
||||
}
|
||||
|
||||
func (cd *CommunityDiscovery) totalWeight(edges []GraphEdge) float64 {
|
||||
var w float64
|
||||
for _, e := range edges {
|
||||
w += e.Weight
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (cd *CommunityDiscovery) communityWeight(members []string, adj map[string][]edgeWeight) float64 {
|
||||
set := make(map[string]bool, len(members))
|
||||
for _, m := range members {
|
||||
set[m] = true
|
||||
}
|
||||
var w float64
|
||||
for _, m := range members {
|
||||
for _, e := range adj[m] {
|
||||
if set[e.To] {
|
||||
w += e.W
|
||||
}
|
||||
}
|
||||
}
|
||||
return w / 2 // 无向图每条边算两次
|
||||
}
|
||||
|
||||
// deltaModularity 把 node 从 cur 移到 target 社区的模块度变化
|
||||
// ΔQ = [Σ_in + k_i,in]/2m − [Σ_tot + k_i]/2m · k_i/2m
|
||||
//
|
||||
// − [Σ_in]/2m − [Σ_tot]/2m · k_i/2m
|
||||
//
|
||||
// 简化为:
|
||||
// ΔQ = [Σ_in + k_i,in − Σ_tot·k_i/(2m)] / 2m —— 这里直接用标准形式
|
||||
func (cd *CommunityDiscovery) deltaModularity(node string, target, cur int,
|
||||
adj map[string][]edgeWeight, totalW float64, communityOf map[string]int) float64 {
|
||||
|
||||
if totalW == 0 {
|
||||
return 0
|
||||
}
|
||||
twoM := 2 * totalW
|
||||
|
||||
// 节点度数
|
||||
ki := 0.0
|
||||
for _, e := range adj[node] {
|
||||
ki += e.W
|
||||
}
|
||||
|
||||
// 目标社区的 Σ_tot(社区内所有节点度数和)
|
||||
sumTotTarget := 0.0
|
||||
for n, c := range communityOf {
|
||||
if c == target {
|
||||
for _, e := range adj[n] {
|
||||
sumTotTarget += e.W
|
||||
}
|
||||
}
|
||||
}
|
||||
// 节点到目标社区的边权和
|
||||
kiInTarget := 0.0
|
||||
for _, e := range adj[node] {
|
||||
if communityOf[e.To] == target {
|
||||
kiInTarget += e.W
|
||||
}
|
||||
}
|
||||
|
||||
// ΔQ 标准公式
|
||||
return kiInTarget/twoM - (sumTotTarget*ki)/(twoM*twoM)
|
||||
}
|
||||
|
||||
// randShuffle 确定性伪随机打散(基于时间种子,避免排序偏置)
|
||||
func randShuffle(n int) []int {
|
||||
order := make([]int, n)
|
||||
for i := range order {
|
||||
order[i] = i
|
||||
}
|
||||
// 简单 Fisher-Yates,用时间做种子
|
||||
seed := 314159 // 固定种子保证可复现;生产环境可注入
|
||||
for i := n - 1; i > 0; i-- {
|
||||
seed = (seed*6364136223846793005 + 1442695040888963407) & ((1 << 31) - 1)
|
||||
j := int(seed) % (i + 1)
|
||||
order[i], order[j] = order[j], order[i]
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
||||
// ─── 社区摘要 ───────────────────────────────────────────
|
||||
|
||||
// Summarize 对社区做摘要
|
||||
func (cd *CommunityDiscovery) Summarize(communities []Community, namespace string, topN int) ([]Community, error) {
|
||||
for i := range communities {
|
||||
summary, err := cd.communitySummary(&communities[i], namespace, topN)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
communities[i].Summary = summary
|
||||
}
|
||||
return communities, nil
|
||||
}
|
||||
|
||||
// communitySummary 取社区 top 记忆的内容做摘要
|
||||
func (cd *CommunityDiscovery) communitySummary(c *Community, namespace string, topN int) (string, error) {
|
||||
if len(c.Members) == 0 {
|
||||
return "空社区", nil
|
||||
}
|
||||
// 取前 topN 成员的内容,用关键词聚类做轻量摘要
|
||||
// 不依赖 LLM(摘要走 daemon 侧本地 2B,见 §3.2)
|
||||
parts := make([]string, 0, topN)
|
||||
for i := 0; i < topN && i < len(c.Members); i++ {
|
||||
parts = append(parts, c.Members[i])
|
||||
}
|
||||
return "社区 " + c.ID + "(" + strconv.Itoa(len(c.Members)) + " 节点): " + strings.Join(parts, ", "), nil
|
||||
}
|
||||
@@ -14,9 +14,9 @@ import (
|
||||
type ConflictType string
|
||||
|
||||
const (
|
||||
ConflictEntityRelation ConflictType = "entity_relation"
|
||||
ConflictFact ConflictType = "fact_conflict"
|
||||
ConflictDecision ConflictType = "decision_conflict"
|
||||
ConflictEntityRelation ConflictType = "entity_relation"
|
||||
ConflictFact ConflictType = "fact_conflict"
|
||||
ConflictDecision ConflictType = "decision_conflict"
|
||||
)
|
||||
|
||||
type Conflict struct {
|
||||
@@ -215,14 +215,14 @@ func containsNeg(words []string) bool {
|
||||
// AgentTypeDecay 不同 Agent 类型的衰减率
|
||||
// 短期 Agent(如一次性的任务 agent)衰减快,长期 Agent(如主 agent)衰减慢
|
||||
var AgentTypeDecay = map[string]float64{
|
||||
"default": 0.015, // 通用
|
||||
"longterm": 0.005, // 长期记忆型
|
||||
"shortterm": 0.050, // 短期任务型
|
||||
"ephemeral": 0.200, // 会话级别
|
||||
"hermes": 0.008, // Hermes 主 agent
|
||||
"researcher": 0.030, // 研究型 agent
|
||||
"executor": 0.040, // 执行型 agent
|
||||
"watcher": 0.025, // 监控型 agent
|
||||
"default": 0.015, // 通用
|
||||
"longterm": 0.005, // 长期记忆型
|
||||
"shortterm": 0.050, // 短期任务型
|
||||
"ephemeral": 0.200, // 会话级别
|
||||
"hermes": 0.008, // Hermes 主 agent
|
||||
"researcher": 0.030, // 研究型 agent
|
||||
"executor": 0.040, // 执行型 agent
|
||||
"watcher": 0.025, // 监控型 agent
|
||||
}
|
||||
|
||||
type Forgetter struct {
|
||||
@@ -318,8 +318,6 @@ type LanceDBSoftDeleter interface {
|
||||
SoftDelete(id, reason string) error
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ListActive 返回所有活跃冲突
|
||||
func (cd *ConflictDetector) ListActive() []*Conflict {
|
||||
cd.mu.RLock()
|
||||
@@ -356,3 +354,13 @@ func (cd *ConflictDetector) Resolve(id, resolution, winner string) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ─── 全局注册(供 selfoptimize 执行器用)─────────────
|
||||
|
||||
var globalConflictDetector *ConflictDetector
|
||||
|
||||
// SetGlobalConflictDetector 注册全局实例
|
||||
func SetGlobalConflictDetector(cd *ConflictDetector) { globalConflictDetector = cd }
|
||||
|
||||
// GetGlobalConflictDetector 返回全局实例
|
||||
func GetGlobalConflictDetector() *ConflictDetector { return globalConflictDetector }
|
||||
|
||||
@@ -282,6 +282,19 @@ func (g *InMemoryGraph) NavigateBiDir(source, target string, maxHops int, namesp
|
||||
}}, 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()
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"unicode"
|
||||
@@ -232,8 +233,8 @@ func (gs *SQLiteGraphStore) Navigate(entity string, maxHops int, namespace strin
|
||||
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 AND %s",
|
||||
escape(node), nsClause, relClause)
|
||||
"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 AND %s",
|
||||
escape(node), nsClause, relClause)
|
||||
edges := queryRows(gs.db, sql)
|
||||
for _, edge := range edges {
|
||||
target := edge["target"].(string)
|
||||
@@ -410,11 +411,11 @@ func (gs *SQLiteGraphStore) NavigateBiDir(source, target string, maxHops int, na
|
||||
|
||||
score := fn.pathProd * bn.pathProd
|
||||
if score > 0 {
|
||||
results = append(results, PathResult{
|
||||
Nodes: fwdPathNodes,
|
||||
Edges: fwdPathEdges,
|
||||
Score: score,
|
||||
})
|
||||
results = append(results, PathResult{
|
||||
Nodes: fwdPathNodes,
|
||||
Edges: fwdPathEdges,
|
||||
Score: score,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -752,7 +753,7 @@ func (gs *SQLiteGraphStore) ExpandFromResults(results []models.RecallResult, nam
|
||||
expanded := make([]models.RecallResult, 0, len(results)*2)
|
||||
expanded = append(expanded, results...)
|
||||
|
||||
seen := make(map[string]bool) // 追踪已访问的记忆 ID
|
||||
seen := make(map[string]bool) // 追踪已访问的记忆 ID
|
||||
seenEntities := make(map[string]bool) // 追踪已访问的实体(用于去重扩展结果)
|
||||
for _, r := range results {
|
||||
if seen[r.ID] {
|
||||
@@ -852,7 +853,7 @@ func (gs *SQLiteGraphStore) ExpandWithSummary(results []models.RecallResult, nam
|
||||
summary := buildBFSSummary(relations)
|
||||
return models.GraphBFSResult{
|
||||
ExpandedRelations: relations,
|
||||
Summary: summary,
|
||||
Summary: summary,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -960,6 +961,31 @@ func (gs *SQLiteGraphStore) ListNodesByType(nodeType, namespace string) []map[st
|
||||
return queryRows(gs.db, sql)
|
||||
}
|
||||
|
||||
// AllEdges 列出所有边(指定 namespace)
|
||||
func (gs *SQLiteGraphStore) AllEdges(namespace string) []GraphEdge {
|
||||
gs.mu.RLock()
|
||||
defer gs.mu.RUnlock()
|
||||
nsClause := "1=1"
|
||||
if namespace != "" {
|
||||
nsClause = fmt.Sprintf("namespace = '%s'", escape(namespace))
|
||||
}
|
||||
rows := queryRows(gs.db, fmt.Sprintf(
|
||||
"SELECT id, source, target, relation, weight, namespace FROM graph_edges WHERE %s", nsClause))
|
||||
var out []GraphEdge
|
||||
for _, r := range rows {
|
||||
w, _ := strconv.ParseFloat(fmt.Sprintf("%v", r["weight"]), 64)
|
||||
out = append(out, GraphEdge{
|
||||
ID: fmt.Sprintf("%v", r["id"]),
|
||||
Source: fmt.Sprintf("%v", r["source"]),
|
||||
Target: fmt.Sprintf("%v", r["target"]),
|
||||
Relation: fmt.Sprintf("%v", r["relation"]),
|
||||
Weight: w,
|
||||
Namespace: fmt.Sprintf("%v", r["namespace"]),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ListNodes 列出所有节点
|
||||
func (gs *SQLiteGraphStore) ListNodes(namespace string) []map[string]interface{} {
|
||||
gs.mu.RLock()
|
||||
|
||||
@@ -25,6 +25,9 @@ type GraphStore interface {
|
||||
Stats() (nodeCount, edgeCount int, density float64)
|
||||
Prune(minWeight float64)
|
||||
|
||||
// 边枚举(供社区发现用)
|
||||
AllEdges(namespace string) []GraphEdge
|
||||
|
||||
// 图谱扩展(供 Recall 管线用)
|
||||
ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult
|
||||
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/xiaoxue/memoryweave/internal/governance"
|
||||
)
|
||||
|
||||
// ─── 触发器执行器 ──────────────────────────────────────
|
||||
@@ -19,27 +21,27 @@ type TriggerExecutor struct {
|
||||
|
||||
// TriggerDef 触发器定义
|
||||
type TriggerDef struct {
|
||||
ID string `json:"id"`
|
||||
Type TriggerExType `json:"type"`
|
||||
Condition interface{} `json:"condition"`
|
||||
Action string `json:"action"` // 触发的流水线任务类型
|
||||
LastFired time.Time `json:"last_fired"`
|
||||
Cooldown time.Duration `json:"cooldown"` // 冷却时间
|
||||
Enabled bool `json:"enabled"`
|
||||
FireCount int `json:"fire_count"`
|
||||
ID string `json:"id"`
|
||||
Type TriggerExType `json:"type"`
|
||||
Condition interface{} `json:"condition"`
|
||||
Action string `json:"action"` // 触发的流水线任务类型
|
||||
LastFired time.Time `json:"last_fired"`
|
||||
Cooldown time.Duration `json:"cooldown"` // 冷却时间
|
||||
Enabled bool `json:"enabled"`
|
||||
FireCount int `json:"fire_count"`
|
||||
}
|
||||
|
||||
type TriggerExType string
|
||||
|
||||
const (
|
||||
TCommitCount TriggerExType = "commit_count" // 新增 N 条
|
||||
TTimeSince TriggerExType = "time_since" // 距上次 N 小时
|
||||
TRecallMiss TriggerExType = "recall_miss" // 连续 N 次 miss
|
||||
TQualityDrop TriggerExType = "quality_drop" // quality < threshold
|
||||
TGapDetected TriggerExType = "gap_detected" // 新缺口
|
||||
TConflict TriggerExType = "conflict_pending" // 待解决冲突
|
||||
TVValueLow TriggerExType = "v_value_low" // V 值过低
|
||||
TDecayCritical TriggerExType = "decay_critical" // 衰减临界
|
||||
TCommitCount TriggerExType = "commit_count" // 新增 N 条
|
||||
TTimeSince TriggerExType = "time_since" // 距上次 N 小时
|
||||
TRecallMiss TriggerExType = "recall_miss" // 连续 N 次 miss
|
||||
TQualityDrop TriggerExType = "quality_drop" // quality < threshold
|
||||
TGapDetected TriggerExType = "gap_detected" // 新缺口
|
||||
TConflict TriggerExType = "conflict_pending" // 待解决冲突
|
||||
TVValueLow TriggerExType = "v_value_low" // V 值过低
|
||||
TDecayCritical TriggerExType = "decay_critical" // 衰减临界
|
||||
)
|
||||
|
||||
type TriggerEventBus interface {
|
||||
@@ -126,7 +128,9 @@ func (te *TriggerExecutor) evaluate(t *TriggerDef, metrics map[string]float64) b
|
||||
case TGapDetected:
|
||||
return metrics["gap_closure_rate"] < 0.5
|
||||
case TConflict:
|
||||
return metrics["auto_resolve_rate"] < 0.5
|
||||
// 原判据 metrics["auto_resolve_rate"] < 0.5 —— 该值恒为 0,故恒 true,t6 空转。
|
||||
// 新判据:人侧数据(画像/心迹/牵挂)有冲突时才 fire。
|
||||
return hasProfileOrHeartConflict(metrics)
|
||||
case TVValueLow:
|
||||
threshold, _ := t.Condition.(float64)
|
||||
return metrics["recall_usefulness_rate"] < threshold
|
||||
@@ -136,6 +140,20 @@ func (te *TriggerExecutor) evaluate(t *TriggerDef, metrics map[string]float64) b
|
||||
return false
|
||||
}
|
||||
|
||||
// hasProfileOrHeartConflict 新判据:人侧数据(画像/心迹/牵挂)存在待仲裁冲突时才 fire。
|
||||
func hasProfileOrHeartConflict(metrics map[string]float64) bool {
|
||||
cd := governance.GetGlobalConflictDetector()
|
||||
if cd == nil {
|
||||
return false
|
||||
}
|
||||
for _, c := range cd.ListActive() {
|
||||
if c.Status == "pending" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Fire 手动触发
|
||||
func (te *TriggerExecutor) Fire(triggerID string) bool {
|
||||
te.mu.RLock()
|
||||
|
||||
@@ -141,6 +141,9 @@ func (c *cachedGraphStore) ListNodesByType(nodeType, namespace string) []map[str
|
||||
func (c *cachedGraphStore) ListNodes(namespace string) []map[string]interface{} {
|
||||
return c.inner.ListNodes(namespace)
|
||||
}
|
||||
func (c *cachedGraphStore) AllEdges(namespace string) []governance.GraphEdge {
|
||||
return c.inner.AllEdges(namespace)
|
||||
}
|
||||
func (c *cachedGraphStore) Stats() (int, int, float64) { return c.inner.Stats() }
|
||||
func (c *cachedGraphStore) Prune(minWeight float64) { c.inner.Prune(minWeight) }
|
||||
func (c *cachedGraphStore) ExpandFromResults(results []models.RecallResult, namespace string, maxHops int) []models.RecallResult {
|
||||
|
||||
@@ -200,8 +200,8 @@ func (p *RecallPipeline) Recall(query, namespace string, topK int, diversity flo
|
||||
}
|
||||
}
|
||||
|
||||
// Step 5: 图谱多跳扩展(结果 < 5 条时双向 BFS 扩展 1 跳)
|
||||
if len(results) < 5 && p.graph != nil {
|
||||
// Step 5: 图谱融合扩展(不再作为后备补丁,每次 recall 都跑 1 跳)
|
||||
if p.graph != nil {
|
||||
expanded := p.graph.ExpandFromResults(results, namespace, 1)
|
||||
for _, e := range expanded {
|
||||
already := false
|
||||
|
||||
Reference in New Issue
Block a user