Skip to content

Commit 3bf94ff

Browse files
committed
docs(architecture): enforce host persistence boundary
1 parent 5df3887 commit 3bf94ff

7 files changed

Lines changed: 124 additions & 73 deletions

docs/architecture-optimization-checklist.md

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain`
2424
4. **治理事实源不一致**:架构规则、总览、AST 基线和 CI 语义存在漂移;快照门禁能证明“没有变化”,
2525
但不能自动证明依赖合理、没有新环或所有运行资源都有生命周期 owner。
2626

27-
当前唯一 P0 是主线 `mypy` ratchet 已失败。后续架构优化应先恢复主线,再按可靠性、边界类型化
28-
生命周期、复杂度的顺序推进;不建议再做一次大规模目录搬迁。
27+
审计时唯一 P0 的主线 `mypy` ratchet 失败已由 `5df388719` 修复并推送。后续架构优化按可靠性
28+
边界类型化、生命周期、复杂度的顺序推进;不建议再做一次大规模目录搬迁。
2929

3030
## 2. 范围与证据边界
3131

@@ -105,8 +105,8 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain`
105105

106106
| ID | 优先级 | 状态 | 事项 | 目标结果 |
107107
|---|---|---|---|---|
108-
| ARCH-001 | P0 | 阻塞 | 恢复 mypy ratchet | 主线所有既有 CI gate 重新通过 |
109-
| ARCH-101 | P1 | 待执行 | 统一规则、总览、基线和语义门禁 | 文档声明与机器拒绝条件一一对应 |
108+
| ARCH-001 | P0 | 已交付 | 恢复 mypy ratchet | `5df388719` 已推送,主线既有 CI gate 通过 |
109+
| ARCH-101 | P1 | 执行中 | 统一规则、总览、基线和语义门禁 | 文档声明与机器拒绝条件一一对应 |
110110
| ARCH-102 | P1 | 待执行 | 将 Transfer pending 升级为真实 E3 状态机 | 崩溃窗口可判定恢复,结果未知时进入人工确认 |
111111
| ARCH-103 | P1 | 待执行 | 类型化 Chain/Agent 数据 Port 与 DTO | 宿主主路径不再注入无 Session Oper,不向入口泄漏 ORM |
112112
| ARCH-104 | P1 | 待执行 | 收口跨多次写入的业务事务 | 站点/规则引用清理可整体回滚或幂等恢复 |
@@ -135,9 +135,9 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain`
135135

136136
**执行要求**
137137

138-
- [ ] 将标题键和位置键使用不同、带语义的变量名,修复真实类型错误。
139-
- [ ] 不得用 `mypy_ratchet.py --write` 接受增长。
140-
- [ ] 保留音乐专辑“精确标题优先、碟号/曲序回退”的现有行为。
138+
- [x] 将标题键和位置键使用不同、带语义的变量名,修复真实类型错误。
139+
- [x] 未使用 `mypy_ratchet.py --write` 接受增长。
140+
- [x] 保留音乐专辑“精确标题优先、碟号/曲序回退”的现有行为。
141141

142142
**验收**
143143

@@ -152,8 +152,8 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain`
152152

153153
**问题与证据**
154154

155-
- `docs/rules/04-design-patterns.md:125-131` 仍示范 `SubscribeOper()` 无 Session 调用,
156-
`docs/rules/10-data-and-persistent.md:111-132` 的生产路径显式 UoW 规则冲突。
155+
- 审计时 `docs/rules/04-design-patterns.md` 仍示范 `SubscribeOper()` 无 Session 调用,
156+
与生产路径显式 UoW 规则冲突;该项已由 S0-L2.1 修复并增加文档门禁
157157
- `docs/rules/05-architecture.md:507` 禁止 `application -> concrete adapter`,但同一文档
158158
`177-183` 又要求 RSS 消费 network adapter;当前测试没有形式化这类例外。
159159
- 规则 `docs/rules/05-architecture.md:516` 禁止任意模块级环,实际 SCC 测试只覆盖特定根。
@@ -163,7 +163,7 @@ MoviePilot V3 已经形成较清晰的模块化单体:`foundation`、`domain`
163163
**目标与步骤**
164164

165165
- [ ] 指定一个机器可读事实源,文档指标由 fixture 生成或只保留不易漂移的语义描述。
166-
- [ ] 修正 Oper 示例,分别展示宿主显式 UoW 与插件兼容 Facade。
166+
- [x] 修正 Oper 示例,分别展示宿主显式 UoW 与插件兼容 Facade,并以文档测试禁止回退
167167
- [ ] 对 Adapter 规则作出明确决策:允许哪些通用技术机制,哪些命名外部/持久化能力必须注入。
168168
- [ ] 让 SCC 规则、精确 allowlist 和文档声明一致。
169169
- [ ] Event 扫描只识别 EventManager 实例/别名和事件装饰器。

docs/architecture-refactor-roadmap.md

Lines changed: 20 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,13 @@ G-ARCH 只有在以下条件全部满足后才可完成:
7272

7373
| Leaf | 状态 | 依赖 | 完成定义 |
7474
|---|---|---|---|
75-
| S0-L1 可信基线恢复 | `VERIFIED` || 交付架构审计/路线图,修复 `ARCH-001` 两个 mypy 增量错误;现有专项和主线门禁通过 |
76-
| S0-L2 规范事实统一 | `PLANNED` | S0-L1 | 修正 Oper、Adapter、HTTP、SCC、调用图规则冲突;规范目标与已执行门禁逐项对应 |
77-
| S0-L3 完整宿主 SCC 门禁 | `PLANNED` | S0-L2 | 完整宿主 SCC 集合只允许 TMDB 精确 allowlist;Chain 环清零前门禁提供可审查低水位,最终由 S2-L2 清零 |
78-
| S0-L4 Adapter/Egress 债务门禁 | `PLANNED` | S0-L2 | Application/Chain Adapter 导入和 direct HTTP egress 有精确分类;未解释项归零且禁止增长 |
79-
| S0-L5 Event 扫描事实修复 | `PLANNED` | S0-L2 | consumer 只识别 EventManager 注册;动态误报归零,台账与真实生产/消费一致 |
75+
| S0-L1 可信基线恢复 | `DELIVERED` || `5df388719`:交付架构审计/路线图,修复 `ARCH-001` 两个 mypy 增量错误;远端 `0/0` |
76+
| S0-L2.1 Host Oper/UoW 规范 | `VERIFIED` | S0-L1 | 宿主规则中未标注兼容范围的无 Session Oper 示例归零,并由文档测试锁定 |
77+
| S0-L2.2 完整宿主 SCC policy | `PLANNED` | S0-L2.1 | 完整宿主 SCC 全部精确分类;Chain 临时债务和 TMDB containment 分离 |
78+
| S0-L2.3 Adapter 直连事实 | `PLANNED` | S0-L2.1 | 收集 Application/Chain 的原始 Adapter import,不因父包展开重复计数 |
79+
| S0-L2.4 Adapter zero-growth | `PLANNED` | S0-L2.3 | 当前直连均登记迁移 owner,新增/替换失败,删除后要求清理陈旧 policy |
80+
| S0-L2.5 Event consumer 识别 | `PLANNED` | S0-L2.1 | consumer 只识别可静态证明的 EventManager 注册,动态误报归零 |
81+
| S0-L2.6 事实源与 CI 投影 | `PLANNED` | S0-L2.2,S0-L2.4,S0-L2.5 | fixture/policy/overview 职责固定,CI 分开报告语义 policy 与快照一致性 |
8082

8183
### S1:可靠性、事务与数据合同
8284

@@ -151,53 +153,38 @@ G-ARCH 只有在以下条件全部满足后才可完成:
151153

152154
## 4. 当前活动叶子
153155

154-
### S0-L1 可信基线恢复
156+
### S0-L2.1 Host Oper/UoW 规范
155157

156158
**Status:** `VERIFIED`(本地验收完成,等待提交、推送和远端一致性确认)
157159

158160
**Outcome**
159161

160-
在不接受新债务的前提下恢复当前主线类型门禁,交付审计清单、Goal 路线图和与实际基线一致的架构总览。
162+
让宿主数据访问规范与已经建立的 Application Port、DB Adapter、显式 Session/UoW
163+
边界一致;无 Session Oper 只作为明确标注的插件 Legacy/Compat ABI 出现。
161164

162165
**Ownership**
163166

164-
- `app/chain/media.py` 的音乐曲目匹配局部类型回归
165-
- `docs/architecture-optimization-checklist.md`
166-
- `docs/architecture-refactor-roadmap.md`
167-
- `docs/architecture-overview.md` 的当前事实与文档索引
167+
- `docs/rules/04-design-patterns.md` 的 Oper、SystemConfig、UserConfig 示例
168+
- `docs/rules/10-data-and-persistent.md` 的对应交叉规则
169+
- `tests/test_architecture_documentation.py` 的无 Session Oper 文档门禁
170+
- 本路线图的叶子状态和交付记录
168171

169172
**Excluded**
170173

171-
- 不在本叶实现 ARCH-102 之后的业务重构
172-
- 不刷新 mypy、Ruff、依赖或复杂度 fixture
173-
- 不修改 `app/plugins/**` 或独立插件仓
174+
- 不迁移当前 startup 注入的无 Session Oper;该债务由 ARCH-103 逐领域切换
175+
- 不修改运行时代码、fixture、`app/plugins/**` 或独立插件仓
176+
- 不以删除 Legacy/Compat ABI 伪装宿主规范收口
174177

175178
**Acceptance**
176179

177180
```bash
178-
.venv/bin/python -m pytest tests/test_music_album_match.py -q
179-
.venv/bin/mypy --config-file mypy.ini
180-
.venv/bin/python scripts/architecture/mypy_ratchet.py
181+
.venv/bin/python -m pytest tests/test_architecture_documentation.py -q
181182
.venv/bin/python scripts/architecture/baseline.py --check-host
182-
.venv/bin/python scripts/architecture/complexity.py
183-
.venv/bin/python scripts/architecture/async_blocking.py
184-
.venv/bin/python scripts/architecture/task_ownership.py
185-
.venv/bin/python scripts/architecture/service_locator.py
186-
.venv/bin/python scripts/architecture/ruff_ratchet.py
187-
.venv/bin/python -m pytest \
188-
tests/test_architecture_dependencies.py \
189-
tests/test_architecture_contract_baseline.py \
190-
tests/test_architecture_baseline_cli.py \
191-
tests/test_complexity_gate.py \
192-
tests/test_async_blocking_gate.py \
193-
tests/test_task_ownership_gate.py \
194-
tests/test_quality_ratchets.py \
195-
tests/test_mypy_gate.py \
196-
tests/test_architecture_ci.py -q
183+
rg -n 'SubscribeOper\(\)|SystemConfigOper\(\)|UserConfigOper\(\)' docs/rules
197184
git diff --check
198185
```
199186

200187
**Delivery**
201188

202-
- 单一提交主题:恢复可信架构基线并建立长期路线图
189+
- 单一提交主题:统一宿主持久化规范并建立文档门禁
203190
- 推送 `origin/v3` 后确认提交祖先关系、远端 SHA 和 ahead/behind `0/0`

docs/rules/04-design-patterns.md

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,9 @@ eventmanager.send_event(EventType.TransferComplete, data_dict)
110110

111111
## 4. Repository (Oper) Pattern
112112

113-
**When to use:** All database reads and writes. Never issue SQLAlchemy queries directly from chain, module, or endpoint code.
113+
**When to use:** Implementing table-oriented persistence behind an Application-owned
114+
Protocol. Never issue SQLAlchemy queries or construct Oper objects directly from
115+
chain, module, endpoint, Agent, scheduler, or workflow code.
114116

115117
**Convention:** Each SQLAlchemy model in `app/db/models/` has a corresponding `<Model>Oper` class in `app/db/oper/<model>.py` — the two packages mirror each other file for file, so the module name carries the entity and the package carries the role.
116118

@@ -120,16 +122,36 @@ app/db/models/systemconfig.py → app/db/oper/systemconfig.py (SystemConfi
120122
app/db/models/transferhistory.py → app/db/oper/transferhistory.py (TransferHistoryOper)
121123
```
122124

123-
**Usage:**
125+
**Host usage:**
126+
127+
Host entrypoints depend on an Application service or Protocol. The concrete
128+
`app/db/adapters/` implementation creates one operation-scoped Session, adapts the
129+
Protocol with Oper objects, and gives commit/rollback ownership to the Application
130+
command. Oper methods only query, stage, or flush in that caller-owned Session.
124131

125132
```python
126-
from app.db.oper.subscribe import SubscribeOper
133+
from app.application.subscription.write import SubscribeWriter
127134

128-
oper = SubscribeOper()
129-
subscribe = oper.get(sid=1)
130-
oper.add(Subscribe(name="Example", type="电影"))
135+
def create_subscription(writer: SubscribeWriter, identity: dict, payload: dict):
136+
return writer.add(identity=identity, payload=payload)
131137
```
132138

139+
The explicit Session/Oper composition belongs in `app/db/adapters/`, not at the
140+
host call site:
141+
142+
```python
143+
with SessionFactory() as session:
144+
command = CreateSubscriptionCommand(
145+
repository=SubscribeOper(session),
146+
unit_of_work=SqlAlchemyUnitOfWork(session),
147+
)
148+
result = command.execute(identity=identity, payload=payload)
149+
```
150+
151+
The no-Session `SubscribeOper()` facade is legacy plugin ABI only. It may remain
152+
available through the curated SDK/Compat boundary, but new host code and examples
153+
must not copy that form.
154+
133155
---
134156

135157
## 5. Config Reload Pattern
@@ -180,17 +202,21 @@ Do not introduce new singletons unless the class genuinely manages global shared
180202

181203
**Enum:** `SystemConfigKey` in `app/schemas/types.py`
182204

183-
**Oper class:** `SystemConfigOper` in `app/db/oper/systemconfig.py`
205+
**Host service:** `SystemConfigService` and `get_configured_system_config()` in
206+
`app/application/configuration.py`.
184207

185208
```python
209+
from app.application.configuration import get_configured_system_config
186210
from app.schemas.types import SystemConfigKey
187-
from app.db.oper.systemconfig import SystemConfigOper
188211

189-
oper = SystemConfigOper()
190-
value = oper.get(SystemConfigKey.RssUrls)
191-
oper.set(SystemConfigKey.RssUrls, ["https://..."])
212+
configuration = get_configured_system_config()
213+
value = configuration.get(SystemConfigKey.RssUrls)
214+
configuration.set(SystemConfigKey.RssUrls, ["https://..."])
192215
```
193216

217+
`SystemConfigOper` is the DB/composition implementation and legacy plugin-facing
218+
facade; canonical host consumers do not construct it.
219+
194220
**Rule:** Never use raw string literals as SystemConfig keys. Always add a new entry to the `SystemConfigKey` enum first.
195221

196222
---
@@ -199,9 +225,12 @@ oper.set(SystemConfigKey.RssUrls, ["https://..."])
199225

200226
**When to use:** Per-user settings that must survive across sessions but differ by user.
201227

202-
**Oper class:** `UserConfigOper` in `app/db/oper/userconfig.py`
228+
**Host service:** `UserConfigurationService` and
229+
`get_configured_user_configuration()` in
230+
`app/application/security/userconfig.py`.
203231

204-
Usage mirrors `SystemConfigOper` but scoped to a `user_id`.
232+
The concrete repository uses `UserConfigOper` behind the service boundary. Host
233+
callers do not construct it.
205234

206235
---
207236

@@ -212,8 +241,8 @@ Usage mirrors `SystemConfigOper` but scoped to a `user_id`.
212241
| `module -> chain` coupling | Move orchestration into `chain` and shared logic into its owning canonical package |
213242
| `module -> module` direct calls | Use `chain` to orchestrate cross-module workflows |
214243
| Lower-level module importing a chain or manager | Register a callback/resolver from `app/startup/` or move orchestration to `chain` |
215-
| Raw SQLAlchemy queries in endpoints or chains | Use the corresponding Oper class in `app/db/oper/` |
244+
| Raw SQLAlchemy queries or Oper construction in host entrypoints | Define/use an Application Protocol or command; implement it in `app/db/adapters/` with an operation-scoped Session/UoW |
216245
| Raw string keys for SystemConfig | Define and use a `SystemConfigKey` enum entry |
217246
| HTTP requests via `requests` or `httpx` directly | Host code uses `RequestUtils` from `app/adapters/network/http.py`; plugins use `app.sdk.network` |
218247

219-
*Last Updated: 2026-08-14*
248+
*Last Updated: 2026-08-27*

docs/rules/07-naming-conventions.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,9 +116,9 @@ All new code must follow these conventions. Consistent naming is how the codebas
116116
| `def GetSubscribe():` | `def get_subscribe():` |
117117
| `TORRENT_info = ...` | `torrent_info = ...` |
118118
| `def handleConfigChanged():` | `def on_config_changed():` or `def handle_config_changed():` |
119-
| `SystemConfigOper().get("RssUrls")` | `SystemConfigOper().get(SystemConfigKey.RssUrls)` |
119+
| `configuration.get("RssUrls")` | `configuration.get(SystemConfigKey.RssUrls)` |
120120
| `class subscribe_oper:` | `class SubscribeOper:` |
121121
| `MessageChannel.Telegram`(新代码) | `NotificationChannel.Telegram` |
122122
| `Notification(title=...)`(新代码) | `Message(title=...)` |
123123

124-
*Last Updated: 2026-08-16*
124+
*Last Updated: 2026-08-27*

docs/rules/08-comment-styles.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ if not self._initialized:
9797

9898
```python
9999
# 获取订阅列表 ← 这只是在重述代码,不需要
100-
subscribes = SubscribeOper().list()
100+
subscribes = repository.list()
101101

102102
# 如果 result 为 None 则返回 ← 无意义
103103
if result is None:
@@ -139,4 +139,4 @@ When modifying code, update or remove any comment that no longer accurately desc
139139
| Commented-out dead code | Delete it; git history preserves it |
140140
| New contract documentation in English inside an otherwise Chinese file | Breaks the repository's default documentation language and local consistency |
141141

142-
*Last Updated: 2026-08-13*
142+
*Last Updated: 2026-08-27*

docs/rules/10-data-and-persistent.md

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -199,19 +199,21 @@ oper.delete(sid=1) # Delete by key
199199

200200
**Enum:** `SystemConfigKey` in `app/schemas/types.py`
201201

202-
**Oper:** `SystemConfigOper` in `app/db/oper/systemconfig.py`
202+
**Host service:** `SystemConfigService` and `get_configured_system_config()` in
203+
`app/application/configuration.py`. `SystemConfigOper` is used behind the
204+
composition/persistence boundary and remains available for legacy plugin ABI.
203205

204206
```python
207+
from app.application.configuration import get_configured_system_config
205208
from app.schemas.types import SystemConfigKey
206-
from app.db.oper.systemconfig import SystemConfigOper
207209

208-
oper = SystemConfigOper()
210+
configuration = get_configured_system_config()
209211

210212
# Read
211-
rss_urls = oper.get(SystemConfigKey.RssUrls)
213+
rss_urls = configuration.get(SystemConfigKey.RssUrls)
212214

213215
# Write
214-
oper.set(SystemConfigKey.RssUrls, ["https://example.com/rss"])
216+
configuration.set(SystemConfigKey.RssUrls, ["https://example.com/rss"])
215217
```
216218

217219
**Rule:** Never use raw string literals as `SystemConfig` keys. Always define a new `SystemConfigKey` enum entry first. Raw string key lookups are not searchable and cannot be refactored safely.
@@ -220,16 +222,21 @@ oper.set(SystemConfigKey.RssUrls, ["https://example.com/rss"])
220222

221223
## UserConfig — Per-User Configuration
222224

223-
**Purpose:** Settings that differ per user account. Uses `UserConfigOper`.
225+
**Purpose:** Settings that differ per user account. Host callers use the configured
226+
`UserConfigurationService`; its concrete repository adapts `UserConfigOper` behind
227+
the persistence boundary.
224228

225229
```python
226-
from app.db.oper.userconfig import UserConfigOper
230+
from app.application.security.userconfig import get_configured_user_configuration
227231

228-
oper = UserConfigOper()
229-
value = oper.get(user_id=1, key="notification_enabled")
230-
oper.set(user_id=1, key="notification_enabled", value=True)
232+
configuration = get_configured_user_configuration()
233+
value = configuration.get(username="alice", key="notification_enabled")
234+
configuration.set(username="alice", key="notification_enabled", value=True)
231235
```
232236

237+
The no-Session `UserConfigOper()` form is legacy plugin ABI only and must not be
238+
copied into host code.
239+
233240
---
234241

235242
## Settings / Environment Configuration
@@ -290,4 +297,4 @@ When `REDIS_HOST` is configured, `app/modules/redis/` provides a distributed cac
290297
- `settings.API_TOKEN` and other secret fields must not be included in log output or API responses.
291298
- The `config list --show-secrets` flag exists specifically to gate secret visibility in the CLI.
292299

293-
*Last Updated: 2026-08-24*
300+
*Last Updated: 2026-08-27*
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""架构规则文档的可执行一致性约束。"""
2+
3+
import re
4+
from pathlib import Path
5+
6+
PROJECT_ROOT = Path(__file__).parents[1]
7+
RULE_DOCUMENTS = tuple(sorted((PROJECT_ROOT / "docs" / "rules").glob("*.md")))
8+
NO_SESSION_OPER = re.compile(r"\b[A-Z][A-Za-z0-9]*Oper\(\)")
9+
COMPATIBILITY_MARKERS = ("legacy plugin abi", "compatibility", "兼容")
10+
11+
12+
def test_no_session_oper_examples_are_explicitly_compatibility_only() -> None:
13+
"""无 Session Oper 示例必须紧邻 Legacy/Compat 说明,不能冒充宿主规范。"""
14+
violations: list[str] = []
15+
for path in RULE_DOCUMENTS:
16+
content = path.read_text(encoding="utf-8")
17+
for occurrence in NO_SESSION_OPER.finditer(content):
18+
context = content[
19+
max(0, occurrence.start() - 500):occurrence.end() + 200
20+
].lower()
21+
if not any(marker in context for marker in COMPATIBILITY_MARKERS):
22+
line = content.count("\n", 0, occurrence.start()) + 1
23+
violations.append(f"{path.relative_to(PROJECT_ROOT)}:{line}")
24+
25+
assert violations == [], (
26+
"无 Session Oper 仅允许出现在明确标注的插件 Legacy/Compat 示例中: "
27+
+ ", ".join(violations)
28+
)

0 commit comments

Comments
 (0)