refactor: 重构 schemas 结构,统一枚举定义

This commit is contained in:
qzl
2026-03-25 12:36:31 +08:00
parent 389f5248fc
commit d22ded21f8
122 changed files with 774 additions and 1456 deletions
@@ -0,0 +1,99 @@
# Protocols 文档修复计划
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** 修复 protocols 文档中与后端实现不一致的错误
**Architecture:** 直接修改 docs/protocols/ 下的 markdown 文件,确保文档与 backend/src/models/ 中的实际模型定义保持一致
**Tech Stack:** Markdown 编辑
---
## 修复任务清单
### Task 1: 修复 Memories Protocol - 移除不存在的 `agent_id` 字段
**文件:**
- 修改: `docs/protocols/models/memory.md`
**修改内容:**
- 从 "数据库存储" 章节的表格中移除 `agent_id` 字段
- 该字段在实现中不存在
---
### Task 2: 修复 InboxMessages Protocol - 添加缺失的 `group_id` 字段
**文件:**
- 修改: `docs/protocols/models/inbox-messages.md`
**修改内容:**
-`InboxMessageResponse` 数据结构中添加 `group_id: uuid | null` 字段
---
### Task 3: 修复 ScheduleItems Protocol - 补充 `permission` 位掩码说明
**文件:**
- 修改: `docs/protocols/calendar/schedule-items.md`
**修改内容:**
-`ScheduleItemResponse` 的说明中,添加 `permission` 字段的位掩码语义:
- `1` = view
- `2` = invite
- `4` = edit
-`ScheduleItemShareRequest` 中补充说明
---
### Task 4: 修复 Friendships Protocol - 补充内部状态说明
**文件:**
- 修改: `docs/protocols/models/friendships.md`
**修改内容:**
-`FriendRequestResponse``status` 字段说明中,添加注释:
- `blocked``declined` 为内部实现状态
- 对外返回时映射为 `rejected`
- 说明这是实现细节,客户端应处理所有枚举值
---
### Task 5: 修复 Memories Protocol - 改进 `source` 列移除说明
**文件:**
- 修改: `docs/protocols/models/memory.md`
**修改内容:**
- 在 "数据库存储" 章节的表格中,明确标注 `source` 列已移除
- 或者在表格下方添加更醒目的 "已移除字段" 说明
---
### Task 6: 修复 Automation Jobs Protocol - 添加 `bootstrap_key` 字段
**文件:**
- 修改: `docs/protocols/models/automation-jobs.md`
**修改内容:**
- 在 "Canonical Fields" 表格中添加 `bootstrap_key: string | null` 字段说明
- 简短说明其用途(引导配置键)
---
## 执行顺序
1. Task 1 - Memories: 移除 agent_id
2. Task 2 - InboxMessages: 添加 group_id
3. Task 3 - ScheduleItems: 补充 permission 说明
4. Task 4 - Friendships: 补充状态说明
5. Task 5 - Memories: 改进 source 说明
6. Task 6 - AutomationJobs: 添加 bootstrap_key
---
## 验证方式
- 人工检查:对比修改后的文档与 backend/src/models/ 中的实际模型定义
- 确保文档中描述的每个字段都能在对应 model 文件中找到
@@ -0,0 +1,29 @@
# Backend Schemas Restructure Design
**Goal:** Restructure `backend/src/schemas` into clear domain/shared/enums modules while keeping API contracts in `backend/src/v1/*/schemas.py`.
**Architecture:** Move reusable validation models and enums into `schemas/domain`, `schemas/shared`, and `schemas/enums.py`. Keep versioned request/response contracts in `v1/*/schemas.py` and update imports to explicit module paths. Remove legacy aggregate exports and duplicate/empty schema directories.
**Tech Stack:** Python 3.13, Pydantic v2, Ruff, Pytest.
---
## Approved decisions
- Use one-shot hard cut.
- Keep API contracts in `backend/src/v1/*/schemas.py`.
- Keep `schemas` as reusable constraints only.
- Remove implicit root re-export usage.
## Target structure
- `backend/src/schemas/enums.py`
- `backend/src/schemas/domain/*.py`
- `backend/src/schemas/shared/*.py`
- `backend/src/v1/*/schemas.py` (unchanged naming and ownership)
## Validation gates
- `uv run ruff check ...`
- `uv run pytest ...` for impacted suites
- `./infra/scripts/dev-migrate.sh migrate`
@@ -0,0 +1,123 @@
# Backend Schemas Restructure Implementation Plan
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
**Goal:** Hard-cut refactor backend schema modules into clear domain/shared/enums boundaries while keeping API contracts in `v1/*/schemas.py`.
**Architecture:** Introduce `schemas/enums.py` and move reusable schema models into `schemas/domain` and `schemas/shared`. Update all backend imports to explicit new module paths and remove old schema package wrappers and duplicate directories.
**Tech Stack:** Python 3.13, Pydantic v2, Ruff, Pytest, Alembic migration runner.
---
### Task 1: Create new schema module layout
**Files:**
- Create: `backend/src/schemas/enums.py`
- Create: `backend/src/schemas/domain/automation.py`
- Create: `backend/src/schemas/domain/inbox.py`
- Create: `backend/src/schemas/domain/schedule.py`
- Create: `backend/src/schemas/domain/memory.py`
- Create: `backend/src/schemas/domain/memory_content.py`
- Create: `backend/src/schemas/domain/chat_message.py`
- Create: `backend/src/schemas/domain/chat_session.py`
- Create: `backend/src/schemas/domain/todo.py`
- Create: `backend/src/schemas/domain/invite_code.py`
- Create: `backend/src/schemas/shared/user.py`
**Step 1: Write failing import checks**
```python
def test_new_schema_paths_importable() -> None:
import schemas.domain.automation # noqa: F401
```
**Step 2: Run test to verify it fails**
Run: `uv run pytest backend/tests/unit -k new_schema_paths_importable -v`
Expected: FAIL with import error
**Step 3: Implement new modules**
Copy and normalize existing reusable models into new modules.
**Step 4: Run test to verify it passes**
Run: `uv run pytest backend/tests/unit -k new_schema_paths_importable -v`
Expected: PASS
### Task 2: Update all backend imports to new schema paths
**Files:**
- Modify: `backend/src/**/*.py` (affected import lines)
**Step 1: Write failing grep assertions**
Run: `uv run python -c "..."` with assertions for old import patterns.
**Step 2: Verify failures with old paths present**
Run: `uv run ruff check backend/src`
**Step 3: Implement import rewrites**
Replace old paths (`schemas.model_enums`, `schemas.automation`, `schemas.memories.memory_content`, etc.) with new explicit modules.
**Step 4: Verify static checks pass**
Run: `uv run ruff check backend/src`
Expected: PASS
### Task 3: Remove legacy schema wrappers and duplicates
**Files:**
- Delete: `backend/src/schemas/model_enums.py`
- Delete: `backend/src/schemas/automation/__init__.py`
- Delete: `backend/src/schemas/inbox/messages.py`
- Delete: `backend/src/schemas/schedule/items.py`
- Delete: `backend/src/schemas/memories/__init__.py`
- Delete: `backend/src/schemas/memories/memory_content.py`
- Delete: `backend/src/schemas/messages/chat_message.py`
- Delete: `backend/src/schemas/messages/__init__.py`
- Delete: `backend/src/schemas/sessions/chat_session.py`
- Delete: `backend/src/schemas/sessions/__init__.py`
- Delete: `backend/src/schemas/todo/contracts.py`
- Delete: `backend/src/schemas/todo/__init__.py`
- Delete: `backend/src/schemas/user/context.py`
- Delete: `backend/src/schemas/user/__init__.py`
- Delete: `backend/src/schemas/inbox/__init__.py`
- Delete: `backend/src/schemas/invite_codes/__init__.py`
- Modify: `backend/src/schemas/__init__.py`
**Step 1: Remove old modules**
Delete legacy wrappers after all imports are rewritten.
**Step 2: Verify no old imports remain**
Run: `uv run python -c "..."` or grep-based assertion commands.
Expected: zero matches
### Task 4: Verification and migration
**Files:**
- Verify only
**Step 1: Run quality gates**
Run: `uv run ruff check backend/src`
**Step 2: Run impacted tests**
Run: `uv run pytest backend/tests/unit/v1/automation_jobs backend/tests/unit/v1/schedule_items backend/tests/unit/v1/todo backend/tests/unit/v1/friendships backend/tests/unit/v1/inbox_messages backend/tests/unit/v1/users backend/tests/unit/v1/agent backend/tests/unit/core/agentscope`
**Step 3: Run migration script**
Run: `./infra/scripts/dev-migrate.sh migrate`
**Step 4: Commit**
```bash
git add backend/src/schemas backend/src/v1 backend/src/models backend/src/core docs/plans
git commit -m "refactor: restructure backend schema modules by domain boundaries"
```
+9 -4
View File
@@ -28,10 +28,10 @@ Base URL: `/api/v1/schedule-items`
| 值 | 说明 |
|---|---|
| `active` | 进行中 |
| `completed` | 已完成 |
| `canceled` | 已取消 |
| `archived` | 已归档 |
兼容策略:历史数据中若存在 `completed` 或 `canceled`,服务端统一按 `archived` 语义处理;新写入仅允许 `active` 或 `archived`。
### ScheduleItemSourceType
| 值 | 说明 |
@@ -96,7 +96,7 @@ Base URL: `/api/v1/schedule-items`
"end_at": "datetime | null (必须包含时区)",
"timezone": "string | null (IANA 时区)",
"metadata": "ScheduleItemMetadata | null",
"status": "ScheduleItemStatus | null"
"status": "ScheduleItemStatus | null (active | archived)"
}
```
@@ -116,7 +116,7 @@ Base URL: `/api/v1/schedule-items`
"source_type": "ScheduleItemSourceType",
"created_at": "datetime",
"updated_at": "datetime",
"permission": "int",
"permission": "int (位掩码: 1=view, 2=invite, 4=edit)",
"is_owner": "boolean"
}
```
@@ -132,6 +132,11 @@ Base URL: `/api/v1/schedule-items`
}
```
说明:`permission_view`、`permission_edit`、`permission_invite` 为布尔值,内部会转换为位掩码整数:
- `permission_view = 1`
- `permission_invite = 2`
- `permission_edit = 4`
### ScheduleItemShareResponse
```json
+1
View File
@@ -10,6 +10,7 @@ scheduler computation, and Flutter settings pages.
- `id`: UUID
- `owner_id`: UUID
- `title`: string
- `bootstrap_key`: string | null (引导配置键,用于标识预设任务模板)
- `config`: object
- `input_template`: string
- `enabled_tools`: string[]
+2
View File
@@ -49,6 +49,8 @@ Base URL: `/api/v1/friends`
}
```
说明:`status` 对外返回的值包括 `pending`、`accepted`、`rejected`、`canceled`。内部实现中还有 `blocked` 和 `declined` 状态,在返回给客户端时会映射为 `rejected` 或 `canceled`。
### FriendResponse
```json
+1
View File
@@ -92,6 +92,7 @@ Base URL: `/api/v1/inbox/messages`
"message_type": "InboxMessageType",
"schedule_item_id": "uuid | null",
"friendship_id": "uuid | null",
"group_id": "uuid | null",
"content": "CalendarInviteContent | CalendarUpdateContent | CalendarDeleteContent | FriendshipContent | null",
"is_read": "boolean",
"status": "InboxMessageStatus",
+4 -3
View File
@@ -172,7 +172,6 @@
|------|------|------|
| `id` | UUID | 主键 |
| `owner_id` | UUID | 所有者用户 ID |
| `agent_id` | UUID | 关联 Agent ID(可选) |
| `memory_type` | VARCHAR(20) | 记忆类型枚举(当前含 `user``work`,可扩展) |
| `content` | JSONB | UserMemoryContent 或 WorkProfileContent |
| `status` | VARCHAR(20) | ACTIVE / DISABLED |
@@ -181,6 +180,7 @@
说明:
- `source` 列已移除,不再作为行级来源标记。
- `agent_id` 列不存在。
- 来源信息如果需要保留,使用 `content` 内各条目的 `meta.source`(字段级来源)。
- 唯一性约束:同一 `owner_id``memory_type` 不能重复(`UNIQUE(owner_id, memory_type)`)。
@@ -306,8 +306,9 @@ build_system_prompt(
| 文件 | 职责 |
|------|------|
| `src/schemas/memories/memory_content.py` | UserMemoryContent、WorkProfileContent 模型 |
| `src/schemas/memories/__init__.py` | MemoryType、MemoryStatus 枚举 |
| `src/schemas/domain/memory_content.py` | UserMemoryContent、WorkProfileContent 模型 |
| `src/schemas/domain/memory.py` | MemoryModel 聚合模型 |
| `src/schemas/enums.py` | MemoryType、MemoryStatus 枚举 |
| `src/models/memories.py` | SQLAlchemy ORM 模型 |
| `src/v1/memories/router.py` | API 端点 |
| `src/v1/memories/service.py` | 业务逻辑层 |