Files
doubao-clone/scripts/probe-agent-system.py
l 76d6445ed6 feat(v1.2): 阶段2 上半 —— 缓存友好段序 + 缓存统计归一化(v2.0.57)
## 缓存友好段序(附录 C 的 v1.2 修订)

主流模型的上下文缓存是**前缀匹配**:一处不同则其后全部失效。
原来的段序把 `<emotion>` 夹在 `<memory>` **前面** —— 情绪一变,
连最长的 memory 段一起失效,而情绪是 AI 每聊几句就可能改的东西。

按稳定性重排:
  稳定前缀  {prompt} → <skills> → <worldview> → <memory>
  易变尾巴  <stats> → <status> → <emotion> → <peer_emotions>

顺带把 `<stats>`/`<status>` 两个占位段位留好(阶段 3 实现)。先留是为了让
模板和渲染两边**一开始就一致**,否则会有"模板里有、渲染不管"的中间状态,
表现是提示词里原样留着 `{stats}` 大括号。

★ 这是整个 v1.2 里**改动最小、省的钱最多**的一处。

## 缓存统计归一化

三家的字段名完全不同,且后两家**只给命中**、未命中要自己推:
  DeepSeek  prompt_cache_hit_tokens / prompt_cache_miss_tokens
  Claude    cache_read_input_tokens
  OpenAI    prompt_tokens_details.cached_tokens(嵌套)

不归一化的话,界面上那个"缓存命中率"会因为换模型就**静默变成 0** ——
静默的 0 最难发现。都没给时返回 0/0,界面**不显示**那一列,
而不是显示一个假的 0%。

落库:`token_usage` 加 `cache_hit`/`cache_miss` 两列 + 老库迁移。
接口:`_usage_payload` 和 `get_token_usage` 都带上了。

## 验证

探针新增两节 17 项:段序 7 项(含"模板顺序必须和 SECTIONS 一致"、
"空段不能留裸占位符")+ 缓存 10 项(四种格式、跨提供商累加、
落库查询、老库迁移)。

★ 顺带证明了一件事:段序一改,探针第 8 节那条**记着旧顺序**的老断言
立刻变红。顺序是协议的一部分,改它就该有人拦。

五个探针全绿。阶段 2 下半(对话上下文窗口 + 用量界面缓存列)下一轮。
2026-10-16 18:02:14 +08:00

698 lines
40 KiB
Python
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.

"""智能体系统(需求 v1.1)的端到端探针 —— 不装机就能验整条链路。
## 怎么做到的
内核的存储层是**无状态**的(路径全靠 `paths.get()` 从数据目录推),
所以只要把 `DOUBAO_DATA` 指到一个临时目录,就能在一个进程里把
"建智能体 → 记东西 → 检索 → 拼提示词 → 导包 → 再导入"整条链路跑一遍。
比装机验证快得多,而且**能断言具体字段**(装机只能截图看个大概)。
## 覆盖
1. 建智能体拿到的是 UUID(需求附录 A)
2. 记忆增删改查 + 检索
3. pinned 保护(AI 改不动)
4. 情绪读写
5. Token 统计(按模型分桶、输入输出分开)
6. 世界观 + **共享记忆**(两个智能体共用一个空间)
7. 写入限权(只能删自己写的)
8. system prompt 注入(附录 C 的五段都在、空段被删掉)
9. 智能体包导出 → 导入(导入两次 = 两个独立实体)
10. 记忆导出/导入(合并按标题去重)
11. 资源 CRUD(世界观 / 模型列表 / Skill)
用法:
python scripts/probe-agent-system.py
"""
import io
import json
import os
import shutil
import sys
import tempfile
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.abspath(os.path.join(HERE, ".."))
KERNEL = os.path.join(REPO, "android", "kernel")
# ★ 必须在 import 内核之前设好:paths.get() 是**懒加载 + 缓存**的
DATA = tempfile.mkdtemp(prefix="doubao-agent-probe-")
os.environ["DOUBAO_DATA"] = DATA
sys.path.insert(0, KERNEL)
fails = []
def check(label, cond, detail=""):
if cond:
print(f" ✓ {label}")
else:
fails.append(label)
print(f" ✗ {label} {detail}")
def section(title):
print(f"\n=== {title} ===")
import agent_context # noqa: E402
import agent_tools # noqa: E402
import agentdb # noqa: E402
import defaults # noqa: E402
import store # noqa: E402
class FakeHandler:
"""冒充 app.py 的 Handler:只要 send_json / read_json_body 两个方法"""
def __init__(self):
self.status = 200
self.payload = None
def send_json(self, code, payload):
self.status = code
self.payload = payload
def read_json_body(self, *a, **k):
return self._body
def call(self, pathname, method, body=None):
body = body or {}
self._body = body
import agent_api
self.status, self.payload = 200, None
# ★ 内核从 `handler.path` 里读 query(`?space=own`),
# 所以这里必须把带 query 的路径原样塞回去
self.path = pathname
agent_api.handle(self, pathname.split('?')[0], method)
return self.payload or {}
def main():
print(f"临时数据目录:{DATA}")
h = FakeHandler()
# ---------------------------------------------------------------- 1
section("1. 智能体:UUID 主键 + 扩展字段")
a1 = store.create_agent({"name": "玄辰", "description": "仙门大师兄", "systemPrompt": "你是玄辰。"})
check("新建的 id 是 UUID", len(a1["id"]) == 36 and a1["id"].count("-") == 4, a1["id"])
check("description 存下来了", a1.get("description") == "仙门大师兄")
a1 = store.update_agent(a1["id"], {"tokenLimit": 5000, "emotionEnabled": True, "skillIds": []}) or a1
check("tokenLimit 存成数字", a1.get("tokenLimit") == 5000, repr(a1.get("tokenLimit")))
check("emotionEnabled 是布尔", a1.get("emotionEnabled") is True)
a2 = store.create_agent({"name": "仙辰"})
check("两个智能体 id 不同", a1["id"] != a2["id"])
# 内置的还在、短 id 没被动过
check("内置智能体保留了短 id", any(x["id"] == "a_doubao" for x in store.list_agents()))
# ---------------------------------------------------------------- 2
section("2. 记忆:增删改查 + 检索")
scope = agentdb.scope_of(a1["id"])
m1 = agentdb.memory_add(scope, "用户的名字", "他叫小林", author_agent=a1["id"])
m2 = agentdb.memory_add(scope, "喝咖啡", "每天早上喝一杯美式", author_agent=a1["id"])
check("加了两条", len(agentdb.memory_list(scope)) == 2)
check("检索命中正文", len(agentdb.memory_search(scope, "美式")) == 1)
check("检索命中标题", len(agentdb.memory_search(scope, "名字")) == 1)
check("检索无关词不命中", len(agentdb.memory_search(scope, "量子力学")) == 0)
agentdb.memory_update(m1["id"], content="他叫小林,做前端的")
check("改正文生效", "前端" in agentdb.memory_get(m1["id"])["content"])
agentdb.memory_forget(m2["id"])
check("删掉一条", len(agentdb.memory_list(scope)) == 1)
# ---------------------------------------------------------------- 3
section("3. pinned 保护(AI 改不动)")
agentdb.memory_set_pinned(m1["id"], True)
import tools_runtime
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
try:
agent_tools.memory_forget({"id": m1["id"]})
check("pinned 的删不掉", False, "居然删成功了")
except ValueError as exc:
check("pinned 的删不掉", "必须保留" in str(exc), str(exc))
try:
agent_tools.memory_update({"id": m1["id"], "content": "改了"})
check("pinned 的改不动", False, "居然改成功了")
except ValueError:
check("pinned 的改不动", True)
check("pinned 的还在", agentdb.memory_get(m1["id"]) is not None)
agentdb.memory_set_pinned(m1["id"], False)
# ---------------------------------------------------------------- 4
section("4. 工具:memory_add / emotion_set / get_token_usage")
r = agent_tools.memory_add({"title": "喜欢猫", "content": "他家有两只猫"})
check("memory_add 返回 id", bool(r.get("id")))
r = agent_tools.memory_search({"keyword": "猫"})
check("memory_search 找到刚记的", r["count"] >= 1, str(r["count"]))
agent_tools.emotion_set({"preset": "喜", "text": "刚被夸了,有点得意"})
check("情绪写进去了(双字段)", "得意" in agentdb.emotion_state(a1["id"])["text"])
check("preset 也写进去了", agentdb.emotion_state(a1["id"])["preset"] == "喜")
agentdb.token_add(a1["id"], "doubao-pro", 1200, 800)
agentdb.token_add(a1["id"], "doubao-pro", 300, 100)
agentdb.token_add(a1["id"], "deepseek-r1", 500, 200)
u = agent_tools.get_token_usage({})
check("总量 = 输入+输出", u["used"] == 1200 + 800 + 300 + 100 + 500 + 200, str(u["used"]))
check("输入输出分开", u["input"] == 2000 and u["output"] == 1100, f'{u["input"]}/{u["output"]}')
check("按模型分桶", len(u["byModel"]) == 2, str([m["model"] for m in u["byModel"]]))
check("剩余额度按限额算", u["remaining"] == 5000 - u["used"], str(u["remaining"]))
# ---------------------------------------------------------------- 5
section("5. 世界观 + 共享记忆")
wv = store.create_resource("worldviews", {"name": "九霄", "setting": "一个仙侠世界,灵气复苏。"})
check("世界观有 UUID", len(wv["id"]) == 36)
store.update_agent(a1["id"], {"worldviewId": wv["id"]})
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
a1 = store.get_agent(a1["id"])
a2 = store.get_agent(a2["id"])
check("绑定后 scope 变成世界观的", agentdb.scope_of(a1["id"], a1["worldviewId"]).startswith("world:"))
wscope = agentdb.scope_of(a1["id"], a1["worldviewId"])
agentdb.memory_add(wscope, "共同约定", "两人都怕师父", author_agent=a1["id"])
check("共享空间两人都看得到", len(agentdb.memory_list(agentdb.scope_of(a2["id"], a2["worldviewId"]))) == 1)
# ---------------------------------------------------------------- 6
section("6. 写入限权:只能删自己写的")
tools_runtime.push_context(agentId=a2["id"], conversationId="c_test")
shared_item = agentdb.memory_list(wscope)[0]
try:
agent_tools.memory_forget({"id": shared_item["id"]})
check("删不了别人写的", False, "居然删成功了")
except ValueError as exc:
check("删不了别人写的", "其他智能体" in str(exc), str(exc))
# 自己写的能删
mine = agent_tools.memory_add({"title": "仙辰的事", "content": "他喜欢御剑"})
agent_tools.memory_forget({"id": mine["id"]})
check("自己的能删", agentdb.memory_get(mine["id"]) is None)
# ---------------------------------------------------------------- 7
section("7. 记忆空间的切换:绑定世界观之后,旧记忆不会「隐身」(复查 4.1)")
# a1 在第 5 节绑了世界观、第 2 节在私有空间里留过记忆 —— 正是"用户攒了
# 三个月私有记忆、一绑世界观列表就空了"的那个场景
active = h.call(f"/api/agents/{a1['id']}/memories", "GET")
check("当前空间是共享的", active.get("shared") is True)
check("**告诉界面私有空间还剩几条**", active.get("ownCount", 0) > 0, str(active.get("ownCount")))
old = h.call(f"/api/agents/{a1['id']}/memories?space=own", "GET")
check("?space=own 能读到旧私有记忆", old.get("own") is True and len(old.get("memories") or []) > 0,
str(old.get("error") or len(old.get("memories") or [])))
check("私有空间标成 own(界面据此说明「这是绑定前的」)", old.get("own") is True)
check("私有空间里不混入共享条目",
all("共同约定" != m.get("title") for m in old.get("memories") or []),
str([m.get("title") for m in old.get("memories") or []]))
check("共享空间里也不混入私有条目",
all("用户的名字" != m.get("title") for m in active.get("memories") or []),
str([m.get("title") for m in active.get("memories") or []]))
# 没绑世界观时不留 ownCount(否则界面会挂一个永远点不出东西的入口)
a_plain = store.create_agent({"name": "没绑世界观的"})
plain = h.call(f"/api/agents/{a_plain['id']}/memories", "GET")
check("没绑世界观时 ownCount = 0", plain.get("ownCount", 0) == 0, str(plain.get("ownCount")))
# ---------------------------------------------------------------- 8
section("8. system prompt 注入(附录 C)")
tools_runtime.push_context(agentId=a1["id"], conversationId="c_test")
agentdb.emotion_set(a2["id"], preset="哀", text="有点烦")
store.update_agent(a2["id"], {"emotionEnabled": True})
# ★ a1 在这一节之前已经绑了世界观 → 它的记忆空间是**共享**的那个,
# 所以验证"记忆进提示词"要往当前 scope 里写(这正是绑定世界观的正确行为)
agentdb.memory_add(agentdb.scope_of(a1["id"], a1["worldviewId"]),
"用户的名字", "他叫小林,做前端的", author_agent=a1["id"])
# 感知开关先关掉,验证"没开就没有同伴情绪段"
store.update_agent(a1["id"], {"emotionEnabled": False})
a1 = store.get_agent(a1["id"])
sk = store.create_resource("skills", {"name": "写作", "content": "写东西要先列大纲。"})
agentdb.bind_skills(a1["id"], [sk["id"]])
prompt = agent_context.build_system_prompt(store.read_settings(), a1)
for tag in ("<skills>", "<worldview>", "<emotion>", "<memory>"):
check(f"{tag} 段在", tag in prompt)
check("人设在最前面", prompt.startswith("你是玄辰。"), prompt[:20])
check("世界观设定进去了", "灵气复苏" in prompt)
# ★ 共享空间的标题带作者署名(复查报告 5):不署名的后果是
# 别人写的经历被模型当成自己的过去
check("记忆进去了(标题+正文)", "用户的名字" in prompt and "前端" in prompt)
check("共享记忆带作者署名", "(你记的)" in prompt, prompt[-300:])
check("自定义 Skill 进去了", "写东西要先列大纲" in prompt)
check("顺序:skills 在 worldview 前", prompt.index("<skills>") < prompt.index("<worldview>"))
check("顺序:worldview 在 memory 前", prompt.index("<worldview>") < prompt.index("<memory>"))
# ★ v1.2 把 emotion 挪到 memory **后面**了(缓存友好排序,详见第 20 节)。
# 这条断言原来记的是旧顺序 —— 顺序一改它就红了,这正是它该干的活。
check("顺序:memory 在 emotion 前(v1.2 缓存友好)",
prompt.index("<memory>") < prompt.index("<emotion>"))
# ★ 情绪感知关着时**仍然给成员名单**(复查报告 5):共享记忆是共用的,
# AI 不知道有别人,就会把别人写的条目当成自己的经历
check("没开感知也有成员名单", "<peer_emotions>" in prompt and "仙辰" in prompt, prompt[-300:])
check("但名单里**没有情绪**", "有点烦" not in prompt, prompt[-300:])
check("名单里也没有 agent 的 JSON", "'builtin'" not in prompt and "worldviewId'" not in prompt)
store.update_agent(a1["id"], {"emotionEnabled": True})
prompt2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
check("开了感知后看到的是**同伴的 preset**(不是他的内心独白)",
"<peer_emotions>" in prompt2 and "仙辰-哀" in prompt2, prompt2[-200:])
check("**同伴的 text 不外泄**", "有点烦" not in prompt2.split("<peer_emotions>")[-1], prompt2[-200:])
# 空段要整段删掉
a3 = store.create_agent({"name": "空白的"})
p3 = agent_context.build_system_prompt(store.read_settings(), a3)
check("没记忆时 <memory> 整段没了", "<memory>" not in p3, p3[-120:])
check("但 <skills> 还在(内置手册)", "<skills>" in p3)
# ---------------------------------------------------------------- 8
section("8. HTTP 接口")
r = h.call("/api/agents", "GET")
check("GET /api/agents", r.get("ok") and len(r["agents"]) >= 4)
r = h.call("/api/agents", "POST", {"name": "接口建的"})
new_id = (r.get("agent") or {}).get("id")
check("POST /api/agents", bool(new_id))
r = h.call(f"/api/agents/{new_id}", "PATCH", {"description": "改过的"})
check("PATCH 生效", (r.get("agent") or {}).get("description") == "改过的")
r = h.call("/api/agents/a_doubao", "DELETE")
check("内置的删不掉", r.get("ok") is False, str(r.get("error")))
check("内置的还在", store.get_agent("a_doubao") is not None)
r = h.call(f"/api/agents/{a1['id']}/memories", "GET")
check("GET 记忆列表", r.get("ok") and r.get("shared") is True)
r = h.call(f"/api/agents/{a1['id']}/usage", "GET")
check("GET 用量", r.get("ok") and r.get("total", 0) > 0)
r = h.call(f"/api/agents/{a1['id']}/emotion", "PUT", {"preset": "喜", "text": "挺开心的"})
check("PUT 情绪(双字段)", (r.get("emotion") or {}).get("text") == "挺开心的", str(r.get("emotion")))
check("preset 也存了", (r.get("emotion") or {}).get("preset") == "喜")
r = h.call("/api/worldviews", "GET")
check("GET 世界观列表", r.get("ok") and len(r["items"]) == 1)
r = h.call("/api/model-entries", "POST", {"name": "豆包 Pro", "model": "doubao-pro", "pricePerK": 0.8})
check("POST 模型列表", r.get("ok") and (r.get("item") or {}).get("id"))
r = h.call("/api/skills", "GET")
check("GET Skill 列表", r.get("ok") and len(r["items"]) == 1)
# ---------------------------------------------------------------- 9
section("9. 智能体包导出 / 导入")
r = h.call(f"/api/agents/{a1['id']}/package", "GET")
check("导出拿到 base64 zip", bool(r.get("data")), str(r.get("error")))
blob = r.get("data")
r = h.call("/api/agents/import", "POST", {"data": blob})
imported = r.get("agent") or {}
check("导入成功", bool(imported.get("id")), str(r.get("error")))
check("导入的是**新** UUID(不是原来那个)", imported.get("id") not in (None, a1["id"]))
check("名字带过来了", imported.get("name") == "玄辰")
check("提示词带过来了", imported.get("systemPrompt") == "你是玄辰。")
check("描述带过来了", imported.get("description") == "仙门大师兄")
check("**模型引用没带过来**(需求 2.5 的边界)", not imported.get("modelId"))
check("**世界观绑定没带过来**", not imported.get("worldviewId"))
check("**限额没带过来**", not imported.get("tokenLimit"))
r2 = h.call("/api/agents/import", "POST", {"data": blob})
check("同一个包导入两次 = 两个独立实体",
(r2.get("agent") or {}).get("id") not in (None, imported.get("id"), a1["id"]))
r = h.call("/api/agents/import", "POST", {"data": "bm90IGEgemlw"})
check("坏包报错而不是崩", r.get("ok") is False, str(r.get("error")))
# ---------------------------------------------------------------- 10
section("10. 记忆导出 / 导入(合并按标题去重)")
r = h.call(f"/api/agents/{a1['id']}/memories/export", "GET")
check("导出 type 正确", r.get("type") == "world-memory", str(r.get("type")))
check("导出带 version", r.get("version") == 1)
check("导出带 Emotion", "Emotion" in r)
check("导出**不含** author_agent",
all("author_agent" not in m for m in r.get("smartMemory") or []))
exported = dict(r)
exported["smartMemory"] = [
{"title": "新的一条", "content": "这是导入进来的", "pinned": False},
] + list(exported["smartMemory"])
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST", {"data": exported, "mode": "merge"})
check("合并模式:新增了 1 条", r.get("added") == 1, str(r))
check("合并模式:同名的跳过了", r.get("skipped", 0) >= 1, str(r))
check("合并模式:保留当前情绪", agentdb.emotion_state(a1["id"])["text"] == "挺开心的")
r = h.call(f"/api/agents/{a1['id']}/memories/import", "POST",
{"data": {"type": "agent-memory", "version": 1, "smartMemory": [], "Emotion": "换掉了"},
"mode": "replace"})
check("覆盖模式:情绪也换了(v1.1 的字符串格式也认)",
agentdb.emotion_state(a1["id"])["text"] == "换掉了", str(agentdb.emotion_state(a1["id"])))
# ---------------------------------------------------------------- 11
section("11. 多模型:引用了就真的用(需求 3.3)")
entry = store.create_resource("models", {
"name": "DeepSeek R1", "apiBase": "https://api.deepseek.com/v1",
"apiKey": "sk-abc", "model": "deepseek-r1-250528", "provider": "deepseek",
})
store.update_agent(a1["id"], {"modelId": entry["id"]})
info = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
check("地址来自模型列表那一项", info["baseUrl"] == "https://api.deepseek.com/v1", info["baseUrl"])
check("模型标识也来自它", info["model"] == "deepseek-r1-250528", info["model"])
check("提供商跟着换", info["provider"] == "deepseek", info["provider"])
# ★ Key 也必须换:只换 model 不换 Key 必然 401(这是"整组覆盖"的理由)
check("**Key 也是那一项的**(不是全局的)", info["apiKey"] == "sk-abc", info["apiKey"])
# 没引用时回落全局
store.update_agent(a1["id"], {"modelId": ""})
info2 = store.provider_info(store.read_settings(), store.get_agent(a1["id"]))
check("没引用时回落全局", info2.get("modelEntryId") is None)
check("回落时不再带那一项的 Key", info2["apiKey"] != "sk-abc")
# ---------------------------------------------------------------- 12
section("12. 资源 CRUD + Skill 导入导出")
r = h.call("/api/skills", "POST", {"name": "另一个", "content": "内容"})
sid = (r.get("item") or {}).get("id")
r = h.call(f"/api/skills/{sid}", "PATCH", {"content": "改过的内容"})
check("PATCH skill", (r.get("item") or {}).get("content") == "改过的内容")
r = h.call(f"/api/skills/{sid}/export", "GET")
check("导出 skill 是单 JSON", r.get("json") and json.loads(r["json"])["type"] == "agent-skill")
r = h.call("/api/skills/import", "POST", {"data": json.loads(r["json"])})
check("导入 skill", (r.get("item") or {}).get("id") not in (None, sid))
r = h.call(f"/api/skills/{sid}", "DELETE")
check("删 skill", r.get("deleted") is True)
# ---------------------------------------------------------------- 13
section("13. 世界观的引用列表(谁绑了它)")
lonely = store.create_resource("worldviews", {"name": "没人用的世界", "setting": "空"})
r = h.call("/api/worldviews", "GET")
items = r.get("items") or []
check("列表每一项都带 agents 字段", items and all("agents" in it for it in items))
mine = next((it for it in items if it.get("id") == wv["id"]), None)
check("绑了它的两个智能体都在", mine is not None and len(mine.get("agents") or []) == 2,
str(mine and mine.get("agents")))
check("给的是名字而不是只有 id",
bool(mine) and all(a.get("name") for a in mine.get("agents") or []),
str(mine and mine.get("agents")))
empty = next((it for it in items if it.get("id") == lonely["id"]), None)
check("没人绑的世界观 agents 为空(能看出没人用)",
empty is not None and empty.get("agents") == [], str(empty and empty.get("agents")))
# 解绑之后要跟着变(缓存住了的话这里会露馅)
store.update_agent(a2["id"], {"worldviewId": ""})
again = next((it for it in (h.call("/api/worldviews", "GET").get("items") or [])
if it.get("id") == wv["id"]), None)
check("解绑之后列表跟着少一个", again is not None and len(again.get("agents") or []) == 1,
str(again and again.get("agents")))
store.update_agent(a2["id"], {"worldviewId": wv["id"]})
# ---------------------------------------------------------------- 14
section("14. 会话隔离:一个会话属于一个智能体(用户报的「串味」)")
# 场景:跟「豆包」聊了半天 → 切到「代码搭子」→ 接着聊。
# 以前 system prompt 换了、历史消息没换,新角色会把上一个角色说过的话
# 当成自己的经历 —— 用户的原话是"智能体怎么串味了"。
conv_a = store.create_conversation("A 的对话", agent_id=a1["id"])
check("新会话记住了主人", (store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"])
legacy = store.create_conversation("老会话")
check("不传主人时是空(老数据的样子)",
not (store.get_conversation(legacy["id"]) or {}).get("agentId"))
store.set_conversation_agent(legacy["id"], a2["id"])
check("没主人的老会话能被认领",
(store.get_conversation(legacy["id"]) or {}).get("agentId") == a2["id"])
# ★★ 这条是关键:有主人的会话**不许改嫁** —— 改名换姓就等于串味
store.set_conversation_agent(conv_a["id"], a2["id"])
check("已经有主人的不会被改嫁(那正是串味的来源)",
(store.get_conversation(conv_a["id"]) or {}).get("agentId") == a1["id"],
str((store.get_conversation(conv_a["id"]) or {}).get("agentId")))
# ---------------------------------------------------------------- 15
section("15. 记忆注入窗口 + 置顶保护(本次新增)")
w = store.create_agent({"name": "窗口测试"})
sc = agentdb.scope_of(w["id"])
for i in range(1, 11):
agentdb.memory_add(sc, f"第{i}条", f"内容{i}", author_agent=w["id"])
ids = agentdb.memory_list(sc)
agentdb.memory_set_pinned(ids[0]["id"], True) # 把**最旧**的一条置顶
# ★ SQLite 里的布尔是 0/1 整数,`is True` 永远是 False(这个坑探针自己踩了)
check("置顶的排在列表最前", bool(agentdb.memory_list(sc)[0]["pinned"]))
# 窗口设成 4:置顶的必须在,其余取最近的
store.write_settings({"memoryWindow": 4})
p = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
seg = p[p.find("<memory>"):p.find("</memory>")]
check("置顶的那条**在**(不受窗口限制)", "第1条" in seg, seg[-200:])
check("最近的在", "第10条" in seg and "第9条" in seg, seg[-200:])
check("中间的被裁掉了", "第5条" not in seg, seg[-200:])
check("裁掉多少写清楚了(告知可检索)", "memory_search" in seg, seg[-200:])
# 0 = 不限
store.write_settings({"memoryWindow": 0})
p2 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
check("窗口 = 0 时全部注入", all(f"第{i}条" in p2 for i in range(1, 11)))
# 接口把窗口信息带给界面
mp = h.call(f"/api/agents/{w['id']}/memories", "GET")
check("界面拿得到窗口/置顶数/实际注入数",
all(k in mp for k in ("window", "pinnedCount", "injected")), str(sorted(mp)[:8]))
check("injected 算得对(先恢复窗口=4)",
(store.write_settings({"memoryWindow": 4}),
(h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected") == 4)[1],
str((h.call(f"/api/agents/{w['id']}/memories", "GET") or {}).get("injected")))
# ---- ★ 可以**多个**置顶(用户明确要求)----
#
# 单条置顶是最容易蒙混过关的:只测一条的话,"置顶逻辑写成只能有一个"
# 也能通过。所以这里标**三条**,而且专挑**最早**的三条 ——
# 窗口只留最近的话它们本来就该被裁掉,只有置顶真的生效才会留下。
ids2 = agentdb.memory_list(sc)
for k in (0, 2, 4):
agentdb.memory_set_pinned(ids2[k]["id"], True)
store.write_settings({"memoryWindow": 5})
p3 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
seg3 = p3[p3.find("<memory>"):p3.find("</memory>")]
check("**多个置顶**都能留(标了三条最早的)",
all(f"第{i}条" in seg3 for i in (1, 3, 5)), seg3[-260:])
check("窗口剩下的名额给最近的", "第10条" in seg3, seg3[-260:])
check("置顶在正文里被标出来", seg3.count("置顶") >= 3, str(seg3.count("置顶")))
# 置顶比窗口还多的时候:置顶**全部**保留(窗口是给普通记忆设的,
# 不是用来否决用户明确置顶的东西)
for k in (6, 8, 9):
agentdb.memory_set_pinned(ids2[k]["id"], True)
store.write_settings({"memoryWindow": 2})
p4 = agent_context.build_system_prompt(store.read_settings(), store.get_agent(w["id"]))
seg4 = p4[p4.find("<memory>"):p4.find("</memory>")]
kept = sum(1 for i in range(1, 11) if f"第{i}条" in seg4)
check("置顶数超过窗口时,置顶的全部保留(6 条)", kept == 6, f"实际 {kept} 条:{seg4[-200:]}")
store.write_settings({"memoryWindow": 50})
# ---------------------------------------------------------------- 16
section("16. 语音:智能体自己的音色要真的生效(用户报的「语音没生效」)")
#
# 内核这边一直是对的(`voice_for` 做"智能体 > 全局"),
# 真正漏的是**界面朗读时不传 agentId** —— 于是内核拿不到人,
# 永远用全局那个嗓子,智能体编辑页里选的音色白配。
# 界面那一侧没法在这里测,所以这里把**契约**钉死:
# 只要 agentId 传进来,音色必须跟着换。
import speech
a_voice = store.create_agent({"name": "嗓音测试"})
store.update_agent(a_voice["id"], {"ttsVoice": "my-voice-123", "ttsEngine": "volc"})
st = store.read_settings()
merged = speech.voice_for(st, store.get_agent(a_voice["id"]))
check("智能体的音色覆盖了全局", merged.get("ttsVoice") == "my-voice-123", str(merged.get("ttsVoice")))
check("引擎也跟着覆盖", merged.get("ttsEngine") == "volc", str(merged.get("ttsEngine")))
plain = speech.voice_for(st, {})
check("没配的智能体回落全局", plain.get("ttsVoice") == speech.voice_for(st, {}).get("ttsVoice"))
# 半配:只设了音色、没设引擎 → 引擎回落,音色用它的
half = store.create_agent({"name": "半配"})
store.update_agent(half["id"], {"ttsVoice": "only-voice"})
m2 = speech.voice_for(st, store.get_agent(half["id"]))
check("只设音色时引擎回落全局", m2.get("ttsVoice") == "only-voice", str(m2.get("ttsVoice")))
# ---------------------------------------------------------------- 17
section("17. v1.2 情绪双字段:老库迁移(**最容易把老用户数据搞丢的地方**)")
#
# ★ 直接在**内存库**上测 `_migrate`,而不是"造一个老库文件再换过去":
# 换文件的做法被 WAL 坑过一次 —— SQLite 连着旧文件的连接、
# 外加 -wal 里的新数据会把复制进去的老库盖掉,测出来是假阴性。
# 内存库没有这个问题,而且不碰任何全局状态。
import sqlite3
def old_db():
"""造一个 v1.1 的 emotions 表(只有 emotion 一列)"""
c = sqlite3.connect(":memory:")
c.row_factory = sqlite3.Row
c.executescript(
"CREATE TABLE emotions (agent_id TEXT PRIMARY KEY, "
"emotion TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);"
)
c.execute(
"INSERT INTO emotions VALUES ('a_old', '刚被师父夸了,心里偷着乐', '2026-01-01T00:00:00Z')"
)
c.commit()
return c
conn_old = old_db()
agentdb._migrate(conn_old)
row = conn_old.execute("SELECT preset, text, emotion FROM emotions WHERE agent_id='a_old'").fetchone()
check("迁移没炸(新列都加上了)", row is not None, str(row))
check("**老的自由文本搬进了 text**", row["text"] == "刚被师父夸了,心里偷着乐", str(tuple(row)))
check("preset 给了默认的「平常」", row["preset"] == "平常", str(tuple(row)))
check("老的 emotion 列留着(SQLite 删列要重建表,不值当)",
row["emotion"] == "刚被师父夸了,心里偷着乐")
# 幂等:再迁移一次不能把 text 冲掉
agentdb._migrate(conn_old)
row2 = conn_old.execute("SELECT text FROM emotions WHERE agent_id='a_old'").fetchone()
check("再迁移一次不会冲掉已有数据(幂等)", row2["text"] == row["text"], str(tuple(row2)))
# 全新的库(表已经是新结构)跑迁移应当什么都不做
conn_new = sqlite3.connect(":memory:")
conn_new.row_factory = sqlite3.Row
conn_new.executescript(agentdb.SCHEMA)
agentdb._migrate(conn_new)
check("新结构的库跑迁移是空操作(不报错、不动数据)", True)
conn_old.close()
conn_new.close()
section("18. v1.2 死亡规则:不能对话、不能自己复活、但用户能复活")
dead = store.create_agent({"name": "会死的"})
did = dead["id"]
check("默认不是死亡", not agentdb.is_dead(did))
tools_runtime.push_context(agentId=did, conversationId="c_probe")
agent_tools.emotion_set({"preset": "死亡", "text": "胸口一凉,倒了下去"})
check("AI 能把自己改成死亡", agentdb.is_dead(did))
# ★ AI 不能自愈(需求 3.5 明文)
try:
agent_tools.emotion_set({"preset": "喜", "text": "我又活了"})
check("**AI 不能把自己从死亡改活**", False, "居然改成功了")
except ValueError as exc:
check("**AI 不能把自己从死亡改活**", "不能自己复活" in str(exc), str(exc))
check("死亡状态没被改掉", agentdb.is_dead(did))
# 死亡**照常播报**给同伴(需求 3.5 明文)
rows = agentdb.peer_emotions("w", "x", [did])
check("死亡也播报给同伴", bool(rows) and rows[0][1] == "死亡", str(rows))
# ★ 用户通道能改活(兜底主权)
r = h.call(f"/api/agents/{did}/emotion", "PUT", {"preset": "喜", "text": "醒来"})
check("**用户能把它改活**(兜底主权)", not agentdb.is_dead(did), str(r.get("emotion")))
# 不认识的 preset 要拒绝,而且理由里要列出合法值
try:
agent_tools.emotion_set({"preset": "暴躁", "text": ""})
check("不认识的 preset 被拒", False, "居然通过了")
except ValueError as exc:
check("不认识的 preset 被拒", "五个之一" in str(exc), str(exc))
# 只给 text 不给 preset:保留当前 preset(emotion_set 是"只写传进来的")
agent_tools.emotion_set({"preset": "怒", "text": "火了"})
agentdb.emotion_set(did, text="气消了一半")
check("只写 text 时 preset 不动",
agentdb.emotion_state(did)["preset"] == "怒"
and agentdb.emotion_state(did)["text"] == "气消了一半",
str(agentdb.emotion_state(did)))
# ---------------------------------------------------------------- 19
section("19. v1.2 立绘表:五档 + 回退链(需求 2.5 / 2.6)")
#
# 真造几个文件出来测 —— 回退链里有一环是 `os.path.isfile`(用户可能
# 手动删过 agent-assets 里的图),不落真文件就测不到那一环。
pic_dir = tempfile.mkdtemp(prefix="doubao-pics-")
def pic(name):
p = os.path.join(pic_dir, name)
with open(p, "wb") as fh:
fh.write(b"\x89PNG\r\n\x1a\n" + name.encode())
return p
normal, happy, sad, gone = pic("normal.png"), pic("happy.png"), pic("sad.png"), pic("deleted.png")
os.remove(gone) # 造一个"文件被删了"的档位
from agent_api import portrait_of
# ① 旧格式(单文件名)经 normalize 之后变成只有「平常」档
old = store.normalize_image({"front": normal})
check("旧格式归一化成「平常」档", old["front"] == {"平常": normal}, str(old["front"]))
check("旧格式的立绘任何 preset 都能用(回退到平常)",
portrait_of(old, "怒") == normal, portrait_of(old, "怒"))
# ② 五档表:命中当前档
five = store.normalize_image({"front": {"喜": happy, "哀": sad, "平常": normal}})
check("命中当前档", portrait_of(five, "喜") == happy)
check("没那一档时回退到「平常」", portrait_of(five, "怒") == normal)
# ③ 没有平常档 → 拿字典里任何一个还能用的(用户可能只传了一档)
only_happy = store.normalize_image({"front": {"喜": happy}})
check("连平常档都没有时,用字典里任何一个能用的",
portrait_of(only_happy, "死亡") == happy, portrait_of(only_happy, "死亡"))
# ④ **文件被删了**的那一档不许返回不存在的路径(那会让界面显示空白)
broken = store.normalize_image({"front": {"喜": gone, "平常": normal}})
check("档位指向的文件不存在时,跳过它去回退",
portrait_of(broken, "喜") == normal, portrait_of(broken, "喜"))
# ⑤ 完全没图 → 空串(界面据此用内置默认人物)
check("没有立绘时返回空串(界面用内置默认人物)",
portrait_of(store.normalize_image({}), "平常") == "")
check("全是坏路径时也返回空串",
portrait_of(store.normalize_image({"front": {"喜": gone}}), "喜") == "")
# ⑥ 归一化不丢自定义档位(用户可能自己加了需求之外的档)
custom = store.normalize_image({"front": {"醉": sad, "平常": normal}})
check("归一化保留自定义档位(不丢信息)", custom["front"].get("醉") == sad, str(custom["front"]))
check("自定义档位也能被选中", portrait_of(custom, "醉") == sad)
shutil.rmtree(pic_dir, ignore_errors=True)
# ---------------------------------------------------------------- 20
section("20. v1.2 缓存友好段序(附录 C 修订,**改动最小、省的钱最多**)")
#
# 主流模型的上下文缓存是**前缀匹配**:一处不同则其后全部失效。
# 所以稳定段必须在前面、易变段必须在后面。
order = list(agent_context.SECTIONS)
check("稳定段在最前(skills 先于 memory)",
order.index('skills') < order.index('memory'), str(order))
check("worldview 也在易变段之前",
order.index('worldview') < order.index('emotion'), str(order))
# ★ 这一条就是 v1.2 改的东西:以前 emotion 在 memory 前面,
# 情绪一变连最长的 memory 段一起失效
check("**emotion 在 memory 之后**(v1.2 改的就是这条)",
order.index('emotion') > order.index('memory'), str(order))
check("数值/状态两个易变段也在 memory 之后",
order.index('stats') > order.index('memory')
and order.index('status') > order.index('memory'), str(order))
check("peer_emotions 排最后(最不可控)", order[-1] == 'peer_emotions', str(order))
# 模板里的顺序必须和 SECTIONS 一致,否则一个说东一个说西
tmpl = defaults.DEFAULT_PROMPT_TEMPLATE
tmpl_order = [m for m in __import__('re').findall(r'<(\w+)>', tmpl) if m in order]
check("模板里的段序和 SECTIONS 一致", tmpl_order == [n for n in order if n in tmpl_order], str(tmpl_order))
# 空的段不能留下 `{stats}` 这种裸占位符
p_bare = agent_context.build_system_prompt(store.read_settings(), store.get_agent(a1["id"]))
check("空段(stats/status)整段删掉,不留裸占位符", '{stats}' not in p_bare and '{status}' not in p_bare)
section("21. v1.2 缓存统计归一化(三家字段名完全不同)")
import agent_loop as _loop
cases = [
("DeepSeek(命中+未命中都给)",
{"prompt_tokens": 1000, "prompt_cache_hit_tokens": 800, "prompt_cache_miss_tokens": 200}, (800, 200)),
("Claude(只给命中,未命中要自己推)",
{"input_tokens": 1000, "cache_read_input_tokens": 600}, (600, 400)),
("OpenAI(嵌套在 details 里)",
{"prompt_tokens": 1000, "prompt_tokens_details": {"cached_tokens": 400}}, (400, 600)),
("这家不返回缓存字段", {"prompt_tokens": 1000}, (0, 0)),
("空 usage", None, (0, 0)),
]
for label, usage, want in cases:
got = _loop.cache_pair(usage)
check(f"{label} → {want}", got == want, f"实际 {got}")
# 累加要累加**归一化之后**的数,不是原始字段(换模型就不会丢)
acc = _loop.add_usage({}, {"prompt_tokens": 1000, "prompt_cache_hit_tokens": 800,
"prompt_cache_miss_tokens": 200})
acc = _loop.add_usage(acc, {"input_tokens": 500, "cache_read_input_tokens": 400})
check("跨提供商累加命中数", acc.get("cache_hit") == 1200, str(acc.get("cache_hit")))
check("跨提供商累加未命中数", acc.get("cache_miss") == 300, str(acc.get("cache_miss")))
# 落库 → 查出来
ca = store.create_agent({"name": "缓存测试"})
agentdb.token_add(ca["id"], "doubao-pro", 1000, 50, 800, 200)
agentdb.token_add(ca["id"], "deepseek-r1", 500, 20, 400, 100)
u = agentdb.token_usage(ca["id"])
check("total 里有缓存数", u["total"].get("cacheHit") == 1200 and u["total"].get("cacheMiss") == 300,
str(u["total"]))
check("按模型分桶里也有",
all("cacheHit" in m for m in u["byModel"]), str(u["byModel"]))
# 老库(没有这两列)要能迁移上来
conn_old_tu = sqlite3.connect(":memory:")
conn_old_tu.row_factory = sqlite3.Row
conn_old_tu.executescript(
"CREATE TABLE emotions (agent_id TEXT PRIMARY KEY, emotion TEXT NOT NULL DEFAULT '', updated_at TEXT NOT NULL);"
"CREATE TABLE token_usage (id INTEGER PRIMARY KEY AUTOINCREMENT, agent_id TEXT NOT NULL,"
" model TEXT NOT NULL DEFAULT '', input INTEGER NOT NULL DEFAULT 0,"
" output INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL);"
)
agentdb._migrate(conn_old_tu)
tcols = {r["name"] for r in conn_old_tu.execute("PRAGMA table_info(token_usage)").fetchall()}
check("老库的 token_usage 能加上缓存两列", {"cache_hit", "cache_miss"} <= tcols, str(sorted(tcols)))
conn_old_tu.close()
# ---------------------------------------------------------------- 汇总
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for f in fails:
print(" -", f)
return 1
print("✅ 全部通过")
return 0
if __name__ == "__main__":
try:
code = main()
finally:
shutil.rmtree(DATA, ignore_errors=True)
sys.exit(code)