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