Commit 540b0f02 by sunqi02

refactor: unify SessionMemory and AgentHub storage to AgentScope Msg.to_dict() format

- refactor SessionMemory.add() to use Msg.to_dict(), rename agent_code to name
- add remove_last() method for conditional cleanup
- update get_messages() summary format to use Msg.to_dict()
- adapt AgentHub to use Msg.from_dict() for history restoration
- remove redundant agent_id/intent fields and sub-agent internal message save
1 parent 76545309
# 消息历史存储格式统一实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 将 `conversation_history` 消息格式统一为 AgentScope `Msg.to_dict()` 标准格式,保留完整 ContentBlock 结构。
**Architecture:** 改 `SessionMemory.add()` 内部用 `Msg.to_dict()` 构建存储格式,删 `_dict_to_msg()` 改用 `Msg.from_dict()`;`_save_tool_interactions()` 保留 Block 结构不再压扁;删子Agent 内部消息单独保存(`call_sub_agent` 作为工具已有 tool_result);`process_message()` 改为先存后剔(`call_count >= 1` 时 `remove_last()`)。
**Tech Stack:** Python 3.12+, AgentScope, FastAPI, pytest
**Spec:** `ai-workflow/Vibe coding for SQ/docs/superpowers/specs/2026-06-15-history-format-fix-design.md`
---
### Task 1: SessionMemory 格式改造
**Files:**
- Modify: `app/service/memory.py`(全文件 ~90 行)
- [ ] **Step 1: 重写 `add()` 方法**
将第 31 行的 `add()` 替换为以下实现。参数 `agent_code` → `name`,content 支持 `str | list[dict]`,内部用 `Msg.to_dict()` 构建存储格式。
```python
def add(self, role: str, content: str | list[dict], name: Optional[str] = None) -> None:
from agentscope.message import Msg
existing = self._store.get(self.session_id)
if not existing:
return
history: list[dict[str, Any]] = list(existing.get("conversation_history") or [])
msg = Msg(
name=name or role,
content=content,
role=role,
)
history.append(msg.to_dict())
existing["conversation_history"] = history
self._store.set(self.session_id, existing)
logger.info(
"[SessionMemory] session=%s add role=%s name=%s → conversation_history 长度=%d",
self.session_id, role, name or role, len(history),
)
```
- [ ] **Step 2: 新增 `remove_last()` 方法**
在 `add()` 和 `get_messages()` 之间插入:
```python
def remove_last(self, role: Optional[str] = None) -> Optional[dict]:
"""移除 conversation_history 最后一条(可限定 role),返回被移除的消息。"""
history = self._load()
if not history:
return None
if role is not None and history[-1].get("role") != role:
return None
popped = history.pop()
data = self._store.get(self.session_id)
if data:
data["conversation_history"] = history
self._store.set(self.session_id, data)
logger.info(
"[SessionMemory] session=%s remove_last role_filter=%s → conversation_history 长度=%d",
self.session_id, role, len(history),
)
return popped
```
- [ ] **Step 3: 修改 `get_messages()` 中的摘要格式**
将第 73-74 行的摘要构造改为使用 `Msg.to_dict()`:
```python
# 旧(第 73-74 行)
result.append({"role": "system", "content": f"[早期对话摘要] {summary}"})
# 新
from agentscope.message import Msg
summary_msg = Msg("system", f"[早期对话摘要] {summary}", "system")
result.append(summary_msg.to_dict())
```
注意 `from agentscope.message import Msg` 已在 `add()` 中有,可以移到文件顶部统一导入。
- [ ] **Step 4: 修改 `mark()` 方法**
将第 89 行改为新 API:
```python
def mark(self, label: str) -> None:
"""Insert a checkpoint marker in conversation history."""
self.add("system", f"[MARK: {label}]")
```
(去掉 `agent_code` 参数,原调用没有传这个参数所以不受影响。)
- [ ] **Step 5: 更新文件顶部 import**
```python
from __future__ import annotations
import logging
from typing import Any, List, Optional
from agentscope.message import Msg
from app.infrastructure.session_store import SessionStore
logger = logging.getLogger(__name__)
```
- [ ] **Step 6: 验证 SessionMemory 单元行为**
在项目根目录运行 Python 快速验证格式:
```bash
cd ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -c "
from app.infrastructure.session_store import SessionStore
from app.service.memory import SessionMemory
store = SessionStore()
store.set('test_fmt', {'conversation_history': [], 'session_id': 'test_fmt'})
mem = SessionMemory('test_fmt', store)
# 文本消息
mem.add('user', '你好', name='user')
# 工具调用(Block 列表)
mem.add('assistant', [{'type': 'tool_use', 'id': 'toolu_001', 'name': 'call_sub_agent', 'input': {'agent_code': '17'}}], name='assistant')
# 工具结果
mem.add('system', [{'type': 'tool_result', 'id': 'toolu_001', 'name': 'call_sub_agent', 'output': '完成'}], name='system')
msgs = mem.get_messages()
print('消息数:', len(msgs))
for m in msgs:
print(' id:', m.get('id'))
print(' name:', m.get('name'))
print(' role:', m.get('role'))
print(' content type:', type(m.get('content')).__name__)
print()
# 测试 remove_last
removed = mem.remove_last()
print('移除最后一条:', removed['role'])
# 测试 Msg.from_dict 恢复
from agentscope.message import Msg
for m in mem.get_messages():
restored = Msg.from_dict(m)
print('恢复:', restored.name, restored.role, type(restored.content).__name__)
"
```
预期:无报错,3 条消息均有 `id` 字段,恢复后的 Msg 对象正常。
- [ ] **Step 7: Commit**
```bash
git add app/service/memory.py
git commit -m "$(cat <<'EOF'
refactor: unify SessionMemory storage to AgentScope Msg.to_dict() format
- add() uses Msg.to_dict() internally, content supports str | list[dict]
- rename agent_code param to name, mapping to Msg.name
- add remove_last() for conditional cleanup
- fix summary truncation to use standard format
- drop redundant agent_id/intent fields
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
EOF
)"
```
---
### Task 2: AgentHub 格式适配
**Files:**
- Modify: `app/service/agent_hub.py:443-449, 563-586, 619-653, 698-703`
- [ ] **Step 1: 删除 `_dict_to_msg()` 方法**
删除第 443-449 行的方法定义:
```python
# 删除这整个方法
def _dict_to_msg(self, m: dict) -> Msg:
"""SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
role = m.get("role", "user")
if role not in ("user", "assistant", "system"):
role = "user"
content = m.get("content") or ""
return Msg(name=role, role=role, content=content)
```
- [ ] **Step 2: 修改历史回灌逻辑**
找到 `history_msgs = [self._dict_to_msg(m) for m in recent]`(约第 523 行),改为:
```python
history_msgs = [Msg.from_dict(m) for m in recent]
```
- [ ] **Step 3: 重写 `_save_tool_interactions()` 方法**
替换第 619-653 行的整个方法:
```python
@staticmethod
def _save_tool_interactions(
memory: SessionMemory,
agent_memory_msgs: list,
) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保留 Block 结构保存到 conversation_history。"""
for msg in agent_memory_msgs:
if not hasattr(msg, "content") or not msg.content:
continue
blocks = msg.content if isinstance(msg.content, list) else []
for block in blocks:
if not isinstance(block, dict):
continue
block_type = block.get("type")
if block_type == "tool_use":
memory.add(
"assistant",
[{
"type": "tool_use",
"id": block["id"],
"name": block["name"],
"input": block.get("input", {}),
}],
name="assistant",
)
elif block_type == "tool_result":
memory.add(
"system",
[{
"type": "tool_result",
"id": block["id"],
"name": block["name"],
"output": block.get("output", ""),
}],
name="system",
)
```
注意:方法签名删除了 `default_agent_code` 参数,调用处需同步修改。
- [ ] **Step 4: 更新 `process_message()` 中 `_save_tool_interactions` 调用**
第 566 行,删掉后续不再需要的 `default_agent_code` 参数预备(当前调用没有传这个参数,确认一致):
```python
# 确认这行调用与新的无参数签名匹配
self._save_tool_interactions(memory, msg_list)
```
- [ ] **Step 5: 修改 `process_message()` 中 `memory.add("user")` 调用**
第 551 行:
```python
# 旧
memory.add("user", user_query, agent_code=target_agent)
# 新
memory.add("user", user_query, name=target_agent)
```
- [ ] **Step 6: 重写 `process_message()` 中 ReAct 完成后的回复处理**
替换第 560-598 行(从 `# Normal path: ReAct succeeded` 到 IM 发送分支结束):
```python
# Normal path: ReAct succeeded
response_content = response_msg.content # 保留原生格式(str 或 list[dict])
target_agent_name = target_agent
# 1. 保存工具交互(先于 assistant,保证 remove_last 只命中最终回复)
try:
msg_list = await agent.memory.get_memory()
self._save_tool_interactions(memory, msg_list)
except Exception:
logger.warning(
"[AgentHub] session=%s 保存工具消息异常(不影响主流程)",
session_id, exc_info=True,
)
# 2. 始终保存 assistant 回复(不干扰 ReAct 循环——循环此时已结束)
memory.add("assistant", response_content, name=target_agent_name)
call_count = self._current_route_ctx.get("call_count", 0)
# 3. call_count >= 1 时剔除最后一条 assistant(主Agent 的"已委派"废话)
if call_count >= 1:
memory.remove_last()
logger.info(
"[主Agent 静默] call_count=%d,已剔除主Agent 最终回复,子Agent(含发言人)已发送回复",
call_count,
)
# 4. 持久化(仅一次)
self.session_service.save_to_db(session_id)
# 5. call_count == 0 时正常发 IM;>= 1 时不发
if call_count == 0:
try:
await self.post_reply_hook.execute({
"agent_name": target_agent_name,
"response_content": response_msg.get_text_content() or "",
"room_id": room_id,
"mentioned_list": [user_id],
"bot_id_mapping": bot_id_mapping or {},
})
except Exception:
logger.warning(
"[最终回复 IM 发送失败] agent=%s session=%s room=%s",
target_agent_name, session_id, room_id, exc_info=True,
)
```
> 注意:原第 563-571 行的独立 try/except(`_save_tool_interactions` 包装)已融入上述代码,原第 573-598 行的 call_count 分支也被替换。无需单独的 Step 8。
- [ ] **Step 7: 删除 `_call_sub_agent()` 中子Agent 内部消息单独保存**
删除第 698-703 行:
```python
# 子Agent 的 ReAct 消息落地到同一 session
sub_msgs = await sub_agent.memory.get_memory()
ctx = self._current_route_ctx
session_memory = ctx.get("session_memory") if ctx else None
if session_memory:
self._save_tool_interactions(session_memory, sub_msgs, default_agent_code=agent_code)
```
保留子Agent 通过 IM 发送最终回复的逻辑(第 705 行之后)。
- [ ] **Step 8: Commit**
```bash
git add app/service/agent_hub.py
git commit -m "$(cat <<'EOF'
refactor: adopt AgentScope Msg.to_dict() format in AgentHub
- delete _dict_to_msg(), use Msg.from_dict() for history restoration
- _save_tool_interactions() preserves full Block structure (type/id/name/input/output)
- tool_use → role=assistant, tool_result → role=system
- process_message() uses save-then-strip pattern for call_count >= 1
- remove sub-agent internal message save (call_sub_agent tool_result is sufficient)
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
EOF
)"
```
---
### Task 3: MessageGate 参数适配
**Files:**
- Modify: `app/service/message_gate.py:215, 263-264, 299`
- [ ] **Step 1: `_handle_chat()` — 第 215 行**
```python
# 旧
mem.add("user", m["msg_content"])
# 新(不变,name 默认 "user")
mem.add("user", m["msg_content"])
```
无需改动,`name` 参数默认值 `None` 时会取 `role` 值 `"user"`。
- [ ] **Step 2: `_handle_casual()` — 第 263-264 行**
```python
# 旧
mem.add("user", merged_text)
mem.add("assistant", decision.reply, agent_code=self.main_agent_key)
# 新
mem.add("user", merged_text)
mem.add("assistant", decision.reply, name=self.main_agent_key)
```
- [ ] **Step 3: `_handle_busy()` — 第 299 行**
```python
# 旧
mem.add("user", merged_text)
# 新(不变,name 默认 "user")
mem.add("user", merged_text)
```
- [ ] **Step 4: Commit**
```bash
git add app/service/message_gate.py
git commit -m "$(cat <<'EOF'
refactor: adapt MessageGate mem.add() to new name parameter
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
EOF
)"
```
---
### Task 4: 测试更新
**Files:**
- Modify: `tests/test_session_persistence.py:162-163`
- Modify: `tests/test_message_gate.py:95`
- Modify: `tests/conftest.py`(新增辅助函数)
- [ ] **Step 1: 更新 `test_session_persistence.py`**
第 162-163 行:
```python
# 旧
memory.add("user", "你好", agent_code="main")
memory.add("assistant", "你好!有什么可以帮你的?", agent_code="main")
# 新
memory.add("user", "你好", name="main")
memory.add("assistant", "你好!有什么可以帮你的?", name="main")
```
第 177-178 行断言维持不变(role/content 仍可验证),但需要额外验证新格式的 `id` 字段存在:
```python
assert messages[0]["role"] == "user"
assert messages[0]["content"] == "你好"
assert "id" in messages[0], "新格式应有 id 字段"
assert messages[1]["role"] == "assistant"
assert "id" in messages[1], "新格式应有 id 字段"
```
- [ ] **Step 2: 更新 `test_message_gate.py`**
第 95 行的 KV mock 数据(`conversation_history: []` 仍是空列表,无变化)。但需要检查测试中是否有断言 `agent_code` 字段——如果有则删除该断言。运行:
```bash
cd ai-workflow/workspace/agent-admin/backend
grep -n "agent_code" tests/test_message_gate.py
```
如果有匹配,逐个检查并删除/更新。
- [ ] **Step 3: 在 `tests/conftest.py` 中新增 `make_msg_dict()`**
```python
def make_msg_dict(role: str, content, name: str = None) -> dict:
"""构造 AgentScope 标准格式的消息 dict,方便测试。"""
from agentscope.message import Msg
msg = Msg(name=name or role, content=content, role=role)
return msg.to_dict()
```
- [ ] **Step 4: Commit**
```bash
git add tests/test_session_persistence.py tests/conftest.py
git commit -m "$(cat <<'EOF'
test: update test data to AgentScope Msg.to_dict() format
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
EOF
)"
```
---
### Task 5: 全量测试验证
- [ ] **Step 1: 运行全部测试**
```bash
cd ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/ -v --tb=short
```
- [ ] **Step 2: 检查失败用例**
如果有失败,逐一排查:
- `KeyError: 'agent_code'` → 测试断言了已删除的字段,更新断言
- `TypeError: add() missing 1 required positional argument` → 有遗漏的调用点,更新参数名
- `AttributeError: 'AgentHub' object has no attribute '_dict_to_msg'` → 有遗漏的引用点,改为 `Msg.from_dict()`
- [ ] **Step 3: 全部通过后最终提交(如有修复)**
```bash
git add -A
git commit -m "$(cat <<'EOF'
fix: resolve test failures after history format migration
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
EOF
)"
```
- [ ] **Step 4: 确认最终测试通过**
```bash
PYTHONPATH=. python -m pytest tests/ -v
```
预期:全部 PASS。
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!