docs: refresh runtime guidance

This commit is contained in:
2026-04-03 13:48:49 +08:00
parent a399384e07
commit 771de8c49c
5 changed files with 34 additions and 501 deletions

View File

@@ -1,239 +0,0 @@
# 关键代码修复方案
## 1. EvoAgent 长期记忆支持 ✅
**状态**: EvoAgent 已支持 `long_term_memory` 参数,但需要移除 Legacy 回退逻辑
**需要修改的文件**:
- `backend/main.py` 第 158-176 行 - 移除记忆启用时的 Legacy 回退
- `backend/core/pipeline.py` - 同样更新
- `backend/core/pipeline_runner.py` - 同样更新
**修复代码** (main.py):
```python
def _create_analyst_agent(...):
# ... 工具包创建代码 ...
use_evo_agent = analyst_type in _resolve_evo_agent_ids()
if use_evo_agent:
workspace_dir = skills_manager.get_agent_asset_dir(config_name, analyst_type)
agent_config = load_agent_workspace_config(workspace_dir / "agent.yaml")
agent = EvoAgent(
agent_id=analyst_type,
config_name=config_name,
workspace_dir=workspace_dir,
model=model,
formatter=formatter,
skills_manager=skills_manager,
prompt_files=agent_config.prompt_files,
long_term_memory=long_term_memory, # 已支持
long_term_memory_mode="static_control",
)
agent.toolkit = toolkit
setattr(agent, "workspace_id", config_name)
return agent
# Legacy fallback (deprecated)
return AnalystAgent(...)
```
## 2. Workspace ID 语义清理
**问题**: `workspace_id` 同时用于 design-time 和 runtime 两个不同概念
**修复方案**:
```python
# backend/api/workspaces.py
# 明确区分两种资源
# Design-time workspaces (CRUD)
@router.get("/design-workspaces/{workspace_id}/...")
async def get_design_workspace(workspace_id: str): ...
# Runtime runs (只读)
@router.get("/runs/{run_id}/agents/{agent_id}/...")
async def get_runtime_agent(run_id: str, agent_id: str): ...
```
## 3. ToolGuard 与 Gateway 审批同步 ✅ 已完成
**状态**: 审批同步已完善,添加了批量审批支持
**API 端点**:
- `POST /api/guard/check` - 检查工具调用是否需要审批
- `POST /api/guard/approve` - 批准单个工具调用
- `POST /api/guard/approve/batch` - ✅ 批量批准多个工具调用(新增)
- `POST /api/guard/deny` - 拒绝工具调用
- `GET /api/guard/pending` - 获取待审批列表
**批量审批示例**:
```python
# 批量批准
await approve_tool_calls(
BatchApprovalRequest(
approval_ids=["approval_001", "approval_002", "approval_003"],
one_time=True,
)
)
```
**超时处理**: 默认 300 秒超时,可在 `ToolGuardMixin._init_tool_guard()` 中配置
## 4. Smoke Test 依赖修复
**需要的依赖**:
```bash
pip install pandas numpy matplotlib seaborn
pip install finnhub-python yfinance
pip install loguru rich
pip install websockets
pip install httpx requests
pip install PyYAML
pip install pandas-market-calendars exchange-calendars
```
## 5. 统一 Agent 工厂 ✅ 已完成
**文件** `backend/agents/unified_factory.py`:
统一工厂已创建,支持:
- 所有 6 种 Agent 角色的创建
- 自动 EvoAgent vs Legacy Agent 选择
- Workspace 驱动配置
- 长期记忆支持
```python
from backend.agents.unified_factory import UnifiedAgentFactory, get_agent_factory
# 使用示例
factory = UnifiedAgentFactory(
config_name="smoke_fullstack",
skills_manager=skills_manager,
)
# 创建分析师
analyst = factory.create_analyst(
analyst_type="fundamentals_analyst",
model=model,
formatter=formatter,
long_term_memory=memory,
)
```
## 6. EvoAgent 默认启用
**修改** `backend/config/constants.py`:
```python
# 默认所有角色使用 EvoAgent
DEFAULT_EVO_AGENT_ROLES = {
"fundamentals_analyst",
"technical_analyst",
"sentiment_analyst",
"valuation_analyst",
"risk_manager",
"portfolio_manager",
}
# EVO_AGENT_IDS 现在用于选择性地禁用 EvoAgent
# 如果设置,只启用指定的角色
# 如果未设置,启用所有角色
```
**修改** `backend/main.py`:
```python
def _resolve_evo_agent_ids() -> set[str]:
"""Return agent ids selected to use EvoAgent.
By default, all supported roles use EvoAgent.
EVO_AGENT_IDS can be used to limit to specific roles.
"""
from backend.config.constants import DEFAULT_EVO_AGENT_ROLES
raw = os.getenv("EVO_AGENT_IDS", "")
if raw.strip():
# Filter to only valid roles
requested = {x.strip() for x in raw.split(",") if x.strip()}
return requested & DEFAULT_EVO_AGENT_ROLES
# Default: all roles use EvoAgent
return DEFAULT_EVO_AGENT_ROLES
```
## 7. 遗留代码清理
**可以删除的文件**:
- `backend/agents/compat.py` ✅ 已删除
- `frontend/src/hooks/useWebsocketSessionSync.js` ✅ 已删除
**标记为废弃的文件** ✅ 已完成:
- `backend/agents/analyst.py` - 已添加 DeprecationWarning
- `backend/agents/risk_manager.py` - 已添加 DeprecationWarning
- `backend/agents/portfolio_manager.py` - 已添加 DeprecationWarning
## 8. 测试修复
**更新** `backend/tests/test_evo_agent_selection.py`:
移除这些测试 ✅ 已完成:
- `test_main_create_analyst_agent_falls_back_to_legacy_when_memory_enabled`
- `test_main_create_risk_manager_falls_back_to_legacy_when_memory_enabled`
- `test_main_create_portfolio_manager_falls_back_to_legacy_when_memory_enabled`
添加新测试 ✅ 已完成:
- `test_evo_agent_supports_long_term_memory`
- `test_all_roles_use_evo_agent_by_default`
新增集成测试文件 ✅ 已完成:
- `backend/tests/test_evo_agent_integration.py` - 13 个集成测试覆盖 Factory、ToolGuard、Workspace 集成
## 9. 快速修复清单
运行以下命令应用关键修复:
```bash
# 1. 修复 EvoAgent 记忆支持 (修改 main.py, pipeline.py, pipeline_runner.py)
# 移除 long_term_memory 检查导致的 Legacy 回退
# 2. 修复默认 EvoAgent 启用
sed -i 's/def _resolve_evo_agent_ids():/def _resolve_evo_agent_ids() -> set[str]:/' backend/main.py
# 3. 确保所有测试通过
pytest backend/tests/test_evo_agent_selection.py -v
# 4. 运行 smoke test
python3 scripts/smoke_evo_runtime.py --test-all-roles
```
## 10. 实施进度
### ✅ 已完成
| 任务 | 状态 | 文件 |
|------|------|------|
| EvoAgent 长期记忆支持 | ✅ 已完成 | `evo_agent.py`, `main.py` |
| 默认启用所有角色 EvoAgent | ✅ 已完成 | `main.py`, `pipeline.py` |
| 统一 Agent 工厂 | ✅ 已完成 | `unified_factory.py` |
| ToolGuard Gateway 同步 | ✅ 已完成 | `tool_guard.py`, `guard.py` |
| ToolGuard 批量审批 | ✅ 已完成 | `guard.py` |
| 废弃标记 Legacy Agent | ✅ 已完成 | `analyst.py`, `risk_manager.py`, `portfolio_manager.py` |
| 集成测试 | ✅ 已完成 | `test_evo_agent_integration.py` |
| 类型注解 | ✅ 已完成 | `unified_factory.py` |
| Team 基础设施 | ✅ 已完成 | `messenger.py`, `task_delegator.py` |
| Skills 沙盒执行 | ✅ 已完成 | `sandboxed_executor.py` |
### 🚧 待完成
| 优先级 | 任务 | 说明 |
|--------|------|------|
| P0 | Smoke Test 依赖修复 | 需要安装 pandas, finnhub, pandas-market-calendars 等 |
| P1 | Workspace ID 语义清理 | ✅ 已添加 `run_id`,保留 `workspace_id` 用于向后兼容 |
| P2 | 文档完善 | ✅ 已完成 |
*最后更新: 2026-04-02*
---
*文档生成时间: 2026-04-01*

View File

@@ -1,249 +0,0 @@
# 大时代项目优化和功能补齐计划
## 当前状态评估
### 已完成的工作
1. ✅ EvoAgent 核心实现 (`backend/agents/base/evo_agent.py`)
2. ✅ ToolGuardMixin 工具守卫 (`backend/agents/base/tool_guard.py`)
3. ✅ Hooks 系统 (`backend/agents/base/hooks.py`)
4. ✅ Smoke test 脚本 (`scripts/smoke_evo_runtime.py`)
5. ✅ 选择性 EvoAgent 测试 (`backend/tests/test_evo_agent_selection.py`)
6. ✅ 删除 `backend/agents/compat.py` 兼容性层
7. ✅ 删除 `useWebsocketSessionSync.js` 旧钩子
### 遗留问题清单
#### 🔴 P0: 阻塞 EvoAgent 全面推出
| # | 问题 | 位置 | 影响 | 解决方案 |
|---|------|------|------|----------|
| P0-1 | EvoAgent 不支持长期记忆 | `evo_agent.py:165-166` | 启用 memory 时回退到 Legacy Agent | 集成 ReMe 记忆系统 |
| P0-2 | Pipeline 运行时分析师创建路径不一致 | `pipeline.py` | 运行时动态创建可能跳过 EvoAgent 路径 | 统一 `_create_runtime_analyst` 逻辑 |
| P0-3 | Workspace 加载路径混乱 | `workspace.py`, `workspace_manager.py` | `workspace_id` vs `run_id` 语义混合 | 明确区分 design-time 和 runtime 路径 |
| P0-4 | Smoke test 失败排查 | `scripts/smoke_evo_runtime.py` | 无法验证 EvoAgent 是否正确启动 | 修复测试并确保通过 |
#### 🟡 P1: 功能完善
| # | 问题 | 位置 | 影响 | 解决方案 |
|---|------|------|------|----------|
| P1-1 | Team 基础设施未完成 | `evo_agent.py:41-48` | Agent 间通信和任务委托不可用 | 完成 messenger 和 task_delegator |
| P1-2 | ToolGuard 与 Gateway 审批流程集成 | `tool_guard.py`, `api/guard.py` | 审批状态同步可能不一致 | 统一审批存储和事件通知 |
| P1-3 | Skills 沙盒执行 | `tools/sandboxed_executor.py` | 生产环境需要 Docker 隔离 | 完善沙盒执行器 |
| P1-4 | 错误处理和重试机制 | 多处 | 部分错误未正确处理 | 添加统一的错误处理 |
#### 🟢 P2: 代码质量和可维护性
| # | 问题 | 位置 | 影响 | 解决方案 |
|---|------|------|------|----------|
| P2-1 | 重复的 Agent 创建逻辑 | `main.py`, `pipeline.py`, `pipeline_runner.py` | 维护困难,容易遗漏 | 提取统一的 Agent 工厂 |
| P2-2 | 类型注解不完整 | 多处 | IDE 提示不足 | 完善类型注解 |
| P2-3 | 缺少 EvoAgent 集成测试 | `backend/tests/` | 无法确保功能完整 | 添加集成测试 |
| P2-4 | 文档和注释 | 多处 | 新贡献者理解困难 | 完善文档 |
---
## 详细实施方案
### Phase 1: P0 阻塞问题修复
#### P0-1: EvoAgent 长期记忆支持
**问题描述**:
```python
# main.py 中当前逻辑
if long_term_memory and agent_id not in EVO_AGENT_IDS:
# 使用 Legacy Agent
else:
# 使用 EvoAgent
```
**目标**: EvoAgent 支持 ReMe 长期记忆系统
**实施步骤**:
1.`EvoAgent.__init__` 中正确接收 `long_term_memory` 参数
2. 集成 ReMe 记忆系统的读写
3. 在 Hooks 中添加记忆相关的生命周期管理
4. 修改 `main.py`, `pipeline.py` 中移除 EvoAgent 的记忆回退逻辑
**文件修改**:
- `backend/agents/base/evo_agent.py`
- `backend/main.py`
- `backend/core/pipeline.py`
#### P0-2: Pipeline 运行时分析师创建统一
**问题描述**:
`TradingPipeline._create_runtime_analyst` 方法需要确保:
1. 检查 `EVO_AGENT_IDS` 环境变量
2. 正确传递所有必要参数给 EvoAgent
3. 处理 workspace 资产准备
**实施步骤**:
1. 统一 `pipeline.py``main.py` 中的 Agent 创建逻辑
2. 确保 EvoAgent 路径和 Legacy 路径参数一致
3. 添加运行时动态 Agent 创建的测试
**文件修改**:
- `backend/core/pipeline.py`
- `backend/main.py`
#### P0-3: Workspace 路径清理
**问题描述**:
- `workspace_id` 有时指 `workspaces/` 目录下的设计时 workspace
- 有时指 `runs/<run_id>/` 下的运行时 workspace
**解决方案**:
1. 明确命名:`design_workspace_id` vs `run_id`
2. 在 API 路由中区分两种资源
3. 内部统一使用 `run_id` 作为运行时标识
**文件修改**:
- `backend/api/workspaces.py`
- `backend/api/agents.py`
- `backend/agents/workspace_manager.py`
#### P0-4: Smoke Test 修复
**当前测试**:
```bash
python3 scripts/smoke_evo_runtime.py --agent-id fundamentals_analyst
```
**验证点**:
1. Gateway 正常启动
2. EvoAgent 日志出现
3. `runtime_state.json` 正确写入
4. 审批流程正常工作
**实施步骤**:
1. 运行测试并识别失败点
2. 修复 EvoAgent 初始化问题
3. 确保所有 6 个角色都能通过测试
---
### Phase 2: P1 功能完善
#### P1-1: Team 基础设施
**当前状态**:
```python
try:
from backend.agents.team.messenger import AgentMessenger
from backend.agents.team.task_delegator import TaskDelegator
TEAM_INFRA_AVAILABLE = True
except ImportError:
TEAM_INFRA_AVAILABLE = False
```
**目标**: 完成 Agent 间通信和任务委托
**实施步骤**:
1. 完成 `AgentMessenger` 实现
2. 完成 `TaskDelegator` 实现
3. 添加 Agent 团队协调的测试
#### P1-2: ToolGuard 与 Gateway 集成
**当前状态**:
- `ToolGuardStore` 是内存存储
- Gateway 通过 `get_global_runtime_manager()` 访问
**改进**:
1. 确保审批状态在 Gateway 和 Agent 间同步
2. 添加审批超时处理
3. 支持批量审批
#### P1-3: Skills 沙盒执行
**当前状态**:
```python
SKILL_SANDBOX_MODE=none # 开发模式,直接执行
```
**目标**: 生产环境使用 Docker 隔离
**实施步骤**:
1. 完成 `DockerSandboxBackend`
2. 添加资源限制CPU、内存、网络
3. 添加执行超时控制
---
### Phase 3: P2 代码质量
#### P2-1: 统一 Agent 工厂
**目标**: 提取 `AgentFactory` 统一处理所有 Agent 创建
**设计**:
```python
class AgentFactory:
def create_analyst(self, analyst_type: str, **kwargs) -> BaseAgent
def create_risk_manager(self, **kwargs) -> BaseAgent
def create_portfolio_manager(self, **kwargs) -> BaseAgent
```
#### P2-2: 类型注解
**目标**: 所有公共 API 完整的类型注解
#### P2-3: 集成测试
**目标**: EvoAgent 完整的端到端测试
---
## 实施顺序
### Week 1: P0 阻塞问题
1. [ ] P0-4: 运行 Smoke Test识别失败点
2. [ ] P0-1: EvoAgent 长期记忆支持
3. [ ] P0-2: Pipeline 运行时统一
4. [ ] P0-3: Workspace 路径清理
5. [ ] 验证所有 Smoke Test 通过
### Week 2: P1 功能完善
1. [ ] P1-1: Team 基础设施
2. [ ] P1-2: ToolGuard 集成优化
3. [ ] P1-3: Skills 沙盒执行
### Week 3: P2 代码质量
1. [ ] P2-1: 统一 Agent 工厂
2. [ ] P2-2: 类型注解
3. [ ] P2-3: 集成测试
4. [ ] P2-4: 文档完善
---
## 成功标准
### EvoAgent 全面推出标准
1. ✅ 所有 6 个角色通过 smoke test
2. ✅ 长期记忆功能正常工作
3. ✅ 无需 `EVO_AGENT_IDS` 环境变量即可使用 EvoAgent
4. ✅ Legacy Agent 代码标记为 deprecated
5. ✅ 集成测试覆盖主要使用场景
### 架构清理标准
1.`runs/<run_id>/` 是唯一的运行时数据来源
2.`workspaces/` 仅用于设计时注册表
3. ✅ 所有服务边界清晰,无循环依赖
4. ✅ 文档和代码一致
---
## 风险和对策
| 风险 | 可能性 | 影响 | 对策 |
|------|--------|------|------|
| EvoAgent 与 Legacy 行为不一致 | 中 | 高 | 并行运行对比测试 |
| 长期记忆集成复杂 | 中 | 中 | 分阶段实现,先支持基础功能 |
| 性能下降 | 低 | 高 | 基准测试,性能剖析 |
| 迁移期间系统不稳定 | 中 | 高 | 保持 Legacy 作为回退 |
---
*计划创建日期: 2026-04-01*
*负责: Claude Code*

View File

@@ -1,8 +1,26 @@
# Runtime Service API 变更文档
# Runtime Service API 说明
## 概述
本文档描述 `runtime_service` API 的改进,包括新增端点、增强响应字段和改进的错误处理
本文档描述当前 `runtime_service` API 的关键端点、增强响应字段和启动/健康检查相关行为
它应被视为 runtime API 的补充说明,而不是迁移过程中的一次性变更记录。
## 适用范围
- 运行时控制面:`backend.apps.runtime_service`
- 运行时 API 前缀:`/api/runtime/*`
- 当前推荐配套阅读:
- `README.md`
- `README_zh.md`
- `docs/current-architecture.md`
## 关于 `schedule_mode` 的当前约定
当前对外约定统一使用 `daily` / `interval`
- `interval` 是当前公开的盘中轮询名称
- `intraday` 仅作为向后兼容输入别名保留
- runtime API 的响应和写回配置应优先输出 `interval`
## 新增端点
@@ -26,7 +44,8 @@
- `mode`: 运行模式,`"live"`(实盘)或 `"backtest"`(回测),运行时停止时为 `"stopped"`
- `is_backtest`: 是否为回测模式
- `run_id`: 当前运行的任务 ID
- `schedule_mode`: 调度模式`"daily"``"intraday"`
- `schedule_mode`: 调度模式字段。当前公开值为 `daily``interval`
历史输入别名 `intraday` 会在服务端归一化为 `interval`
- `is_running`: Gateway 是否正在运行
---
@@ -113,7 +132,7 @@
---
## 改进的端点
## 关键端点说明
### GET /api/runtime/gateway/status
@@ -256,7 +275,8 @@ Gateway 启动前会自动验证以下配置:
- `start_date` 必须早于 `end_date`
6. **调度模式**
- `schedule_mode` 必须是 `"daily"` `"intraday"`
- 当前公开校验值为 `"daily"` / `"interval"`
- 历史输入 `"intraday"` 会被兼容性归一化为 `"interval"`
**验证失败响应**:

View File

@@ -51,19 +51,18 @@ Examples:
## Compatibility Rule
Some API paths and fields still use legacy names:
Some fields still use legacy names:
- `/api/workspaces/{workspace_id}/agents/...`
- `workspace_id` on approval records
When reading those surfaces:
Current API path rule:
- design-time CRUD routes use `workspace_id` literally
- runtime-read routes may use the same slot for `run_id`
- design-time CRUD uses `/api/workspaces/{workspace_id}/...`
- runtime agent assets use `/api/runs/{run_id}/agents/...`
For new code:
- prefer `runId` for runtime variables
- prefer `runId` for runtime variables and runtime API paths
- prefer `workspaceId` only for design-time registry flows
## UI Wording