Files
HomeAgent/internal/agent/core/inputunify_test.go
JianFeeeee 49695c38f3 feat(memory): 场景双通道——主动声明与被动涌现并存,且互不吞噬
按「声明式的也要支持,相当于主动被动两条路」落实。此前两者只是恰好并存,
没有边界,实测会互相吃掉(下面的坑就是)。

- Triple.Scenes []string(多值):一轮写下的记忆**两条路都挂**。
  只挂一条会丢东西——只挂声明则细粒度唤起丢失,只挂涌现则首次交互
  (场景还没长出来)没有兜底。单值 Scene 保留兼容。
- TurnScene:Primary 用于写(优先涌现场景,首次退到声明场景兜底),
  Keys 是两条路的并集,用于召回(声明+涌动的场景一起进 RecallByScene)。
- EnterSceneWithHint:主动路 EnsureScene(声明即建场景,不等第二次),
  被动路 EnterScene(指纹聚类)。写侧由 executeToolCall 把本轮场景集合
  传给 memory_commit,模型不需要知道"场景"这回事。

踩到并修掉的坑(两条路互相吞噬):
  最初让声明场景也吸收**整轮指纹**,于是 chan:qq 的相似度永远是 1.0,
  把后续所有同类轮次全部吃掉 → 被动路再也长不出更细的场面,
  实测 turn2.Emergent=true 但 Primary 仍是 chan:qq、没有 auto: 场景。
  修法:给场景加 origin(declared/emergent):
  - 被动聚类只认 origin='emergent' 的场景(声明场景不进相似度空间);
  - 声明场景的特征**只从键自身解析**(chan:qq/peer:group_1 → {chan:qq, peer:group_1}),
    白名单 kind(chan/peer/peer_group/tool/topic/part),不猜——
    「老大2026-09-04_12:27_qq私聊图片」里的 12:27 也是 kind:value 形态,
    放进特征空间就是往相似度里灌垃圾(有测试钉住)。
  - 声明路的泛化靠**层级键前缀**(chan:qq 覆盖 chan:qq/peer:x),机制各归各。
- memgc -scene-stats 增加 [declared|emergent] 与 strength/features 两栏,
  可直接观察两条路各自在长什么。

新增/改写用例:
- TestDeclaredAndEmergentBothLearn:首次交互兜底到声明场景 → 第 2 轮长出
  细粒度涌现场景且**优先用于写入** → 声明场景不进相似度空间(防止压死被动路)
  但仍走声明键取回 → 两条路都进召回集合 → 声明键特征解析与白名单。
- TestEffectiveScenes:多值+单值合并去重保序。

go build/vet 干净,go test -count=1 ./... 全绿。
2026-09-15 09:37:29 +08:00

616 lines
18 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.

package core
import (
"path/filepath"
"strconv"
"strings"
"testing"
agentAPI "gitcode.com/JianFeeeee/HomeAgent/internal/agent/api"
agentIO "gitcode.com/JianFeeeee/HomeAgent/internal/agent/io"
"gitcode.com/JianFeeeee/HomeAgent/internal/memory"
"gitcode.com/JianFeeeee/HomeAgent/internal/memory/document"
"gitcode.com/JianFeeeee/HomeAgent/internal/memory/media"
pubsdk "gitcode.com/JianFeeeee/homeagent-sdk/sdk"
)
// 统一输入主干processInput / resolveInput / injectedBlocks
// 模型可调用工具的媒体接线测试。
//
// 这一层此前的结构性缺陷text 与 image/audio 各有一个 process 函数,
// 媒体那条缺了去重、no_memory、通道 Cleaner、中断语义、EventRawInput 五项。
// 归一成一条主干后,这些行为对所有模态一致——下面的断言就是这个不变量。
func newInputTestAgent(t *testing.T) (*Agent, *media.Store) {
t.Helper()
dir := t.TempDir()
ms, err := media.New(filepath.Join(dir, "media"))
if err != nil {
t.Fatalf("media.New: %v", err)
}
t.Cleanup(func() { ms.Close() })
return &Agent{mediaStore: ms}, ms
}
// ---------- injectedBlocks ----------
// 内核内部注入直接给 []agentAPI.ContentBlock经公共 SDK 的 IOInjector 过来的是
// []pubsdk.ContentBlock。两者字段一致但 Go 不会自动转换,只认一种的后果是
// 另一种被静默丢弃——插件注入的图到 payload 就断了,且不报错。
func TestInjectedBlocks_AcceptsBothStaticTypes(t *testing.T) {
t.Run("内核类型", func(t *testing.T) {
blocks, kind := injectedBlocks(map[string]interface{}{
"media_blocks": []agentAPI.ContentBlock{
{Type: "text", Text: "看图"},
{Type: "image_url", ImageURL: &agentAPI.ImageURL{URL: "data:image/png;base64,AAA"}},
},
})
if len(blocks) != 2 {
t.Fatalf("blocks = %d期望 2", len(blocks))
}
if kind != "image" {
t.Errorf("mediaType = %q期望 image", kind)
}
})
t.Run("公共SDK类型", func(t *testing.T) {
blocks, kind := injectedBlocks(map[string]interface{}{
"media_blocks": []pubsdk.ContentBlock{
{Type: "text", Text: "听音频"},
{Type: "audio_url", AudioURL: &pubsdk.AudioURL{URL: "data:audio/wav;base64,BBB"}},
},
})
if len(blocks) != 2 {
t.Fatalf("blocks = %d期望 2公共 SDK 类型被静默丢弃)", len(blocks))
}
if kind != "audio" {
t.Errorf("mediaType = %q期望 audio", kind)
}
// 转换必须保留 URL否则块到了模型手上是空的
if blocks[1].AudioURL == nil || blocks[1].AudioURL.URL != "data:audio/wav;base64,BBB" {
t.Errorf("AudioURL 转换丢失: %+v", blocks[1].AudioURL)
}
})
t.Run("图优先于音频", func(t *testing.T) {
_, kind := injectedBlocks(map[string]interface{}{
"media_blocks": []agentAPI.ContentBlock{
{Type: "audio_url", AudioURL: &agentAPI.AudioURL{URL: "a"}},
{Type: "image_url", ImageURL: &agentAPI.ImageURL{URL: "b"}},
},
})
if kind != "image" {
t.Errorf("mediaType = %q期望 image", kind)
}
})
t.Run("无媒体块", func(t *testing.T) {
blocks, kind := injectedBlocks(map[string]interface{}{"content": "纯文本"})
if blocks != nil || kind != "" {
t.Errorf("无 media_blocks 时应返回 (nil,\"\"),实际 (%v,%q)", blocks, kind)
}
})
t.Run("ImageURL 的 Detail 透传", func(t *testing.T) {
blocks, _ := injectedBlocks(map[string]interface{}{
"media_blocks": []pubsdk.ContentBlock{
{Type: "image_url", ImageURL: &pubsdk.ImageURL{URL: "u", Detail: "high"}},
},
})
if len(blocks) != 1 || blocks[0].ImageURL.Detail != "high" {
t.Errorf("Detail 未透传: %+v", blocks)
}
})
}
// ---------- resolveInput ----------
func TestResolveInput_UnifiesAllModalities(t *testing.T) {
a, _ := newInputTestAgent(t)
t.Run("用户上传图片", func(t *testing.T) {
in, ok := a.resolveInput(&agentIO.InputEvent{
Source: "qq",
Type: "image",
Payload: map[string]interface{}{"data": "AAAA", "mime": "image/png"},
})
if !ok {
t.Fatal("图片输入被判为无效")
}
if in.mediaType != "image" || in.captureTool != "input_image" {
t.Errorf("mediaType=%q captureTool=%q", in.mediaType, in.captureTool)
}
if in.text == "" {
t.Error("纯媒体输入应有 alt 文案作为文本落点")
}
if len(in.blocks) == 0 {
t.Error("图片应转成内容块")
}
})
t.Run("插件注入的媒体", func(t *testing.T) {
in, ok := a.resolveInput(&agentIO.InputEvent{
Source: "myplugin",
Type: "text",
Payload: map[string]interface{}{
"content": "帮我看看这张图",
"media_blocks": []pubsdk.ContentBlock{
{Type: "image_url", ImageURL: &pubsdk.ImageURL{URL: "data:image/png;base64,AAA"}},
},
},
})
if !ok {
t.Fatal("带媒体的文本输入被判为无效")
}
if in.text != "帮我看看这张图" {
t.Errorf("text = %q", in.text)
}
if len(in.blocks) != 1 || in.mediaType != "image" {
t.Errorf("blocks=%d mediaType=%q —— 插件注入的媒体到 payload 就断了", len(in.blocks), in.mediaType)
}
if in.captureTool != "inject_myplugin" {
t.Errorf("captureTool = %q期望带来源便于溯源", in.captureTool)
}
})
t.Run("只带图不带字也合法", func(t *testing.T) {
_, ok := a.resolveInput(&agentIO.InputEvent{
Source: "myplugin",
Type: "text",
Payload: map[string]interface{}{
"media_blocks": []agentAPI.ContentBlock{
{Type: "image_url", ImageURL: &agentAPI.ImageURL{URL: "u"}},
},
},
})
if !ok {
t.Error("只带媒体不带文本应视为有效输入(插件注入常这样)")
}
})
t.Run("文本与媒体都空才无效", func(t *testing.T) {
if _, ok := a.resolveInput(&agentIO.InputEvent{
Source: "cli",
Type: "text",
Payload: map[string]interface{}{"content": ""},
}); ok {
t.Error("空输入应被拒")
}
})
t.Run("纯文本", func(t *testing.T) {
in, ok := a.resolveInput(&agentIO.InputEvent{
Source: "cli",
Type: "text",
Payload: map[string]interface{}{"content": "你好"},
})
if !ok || in.text != "你好" || len(in.blocks) != 0 || in.mediaType != "" {
t.Errorf("纯文本路径异常: ok=%v in=%+v", ok, in)
}
})
}
// ---------- 模型工具侧memory_digests 结构化传递 ----------
// 模型只知道 digest从对话或 memory_recall 的「关联媒体」读到)。
// 它不再需要自己拼任何标记digest 作为结构化字段随三元组提交。
func TestResolveMediaDigestsAndNoMarkerText(t *testing.T) {
a, ms := newInputTestAgent(t)
digest, err := ms.Put([]byte("marker-bytes"), media.Item{MIME: "image/png"})
if err != nil {
t.Fatalf("Put: %v", err)
}
t.Run("短digest补全", func(t *testing.T) {
got := a.resolveMediaDigests([]string{digest[:12]})
if len(got) != 1 || got[0] != digest {
t.Fatalf("短 digest 应补全为完整 digest得到 %v", got)
}
})
t.Run("无法解析的digest被丢弃", func(t *testing.T) {
if got := a.resolveMediaDigests([]string{"ffffffffffff"}); len(got) != 0 {
t.Errorf("不存在的 digest 不该保留: %v", got)
}
})
t.Run("无媒体存储时返回nil", func(t *testing.T) {
bare := &Agent{}
if got := bare.resolveMediaDigests([]string{digest}); got != nil {
t.Errorf("无媒体存储时应返回 nil: %v", got)
}
})
}
// 句子文本必须保持原样:媒体归属走结构化块边,不往文本里贴 marker。
func TestMemoryCommit_DoesNotPolluteSentenceText(t *testing.T) {
dir := t.TempDir()
g, err := memory.NewGraphDB(filepath.Join(dir, "graph.db"))
if err != nil {
t.Fatal(err)
}
defer g.Close()
ms, err := media.New(filepath.Join(dir, "media"))
if err != nil {
t.Fatal(err)
}
defer ms.Close()
a := &Agent{memory: g, mediaStore: ms}
digest, _ := ms.Put([]byte("clean-sentence"), media.Item{MIME: "image/png"})
sentence := "用户发来一张图。"
triples := []memory.Triple{{
Subject: "用户", Relation: "发来", Object: "图片",
SentenceText: sentence,
MediaDigests: a.resolveMediaDigests([]string{digest[:12]}),
}}
if _, _, _, err := a.commitTriplesWithMedia(triples, "s1", 0, nil); err != nil {
t.Fatal(err)
}
res, err := a.memory.Recall([]string{"用户"}, nil, 2, "")
if err != nil {
t.Fatal(err)
}
if len(res.Relations) == 0 {
t.Fatal("召回为空")
}
if res.Relations[0].SentenceText != sentence {
t.Errorf("句子文本被污染: %q", res.Relations[0].SentenceText)
}
blocks, err := a.memory.BlocksForNode("sentence", strconv.FormatInt(res.Relations[0].SentenceID, 10))
if err != nil {
t.Fatal(err)
}
if len(blocks) != 1 || blocks[0].PayloadDigest != digest {
t.Errorf("块应挂到句子,实际 %+v", blocks)
}
}
// ---------- resolveMediaDigests ----------
func TestResolveMediaDigests(t *testing.T) {
a, ms := newInputTestAgent(t)
d1, _ := ms.Put([]byte("one"), media.Item{MIME: "image/png"})
d2, _ := ms.Put([]byte("two"), media.Item{MIME: "image/png"})
got := a.resolveMediaDigests([]string{d1[:10], d2, d1, "ffffffffffff"})
if len(got) != 2 {
t.Fatalf("got = %v期望 2 条(去重 + 丢弃无法解析的)", got)
}
for _, d := range got {
if len(d) != 64 {
t.Errorf("应返回完整 digest实际 %q", d)
}
}
if a.resolveMediaDigests(nil) != nil {
t.Error("空输入应返回 nil")
}
bare := &Agent{}
if bare.resolveMediaDigests([]string{d1}) != nil {
t.Error("无媒体存储时应返回 nil")
}
}
// ---------- 文档持有的一等记忆块 ----------
func TestDocCommit_StoresBlocks(t *testing.T) {
// doc_commit 带 media_digests 时,媒体应作为一等块直接存在文档上,
// 并随 doc 一起持久化(不再靠 media_refs 保活)。
dir := t.TempDir()
ds := document.NewStore(filepath.Join(dir, "docs"), memory.TokenizeWords)
if err := ds.Start(); err != nil {
t.Fatal(err)
}
defer ds.Stop()
ms, err := media.New(filepath.Join(dir, "media"))
if err != nil {
t.Fatal(err)
}
defer ms.Close()
d1, _ := ms.Put([]byte("doc-one"), media.Item{MIME: "image/png"})
d2, _ := ms.Put([]byte("doc-two"), media.Item{MIME: "image/png"})
doc := &document.Doc{ID: "doc_x", Summary: "s", Content: "c"}
for _, d := range []string{d1, d2} {
if b, ok := (&Agent{mediaStore: ms}).blockFromDigest(d); ok {
doc.Blocks = append(doc.Blocks, b)
}
}
if err := ds.Insert(doc); err != nil {
t.Fatal(err)
}
blocks := ds.Blocks()
if len(blocks) != 2 {
t.Fatalf("文档应持有 2 个块,实际 %d", len(blocks))
}
seen := map[string]bool{}
for _, b := range blocks {
seen[b.PayloadDigest] = true
}
if !seen[d1] || !seen[d2] {
t.Errorf("块 digest 不对: %+v", blocks)
}
}
// ---------- 文档持有块标签doc_query 展示用) ----------
func TestBlockLabelsForDoc(t *testing.T) {
a, ms := newInputTestAgent(t)
digest, _ := ms.Put([]byte("ctx-bytes"), media.Item{MIME: "image/png"})
b, ok := a.blockFromDigest(digest)
if !ok {
t.Fatal("blockFromDigest 失败")
}
t.Run("从文档持有的一等块渲染", func(t *testing.T) {
got := a.blockLabelsForDoc(&document.Doc{ID: "doc_1", Blocks: []memory.MemoryBlock{b}})
if !strings.Contains(got, shortDigest(digest)) {
t.Errorf("标签应含短 digest: %q", got)
}
if !strings.Contains(got, "image/png") {
t.Errorf("标签应含 MIME: %q", got)
}
})
t.Run("无块时为空", func(t *testing.T) {
if got := a.blockLabelsForDoc(&document.Doc{ID: "doc_x", Content: "普通正文"}); got != "" {
t.Errorf("应返回空串,实际 %q", got)
}
})
t.Run("无媒体存储", func(t *testing.T) {
bare := &Agent{}
if got := bare.blockLabelsForDoc(&document.Doc{ID: "doc_x"}); got != "" {
t.Errorf("无媒体存储时应返回空串,实际 %q", got)
}
})
}
// ---------- mediaLabel ----------
// 媒体标签的唯一生成处:只含 MIME 与短 digest不含任何生成的描述。
func TestMediaLabel(t *testing.T) {
a, ms := newInputTestAgent(t)
_ = a
digest, _ := ms.Put([]byte("labelled"), media.Item{MIME: "image/png"})
it, err := ms.Stat(digest)
if err != nil {
t.Fatal(err)
}
got := mediaLabel(it)
if !strings.Contains(got, "image/png") {
t.Errorf("标签应含 MIME: %q", got)
}
if !strings.Contains(got, shortDigest(digest)) {
t.Errorf("必须带短 digest 供反查: %q", got)
}
if got := mediaLabel(nil); got != "" {
t.Errorf("nil 应返回空串,实际 %q", got)
}
}
// ---------- 模型工具端到端memory_commit / doc_commit / doc_query ----------
func newToolTestAgent(t *testing.T) (*Agent, *media.Store) {
t.Helper()
dir := t.TempDir()
g, err := memory.NewGraphDB(filepath.Join(dir, "graph.db"))
if err != nil {
t.Fatalf("NewGraphDB: %v", err)
}
t.Cleanup(func() { g.Close() })
ds := document.NewStore(filepath.Join(dir, "documents"), memory.TokenizeWords)
if err := ds.Start(); err != nil {
t.Fatalf("doc store: %v", err)
}
t.Cleanup(func() { ds.Stop() })
ms, err := media.New(filepath.Join(dir, "media"))
if err != nil {
t.Fatalf("media.New: %v", err)
}
t.Cleanup(func() { ms.Close() })
emb := memory.NewStaticEmbedder("")
a := &Agent{
id: "tester",
memory: g,
docStore: ds,
mediaStore: ms,
context: NewRelevanceContext("", emb),
}
return a, ms
}
// memory_commit 带 media_digests三元组入库后必须能从句子反查回那份字节。
func TestToolMemoryCommit_BindsMedia(t *testing.T) {
a, ms := newToolTestAgent(t)
digest, _ := ms.Put([]byte("commit-bytes"), media.Item{MIME: "image/png"})
out := a.executeMemoryTool(agentAPI.ToolCall{
Name: "memory_commit",
Arguments: map[string]interface{}{
"triples": []interface{}{
map[string]interface{}{
"subject": "配色方案",
"relation": "参考",
"object": "三色带图",
"media_digests": []interface{}{digest[:12]},
},
},
},
}, nil)
if !strings.Contains(out, "关联") {
t.Errorf("返回值应告知模型媒体已关联: %q", out)
}
res, err := a.memory.Recall([]string{"配色方案"}, nil, 2, "")
if err != nil {
t.Fatalf("Recall: %v", err)
}
if len(res.Relations) == 0 || res.Relations[0].SentenceID == 0 {
t.Fatal("没有句子落点 —— 媒体引用无从挂起")
}
blocks, err := a.memory.BlocksForNode("sentence", strconv.FormatInt(res.Relations[0].SentenceID, 10))
if err != nil {
t.Fatalf("BlocksForNode: %v", err)
}
if len(blocks) != 1 || blocks[0].PayloadDigest != digest {
t.Errorf("句子块 = %+v期望 [%s]", blocks, digest)
}
}
// 不带 media_digests 时行为与本特性上线前一致(不多写句子、不报错)。
func TestToolMemoryCommit_WithoutMedia(t *testing.T) {
a, _ := newToolTestAgent(t)
out := a.executeMemoryTool(agentAPI.ToolCall{
Name: "memory_commit",
Arguments: map[string]interface{}{
"triples": []interface{}{
map[string]interface{}{"subject": "甲方", "relation": "签署", "object": "合同"},
},
},
}, nil)
if strings.Contains(out, "失败") {
t.Errorf("普通提交不该失败: %q", out)
}
if strings.Contains(out, "关联") {
t.Errorf("无媒体时不该提媒体: %q", out)
}
}
// sentence_text 必须透传:丢了它,图谱就回不到原文。
func TestToolMemoryCommit_CarriesSentenceText(t *testing.T) {
a, _ := newToolTestAgent(t)
a.executeMemoryTool(agentAPI.ToolCall{
Name: "memory_commit",
Arguments: map[string]interface{}{
"triples": []interface{}{
map[string]interface{}{
"subject": "李四",
"relation": "住在",
"object": "杭州",
"sentence_text": "李四搬到杭州已经三年了。",
},
},
},
}, nil)
res, _ := a.memory.Recall([]string{"李四"}, nil, 2, "")
if len(res.Relations) == 0 {
t.Fatal("召回为空")
}
if res.Relations[0].SentenceText != "李四搬到杭州已经三年了。" {
t.Errorf("SentenceText = %q", res.Relations[0].SentenceText)
}
}
// doc_commit 带 media_digests媒体成为文档直接持有的一等块正文保持原样。
func TestToolDocCommit_BindsMedia(t *testing.T) {
a, ms := newToolTestAgent(t)
digest, _ := ms.Put([]byte("doc-commit-bytes"), media.Item{MIME: "image/png"})
out := a.executeDocTool(agentAPI.ToolCall{
Name: "doc_commit",
Arguments: map[string]interface{}{
"content": "这是一篇带图的笔记正文。",
"summary": "带图笔记",
"media_digests": []interface{}{digest[:12]},
},
})
if !strings.Contains(out, "关联") {
t.Errorf("返回值应告知模型媒体已关联: %q", out)
}
docs := a.docStore.RecentDocs(5)
if len(docs) == 0 {
t.Fatal("文档未写入")
}
d := docs[0]
if strings.Contains(d.Content, "image/png") {
t.Errorf("正文不该被媒体标记污染: %q", d.Content)
}
var held bool
for _, b := range d.Blocks {
if b.PayloadDigest == digest {
held = true
}
}
if !held {
t.Errorf("文档应持有一等记忆块 [%s],实际 %+v", digest, d.Blocks)
}
}
// doc_query 必须把媒体说明附在返回值里,否则模型检索到带图文档也不知道有图。
func TestToolDocQuery_ShowsMedia(t *testing.T) {
a, ms := newToolTestAgent(t)
digest, _ := ms.Put([]byte("query-bytes"), media.Item{MIME: "image/png"})
a.executeDocTool(agentAPI.ToolCall{
Name: "doc_commit",
Arguments: map[string]interface{}{
"content": "紫蓝红三色带配色说明正文",
"summary": "紫蓝红三色带",
"media_digests": []interface{}{digest},
},
})
a.executeDocTool(agentAPI.ToolCall{
Name: "doc_query",
Arguments: map[string]interface{}{"query": "紫蓝红三色带 配色说明", "top_k": float64(3)},
})
// 正文进的是 cold_storage 事件(工具返回值只给引用编号),媒体说明也在那里。
var found bool
for _, e := range a.context.Recent(10) {
if strings.Contains(e.Response, shortDigest(digest)) {
found = true
}
}
if !found {
t.Error("doc_query 未把媒体说明带进上下文 —— 模型不知道这篇文档带过图")
}
}
// 无媒体存储时三个工具的行为与本特性上线前完全一致。
func TestTools_NilMediaStoreDegrades(t *testing.T) {
a, _ := newToolTestAgent(t)
a.mediaStore = nil
out := a.executeMemoryTool(agentAPI.ToolCall{
Name: "memory_commit",
Arguments: map[string]interface{}{
"triples": []interface{}{
map[string]interface{}{
"subject": "无存储", "relation": "仍可", "object": "提交",
"media_digests": []interface{}{"aabbccddeeff"},
},
},
},
}, nil)
if strings.Contains(out, "失败") {
t.Errorf("无媒体存储时提交不该失败: %q", out)
}
out = a.executeDocTool(agentAPI.ToolCall{
Name: "doc_commit",
Arguments: map[string]interface{}{
"content": "无媒体存储的文档",
"media_digests": []interface{}{"aabbccddeeff"},
},
})
if strings.Contains(out, "失败") {
t.Errorf("无媒体存储时文档写入不该失败: %q", out)
}
}