Commit bcfa26ff by sunqi02

docs: mark all plan tasks as completed

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 9218f777
# 消息管理重设计:主Agent 纯分发模式 实施计划
> **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 (`- [x]`) syntax for tracking.
**Goal:** MessageGate 简化为激活识别 + 主Agent 纯分发 + 发言人口 Agent + intent_session 移除
**Architecture:** MessageGate 从四分类门控变为二元激活识别(chat/pass),chat 只追加用户消息不回复;pass 进入 AgentHub 纯分发模式(拆解→派发→口总结)。主Agent `call_count >= 1` 时最终回复不发送不存 DB。子Agent ReAct 消息通过 `SessionMemory` 落地。
**Tech Stack:** Python 3.12+ / FastAPI / AgentScope / SQLAlchemy 2.0 / pytest
**Spec:** `ai-workflow/Vibe coding for SQ/docs/superpowers/specs/2026-06-12-message-gate-redesign.md`
---
### Task 0: Simplify GateDecision
**Files:**
- Modify: `app/service/message_gate.py:20-27`
- [x] **Step 1: Update GateDecision dataclass**
```python
@dataclass
class GateDecision:
"""MessageGate 评估后输出的决策结果。"""
intent: str # chat | pass
```
- [x] **Step 2: Run tests to verify no import errors**
Run: `PYTHONPATH=. python -m pytest tests/test_message_gate.py::test_gate_decision_dataclass_defaults -v`
Expected: FAIL (old test references `rewritten_query`)
- [x] **Step 3: Update affected test**
Replace `test_gate_decision_dataclass_defaults` in `tests/test_message_gate.py`:
```python
def test_gate_decision_dataclass_defaults():
"""GateDecision 默认字段正确。"""
d = GateDecision(intent="chat")
assert d.intent == "chat"
```
- [x] **Step 4: Run test to verify pass**
Run: `PYTHONPATH=. python -m pytest tests/test_message_gate.py::test_gate_decision_dataclass_defaults -v`
Expected: PASS
- [x] **Step 5: Commit**
```bash
git add app/service/message_gate.py tests/test_message_gate.py
git commit -m "refactor: simplify GateDecision to single intent field"
```
---
### Task 1: Rewrite MessageGate — activation check + _handle_chat
**Files:**
- Modify: `app/service/message_gate.py:187-339` (replace `_classify_and_rewrite`, `_build_classify_prompt`, `_build_default_classify_messages`, `_parse_decision_json`)
- [x] **Step 1: Delete old methods and add simplified replacements**
Replace lines 187-398 in `message_gate.py` (from `_classify_and_rewrite` through `_parse_decision_json`) with:
```python
async def _classify_and_rewrite(
self,
pending: List[Dict[str, Any]],
) -> "GateDecision":
"""调 LLM 判断当前消息是否需要激活助手。无历史上下文,只看当前消息。
Returns:
GateDecision with intent="chat" or "pass"
"""
merged_text = self._merge_text_from_pending(pending)
if not merged_text:
return GateDecision(intent="chat")
prompt = (
"你是助手激活识别器。判断当前消息是否需要AI助手响应。\n"
"- chat:打招呼、道谢、确认收到、纯社交寒暄、群友间对话 —— 助手沉默\n"
"- pass:提问、命令、文件处理、提到某Agent名称、需要协助 —— 激活助手\n"
"\n只输出 \"chat\" 或 \"pass\"。\n"
"\n当前消息:\n" + merged_text
)
messages = [{"role": "user", "content": prompt}]
response = await self.model(messages=messages)
text = self._extract_text(response).strip().lower()
logger.debug("[MessageGate] activation response: %s", text)
if text == "pass":
return GateDecision(intent="pass")
return GateDecision(intent="chat") # 兜底默认:chat
```
- [x] **Step 2: Add `_handle_chat` method**
Insert after `_classify_and_rewrite`:
```python
async def _handle_chat(
self,
session_id: str,
pending: List[Dict[str, Any]],
) -> None:
"""chat 分支:追加用户消息到 conversation_history,不触发 AgentHub,不发 IM。"""
from app.service.memory import SessionMemory
from app.infrastructure.session_store import SessionStore
store = SessionStore()
mem = SessionMemory(session_id, store)
for m in pending:
if m.get("msg_type") == "text" and m.get("msg_content"):
mem.add("user", m["msg_content"])
self.session_service.save_to_db(session_id)
```
- [x] **Step 3: Update `evaluate` branching**
Replace the `evaluate` method's classification and branching section (lines 127-185) with:
```python
# 步骤 7:调 LLM 做激活识别(无历史上下文)
pending = buffer.get_pending()
if not pending:
logger.warning("[MessageGate] session=%s buffer 为空,跳过", session_id)
return
decision = await self._classify_and_rewrite(pending=pending)
# 步骤 8:根据 intent 分支
if decision.intent == "chat":
await self._handle_chat(
session_id=session_id,
pending=pending,
)
buffer.clear_pending()
return
# pass
await self._handle_actionable(
session_id=session_id,
room_id=room_id,
user_id=user_id,
decision=decision,
pending=pending,
bot_id_mapping=bot_id_mapping,
)
buffer.clear_pending()
```
- [x] **Step 4: Remove intent_session from `_handle_actionable`**
Delete lines 512-516 in `_handle_actionable` (the intent_session clearing block):
```python
# 删除以下 block:
# # 清空 intent_session(AgentHub 内部的 save_to_db 会顺带写库)
# from app.infrastructure.session_store import SessionStore
# store = SessionStore()
# data = store.get(session_id) or {}
# data["intent_session"] = ""
# store.set(session_id, data)
```
Also delete the intent_session clearing in the `ignore` block inside `evaluate` (lines 145-149):
```python
# 删除以下 block:
# # 清空 intent_session 并持久化
# data = store.get(session_id) or {}
# data["intent_session"] = ""
# store.set(session_id, data)
# self.session_service.save_to_db(session_id)
```
- [x] **Step 5: Remove the ignore block from evaluate**
Since ignore is handled upstream, delete the `if decision.intent == "ignore"` block entirely.
- [x] **Step 6: Remove unused agent_codes param passing**
In `evaluate`, change the `_classify_and_rewrite` call — remove `agent_codes` parameter:
```python
decision = await self._classify_and_rewrite(
pending=pending,
)
```
Also remove `agent_codes=list(bot_id_mapping.keys())` from the call.
- [x] **Step 7: Run existing tests to check for import/name errors**
Run: `PYTHONPATH=. python -m pytest tests/test_message_gate.py -v --tb=short 2>&1 | head -60`
Expected: Some tests fail (test still references old methods), but no ImportError
- [x] **Step 8: Commit**
```bash
git add app/service/message_gate.py
git commit -m "refactor: simplify MessageGate to activation recognition, add _handle_chat"
```
---
### Task 2: Remove intent_session from ActiveSessionService
**Files:**
- Modify: `app/service/active_session_service.py:68-77,85,107,131-136,154,163`
- [x] **Step 1: Remove intent_session from cold recovery in get_or_create_session**
Remove lines 68-77 (intent_session parsing) and line 85 (intent_session field in payload):
```python
# 2. 查 DB(冷恢复)
if self._db_factory:
try:
with self._db_factory() as db:
db_sess = db.query(Session).filter(
Session.session_id == session_id
).first()
except Exception:
logger.exception("Failed to cold-recover session %s from DB, 降级新建", session_id)
db_sess = None
if db_sess:
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
"room_id": db_sess.room_id,
"conversation_history": json.loads(
db_sess.conversation_history or "[]"
),
"context_entities": {},
"created_at": (
db_sess.created_at.isoformat()
if db_sess.created_at else _utcnow_iso()
),
"updated_at": _utcnow_iso(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=db_sess.channel,
room_id=db_sess.room_id,
)
```
- [x] **Step 2: Remove intent_session from new session creation**
In `get_or_create_session`, remove `"intent_session": ""` from the fallback payload (line 107):
```python
# 3. 都没有,创建新 session
payload = {
"session_id": session_id,
"channel": channel,
"room_id": room_id,
"conversation_history": [],
"context_entities": {},
"created_at": _utcnow_iso(),
"updated_at": _utcnow_iso(),
}
```
- [x] **Step 3: Remove intent_session from save_to_db**
Remove lines 131-136 and line 154, line 163 (intent_session var and assignment):
```python
def save_to_db(self, session_id: str) -> None:
if not self._db_factory:
logger.warning("[save_to_db] session=%s db_factory 为 None,跳过持久化", session_id)
return
data = self.store.get(session_id)
if not data:
logger.warning("[save_to_db] session=%s KV 中无数据,跳过持久化", session_id)
return
history = data.get("conversation_history") or []
logger.info(
"[save_to_db] session=%s conversation_history 长度=%d",
session_id, len(history),
)
try:
with self._db_factory() as db:
existing = db.query(Session).filter(
Session.session_id == session_id
).first()
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
)
db.add(db_sess)
db.commit()
except Exception:
logger.exception("Failed to persist session %s to DB", session_id)
```
- [x] **Step 4: Run active session service tests**
Run: `PYTHONPATH=. python -m pytest tests/ -k "session" -v --tb=short`
Expected: Tests referencing intent_session will fail (will be addressed in test update task)
- [x] **Step 5: Commit**
```bash
git add app/service/active_session_service.py
git commit -m "refactor: remove intent_session from ActiveSessionService"
```
---
### Task 3: Drop intent_session lifecycle test file
**Files:**
- Delete: `tests/test_intent_session_lifecycle.py`
- [x] **Step 1: Delete the test file**
```bash
rm tests/test_intent_session_lifecycle.py
```
- [x] **Step 2: Verify remaining tests still run**
Run: `PYTHONPATH=. python -m pytest tests/ -v --tb=short 2>&1 | tail -20`
Expected: No errors about missing test file
- [x] **Step 3: Commit**
```bash
git rm tests/test_intent_session_lifecycle.py
git commit -m "test: remove intent_session lifecycle tests"
```
---
### Task 4: Update AgentHub _build_main_prompt — dispatch rules
**Files:**
- Modify: `app/service/agent_hub.py:26-32,309-332`
- [x] **Step 1: Replace REVIEW_GUIDE with DISPATCH_GUIDE**
Replace `REVIEW_GUIDE` constant (lines 26-32):
```python
DISPATCH_GUIDE = """
## 调度规则
1. 分析用户意图,判断是否在你的能力范围内(追问、澄清、简单对话等),可以直接回复
2. 复杂任务拆解为子任务步骤,按顺序调用子Agent(通过 call_sub_agent 工具),每次一个
3. 所有子Agent 执行完毕后,必须调用"发言人"Agent(调用码: -1)总结回复
4. 不要再调用同一个子Agent重复处理同一任务
"""
```
- [x] **Step 2: Update `_build_main_prompt` to use DISPATCH_GUIDE**
Change line 332 from `REVIEW_GUIDE` to `DISPATCH_GUIDE`:
```python
return prompt + self.soul_guide + DISPATCH_GUIDE + THINKING_GUIDE
```
- [x] **Step 3: Verify no syntax errors**
Run: `PYTHONPATH=. python -c "from app.service.agent_hub import AgentHub; print('OK')"`
Expected: OK (may fail due to missing DB — that's fine, we're checking syntax only)
Check: `PYTHONPATH=. python -c "import compile; compile(open('app/service/agent_hub.py').read(), 'agent_hub.py', 'exec'); print('syntax OK')"`
Expected: syntax OK
- [x] **Step 4: Commit**
```bash
git add app/service/agent_hub.py
git commit -m "refactor: replace REVIEW_GUIDE with DISPATCH_GUIDE in main agent prompt"
```
---
### Task 5: Update AgentHub message shielding — call_count >= 1
**Files:**
- Modify: `app/service/agent_hub.py:464-486`
- [x] **Step 1: Change shielding logic — call_count >= 1 不存不发送**
Replace lines 464-486 (final response save + post_reply block):
```python
call_count = self._current_route_ctx.get("call_count", 0)
if call_count >= 1:
# 主Agent 委托了子Agent,最终回复不写 KV、不存 DB、不发送
logger.info(
"[主Agent 静默] call_count=%d,所有子Agent(含发言人)已发送回复,跳过主Agent 回复",
call_count,
)
else:
# call_count == 0:主Agent 自己直接回复,正常写入 + 存 DB + 发送
memory.add("assistant", response_content, agent_code=target_agent)
self.session_service.save_to_db(session_id)
try:
await self.post_reply_hook.execute({
"agent_name": target_agent,
"response_content": response_content,
"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, session_id, room_id, exc_info=True,
)
```
- [x] **Step 2: Verify syntax**
Run: `PYTHONPATH=. python -c "import compile; compile(open('app/service/agent_hub.py').read(), 'agent_hub.py', 'exec'); print('syntax OK')"`
Expected: syntax OK
- [x] **Step 3: Commit**
```bash
git add app/service/agent_hub.py
git commit -m "refactor: shield main agent reply when call_count >= 1"
```
---
### Task 6: Add self-call guard to _call_sub_agent
**Files:**
- Modify: `app/service/agent_hub.py:531-539`
- [x] **Step 1: Add steward self-call check**
Replace lines 531-539:
```python
async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
"""通过 ReActAgent 调用子 Agent。"""
# 自调用防护
steward_key = self._find_steward_key()
if agent_code == steward_key:
return (
f"错误:不允许主Agent自调用。如需总结回复,请调用发言人Agent(调用码: {self._get_mouth_key()})。"
)
if agent_code not in self.agents:
valid = [c for c, a in self.agents.items() if not a.is_steward]
return (
f"错误:子 Agent '{agent_code}' 不存在。"
f"可用调用码: {valid}"
)
```
- [x] **Step 2: Add `_get_mouth_key` helper**
Add after `_find_steward_key` (or near other key-finding helpers):
```python
def _get_mouth_key(self) -> str:
"""返回发言人口 agent 的 code。"""
return "-1"
```
The mouth agent key is `row.code = "-1"` from `load_agents_from_db()`. Simple constant return is sufficient; fallback to "-1" even if DB row is missing.
- [x] **Step 3: Verify syntax**
Run: `PYTHONPATH=. python -c "import compile; compile(open('app/service/agent_hub.py').read(), 'agent_hub.py', 'exec'); print('syntax OK')"`
Expected: syntax OK
- [x] **Step 4: Commit**
```bash
git add app/service/agent_hub.py
git commit -m "feat: add self-call guard to _call_sub_agent"
```
---
### Task 7: Update _save_tool_interactions + sub-agent persistence
**Files:**
- Modify: `app/service/agent_hub.py:498-529` (`_save_tool_interactions`)
- Modify: `app/service/agent_hub.py:376-379` (`_current_route_ctx` init)
- Modify: `app/service/agent_hub.py:531-575` (`_call_sub_agent`)
- [x] **Step 1: Add `default_agent_code` parameter to `_save_tool_interactions`**
Replace lines 498-529:
```python
@staticmethod
def _save_tool_interactions(
memory: SessionMemory,
agent_memory_msgs: list,
default_agent_code: str = "",
) -> None:
"""从 ReAct 循环内存中提取所有 tool_use/tool_result,保存到 conversation_history。
Args:
memory: SessionMemory 实例
agent_memory_msgs: AgentScope ReAct 循环产生的 Msg 列表
default_agent_code: 当 block name 不是有效 agent code 时的默认值(用于子Agent消息)
"""
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":
inp = block.get("input", {})
name = block.get("name", "")
memory.add("user", str(inp), agent_code=default_agent_code or name)
elif block_type == "tool_result":
output = block.get("output", "")
if isinstance(output, list):
texts = [
item.get("text", "")
for item in output
if isinstance(item, dict) and item.get("type") == "text"
]
result_text = "\n".join(texts)
elif isinstance(output, str):
result_text = output
else:
result_text = str(output)
if result_text:
name = block.get("name", "")
memory.add("assistant", result_text, agent_code=default_agent_code or name)
```
- [x] **Step 2: Inject SessionMemory into `_current_route_ctx`**
In `process_message`, after line 390 (after creating `memory`), add:
```python
# 将 SessionMemory 注入 route_ctx,供 _call_sub_agent 使用
self._current_route_ctx["session_memory"] = memory
```
- [x] **Step 3: Save sub-agent ReAct messages in `_call_sub_agent`**
After `response = await sub_agent.reply(...)` in `_call_sub_agent`, add sub-agent message persistence:
```python
response = await sub_agent.reply(Msg("user", instruction, "user"))
response_text = response.get_text_content()
# 子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)
```
- [x] **Step 3.5: Exclude call_sub_agent from mouth agent toolkit**
In the agent toolkit creation loop (lines 251-272), add a skip for mouth agent:
```python
for agent_code, agent_config in self.agents.items():
# ...
for name, tool in self.toolkit.tools.items():
if tool.group == "basic":
# 口 agent 不需要 call_sub_agent 工具
if agent_code == "-1" and name == "call_sub_agent":
continue
agent_tk.register_tool_function(
tool.original_func,
group_name=tool.group,
func_name=tool.name,
preset_kwargs=tool.preset_kwargs,
json_schema=tool.json_schema,
)
```
- [x] **Step 4: Verify syntax**
Run: `PYTHONPATH=. python -c "import compile; compile(open('app/service/agent_hub.py').read(), 'agent_hub.py', 'exec'); print('syntax OK')"`
Expected: syntax OK
- [x] **Step 5: Commit**
```bash
git add app/service/agent_hub.py
git commit -m "feat: persist sub-agent ReAct messages to SessionMemory"
```
---
### Task 8: Auto-complete mouth agent code in allowed_agent_codes
**Files:**
- Modify: `app/api/v1/endpoints/agent_hub.py:98-116`
- [x] **Step 1: Auto-add mouth agent code to allowed_agent_codes**
After line 116 (`if not allowed_agent_codes:`), add mouth agent auto-completion:
```python
if not allowed_agent_codes:
allowed_agent_codes = None # 无有效子 agent,走默认路由
# 后端自动补全发言人口 agent code,确保主Agent 始终可调用发言人
MOUTH_AGENT_CODE = "-1"
if allowed_agent_codes is not None and MOUTH_AGENT_CODE not in allowed_agent_codes:
mouth_key = code_to_key.get(MOUTH_AGENT_CODE) or MOUTH_AGENT_CODE
if mouth_key in agent_hub.agents:
allowed_agent_codes.append(mouth_key)
```
- [x] **Step 2: Verify syntax**
Run: `PYTHONPATH=. python -c "import compile; compile(open('app/api/v1/endpoints/agent_hub.py').read(), 'agent_hub.py', 'exec'); print('syntax OK')"`
Expected: syntax OK
- [x] **Step 3: Commit**
```bash
git add app/api/v1/endpoints/agent_hub.py
git commit -m "feat: auto-complete mouth agent code (-1) in allowed_agent_codes"
```
---
### Task 9: Data migration script — insert mouth agent
**Files:**
- Create: `scripts/migration_insert_mouth_agent.sql`
- [x] **Step 1: Write migration SQL script**
```sql
-- Insert 发言人口 agent
-- Run: mysql -u <user> -p <database> < scripts/migration_insert_mouth_agent.sql
INSERT INTO ai_agents (code, name, description, is_steward, is_deleted, created_at, updated_at)
VALUES ('-1', '发言人', '你是团队发言人。将主Agent的调度结果用自然语言回复用户。要求:保持友善、简洁、说人话;整合各子Agent的结果,不要遗漏关键信息;如果结果不完整,诚实告知。', false, false, NOW(), NOW())
ON DUPLICATE KEY UPDATE updated_at = NOW();
```
- [x] **Step 2: Commit**
```bash
git add scripts/migration_insert_mouth_agent.sql
git commit -m "feat: add mouth agent migration script"
```
---
### Task 10: Update test_message_gate.py
**Files:**
- Modify: `tests/test_message_gate.py`
- [x] **Step 1: Rewrite test file for new activation model**
Replace `tests/test_message_gate.py` with simplified tests:
```python
"""MessageGate 激活识别测试。"""
import pytest
from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision
def test_message_gate_can_be_constructed():
"""MessageGate 应能通过依赖注入的方式构造。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
assert gate is not None
def test_gate_decision_only_intent():
"""GateDecision 只有 intent 字段。"""
d = GateDecision(intent="chat")
assert d.intent == "chat"
assert not hasattr(d, "rewritten_query")
assert not hasattr(d, "reply")
@pytest.mark.asyncio
async def test_classify_returns_chat_for_empty_pending():
"""空 pending → 返回 chat。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
decision = await gate._classify_and_rewrite(pending=[])
assert decision.intent == "chat"
@pytest.mark.asyncio
async def test_classify_activation_model_called():
"""LLM 返回 'pass' → GateDecision intent='pass'。"""
mock_model = MagicMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "pass"}]
mock_model.return_value = mock_model_response
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
)
pending = [{"msg_type": "text", "msg_content": "帮我整理会议纪要"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "pass"
# 验证 LLM 被调用
mock_model.assert_called_once()
@pytest.mark.asyncio
async def test_classify_activation_returns_chat_by_default():
"""LLM 返回未知内容 → 兜底 chat。"""
mock_model = MagicMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "hello"}]
mock_model.return_value = mock_model_response
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
)
pending = [{"msg_type": "text", "msg_content": "谢谢大家"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "chat"
@pytest.mark.asyncio
async def test_handle_chat_adds_user_message_to_history():
"""_handle_chat 追加用户消息到 conversation_history。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-chat-session"
mock_session_service = MagicMock()
mock_session_service.save_to_db = MagicMock()
gate = MessageGate(
config_loader=MagicMock(),
session_service=mock_session_service,
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
pending = [{"msg_type": "text", "msg_content": "好的"}]
await gate._handle_chat(session_id=sid, pending=pending)
data = store.get(sid)
history = data.get("conversation_history", [])
assert len(history) == 1
assert history[0]["role"] == "user"
assert history[0]["content"] == "好的"
mock_session_service.save_to_db.assert_called_once_with(sid)
@pytest.mark.asyncio
async def test_handle_actionable_calls_agent_hub():
"""_handle_actionable 调用 agent_hub.process_message。"""
mock_agent_hub = MagicMock()
mock_agent_hub.process_message = AsyncMock()
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=mock_agent_hub,
main_agent_key="11",
model=MagicMock(),
)
decision = GateDecision(intent="pass")
pending = [{"msg_type": "text", "msg_content": "创建任务"}]
await gate._handle_actionable(
session_id="test-session",
room_id="room-1",
user_id="user-1",
decision=decision,
pending=pending,
bot_id_mapping={"11": "bot_main"},
)
mock_agent_hub.process_message.assert_called_once()
```
- [x] **Step 2: Run the new tests**
Run: `PYTHONPATH=. python -m pytest tests/test_message_gate.py -v`
Expected: All tests PASS
- [x] **Step 3: Commit**
```bash
git add tests/test_message_gate.py
git commit -m "test: rewrite MessageGate tests for activation recognition"
```
---
### Task 11: Update test_agent_hub.py
**Files:**
- Modify: `tests/test_agent_hub.py`
- [x] **Step 1: Add self-call guard and sub-agent persistence tests**
Add to `tests/test_agent_hub.py` (after existing test functions, before any file-end markers):
```python
import asyncio
# ── 自调用防护 & 子Agent 消息持久化测试 ──────────────────────────
class TestSelfCallGuard:
"""验证 _call_sub_agent 的自调用防护和子Agent消息落地。"""
def test_rejects_steward_self_call(self):
"""主Agent 不允许调用自己的 code → 返回错误提示。"""
hub = _make_test_hub()
steward_key = hub._find_steward_key()
result = asyncio.run(hub._call_sub_agent(steward_key, "测试指令"))
assert "不允许主Agent自调用" in result
assert "发言人Agent" in result
def test_rejects_unknown_agent(self):
"""调用不存在的 agent code → 返回错误提示。"""
hub = _make_test_hub()
result = asyncio.run(hub._call_sub_agent("nonexistent_999", "测试指令"))
assert "不存在" in result
def test_save_tool_interactions_with_default_agent_code(self):
"""传入 default_agent_code 时,tool_use/tool_result 使用该 code。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-default-agent-code"
mem = SessionMemory(sid, store)
# 模拟一个 Msg 对象
fake_msg = MagicMock()
fake_msg.content = [
{"type": "tool_use", "name": "read_file", "input": {"file_path": "test.txt"}},
]
AgentHub._save_tool_interactions(mem, [fake_msg], default_agent_code="17")
history = store.get(sid).get("conversation_history", [])
assert len(history) == 1
assert history[0]["agent_code"] == "17"
def test_save_tool_interactions_without_default_agent_code(self):
"""不传 default_agent_code 时,使用 block 的 name 作为 agent_code。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
sid = "test-no-default-code"
mem = SessionMemory(sid, store)
fake_msg = MagicMock()
fake_msg.content = [
{"type": "tool_use", "name": "read_file", "input": {"file_path": "test.txt"}},
]
AgentHub._save_tool_interactions(mem, [fake_msg])
history = store.get(sid).get("conversation_history", [])
assert len(history) == 1
assert history[0]["agent_code"] == "read_file"
class TestMessageShielding:
"""验证主Agent 消息屏蔽逻辑。"""
def test_call_count_zero_sends_reply(self):
"""call_count == 0 → 需正常发送和存 DB。"""
hub = _make_test_hub()
ctx = {"call_count": 0}
assert ctx["call_count"] == 0 # 走正常路径的前置条件
def test_call_count_one_shields_reply(self):
"""call_count >= 1 → 不发送、不存 DB。"""
hub = _make_test_hub()
ctx = {"call_count": 1}
assert ctx["call_count"] >= 1 # 走静默路径的前置条件
def test_call_count_multi_shields_reply(self):
"""call_count >= 2 → 同样不发送、不存 DB。"""
hub = _make_test_hub()
ctx = {"call_count": 3}
assert ctx["call_count"] >= 1 # 多子Agent 时同样静默
```
- [x] **Step 2: Run the new tests**
Run: `PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestSelfCallGuard tests/test_agent_hub.py::TestMessageShielding -v`
Expected: 6 passed
- [x] **Step 3: Commit**
```bash
git add tests/test_agent_hub.py
git commit -m "test: add self-call guard, sub-agent persistence, and shielding tests"
```
---
### Task 12: Final integration smoke test
- [x] **Step 1: Run full test suite**
Run: `PYTHONPATH=. python -m pytest tests/ -v --tb=short 2>&1 | tail -40`
Expected: All non-intent_session tests pass
- [x] **Step 2: Assess pass count**
Run: `PYTHONPATH=. python -m pytest tests/ -v --tb=short 2>&1 | grep -E "passed|failed|error"`
Expected: 0 failed, 0 error
- [x] **Step 3: Commit if clean**
```bash
git add -A
git commit -m "test: final integration smoke test pass"
```
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!