Session 持久化实施计划
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: 将 session 对话历史持久化到 DB,每次请求结束时 upsert,下次请求时自动恢复,让 agent 不"失忆"。
Architecture: DB 为唯一持久源,内存 KV 作为请求处理期间的缓存(TTL 30min,读取时续期)。单表 ai_sessions 存储 session 元数据和 conversation_history JSON blob。同时移除 current_agent_code 粘性路由,始终路由到 main agent。
Tech Stack: Python 3.12+ / FastAPI / SQLAlchemy 2.0 / SQLite / pytest
Design Doc: ai-workflow/Vibe coding for SQ/docs/superpowers/specs/2026-05-26-session-persistence-design.md
文件结构总览
| 文件 | 操作 | Task |
|---|---|---|
app/model/session.py |
新建 | 1 |
app/main.py |
修改 — 添加 Session 模型注册 + DB 注入 | 1, 5 |
app/infrastructure/session_store.py |
修改 — get() 读取时续期 |
2 |
app/service/active_session_service.py |
修改 — 移除 user_id/current_agent_code,添加 DB 持久化 | 3 |
app/service/agent_hub.py |
修改 — 路由简化 + save_to_db 调用 | 5 |
tests/test_session_persistence.py |
新建 | 2, 4 |
tests/test_agent_hub.py |
修改 — 更新路由测试 | 5 |
Task 1: Session ORM 模型
Files:
- Create:
app/model/session.py Modify:
app/main.py:19(add import)Step 1: 创建
app/model/session.py
from sqlalchemy import Column, String, Text, DateTime
from sqlalchemy.sql import func
from app.infrastructure.database import Base
class Session(Base):
__tablename__ = "ai_sessions"
session_id = Column(String, primary_key=True, index=True)
room_id = Column(String, nullable=False, default="")
channel = Column(String, nullable=False, default="wechat_group")
conversation_history = Column(Text, nullable=False, default="[]")
created_at = Column(DateTime, server_default=func.now(), nullable=False)
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now(), nullable=False)
-
Step 2: 在
app/main.py注册模型
在现有模型导入区域(约第 19 行后)添加:
from app.model.session import Session # noqa: F401
完整导入区域变为:
from app.model.agent import Agent, AgentPosition, AgentSkill # noqa: F401
from app.model.position_tag import PositionTag, OfficialTab # noqa: F401
from app.model.skill import Skill # noqa: F401
from app.model.session import Session # noqa: F401
- Step 3: 验证表创建
Run:
PYTHONPATH=. python -c "
from app.infrastructure.database import Base, engine
from app.model.session import Session
Base.metadata.create_all(bind=engine)
print('ai_sessions table:', 'ai_sessions' in Base.metadata.tables)
print('Columns:', [c.name for c in Session.__table__.columns])
"
Expected: ai_sessions table: True + 6 columns listed.
- Step 4: 运行现有测试确认无回归
Run:
PYTHONPATH=. python -m pytest tests/test_agent_hub.py tests/test_memory.py -v --tb=short
Expected: 所有现有测试通过。
- Step 5: Commit
git add app/model/session.py app/main.py
git commit -m "feat(session): add Session ORM model for persistence"
Task 2: SessionStore 读取时续期
Files:
Modify:
app/infrastructure/session_store.py:36-37Step 1: 创建 TTL 续期测试
创建 tests/test_session_persistence.py,先只写 TTL 测试:
"""Session 持久化测试"""
import json
import time
import pytest
from app.infrastructure.session_store import (
SessionStore, SESSION_TTL_SECONDS, active_session_key,
)
from app.infrastructure.kv_store import InMemoryKeyValueStore
from app.service.active_session_service import ActiveSessionService, ActiveSessionInfo
class TestSessionStoreTTLRefresh:
def test_get_refreshes_ttl(self):
"""读取 session 时 TTL 自动续期"""
kv = InMemoryKeyValueStore()
store = SessionStore(kv=kv)
store.set("test_ttl", {"session_id": "test_ttl"})
key = active_session_key("test_ttl")
original_expires = kv._store[key].expires_at
time.sleep(0.1)
result = store.get("test_ttl")
assert result is not None
new_expires = kv._store[key].expires_at
assert new_expires > original_expires, "TTL should be refreshed on read"
def test_expired_session_returns_none(self):
"""过期的 session 返回 None"""
kv = InMemoryKeyValueStore()
store = SessionStore(kv=kv)
store.set("expired_sess", {"session_id": "expired_sess"})
# 手动将 expires_at 设为过去时间
key = active_session_key("expired_sess")
kv._store[key].expires_at = time.time() - 1
assert store.get("expired_sess") is None
- Step 2: 运行测试确认 TTL 续期测试失败
Run:
PYTHONPATH=. python -m pytest tests/test_session_persistence.py::TestSessionStoreTTLRefresh::test_get_refreshes_ttl -v
Expected: FAIL — 当前 get() 不调用 refresh_ttl()。
-
Step 3: 修改
SessionStore.get()添加读取时续期
修改 app/infrastructure/session_store.py 第 36-37 行:
def get(self, session_id: str) -> Optional[dict[str, Any]]:
data = self._kv.get_json(active_session_key(session_id))
if data is not None:
self._kv.refresh_ttl(active_session_key(session_id), expire_seconds=SESSION_TTL_SECONDS)
return data
- Step 4: 运行测试确认通过
Run:
PYTHONPATH=. python -m pytest tests/test_session_persistence.py::TestSessionStoreTTLRefresh -v
Expected: PASS
- Step 5: Commit
git add app/infrastructure/session_store.py tests/test_session_persistence.py
git commit -m "fix(session): refresh TTL on SessionStore read to keep active sessions alive"
Task 3: ActiveSessionService 简化 — 移除路由状态
Files:
Modify:
app/service/active_session_service.py(全文重写)Step 1: 更新 ActiveSessionInfo 和 ActiveSessionService 测试
在 tests/test_session_persistence.py 添加:
class TestActiveSessionServiceSimplified:
def test_active_session_info_has_no_user_id(self):
"""ActiveSessionInfo 不再包含 user_id"""
info = ActiveSessionInfo(
id="s1", session_id="s1",
channel="wechat_group", room_id="r1",
)
assert not hasattr(info, "user_id")
assert not hasattr(info, "current_agent_code")
def test_get_or_create_session_no_user_id(self):
"""get_or_create_session 不再接受 user_id 参数"""
svc = ActiveSessionService()
session = svc.get_or_create_session(
session_id="sess_no_uid",
room_id="room_001",
)
assert session.session_id == "sess_no_uid"
assert session.room_id == "room_001"
assert session.channel == "wechat_group"
def test_no_update_current_agent_method(self):
"""update_current_agent 方法已移除"""
svc = ActiveSessionService()
assert not hasattr(svc, "update_current_agent")
def test_payload_no_user_id_or_agent_code(self):
"""KV payload 不包含 user_id 和 current_agent_code"""
svc = ActiveSessionService()
svc.get_or_create_session(session_id="sess_payload", room_id="r1")
data = svc.store.get("sess_payload")
assert "user_id" not in data
assert "current_agent_code" not in data
assert "session_id" in data
assert "conversation_history" in data
assert "channel" in data
assert "room_id" in data
- Step 2: 运行测试确认失败
Run:
PYTHONPATH=. python -m pytest tests/test_session_persistence.py::TestActiveSessionServiceSimplified -v
Expected: FAIL — ActiveSessionInfo 仍有 user_id 和 current_agent_code。
-
Step 3: 重写
app/service/active_session_service.py
完整文件内容:
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
from app.infrastructure.session_store import SessionStore
def _utcnow_iso() -> str:
return datetime.now(timezone.utc).isoformat()
@dataclass(frozen=True)
class ActiveSessionInfo:
id: str
session_id: str
channel: str
room_id: str
status: str = "active"
class ActiveSessionService:
def __init__(self, store: Optional[SessionStore] = None, db=None) -> None:
self.store = store or SessionStore()
self._db = db
def get_or_create_session(
self,
session_id: str,
room_id: str = "",
channel: str = "wechat_group",
) -> ActiveSessionInfo:
# 1. 先查内存(热路径)
existing = self.store.get(session_id)
if existing:
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=existing.get("channel", channel),
room_id=existing.get("room_id", room_id),
)
# 2. 查 DB(冷恢复)
if self._db:
from app.model.session import Session
db_sess = self._db.query(Session).filter(
Session.session_id == session_id
).first()
if db_sess:
import json
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,
)
# 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(),
}
self.store.set(session_id, payload)
return ActiveSessionInfo(
id=session_id,
session_id=session_id,
channel=channel,
room_id=room_id,
)
def save_to_db(self, session_id: str) -> None:
"""将内存中的 session 持久化到 DB。"""
if not self._db:
return
data = self.store.get(session_id)
if not data:
return
import json
from app.model.session import Session
existing = self._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
),
)
self._db.add(db_sess)
self._db.commit()
- Step 4: 运行测试确认通过
Run:
PYTHONPATH=. python -m pytest tests/test_session_persistence.py -v
Expected: 所有测试通过(TTL + Simplified 两组)。
- Step 5: 确认 test_agent_hub.py 的预期失败
Run:
PYTHONPATH=. python -m pytest tests/test_agent_hub.py -v --tb=short
Expected: 所有测试失败,因为 process_message() 仍传 user_id=user_id 给 get_or_create_session(),而新签名已移除该参数,触发 TypeError。这是预期的——Task 5 Step 1 会修复调用方。路由测试的断言也需要更新(Task 5 Step 6)。
- Step 6: Commit
git add app/service/active_session_service.py tests/test_session_persistence.py
git commit -m "refactor(session): remove user_id and current_agent_code, add db param and save_to_db"
Task 4: DB 持久化完整测试
Files:
Modify:
tests/test_session_persistence.py(添加 DB 测试)Step 1: 添加 DB 持久化测试
在 tests/test_session_persistence.py 末尾添加:
from tests.conftest import TestingSessionLocal
from app.infrastructure.database import Base, engine
class TestDatabasePersistence:
@pytest.fixture(autouse=True)
def setup_db(self):
"""确保 ai_sessions 表存在"""
Base.metadata.create_all(bind=engine)
@pytest.fixture
def db(self):
db = TestingSessionLocal()
yield db
db.close()
@pytest.fixture
def svc(self, db):
return ActiveSessionService(db=db)
def test_save_to_db_creates_record(self, svc, db):
"""新 session save_to_db 后 DB 有记录"""
from app.model.session import Session as DbSession
svc.get_or_create_session("db_new", room_id="room_001")
svc.save_to_db("db_new")
db_record = db.query(DbSession).filter(
DbSession.session_id == "db_new"
).first()
assert db_record is not None
assert db_record.room_id == "room_001"
assert db_record.channel == "wechat_group"
def test_save_to_db_upsert(self, svc, db):
"""第二次 save_to_db 更新而非重复创建"""
from app.model.session import Session as DbSession
svc.get_or_create_session("db_upsert", room_id="room_001")
svc.save_to_db("db_upsert")
# 修改内存中的 room_id
data = svc.store.get("db_upsert")
data["room_id"] = "room_002"
svc.store.set("db_upsert", data)
svc.save_to_db("db_upsert")
count = db.query(DbSession).filter(
DbSession.session_id == "db_upsert"
).count()
assert count == 1
record = db.query(DbSession).filter(
DbSession.session_id == "db_upsert"
).first()
assert record.room_id == "room_002"
def test_db_fallback_restores_session(self, svc, db):
"""内存不存在但 DB 存在 → 从 DB 恢复"""
svc.get_or_create_session("db_restore", room_id="room_001")
svc.save_to_db("db_restore")
# 清除内存
svc.store.delete("db_restore")
assert svc.store.get("db_restore") is None
# 再次获取 → 从 DB 恢复
session = svc.get_or_create_session("db_restore")
assert session.session_id == "db_restore"
assert session.room_id == "room_001"
def test_restore_preserves_conversation_history(self, svc, db):
"""恢复后 conversation_history 完整保留"""
from app.service.memory import SessionMemory
svc.get_or_create_session("db_hist", room_id="room_001")
memory = SessionMemory(
session_id="db_hist", store=svc.store, max_rounds=20
)
memory.add("user", "你好", agent_code="main")
memory.add("assistant", "你好!有什么可以帮你的?", agent_code="main")
svc.save_to_db("db_hist")
# 清除内存
svc.store.delete("db_hist")
# 恢复
svc.get_or_create_session("db_hist")
restored_memory = SessionMemory(
session_id="db_hist", store=svc.store, max_rounds=20
)
messages = restored_memory.get_messages()
assert len(messages) == 2
assert messages[0]["role"] == "user"
assert messages[0]["content"] == "你好"
assert messages[1]["role"] == "assistant"
def test_save_to_db_no_db_silent_skip(self):
"""无 DB 连接时 save_to_db 静默跳过"""
svc = ActiveSessionService() # db=None
svc.get_or_create_session("no_db", room_id="room_001")
svc.save_to_db("no_db") # 不应抛异常
- Step 2: 运行 DB 测试
Run:
PYTHONPATH=. python -m pytest tests/test_session_persistence.py::TestDatabasePersistence -v --tb=short
Expected: 全部通过(save_to_db 和 DB fallback 在 Task 3 Step 3 已实现)。
- Step 3: 运行全部持久化测试
Run:
PYTHONPATH=. python -m pytest tests/test_session_persistence.py -v
Expected: 所有测试通过(TTL + Simplified + DB 三组)。
- Step 4: Commit
git add tests/test_session_persistence.py
git commit -m "test(session): add database persistence and recovery tests"
Task 5: AgentHub 路由简化 + 持久化集成
Files:
- Modify:
app/service/agent_hub.py—process_message()方法 - Modify:
app/main.py— lifespan 传入 DB session Modify:
tests/test_agent_hub.py— 路由测试更新Step 1: 修改
process_message()— 路由简化
在 app/service/agent_hub.py 的 process_message() 方法中,找到以下代码块(约第 230-260 行):
session = self.session_service.get_or_create_session(
session_id=session_id,
room_id=room_id,
user_id=user_id,
channel=channel
)
替换为(移除 user_id 参数):
session = self.session_service.get_or_create_session(
session_id=session_id,
room_id=room_id,
channel=channel
)
- Step 2: 修改路由决策逻辑
找到路由决策块(约第 244-270 行):
# Determine target agent and routing reason
position_restricted = allowed_agent_codes is not None
if mentioned_agent_code and mentioned_agent_code in self.agents:
if position_restricted and mentioned_agent_code not in allowed_agent_codes:
target_agent = "main"
routing_reason = "position_restricted"
else:
target_agent = mentioned_agent_code
routing_reason = "mention"
elif session.current_agent_code and session.current_agent_code in self.agents:
if position_restricted and session.current_agent_code not in allowed_agent_codes:
target_agent = "main"
routing_reason = "position_restricted"
else:
target_agent = session.current_agent_code
routing_reason = "inheritance"
else:
target_agent = "main"
routing_reason = "default"
替换为:
# 始终路由到 main agent
target_agent = "main"
routing_reason = "default"
- Step 3: 修改消息存储和末尾持久化
找到消息存储和路由更新块(约第 290-300 行):
# Store messages via SessionMemory
memory.add("user", user_query, agent_code=mentioned_agent_code or "main")
memory.add("assistant", response_content, agent_code=target_agent)
if target_agent != "main":
self.session_service.update_current_agent(session.id, target_agent)
替换为:
# Store messages via SessionMemory
memory.add("user", user_query, agent_code="main")
memory.add("assistant", response_content, agent_code=target_agent)
# 持久化到 DB
self.session_service.save_to_db(session_id)
-
Step 4: 修改
app/main.py— lifespan 传入 DB session
在 app/main.py 做以下 3 处修改:
4a. 在导入区(第 10 行后)添加 SessionLocal 导入:
from app.infrastructure.database import engine, SessionLocal
(原来是 from app.infrastructure.database import engine,加上 SessionLocal)
4b. 在 lifespan() 函数中,将第 43 行:
session_service = ActiveSessionService()
替换为:
db = SessionLocal()
session_service = ActiveSessionService(db=db)
4c. 在 yield 后的清理区域(第 67-68 行),将:
if agent_hub_instance:
await agent_hub_instance.close()
替换为:
if agent_hub_instance:
await agent_hub_instance.close()
db.close()
- Step 5: 运行 test_agent_hub.py 查看剩余失败
Run:
PYTHONPATH=. python -m pytest tests/test_agent_hub.py -v --tb=short
Expected: 非路由测试全部通过。路由测试中,test_default_routing_to_main 通过,其他路由测试需更新。
- Step 6: 更新路由测试
修改 tests/test_agent_hub.py 中以下测试:
5a. test_mention_routing_to_sub_agent (约第 494 行) — 始终路由 main:
@pytest.mark.asyncio
async def test_mention_routing_always_main(self):
"""即使传入 mentioned_agent_code,也始终路由到 main"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("已为你整理会议纪要")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_route_002",
room_id="room_001",
user_id="user_001",
user_query="整理会议纪要",
mentioned_agent_code="meeting",
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
5b. test_inheritance_routing (约第 510 行) — 替换为验证无粘性路由:
@pytest.mark.asyncio
async def test_no_sticky_routing(self):
"""不再粘性继承 agent,每次始终路由 main"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("会议纪要内容")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
sid = "sess_route_003"
r1 = await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query="查会议纪要",
mentioned_agent_code="meeting",
)
assert r1["response_agent_code"] == "main"
r2 = await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query="再查一个",
)
assert r2["response_agent_code"] == "main"
assert r2["routing_reason"] == "default"
5c. test_allowed_agent_codes_restricts_routing (约第 582 行) — 始终 main + default:
@pytest.mark.asyncio
async def test_allowed_agent_codes_still_routes_main(self):
"""allowed_agent_codes 不影响路由(始终 main),仅影响 prompt 中 advertised 的子 agent"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_restricted",
room_id="room_001",
user_id="user_001",
user_query="整理会议纪要",
mentioned_agent_code="meeting",
allowed_agent_codes=[],
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
- Step 7: 运行全量测试
Run:
PYTHONPATH=. python -m pytest tests/test_agent_hub.py tests/test_memory.py tests/test_session_persistence.py -v --tb=short
Expected: 全部通过。
- Step 8: Commit
git add app/service/agent_hub.py app/main.py tests/test_agent_hub.py
git commit -m "refactor(session): simplify routing to always main, integrate save_to_db"
全量回归验证
完成所有 Task 后,运行完整测试套件:
PYTHONPATH=. python -m pytest tests/ -v --tb=short
预期结果:
-
test_session_persistence.py— 全部通过(TTL + Simplified + DB) -
test_agent_hub.py— 全部通过(路由测试已更新) -
test_memory.py— 全部通过(Memory 未改动) -
test_routing_api.py— 与本次无关(RoutingService 独立模块),保持原样 - 其他测试 — 不受影响
手动验证(可选):
# 1. 启动服务
PYTHONPATH=. python -m app.main
# 2. 发送请求
curl -X POST http://localhost:8000/api/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"group": {"group_contact_id": "test_persist_001", "group_name": "测试群"},
"position": {"position_id": 1, "position_code": "test", "position_name": "测试"},
"agents": [{"agent_id": 14, "agent_name": "会议纪要 Agent"}],
"messages": [{"msg_id": "m1", "msg_time": "2026-05-26T10:00:00Z", "sender_id": "u1", "sender_name": "测试", "msg_type": "text", "msg_content": "你好"}]
}'
# 3. 检查 DB 有记录
sqlite3 dev.db "SELECT session_id, room_id, length(conversation_history) FROM ai_sessions;"
# 4. 重启进程后再次请求同一 session_id,验证历史恢复