diff --git a/internal/agent/core/eventloop.go b/internal/agent/core/eventloop.go index 9e8575f..467b422 100644 --- a/internal/agent/core/eventloop.go +++ b/internal/agent/core/eventloop.go @@ -373,20 +373,13 @@ func (a *Agent) emitResponse(evt *agentIO.InputEvent, response string) { // // 查询向量取**清洗后**的输入(通道 Cleaner 的输出),与工具侧同一套语义: // 原始输入里的 ANSI/base64/JSON 包装会把相关性打分带偏,裁掉本该保留的事件。 +// +// 实际执行交由 memoryPass(与召回共用入口、query、预算与审计)。 func (a *Agent) pruneOnInput(evt *agentIO.InputEvent, cleanInput string) int { - if a.context == nil || !a.pruneDeclared(evt) { + if !a.pruneDeclared(evt) { return 0 } - // **动态上下文**是父 agent 专属能力:轻量内核(驻留子)用传统上下文, - // 不做按相关度的裁剪与向 doc 记忆的归档(子也没有 doc 记忆)。 - if a.isLightKernel() { - return 0 - } - topK := a.maxContextSize - 1 - if topK < 1 { - topK = 1 - } - return a.context.Prune(cleanInput, topK, a.docStore) + return a.memoryPass(cleanInput, "input:"+evt.Source, true, false).Archived } // pruneDeclared 判定这次输入是否显式声明了裁剪。 diff --git a/internal/agent/core/memorypass.go b/internal/agent/core/memorypass.go new file mode 100644 index 0000000..babe4f3 --- /dev/null +++ b/internal/agent/core/memorypass.go @@ -0,0 +1,65 @@ +package core + +import "log" + +// memoryPassOut 是一次记忆操作(取进来 / 踢出去)的结果。 +type memoryPassOut struct { + // Archived 是被归档进文档记忆的低相关 L0 事件数(prune 的输出)。 + Archived int + // RecallText 是可注入 prompt 的记忆索引文本(recall 的输出,空串表示无)。 + RecallText string +} + +// memoryPass 是「取进来(召回)」与「踢出去(裁剪)」的**唯一入口**。 +// +// prune 与 recall 是两根正交的声明轴(默认值刻意相反:裁剪是破坏性的、 +// 默认关;召回是只读增量、默认开),但两者都建立在**同一份清洗后的 query** +// 之上。调用点只负责解析声明,这里统一做三件各写一遍就会写歪的事: +// +// 1. 同一 query:prune 与 recall 用同一个查询向量来源,避免「裁错事件、 +// 召回错记忆」——原始内容里的 ANSI/base64/JSON 噪声会把相关性打分带偏。 +// 2. 同一次预算:召回文本按 token 预算截断只做一次(见 recallText)。 +// 3. 同一条审计:谁(trigger)据什么触发了哪种操作都落一条日志, +// 否则又是一个「幕后发生、查不出是谁」的机制(对齐 prune 的设计初衷)。 +// +// 边界:prune 与 recall 目前仍走**各自的相关性空间**(prune 用 L0 事件的 +// 稠密/词向量给已有事件打分,recall 用图 + TF-IDF 实体索引)。真正的 +// 「一次打分」要先统一打分空间(后续步骤);这里统一的是**入口、query、 +// 预算与审计**——这已是「一个过程」的可审计外壳,剩下的差在打分空间。 +func (a *Agent) memoryPass(query, trigger string, prune, recall bool) memoryPassOut { + var out memoryPassOut + if a == nil || (!prune && !recall) { + return out + } + if prune { + out.Archived = a.pruneByQuery(query) + } + if recall && query != "" { + out.RecallText = a.recallTextFor(query, trigger) + } + if out.Archived > 0 || out.RecallText != "" { + log.Printf("[agent] memory pass (%s): archived=%d recalled=%d chars", + trigger, out.Archived, len(out.RecallText)) + } + return out +} + +// pruneByQuery 按相关性把低相关 L0 事件归档进文档记忆,返回归档数。 +// +// **不做声明判定**——声明已由调用方(pruneOnInput / stepToolAfter)解析, +// 这里只负责执行。放在 memoryPass 内部是为了让裁剪与召回共享入口。 +func (a *Agent) pruneByQuery(query string) int { + if a == nil || a.context == nil { + return 0 + } + // **动态上下文**是父 agent 专属能力:轻量内核(驻留子)用传统上下文, + // 不做按相关度的裁剪与向 doc 记忆的归档(子也没有 doc 记忆)。 + if a.isLightKernel() { + return 0 + } + topK := a.maxContextSize - 1 + if topK < 1 { + topK = 1 + } + return a.context.Prune(query, topK, a.docStore) +} diff --git a/internal/agent/core/memorypass_test.go b/internal/agent/core/memorypass_test.go new file mode 100644 index 0000000..af67350 --- /dev/null +++ b/internal/agent/core/memorypass_test.go @@ -0,0 +1,107 @@ +package core + +import ( + "path/filepath" + "strings" + "testing" + "time" + + "gitcode.com/JianFeeeee/HomeAgent/internal/memory" + "gitcode.com/JianFeeeee/HomeAgent/internal/memory/document" +) + +// memoryPass 是「裁剪」与「召回」的唯一入口:两根正交轴,但共用同一份 query。 +// +// 这一组测试锁死三件事: +// 1. 两个策略都不声明时是 no-op(不裁剪、不召回); +// 2. 同时声明时一次调用同时产出「归档数」与「召回文本」; +// 3. 单一策略只产出对应的那一个输出(正交,不互相触发)。 +func TestMemoryPass_NoPolicyIsNoOp(t *testing.T) { + a := &Agent{ + context: newPruneableContext(15), + maxContextSize: 4, + indexer: newTestIndexer(t, "咖啡", "张三"), + } + out := a.memoryPass("咖啡", "test", false, false) + if out.Archived != 0 || out.RecallText != "" { + t.Fatalf("未声明任何策略时不应有任何输出,实际 %+v", out) + } +} + +func TestMemoryPass_PruneAndRecallTogether(t *testing.T) { + a := newMemoryPassAgent(t) + before := a.context.Len() + out := a.memoryPass("咖啡", "tool:test", true, true) + if out.Archived == 0 { + t.Fatal("声明 prune 应归档低相关事件") + } + if a.context.Len() >= before { + t.Fatalf("裁剪后上下文应变短:%d → %d", before, a.context.Len()) + } + if !strings.Contains(out.RecallText, "【记忆索引】") { + t.Fatalf("声明 recall 应产出记忆索引文本,实际 %q", out.RecallText) + } +} + +func TestMemoryPass_PoliciesAreOrthogonal(t *testing.T) { + // 只裁不召回:输出只有归档数。 + onlyPrune := &Agent{ + context: newPruneableContext(15), + maxContextSize: 4, + indexer: newTestIndexer(t, "咖啡", "张三"), + } + if out := onlyPrune.memoryPass("咖啡", "test", true, false); out.RecallText != "" { + t.Fatalf("只声明 prune 不应召回,实际 %q", out.RecallText) + } + // 只召回不裁剪:输出只有召回文本,上下文条数不变。 + onlyRecall := &Agent{ + context: newPruneableContext(15), + maxContextSize: 4, + indexer: newTestIndexer(t, "咖啡", "张三"), + } + before := onlyRecall.context.Len() + out := onlyRecall.memoryPass("咖啡", "test", false, true) + if out.Archived != 0 { + t.Fatalf("只声明 recall 不应裁剪,实际归档 %d", out.Archived) + } + if onlyRecall.context.Len() != before { + t.Fatalf("只声明 recall 不应改变上下文条数:%d → %d", before, onlyRecall.context.Len()) + } +} + +// 输入侧召回必须用**清洗后**的 query(通道 Cleaner 的输出),与裁剪侧一致。 +// 用无关原文 + 命中清洗文本做区分,锁死「用的是 CleanInput 而不是 Input」。 +func TestBuildTaskMemoryContext_UsesCleanInput(t *testing.T) { + a := &Agent{indexer: newTestIndexer(t, "咖啡", "张三")} + + // CleanInput 命中实体、原文完全不相关 → 应召回(证明用了清洗文本)。 + f := &TaskFrame{Evt: nil, CleanInput: "咖啡"} + if got := a.buildTaskMemoryContext(f, "zzz", 0); !strings.Contains(got, "【记忆索引】") { + t.Fatalf("应据清洗后的 query 召回,实际 %q", got) + } + // 清洗为空 → 回退原文;原文无关则不召回。 + f2 := &TaskFrame{CleanInput: ""} + if got := a.buildTaskMemoryContext(f2, "zzz", 0); got != "" { + t.Fatalf("清洗为空且原文无关时不应召回,实际 %q", got) + } +} + +// newMemoryPassAgent 造一个同时能做裁剪与召回的 agent(含 doc 记忆落点)。 +func newMemoryPassAgent(t *testing.T) *Agent { + t.Helper() + return &Agent{ + context: newPruneableContext(15), + maxContextSize: 4, + indexer: newTestIndexer(t, "咖啡", "张三"), + docStore: document.NewStore(filepath.Join(t.TempDir(), "docs"), memory.TokenizeWords), + } +} + +// newPruneableContext 造 n 条可被裁剪的上下文(最近 10 条受保护)。 +func newPruneableContext(n int) *RelevanceContext { + ctx := NewRelevanceContext("", memory.NewStaticEmbedder("")) + for i := 0; i < n; i++ { + ctx.Append(ContextEvent{Timestamp: time.Now(), Source: "user", Input: "事件内容"}) + } + return ctx +} diff --git a/internal/agent/core/task.go b/internal/agent/core/task.go index 7f1bdd1..ecf9deb 100644 --- a/internal/agent/core/task.go +++ b/internal/agent/core/task.go @@ -395,10 +395,8 @@ func (a *Agent) prepareInputTask(evt *agentIO.InputEvent) (*TaskFrame, taskTermi } a.publishEvent(events.EventRawInput, rawPayload) - archived := a.pruneOnInput(evt, cleanInput) - if archived > 0 { - log.Printf("[agent] pruned %d low-relevance events to document memory", archived) - } + // 裁剪与审计统一在 memoryPass 内(日志已带 trigger)。 + a.pruneOnInput(evt, cleanInput) // 本轮 inputch(处理表按它记账)+ contextfull 检测(只有驻留子设了钩子)。 a.tableMu.Lock() @@ -746,7 +744,8 @@ func (a *Agent) stepToolAfter(f *TaskFrame) stepOutcome { // 工具后处理:一次相关性过程,两个**正交**声明—— // ContextPolicy=prune → 裁剪(踢出去,归档低相关 L0 事件) // RecallPolicy=auto → 召回(取进来,注入 L2/L3 相关记忆) - // 两者共用同一份**清洗后**的 query:查询向量取清洗后的有效内容,否则噪声 + // 两者共用同一份**清洗后**的 query,并统一走 memoryPass(同一入口、 + // 同一次预算与审计)。查询向量取清洗后的有效内容,否则噪声 // (ANSI/base64/JSON 包装)会把相关性打分带偏,裁错事件、召回错记忆。 var recallText string if def := a.stageHost.ToolDef(tc.Name); def != nil { @@ -754,16 +753,7 @@ func (a *Agent) stepToolAfter(f *TaskFrame) stepOutcome { needRecall := def.RecallPolicy == sdk.RecallPolicyAuto if needPrune || needRecall { query := a.toolOutputForQuery(tc.Name, result) - if needPrune && a.context != nil { - topK := a.maxContextSize - 1 - if topK < 1 { - topK = 1 - } - a.context.Prune(query, topK, a.docStore) - } - if needRecall { - recallText = a.recallTextFor(query, "tool:"+tc.Name) - } + recallText = a.memoryPass(query, "tool:"+tc.Name, needPrune, needRecall).RecallText } } diff --git a/internal/agent/core/tooldefs.go b/internal/agent/core/tooldefs.go index 4118294..44d9afd 100644 --- a/internal/agent/core/tooldefs.go +++ b/internal/agent/core/tooldefs.go @@ -44,27 +44,49 @@ func (a *Agent) buildMemoryContext(input string, maxTokens int) string { // // 默认 auto(保持“每条输入都召回”的既有行为);输入/注入声明 // recall_policy=none 时返回空串,从而不注入记忆。策略与裁剪(ContextPolicy)正交。 +// +// query 取**清洗后**的输入(通道 Cleaner 的输出),与裁剪侧同一套语义: +// 原始输入里的 ANSI/base64/JSON 包装会把相关性打分带偏。清洗为空时回退原文。 func (a *Agent) buildTaskMemoryContext(f *TaskFrame, input string, maxTokens int) string { - if f != nil && !a.recallDeclared(f.Evt) { + if f == nil { + return a.recallText(input, "input", maxTokens) + } + if !a.recallDeclared(f.Evt) { return "" } - return a.buildMemoryContext(input, maxTokens) + query := strings.TrimSpace(f.CleanInput) + if query == "" { + query = input + } + trigger := "input" + if f.Evt != nil && f.Evt.Source != "" { + trigger = "input:" + f.Evt.Source + } + return a.recallText(query, trigger, maxTokens) } -// recallTextFor 以 query 触发一次记忆召回,返回可注入的文本(空串表示无)。 +// recallTextFor 以 query 触发一次记忆召回,按当前预算截断,返回可注入的文本。 // // 这是“召回”侧的单一入口:与 Prune 共用同一份**清洗后**的 query, // 使“取进来”(召回)与“踢出去”(裁剪)落在同一个相关性过程上。 // trigger 仅用于日志溯源(如 "tool:qq_get_message")。 func (a *Agent) recallTextFor(query, trigger string) string { - if query == "" || a.indexer == nil { - return "" - } memTokens := 0 // 0 = 不截断 - if a.provider != nil { + if a != nil && a.provider != nil { memTokens = ComputeTokenBudget(a.provider, a.systemPrompt).MemoryTokens } - text := a.buildMemoryContext(query, memTokens) + return a.recallText(query, trigger, memTokens) +} + +// recallText 是召回侧的共同实现:query → 记忆索引文本(空串表示无)。 +// +// 输入侧的 buildTaskMemoryContext 与工具侧的 recallTextFor 都收敛到这里, +// 使“同一份 query、同一次预算、同一条审计日志”只写一遍。 +func (a *Agent) recallText(query, trigger string, maxTokens int) string { + if a == nil || query == "" || a.indexer == nil { + return "" + } + text := a.buildMemoryContext(query, maxTokens) if text == "" { return "" } diff --git a/third_party/homeagent-sdk/example/qq/plugin.go b/third_party/homeagent-sdk/example/qq/plugin.go index df12820..d295527 100644 --- a/third_party/homeagent-sdk/example/qq/plugin.go +++ b/third_party/homeagent-sdk/example/qq/plugin.go @@ -489,6 +489,12 @@ type 枚举: text(文字)/ voice(语音转文字后发送)/ image(图 Name: tp + "get_history", Description: "获取QQ群聊/私聊最近历史消息。当收到引用回复消息或需要了解对话上下文时应优先调用此工具查看前后文。返回值每条格式为 [时间] 发送者: 消息内容。如果消息包含文件,会额外返回 files 字段(含 file_id 和 name),可用 qq_download_file 工具下载。", NoMemory: false, Cleaner: cleaner, + // 与 get_message 同理:返回的是**真实聊天正文**,不只当轮需要, + // 还可能牵出与这些正文相关的长期记忆。故取回后既裁剪(用完不长期占 + // L0)又据正文召回(取进来)。不声明 recall 的话就是「记忆里有、但 + // 拉回历史消息时不注入」的盲区。 + ContextPolicy: "prune", + RecallPolicy: "auto", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "group_id": map[string]interface{}{"type": "integer", "description": "群号(与user_id二选一)"},