refactor: 梳理规则体系并统一记忆与部署流程

This commit is contained in:
qzl
2026-03-23 17:57:24 +08:00
parent 2a14ad1d8e
commit f4b7eb7e09
39 changed files with 2091 additions and 1454 deletions
@@ -1,231 +0,0 @@
# Memories 界面实现计划
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** 实现前端memories界面,卡片列表展示user和work记忆,支持查看详情和更新
**Architecture:**
- 使用现有ApiClient调用后端 `/api/v1/memories` 接口
- 数据模型解析UserMemoryContent和WorkProfileContent
- 遵循项目视觉设计语言(soft blue, layered card-based)
- 通过GoRouter管理导航
**Tech Stack:** Flutter, Dio, GoRouter, GetIt依赖注入
---
### Task 1: 创建Memory数据模型
**Files:**
- Create: `apps/lib/features/settings/data/models/memory_models.dart`
**Step 1: 创建数据模型文件**
```dart
// UserMemoryContent - 用户记忆
class UserMemoryContent {
final String? occupation;
final String? timezone;
final String? primaryLanguage;
final List<Person> people;
final List<Place> places;
final UserPreferences preferences;
final SchedulingPreferences schedulingPreferences;
final List<String> interests;
final List<String> avoidTopics;
final List<String> customRules;
final List<RecurringRoutine> recurringRoutines;
// ... 工厂方法 fromJson
}
class Person {
final String name;
final String? relationship;
final String? role;
final String? preferredContactChannel;
final String? notes;
final PersonMeta? meta;
}
class Place {
final String name;
final String? category;
final String? address;
final String? timezone;
final int? commuteMinutes;
final String? preference;
final String? notes;
final PlaceMeta? meta;
}
// WorkProfileContent - 工作记忆
class WorkProfileContent {
final String? occupation;
final List<String> expertise;
final List<String> preferredTools;
final List<CurrentProject> currentProjects;
final WorkHabits workHabits;
final List<TeamMember> teamMembers;
final String? teamContext;
final List<String> workRules;
}
// MemoryListResponse - API响应
class MemoryListResponse {
final UserMemoryContent? userMemory;
final WorkProfileContent? workMemory;
}
```
---
### Task 2: 更新MemoryService调用真实API
**Files:**
- Modify: `apps/lib/features/settings/data/services/memory_service.dart`
**Step 1: 重写MemoryService**
```dart
import 'package:social_app/core/api/i_api_client.dart';
import '../models/memory_models.dart';
class MemoryService {
final IApiClient _client;
static const _prefix = '/api/v1/memories';
MemoryService(this._client);
Future<MemoryListResponse> getAllMemories() async { ... }
Future<UserMemoryContent?> getUserMemory() async { ... }
Future<WorkProfileContent?> getWorkMemory() async { ... }
Future<UserMemoryContent> updateUserMemory(UserMemoryContent content) async { ... }
Future<WorkProfileContent> updateWorkMemory(WorkProfileContent content) async { ... }
Future<UserMemoryContent> patchUserMemory(Map<String, dynamic> content) async { ... }
Future<WorkProfileContent> patchWorkMemory(Map<String, dynamic> content) async { ... }
}
```
---
### Task 3: 在injection.dart中注册MemoryService
**Files:**
- Modify: `apps/lib/core/di/injection.dart:26` - 添加import
- Modify: `apps/lib/core/di/injection.dart` - 注册MemoryService
---
### Task 4: 重新设计MemoryScreen主页面
**Files:**
- Modify: `apps/lib/features/settings/ui/screens/memory_screen.dart`
**设计要点:**
- 顶部启用记忆开关卡片
- 两个主要卡片: User Memory (用户记忆) 和 Work Memory (工作记忆)
- 每个卡片显示关键摘要信息
- 点击卡片进入对应详情页
- 底部"管理记忆条目"按钮可点击展开更多信息
- 遵循soft blue品牌、layered card-based界面
**卡片内容:**
- User Memory: 显示 occupation, people数量, places数量, interests数量
- Work Memory: 显示 occupation, expertise数量, currentProjects数量, teamMembers数量
---
### Task 5: 创建UserMemoryDetailScreen
**Files:**
- Create: `apps/lib/features/settings/ui/screens/user_memory_detail_screen.dart`
**功能:**
- 显示完整的UserMemoryContent信息
- 支持编辑和更新
- 分组展示: 基本信息、联系人、地点、偏好设置、日程偏好、兴趣、回避话题等
- 使用可折叠的Section展示
---
### Task 6: 创建WorkMemoryDetailScreen
**Files:**
- Create: `apps/lib/features/settings/ui/screens/work_memory_detail_screen.dart`
**功能:**
- 显示完整的WorkProfileContent信息
- 支持编辑和更新
- 分组展示: 基本信息、项目、团队成员、工作习惯等
- 使用可折叠的Section展示
---
### Task 7: 添加路由配置
**Files:**
- Modify: `apps/lib/core/router/app_router.dart:26` - 添加import
- Modify: `apps/lib/core/router/app_router.dart` - 添加路由
- Modify: `apps/lib/core/router/app_routes.dart` - 添加路由常量
**新增路由:**
- `/settings/memory/user` - UserMemoryDetailScreen
- `/settings/memory/work` - WorkMemoryDetailScreen
---
### Task 8: 更新MemoryScreen导航
**Files:**
- Modify: `apps/lib/features/settings/ui/screens/memory_screen.dart`
**Step 1: 添加导航跳转**
```dart
// 点击User Memory卡片
context.push('/settings/memory/user');
// 点击Work Memory卡片
context.push('/settings/memory/work');
```
---
### Task 9: 验证和测试
**Step 1: 运行flutter analyze检查代码质量**
```bash
cd apps && flutter analyze
```
**Step 2: 验证设计token使用正确**
检查所有颜色、间距、圆角都来自design_tokens.dart
**Step 3: 验证API调用正确**
确认使用正确的endpoint和HTTP方法
---
### 关键文件路径参考
- Design tokens: `apps/lib/core/theme/design_tokens.dart`
- Visual design language: `apps/rules/visual_design_language.md`
- Settings scaffold: `apps/lib/features/settings/ui/widgets/settings_page_scaffold.dart`
- API client: `apps/lib/core/api/api_client.dart`
- 后端router: `backend/src/v1/memories/router.py`
- Protocol文档: `docs/protocols/models/memory.md`
---
### 视觉设计要点
1. **Surface层次**: Background → Primary cards → Secondary grouped surfaces
2. **Color**: 使用AppColors.blue系列作为品牌色,避免过度使用
3. **Spacing**: 使用AppSpacing (xs=4, sm=8, md=12, lg=16, xl=20, xxl=24)
4. **Radius**: 使用AppRadius (sm=6, md=12, lg=16, xl=18, xxl=24)
5. **Motion**: 150-300ms micro-interactions, soft press feedback
6. **卡片阴影**: 使用soft shadow如 `blurRadius: 8, offset: (0, 2)`
@@ -1,78 +0,0 @@
# Memory System Design
## Overview
每用户有两条记忆记录(user_type 和 work_type),存储在 `memories` 表的 `content` JSONB 字段中。
## Data Model
### UserMemoryContent
```python
class UserPreferences(BaseModel):
time_preference: str | None = None # "上午效率高"
communication_style: str | None = None # "简洁直接"
location_preference: str | None = None # "喜欢远程工作"
work_lifestyle: str | None = None # "早睡早起"
class UserMemoryContent(BaseModel):
occupation: str | None = None # 职业
timezone: str | None = None # 时区
language: str | None = None # 语言偏好
people: list[str] = [] # 重要人物
places: list[str] = [] # 常去地点
projects: list[str] = [] # 个人项目
preferences: UserPreferences = UserPreferences()
interests: list[str] = [] # 兴趣爱好
avoid_topics: list[str] = [] # 不想讨论的话题
custom_rules: list[str] = [] # 自定义规则
recurring_contexts: list[str] = [] # 周期性场景
```
### WorkMemoryContent
```python
class WorkProject(BaseModel):
name: str
description: str | None = None
status: str | None = None # "active", "paused"
key_milestones: list[str] = [] # 关键里程碑
class WorkHabit(BaseModel):
available_hours: dict[str, str] = {} # {"monday": "09:00-18:00"}
deep_work_blocks: list[str] = [] # 深度工作时段
meeting_preference: str | None = None # "short", "30min最佳"
notification_channel: str | None = None # 首选沟通渠道
class WorkMemoryContent(BaseModel):
expertise: list[str] = [] # 专业领域
preferred_tools: list[str] = [] # 惯用工具
current_projects: list[WorkProject] = []
work_habits: WorkHabit = WorkHabit()
team_members: list[str] = [] # 团队成员
team_context: str | None = None # 团队概述
```
## API Endpoints
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/v1/memories` | 获取用户所有记忆 |
| PUT | `/api/v1/memories/user` | 创建/更新用户记忆 |
| PUT | `/api/v1/memories/work` | 创建/更新工作记忆 |
| DELETE | `/api/v1/memories/{type}` | 删除指定类型记忆 |
## TaskType支撑关系
| TaskType | Router决策依赖 | Worker执行依赖 |
|----------|---------------|---------------|
| SCHEDULING | timezone, available_hours | current_projects, team_members |
| PLANNING | preferences, work_lifestyle | expertise, work_habits |
| COMMUNICATION_DRAFTING | communication_style, avoid_topics | team_context, preferred_tools |
| RECOMMENDATION | interests, people | expertise, current_projects |
## Frontend UI
- MemoryScreen: 主列表页,展示user/work两条记忆卡片
- MemoryDetailScreen: 详情/编辑页,分Tab展示各字段
- 支持新建/编辑/删除操作
-151
View File
@@ -1,151 +0,0 @@
# 可见性掩码重构方案
> 日期:2026-03-22
> 状态:待执行
## 背景
现有可见性系统存在以下问题:
- `UI_REALTIME` 定义但从未使用
- `visibility_consumer_bit` 语义模糊,用于 context 过滤但无法正确区分 chat/automation
- stage bits (16/17/18) 在 chat/automation 永不共享 thread 的设计下无意义
- 无法正确实现:automation user_message 不进 /history、不进 contextautomation agent_reply 进 /history 但不进 context
## 设计目标
| runtime_mode | 消息 | /history 可见 | context_messages 组装 |
|-------------|------|:-------------:|:-------------------:|
| chat | user_message | ✅ | ✅ |
| chat | agent_reply | ✅ | ✅ |
| automation | user_message | ❌ | ❌ |
| automation | agent_reply | ✅ | ❌ |
## 前提条件
- chat 和 automation **永不共享 thread_id**(已确认的设计约束)
- memory == automation,无需单独处理
---
## Bit 定义
```
BIT 0 → UI_HISTORY → /history API 可见
BIT 1 → CONTEXT_ASSEMBLY → 组装进 context_messages
```
> `UI_REALTIME` 废弃,删除。
> `visibility_consumer_bit` 废弃,删除。
> Stage bits (16/17/18) 废弃,删除。
---
## 消息 Mask 矩阵
| 消息 | runtime_mode | UI_HISTORY | CONTEXT_ASSEMBLY | Mask |
|------|-------------|:----------:|:---------------:|:----:|
| user_message | chat | 1 | 1 | **3** |
| user_message | automation | 0 | 0 | **0** |
| agent_reply | chat | 1 | 1 | **3** |
| agent_reply | automation | 1 | 0 | **1** |
---
## 查询设计
| 查询 | Mask | 匹配规则 |
|------|------|---------|
| `/history` | `UI_HISTORY = 1` | `(message_mask & 1) != 0` |
| `context_messages` | `CONTEXT_ASSEMBLY = 2` | `(message_mask & 2) != 0` |
---
## 查询结果验证
| 消息 | Mask | `/history & 1` | `/history` | `context & 2` | `context` |
|------|------|:-------------:|:----------:|:-------------:|:---------:|
| chat user_message | 3 | 1 ✅ | ✅ | 1 ✅ | ✅ |
| chat agent_reply | 3 | 1 ✅ | ✅ | 1 ✅ | ✅ |
| automation user_message | 0 | 0 ❌ | ❌ | 0 ❌ | ❌ |
| automation agent_reply | 1 | 1 ✅ | ✅ | 0 ❌ | ❌ |
---
## 变更清单
### 1. `schemas/agent/visibility.py`
- [ ] 删除 `UI_REALTIME = 1``SystemVisibilityBit`
- [ ] 删除 `VisibilityBitRef`
- [ ] 保留 `bit_mask()` 函数
- [ ] 保留 `VisibilityMask` 类(其他模块可能使用)
### 2. `schemas/agent/system_agent.py`
- [ ] 删除 `SystemAgentLLMConfig.visibility_consumer_bit` 字段
### 3. `core/config/static/database/system_agents.yaml`
- [ ] 删除 `router.visibility_consumer_bit`
- [ ] 删除 `worker.visibility_consumer_bit`
### 4. `v1/agent/service.py`
- [ ] 重写 `_resolve_user_message_visibility_mask`
```python
async def _resolve_user_message_visibility_mask(
self, *, runtime_mode: RuntimeMode
) -> int:
if runtime_mode == RuntimeMode.CHAT:
return UI_HISTORY | CONTEXT_ASSEMBLY # = 3
return 0 # automation user_message
```
### 5. `core/agentscope/events/store.py`
- [ ] 重写 `_resolve_stage_visibility_mask`
- chat stage (router/worker) → `UI_HISTORY | CONTEXT_ASSEMBLY` = 3
- automation stage (memory) → `UI_HISTORY` = 1
- [ ] 删除 `_load_stage_visibility_bit_map` 中对 `visibility_consumer_bit` 的依赖
- [ ] 删除 `system_agents.yaml` 配置加载逻辑
### 6. `core/agentscope/runtime/context_service.py`
- [ ] `load_context_messages` 查询 mask 改为 `CONTEXT_ASSEMBLY = 2`
```python
visibility_mask = bit_mask(bit=int(SystemVisibilityBit.CONTEXT_ASSEMBLY))
```
### 7. `core/agentscope/runtime/tasks.py`
- [ ] 删除 `_build_recent_context_messages` 中 memory job 的特殊处理
- [ ] memory mode 改用 `runtime_mode=automation` 语义
### 8. `core/agentscope/runtime/runner.py`
- [ ] 删除硬编码 `visibility_consumer_bit=18` 的 `SystemAgentLLMConfig`
- [ ] memory agent 配置改用 automation 语义
### 9. 清理迁移
- [ ] 更新 `schemas/agent/__init__.py` 导出(删除 `visibility_consumer_bit` 相关)
- [ ] 更新所有引用 `visibility_consumer_bit` 的文件
- [ ] 运行测试验证 /history 和 context 组装行为
---
## 实施顺序
1. 新增 `CONTEXT_ASSEMBLY = 1` bit,更新 `service.py`
2. 更新 `events/store.py` 可见性逻辑
3. 更新 `context_service.py` 查询 mask
4. 清理废弃配置和字段
5. 运行测试验证
---
## 风险
- `VisibilityBitRef` 可能在其他未知位置使用(需全面搜索)
- `visibility_consumer_bit` 被 `runner.py` 硬编码,修改可能影响 memory pipeline
- 测试覆盖不足可能导致 regression
@@ -1,78 +0,0 @@
# Worker Token/Latency 优化 TODO
日期: 2026-03-17
Owner: backend runtime
状态: pending
## 背景
- Router 阶段成本与延迟基本可接受。
- Worker 阶段(deepseek-chat`input_tokens``latency` 显著偏高,是总成本的主要来源。
- 优化目标是在不降低结果质量与稳定性的前提下,优先压缩 Worker 输入 token。
## 现状观察
- Worker 平均 `input_tokens` 明显高于 Router。
- Worker 平均延迟明显高于 Router。
- 成本主要由 Worker 阶段贡献。
## 核心优化方向(按优先级)
### P0(优先执行,低风险高收益)
1. 路由提示词瘦身:从“全量路由清单”改为“route_id 约束 + 服务端映射”。
- 模型仅输出 `route_id` 与必要参数。
- 后端基于静态 route catalog 映射到最终 `path`
- 目标:减少每次 system prompt 的固定 token 开销。
2. Finalize 最小上下文化:避免 finalize 回放完整 memory。
- finalize 阶段仅输入:最后一轮候选答案 + 必要工具结果摘要 + schema 指令。
- 不再注入完整历史会话。
- 目标:降低两段式结构化输出的额外输入成本。
3. 工具按需暴露(dynamic tool allowlist)。
- 按 router 的 task/result typing 只下发当前任务必需工具。
- 避免每轮 ReAct 携带全量工具 schema。
- 目标:降低每次 reasoning 的工具描述负担。
### P1(次优先,稳定收益)
4. system prompt 分层裁剪。
-`agent_type``ui_mode` 组装最小提示词集合。
- Router 不携带 Worker 专属规则;`ui_mode=none` 不携带 rich UI 细则。
5. 输出体积约束。
- 限制 `key_points``suggested_actions``ui_hints.actions` 数量与文本长度。
- 降低 `output_tokens`,同时减少前端渲染负担。
6. 上下文策略优化(摘要 + 最近少量原文)。
- 从“固定最近 N 轮原文”改为“结构化摘要 + 最近 1~2 轮原文”。
- 控制长会话 token 膨胀。
### P2(可选增强)
7. Prompt 缓存命中优化。
- 固定可缓存前缀,动态段后置。
- 利用 provider prompt cache 降低计费 token(若模型侧支持)。
## 不建议作为当前主线
- 直接切换为 ReAct 原生 `structured_model` 作为主方案(当前实测稳定性与成本不占优)。
- 在未完成 P0 优化前,优先投入复杂的 ReAct 内核重写。
## 验收指标(更新)
- 在典型多轮场景中,Worker `input_tokens` 降低 >= 30%。
- Worker p95 `latency_ms` 降低 >= 20%。
- 结构化输出校验成功率不低于当前基线。
- 关键路径功能行为保持不变(agent run 结果与前端交互不回退)。
## 验证方式
1. 固定场景脚本对比(优化前/后同输入):
- 指标:`input_tokens``output_tokens``latency_ms``cost`、结构化成功率。
2. 线上观测(`public.messages`):
- 按 stagerouter/worker)聚合对比日均与 p95。
3. 回归校验:
- 工具调用结果一致性;
- `ui_hints`/`ui_schema` 可渲染性与导航动作正确性。
@@ -1,27 +0,0 @@
# Calendar Reminder Migration Checklist
## Scope
本清单用于跟踪提醒模块迁移后旧代码清理,字段固定为:文件路径、符号名、处理决策、责任人、状态。
## Items
| File | Symbol | Decision | Owner | Status | Notes |
|---|---|---|---|---|---|
| `apps/lib/features/calendar/reminders/models/reminder_action.dart` | `ReminderAction.cancel` | delete | agent | done | 枚举项删除,保留字符串兼容映射到 `archive` |
| `apps/lib/features/calendar/reminders/models/reminder_action.dart` | `ReminderAction.timeout30s` | delete | agent | done | 枚举项删除,保留字符串兼容映射到 `snooze10m` |
| `apps/lib/features/calendar/reminders/models/reminder_action.dart` | `ReminderAction.autoArchive` | delete | agent | done | 枚举项删除,保留字符串兼容映射到 `archive` |
| `apps/lib/features/calendar/reminders/models/reminder_action.dart` | `ReminderAction.normalized` | delete | agent | done | canonical 枚举后不再需要 |
| `apps/lib/core/notifications/local_notification_service.dart` | `_actionSnooze = 'snooze_10m'` | replace | agent | done | 统一为 `_actionSnooze = 'snooze10m'` |
| `apps/lib/core/notifications/local_notification_service.dart` | `_iosCategoryId = 'calendar_reminder_actions_v1'` | replace | agent | done | 已升级为 `calendar_reminder_v2` |
## Verification Commands
```bash
rg "calendar_reminder_actions_v1|ReminderAction\.cancel|_oldReminderEntry|_legacyReminderRoute" apps/lib apps/test
rg "snooze_10m" apps/lib apps/test
```
Expected:
- 第一条:no matches
- 第二条:仅允许出现在兼容映射分支(若存在)