chore: trim dead code, modularize CLI, and archive stale docs

Extract review-plan, report, quarantine, state, and config handlers into
commands/ with shared cli_helpers; remove unused exceptions and duplicate
plan summary wrappers. Archive superseded review markdown, sync docs to
517-test baseline, and fix empty series titles when only a quality tag remains.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
windyboy
2026-05-21 10:36:03 +08:00
co-authored by Claude Sonnet 4.5 Cursor
parent 5f0b531269
commit 79797644e1
40 changed files with 1714 additions and 1165 deletions
@@ -1,127 +0,0 @@
# Refactor and Refinement Execution Plan
## Objective
Refactor the current `vlm` codebase to reduce structural technical debt while preserving the existing safety-first pipeline behavior. The plan focuses on improving CLI maintainability, strengthening stage boundaries, clarifying state semantics, enabling provider and strategy extensibility, and increasing testability and observability without changing the user-visible safety guarantees.
## Context and Scope
This plan is based on the verified review findings in the code analysis report, especially the structural issues around CLI size and repetitive error handling, weak dict/JSON contracts between stages, analyze-phase ordering coupling, duplicated sample-path rules, filesystem-dependent plan generation, configuration semantic overlap, review-state ambiguity, provider hard-coding, and the lack of unified state and strategy abstractions. Key source areas include `src/vlm/cli.py:158-603`, `src/vlm/commands/parse.py:66-155`, `src/vlm/io.py:85-249`, `src/vlm/commands/analyze.py:41-55`, `src/vlm/planner.py:34-40`, `src/vlm/planner.py:43-76`, `src/vlm/planner.py:354-358`, `src/vlm/enrichment.py:203-225`, `src/vlm/state.py:22-205`, `src/vlm/models.py:46-53`, and `src/vlm/models.py:79-85`.
## Assumptions
- Preserve the current pipeline order and safety behavior unless a change explicitly improves safety or determinism.
- Avoid introducing breaking changes to the CLI surface in the first refactor wave.
- Prefer incremental, reviewable changes that can ship independently.
- Keep the artifact-driven workflow as the default, while making room for future hybrid or streaming modes.
- Treat documentation, tests, and observability updates as first-class deliverables rather than afterthoughts.
## Implementation Plan
### Phase 0: Baseline, guardrails, and dependency mapping
- [ ] Capture the current behavior baseline for the full workflow, including `scan`, `parse`, `enrich`, `analyze`, `plan`, and `execute`, so every later refactor can be compared against the existing safety model. This is necessary because the codebase relies on many cross-stage assumptions and the review identified several fragile boundaries.
- [ ] Map the exact data flow between artifact files and in-memory models for `inventory`, `identities`, `analysis`, and `plan` outputs. This reduces the chance of accidental schema drift while refactoring the stage contracts.
- [ ] Identify the minimum set of high-value integration paths to protect first: CLI startup, parse/enrich transition, analyze pairing, plan generation, execute rollback, and quarantine handling. These paths correspond to the highest-risk areas in the review.
### Phase 1: CLI decomposition and unified error handling
- [ ] Extract a shared command execution/error-wrapping layer from `src/vlm/cli.py:158-603` so repeated `try/except + echo + logger + exit` logic is centralized. This is needed to stop the CLI file from continuing to grow and to keep error behavior consistent.
- [ ] Split non-core commands and support workflows into smaller command modules and keep the CLI module focused on registration and dispatch. This reduces the blast radius of future command additions and improves discoverability.
- [ ] Standardize CLI-level error presentation so file, JSON, validation, and OS errors all follow one predictable response shape. This improves user experience and avoids duplicated branching.
- [x] Update the CLI workflow description to match the actual supported flow, including `enrich`, so the user-facing guidance reflects the true pipeline. This is a low-cost refinement that removes user confusion.
### Phase 2: Stronger stage contracts and typed intermediate models
- [ ] Replace the most fragile dict-based stage boundaries with typed records or `TypedDict` models, starting with parse output and the io conversion layer in `src/vlm/commands/parse.py:66-155` and `src/vlm/io.py:85-249`. This directly addresses schema drift and makes refactors safer.
- [x] Define explicit schemas for `identities.json`, `analysis.json`, and `plan.json`, and validate them on load/save. This adds a durable guardrail against silent data-shape changes.
- [ ] Align enrichment output mutation with typed contracts so fields like `display_title`, `needs_review`, and review metadata have a single authoritative shape. This prevents inconsistent stage assumptions.
- [x] Refactor `identities_to_analysis_input()` so it returns explicit identity-file pairs instead of relying on positional slicing and zipping in `src/vlm/commands/analyze.py:41-55`. This removes the fragile ordering dependency identified in the review.
### Phase 3: Shared rule extraction and deterministic planning
- [x] Extract the duplicated sample-path rule from `src/vlm/planner.py:34-40`, `src/vlm/duplicate_resolve.py:11-16`, and `src/vlm/plan_review.py:12-16` into a single shared helper. This reduces duplication and guarantees consistent classification behavior.
- [x] Separate logical plan generation from live environment validation so plan output becomes reproducible and execute-time validation becomes an explicit pass. This addresses the filesystem-state coupling in `src/vlm/planner.py:43-76` and `src/vlm/planner.py:354-358`.
- [x] Tag any environment-derived metadata in plan artifacts as snapshots rather than intrinsic plan facts. This makes the distinction between logical intent and runtime validation clear.
- [ ] Review plan-related metadata and operation structures so they can support deterministic comparisons across runs. This is important for review tooling and regression analysis.
### Phase 4: Unified state model and review semantics
- [ ] Introduce a centralized state model that clearly separates processing, review, execution, and quarantine semantics. This directly addresses the spread of state concepts across `src/vlm/state.py:22-205`, `src/vlm/models.py:46-53`, and `src/vlm/models.py:79-85`.
- [ ] Make `needs_review` a derived or secondary field rather than the main source of truth, and ensure `review_status` and `review_reason` are the primary review semantics. This removes the current overlap and reduces future workflow ambiguity.
- [ ] Align execution and rollback state transitions with the centralized model so success, failure, rollback, and restore paths are all represented consistently.
- [ ] Review persisted state files and transition logic for atomicity and consistency after the model changes are introduced.
### Phase 5: Provider extensibility and strategy abstractions
- [ ] Replace hard-coded provider assembly in `src/vlm/enrichment.py:203-225` with a registry or plugin-style registration mechanism. This enables new metadata sources without requiring direct edits to the core enrichment orchestration.
- [ ] Introduce a strategy layer for naming, conflict handling, and keep/delete decisions so `Config` is no longer the only mechanism for behavior variation. This addresses the current static-config limitation in `src/vlm/config.py:13-148`.
- [ ] Refactor media-type and operation-type dispatch toward registered handlers rather than expanding `if/elif` chains in the parser and executor. This makes future media types and operation kinds easier to add.
- [ ] Keep the default built-in behavior intact while allowing new strategies to be added incrementally. This limits regression risk while improving extensibility.
### Phase 6: Error taxonomy and observability
- [ ] Define a small domain exception hierarchy for enrichment, planning, and execution safety failures, and update command-layer handling to use those typed errors. This makes failure handling more precise than broad exception catching.
- [ ] Add structured logging or event fields for high-value workflow events such as cache hits, quarantine operations, rollback actions, and plan conflicts. This improves supportability and analysis quality.
- [ ] Add stage-level timing and outcome metrics so long-running operations can be measured consistently. This is especially useful once the pipeline grows beyond small libraries.
### Phase 7: Testing expansion and validation coverage
- [ ] Add integration tests for cross-stage transitions, especially parse→enrich, analyze→plan, and plan→execute. These paths need stronger guarantees than isolated unit tests.
- [ ] Add end-to-end tests that run a complete safe workflow against a controlled fixture library, including rollback and quarantine behavior. This validates the pipeline as a whole rather than one module at a time.
- [ ] Add performance-oriented checks or benchmark fixtures for larger datasets so future changes can be evaluated against scaling regressions.
- [ ] Extend property-based coverage where the new typed contracts or state transitions create meaningful invariants.
### Phase 8: UX refinement and future-mode readiness
- [ ] Refresh help text and workflow guidance after the CLI and pipeline changes are stable, so the documented flow stays aligned with actual behavior.
- [ ] Evaluate whether a hybrid execution mode or a guided interactive mode should be introduced once the state model and contracts are stable. This is a future-facing refinement to improve usability without sacrificing safety.
- [ ] Keep the artifact-first mode as the default until the alternative execution modes have matching safety guarantees and test coverage.
## Verification Criteria
- [ ] CLI startup and command registration still work, and repeated command-level error handling is no longer duplicated across the main CLI file.
- [x] Stage artifact schemas are explicitly validated, and malformed inputs fail early with clear errors.
- [x] Analyze no longer depends on positional assumptions between identities and video files.
- [x] Sample-path classification produces one consistent result across planner, duplicate resolution, and review flows.
- [x] Plan generation is reproducible for the same logical inputs, with live filesystem checks clearly separated as validation snapshots.
- [ ] Review state semantics are no longer ambiguous, and `review_status` is the primary review source of truth.
- [ ] Provider registration can be extended without editing the core orchestration logic.
- [ ] Integration and E2E coverage exists for the main safe workflow and rollback/quarantine scenarios.
- [ ] Structured logs or metrics expose workflow health and failure patterns.
- [ ] The default user-visible pipeline still preserves the safety-first execution model.
## Potential Risks and Mitigations
1. **Risk: Refactor scope expands faster than the code can be stabilized**
Mitigation: Keep the work split into independently shippable phases and require the baseline behavior to remain intact after each phase.
2. **Risk: Typed contracts introduce temporary friction in serialization/deserialization code**
Mitigation: Introduce schema validation and typed records incrementally, starting with the highest-risk artifacts.
3. **Risk: State model changes cascade through planner, executor, and review flows**
Mitigation: Centralize the new model first, then migrate consumers one by one while keeping compatibility adapters where needed.
4. **Risk: Provider and strategy abstraction can become too generic too early**
Mitigation: Start with the current built-in cases as default registrations before allowing external extensibility.
5. **Risk: New tests may be slow or hard to maintain if they overuse large fixtures**
Mitigation: Prefer focused fixtures for unit/integration coverage and reserve large datasets for targeted performance checks.
## Alternative Approaches
1. **Incremental refactor first**: Keep the current artifact-first architecture and only extract the most painful seams now. Trade-off: lowest regression risk, but slower progress on deeper extensibility issues.
2. **Boundary-first refactor**: Prioritize typed contracts, state model, and deterministic planning before provider and strategy work. Trade-off: better long-term clarity, but requires more cross-module updates early.
3. **Platform-style refactor**: Introduce registries, strategies, and structured observability as a broader platform layer. Trade-off: highest flexibility, but the largest immediate complexity increase.
## Status Tracking
- **Not Started**: Phase 0 baseline capture and dependency mapping
- **Partially Completed**: Phase 1 CLI decomposition and unified error handling
- **Partially Completed**: Phase 2 stronger stage contracts and typed intermediate models
- **Partially Completed**: Phase 3 shared rule extraction and deterministic planning
- **Not Started**: Phase 4 unified state model and review semantics
- **Not Started**: Phase 5 provider extensibility and strategy abstractions
- **Not Started**: Phase 6 error taxonomy and observability
- **Not Started**: Phase 7 testing expansion and validation coverage
- **Not Started**: Phase 8 UX refinement and future-mode readiness
@@ -1,102 +0,0 @@
# Review-Plan Output Refactor Plan
## Objective
在不修改 `plan.json` schema、不中断现有 CSV 手工审核流程的前提下,重构 `vlm review-plan` 的输出体验,让用户在终端中直接看到计划的核心内容和可审核的操作预览,减少必须打开 `plan.json` 才能继续操作的成本。
## Validated Baseline
- `review-plan` 当前只输出计划加载提示、风险统计、CSV 保存路径和前 5 条样例,没有输出完整计划预览,见 `src/vlm/cli.py:536-563`
- `ExecutionPlan` 已包含 `operations``summary``summary_by_reason``human_summary``metadata`,足以支撑更强的终端展示,见 `src/vlm/models.py:133-153`
- 计划保存时会把上述字段全部写入 JSON,因此无需改动 plan schema,见 `src/vlm/planner.py:591-625`
- CLI 中已经存在 fallback 计划摘要逻辑,可复用于 `review-plan`,见 `src/vlm/cli.py:976-987`
- `execute` 已经采用“计划概要 + 样例操作”的输出方式,可作为统一风格参考,见 `src/vlm/commands/execute.py:84-103``src/vlm/commands/execute.py:137-146`
- 当前测试只覆盖 summary 和 CSV 导出,未覆盖完整计划预览输出,见 `tests/test_cli_review_plan.py:31-88`
## Recommended Approach
采用推荐方案:**抽离通用渲染层,并为 `review-plan` 提供受控预览输出**。
原因:
1. 只加 `human_summary` 无法解决“看不到计划内容”的核心问题。
2. 直接打印全部 operations 会在大计划场景下严重刷屏。
3. 抽离通用渲染层可以同时提升用户体验、结构清晰度和后续复用性。
## Scope
### In Scope
- 优化 `review-plan` 的终端输出结构。
- 复用已有 `human_summary` / fallback summary。
- 增加受控的操作预览输出。
- 为计划展示提取可复用 helper。
- 补充 CLI 测试,覆盖新增展示行为。
### Out of Scope
- 修改 `ExecutionPlan` 数据模型。
- 修改 `plan.json` schema。
- 修改 review CSV 字段或 `apply-review` 工作流。
- 引入交互式 TUI/Web 界面。
## Implementation Plan
- [x] Task 1. [Status: Done] 重新定义 `review-plan` 的输出顺序为“计划概览 → 风险统计 → 操作预览 → CSV 路径”,优先展示决策信息,再展示审核细节,以替代当前仅有 summary 和 5 条样例的输出方式,现状见 `src/vlm/cli.py:546-563`
- [x] Task 2. [Status: Done] 在 `review-plan` 中优先输出 `ExecutionPlan.human_summary`,若为空则复用现有 fallback summary,避免重复设计摘要逻辑并统一跨命令体验,相关能力见 `src/vlm/planner.py:169-184``src/vlm/cli.py:976-987`
- [x] Task 3. [Status: Done] 提取统一的计划终端渲染 helper,负责 plan header、summary、reason 分布和 operation preview 的格式化输出,避免 CLI 命令函数继续承载大量展示细节,参考现有输出风格见 `src/vlm/commands/execute.py:84-103`
- [x] Task 4. [Status: Done] 设计受控预览机制,默认仅展示有限条操作并提示剩余数量,同时预留完整显示模式的扩展点,以兼顾可读性和信息完整性。
- [x] Task 5. [Status: Done] 在预览输出中优先展示审核价值最高的字段,包括 `index``operation_type``risk_flags``source_path``destination_path``reason`,以便用户在不打开 JSON 的情况下完成多数审核判断,字段来源见 `src/vlm/plan_review.py:75-83``src/vlm/planner.py:606-620`
- [x] Task 6. [Status: Done] 保持 `ExecutionPlan` 模型、plan JSON schema 和 review CSV schema 完全兼容,将改动严格限制在输出层,降低对 `execute``report``apply-review` 的影响,相关结构见 `src/vlm/models.py:133-153``src/vlm/planner.py:591-625`
- [x] Task 7. [Status: Done] 扩展 `review-plan` CLI 测试,覆盖默认摘要输出、受控预览、完整显示模式、CSV 不变性和原有 summary 输出兼容性,弥补当前测试缺口,基线见 `tests/test_cli_review_plan.py:31-88`
- [x] Task 8. [Status: Done] 评估是否将 `execute` 的计划摘要展示逐步迁移到同一渲染 helper,减少跨命令输出风格分叉,参考现有入口见 `src/vlm/commands/execute.py:84-103``src/vlm/commands/execute.py:137-146`
- [x] Task 9. [Status: Done] 在最终验收中重点验证大计划场景下的可读性,确保默认输出足够简洁、重点清晰,并且不影响后续 `apply-review` 使用链路,相关流程见 `src/vlm/cli.py:589-643`
## Verification Criteria
- [x] `vlm review-plan` 默认输出中包含计划摘要,而不只是风险计数。
- [x] 默认输出中包含可读的操作预览,且预览字段足以支持人工初步审核。
- [x] 大计划场景下默认输出不会无上限刷屏,并会提示仍有未展示操作。
- [x] review CSV 的字段、写入逻辑与后续 `apply-review` 流程保持兼容,相关链路见 `src/vlm/plan_review.py:89-96``src/vlm/cli.py:621-643`
- [x] `plan.json` 的 schema、读写行为与现有字段保持不变,见 `src/vlm/planner.py:591-625``src/vlm/planner.py:628-671`
- [x] CLI 测试覆盖新增预览行为,并保留现有 summary/CSV 行为验证,基线见 `tests/test_cli_review_plan.py:31-88`
## Risks and Mitigations
1. **默认输出过长,降低可读性**
Mitigation: 使用默认限量预览,只展示高价值字段,并明确提示剩余条目数量。
2. **展示逻辑分散,后续难维护**
Mitigation: 将计划渲染抽离为统一 helper,让 CLI 命令函数只负责流程编排与参数处理。
3. **改动误伤 CSV 手工审核链路**
Mitigation: 将 CSV 视为稳定接口,不调整字段结构与导出逻辑,保持 `src/vlm/plan_review.py:89-96` 行为不变。
4. **CLI 输出测试过于脆弱**
Mitigation: 测试聚焦结构性关键片段与核心字段,不对整段输出做过度刚性匹配。
## Alternatives Considered
1. **仅增加 `human_summary` 输出**
优点:改动最小,交付最快。
缺点:仍然看不到操作层内容。
2. **直接打印全部 operations**
优点:实现简单,信息最完整。
缺点:大计划会严重刷屏。
3. **抽离通用渲染层并提供受控预览**
优点:用户体验、可维护性与复用性最平衡。
缺点:实现成本略高于局部修补。
结论:**推荐采用**。
## Recommended Outcome
推荐采用“仅重构展示层、不改数据层”的方案:
- 保持 `ExecutionPlan`、plan JSON、review CSV 全部兼容。
-`review-plan` 增加计划摘要与受控操作预览。
- 把计划展示逻辑抽离为可复用渲染能力。
- 用测试确保 CLI 可见行为稳定。
这样可以以最小风险解决当前“review 时看不到计划内容”的核心问题。
@@ -1,45 +0,0 @@
# Refactor Plan: Safety, Determinism, and Baseline Alignment
**Date:** 2026-04-07
**Basis:** Verified repository state plus `REVIEW_REPORT.md`.
**Status:** Completed.
## Objective
Refactor the codebase to resolve the safety and determinism issues identified during review, restore a truthful green baseline, and reconcile the review artifacts with the post-refactor state.
## Execution Outcome
- Full-suite baseline restored: `pytest -q`**507 passed**.
- The review-plan TUI is now a true optional runtime boundary via guarded Textual imports in `src/vlm/review_tui.py:16-30` and lazy CLI import/use in `src/vlm/cli.py:567-602`.
- Move and rename execution now validate both source and destination paths against `library_root` in `src/vlm/executor.py:204-249`.
- Duplicate handling is now explicit and deterministic through strict resolver errors in `src/vlm/duplicate_resolve.py:16-58` plus canonicalized planner matching and manual-review fallback in `src/vlm/planner.py:42-57` and `src/vlm/planner.py:151-203`.
- Scanner behavior for non-zero `find` exits is now documented in code and deterministic in `src/vlm/scanner.py:158-214`.
- Plan loading now crosses a validated typed boundary in `src/vlm/io.py:247-326`.
## Implementation Plan
- [x] Task 1. [Status: Done] Re-established a reliable baseline by making the Textual review UI a true optional boundary. Evidence: `src/vlm/cli.py:567-602`, `src/vlm/review_tui.py:16-30`, `tests/test_cli_review_plan.py:237-343`.
- [x] Task 2. [Status: Done] Added source-root validation for move and rename operations so execution checks both source and destination against `library_root`. Evidence: `src/vlm/executor.py:204-249`, `tests/test_path_safety.py:76-137`.
- [x] Task 3. [Status: Done] Unified execution failure contracts so unsupported quarantine categories now return failed `OperationResult`s, and batch execution contains per-operation exceptions. Evidence: `src/vlm/quarantine.py:116-140`, `src/vlm/executor.py:108-130`, `tests/test_quarantine.py:84-110`, `tests/test_executor.py:951-1004`.
- [x] Task 4. [Status: Done] Removed silent duplicate fallback behavior by raising explicit resolver errors and routing unresolved groups into manual review. Evidence: `src/vlm/duplicate_resolve.py:44-58`, `src/vlm/planner.py:187-203`, `tests/test_duplicate_resolve.py:223-237`, `tests/test_planner.py:619-669`.
- [x] Task 5. [Status: Done] Introduced canonical path-normalization for duplicate-group matching. Evidence: `src/vlm/planner.py:42-57`, `src/vlm/planner.py:152-169`, `tests/test_planner.py:672-720`.
- [x] Task 6. [Status: Done] Defined and implemented an explicit scanner contract for non-zero `find` exits with partial or empty stdout. Evidence: `src/vlm/scanner.py:158-214`, `tests/test_scanner.py:140-186`.
- [x] Task 7. [Status: Done] Strengthened the plan I/O boundary with validated typed construction and canonical serialization helpers. Evidence: `src/vlm/io.py:247-326`, `tests/test_io.py:112-203`.
- [x] Task 8. [Status: Done] Expanded regression coverage around the identified weak points. Evidence: `tests/test_cli_review_plan.py:237-343`, `tests/test_path_safety.py:76-137`, `tests/test_quarantine.py:84-110`, `tests/test_executor.py:951-1004`, `tests/test_duplicate_resolve.py:223-237`, `tests/test_planner.py:619-720`, `tests/test_scanner.py:140-186`, `tests/test_io.py:112-203`.
- [x] Task 9. [Status: Done] Updated existing review artifacts to reflect the final baseline and current findings. Evidence: `REVIEW_REPORT.md`, `docs/TECHNICAL_REVIEW.md`.
## Verification Criteria
- [x] `pytest -q` passes, including the review-plan TUI tests in `tests/test_cli_review_plan.py:271-343`.
- [x] Manual or crafted plans cannot move or rename sources outside `library_root`. Evidence: `src/vlm/executor.py:204-249`, `tests/test_path_safety.py:106-137`.
- [x] Unsupported quarantine categories are recorded as failed results and do not abort later operations in the same execution batch. Evidence: `src/vlm/quarantine.py:116-140`, `src/vlm/executor.py:108-130`, `tests/test_executor.py:951-1004`.
- [x] Duplicate resolution no longer silently selects index `0` for quality-data mismatch or unexpected low-level strategy input. Evidence: `src/vlm/duplicate_resolve.py:44-58`, `tests/test_duplicate_resolve.py:223-237`, `tests/test_planner.py:619-669`.
- [x] Duplicate-group matching is stable across supported path-format variations and covered by planner tests. Evidence: `src/vlm/planner.py:42-57`, `tests/test_planner.py:672-720`.
- [x] Scanner behavior for non-zero `find` exit is explicit, deterministic, and test-covered. Evidence: `src/vlm/scanner.py:158-214`, `tests/test_scanner.py:140-186`.
- [x] Plan loading crosses one validated, typed boundary rather than propagating plain dicts after schema validation. Evidence: `src/vlm/io.py:247-326`, `tests/test_io.py:112-203`.
- [x] Existing review documents reflect the actual test baseline and remaining findings.
## Post-plan Note
The refactor plan is complete. One low-priority packaging observation remains outside the implementation scope: `textual` is still listed in both `dev` and `tui` optional extras in `pyproject.toml:12-20`. The runtime optional-dependency bug itself is resolved via `src/vlm/cli.py:567-602` and `src/vlm/review_tui.py:16-30`.
@@ -0,0 +1,266 @@
# 修改计划:只保留对功能有贡献的代码
**日期:** 2026-05-21
**状态:** 已完成(2026-05-21
**基线:** `uv run pytest -q`**517 passed**2026-05-21 实测)
**原则:** 删除或合并**无运行时贡献**的代码与文档;**不**削减 CLI 命令、配置项、产物格式、安全策略或用户工作流。
---
## 1. 目标
| 目标 | 说明 |
|------|------|
| 减噪 | 去掉从未被 import / 调用的模块与一层包装函数 |
| 减重复 | 同一语义只保留一处实现(如 plan 摘要) |
| 减结构债 | 把 `cli.py` 中已独立的命令体迁出,**行为不变** |
| 减文档漂移 | 归档已完成的历史审查/实施计划,避免与 `README`/`CHANGELOG` 冲突 |
| 不丢功能 | 全量 pytest + 现有 `tests/test_cli_*` 作为回归门禁 |
**非目标(本计划不做):**
- 删除 duplicate 策略、`legacy` 产物回退、anime 扫描分类、TUI、TMDB enrich、transaction/rollback
- 合并 `needs_review``review_status`(会改变 enrich/plan/CSV 语义)
- 缩小 `quarantine.py` / `executor.py` 的**对外 API**(仅允许内部拆分 + re-export
---
## 2. 功能贡献判定标准
代码/文件在下列情况之一时视为**有贡献**,保留:
1.`vlm` CLI 路径或 `pyproject.toml` entry point 直接或间接调用
2.`tests/` 覆盖且对应用户可见行为(含可选 `[tui]`
3. 被其他保留模块 import 且删除会导致 import 失败或行为变化
4. 属于安全/数据契约:`io` 校验、`executor` 边界、`duplicate_resolve` 显式失败
下列情况视为**无贡献**,可删或合并:
1. 全仓库零 import(静态可证)
2. 仅转发到另一函数的薄包装(调用方可直接调目标)
3. 已完成且被 `CHANGELOG` 取代的历史计划/审查 markdown
4. 与保留文档逐字重复、无额外运维价值的 agent 副本(如 `GEMINI.md`
---
## 3. 审计清单
### 3.1 可删除(运行时零贡献)
| 项 | 路径 | 证据 | 操作 |
|----|------|------|------|
| 未使用异常层次 | `src/vlm/exceptions.py` | 全仓库无 `from vlm.exceptions` | **删除文件** |
| CLI 薄包装 | `cli.py` `_fallback_plan_summary()` L11831185 | 仅调用 `plan_render.fallback_plan_summary` | **删除**;调用改 `preferred_plan_summary` |
| 重复 import | `cli.py``fallback_plan_summary` 的 import | 包装删除后不再需要 | **删除 import** |
### 3.2 可合并(保留行为,减重复)
| 项 | 位置 | 现状 | 操作 |
|----|------|------|------|
| Plan 摘要 | `cli.py` L1332、L1451 | `human_summary or _fallback_plan_summary(...)` | 改为 `preferred_plan_summary(execution_plan)`(与 `execute`/`review-plan` 一致;空白 `human_summary` 处理更一致) |
| 可选依赖声明 | `pyproject.toml` `[dev]` | `textual``[tui]` 重复 | **从 `[dev]` 移除 textual**;开发需 TUI 时用 `uv pip install -e ".[dev,tui]"` 或文档说明 |
### 3.3 保留(有贡献,勿删)
| 模块 | 贡献 |
|------|------|
| `scanner` / `parser` / `analysis` / `planner` / `executor` | 主管道 |
| `duplicate_resolve` | 重复策略与显式失败 |
| `io` | 产物校验与 typed plan |
| `plan_review` / `plan_render` / `review_display` / `review_tui` | 人工复核与可选 TUI |
| `plan_structure_preview` | `review-plan` 结构预览(`cli` + `test_plan_review` |
| `transaction` | `executor` 执行期事务日志 |
| `quarantine` / `state` / `reports` / `enrichment` / `cache` / `providers` | 对应子命令 |
| `commands/*`(已有) | scan/parse/enrich/analyze/plan/execute/rollback |
| `logging_config` | CLI + executor + quarantine + 测试 |
| `context` / `config` / `models` / `utils` | 全局基础设施 |
### 3.4 文档归档(不删功能,减仓库噪音)
移至 `docs/archive/2026-pre-baseline/`(或删除若确认无历史查阅需求):
| 文件 | 理由 |
|------|------|
| `REVIEW_REPORT.md` | 2026-04-07 计划已 Completed |
| `ARCHITECTURE_REVIEW.md` | 历史架构审查,多处已修复 |
| `VLM_PROJECT_AUDIT_REPORT.md` | 审计快照 |
| `AUDIT_FIX_PLAN.md` | 任务已勾选完成 |
| `FIX_PLAN.md` | 同上 |
| `CODE_IMPROVEMENTS.md` | 建议清单,非现行规范 |
| `CODE_ANALYSIS_2026-04-01.md` | 一次性分析 |
| `IMPLEMENTATION_PLAN_2026-02-13.md` | 已过期 |
| `IMPROVEMENT_RECOMMENDATIONS_2026-02-13.md` | 已过期 |
| `TMDB_REFACTOR_PLAN.md` | 若 TMDB 已落地则归档 |
| `codex_review.md` | 外部审查副本 |
| `plans/2026-04-07-review-report-refactor-plan-v1.md` | Status: Completed |
| `plans/2026-04-02-review-plan-output-refactor-v1.md` | 已完成 |
| `plans/2026-04-01-CODE_REFACTOR_REFINEMENT_PLAN-v1.md` | 已完成 |
| `GEMINI.md` | 与 `CLAUDE.md`/`AGENTS.md` 重复 |
**保留为现行文档:**
- `README.md``CHANGELOG.md``CLAUDE.md``AGENTS.md`
- `docs/TECHNICAL_REVIEW.md`(可选:精简后保留为「设计备忘」或一并归档)
- `skills/vlm-library-workflow/**`Agent 操作指引)
- `plans/2026-05-21-functional-code-simplification-plan-v1.md`(本计划)
**可选归档:** `.kiro/specs/video-library-manager/` — 若与当前实现严重偏离且团队不用 Kiro,整目录归档。
### 3.5 结构重组(不删命令,减 `cli.py` 体积)
将下列 Click 命令体迁到 `commands/``cli.py` 只保留装饰器 + 一行委托:
| 新文件 | 迁出命令 |
|--------|----------|
| `commands/review_plan.py` | `review_plan_cmd`, `apply_review_cmd` |
| `commands/report.py` | `report` 组及四个子命令 |
| `commands/quarantine_cmd.py` | `quarantine` 组(避免与 `quarantine.py` 模块名冲突) |
| `commands/state_cmd.py` | `state` 组 |
| `commands/config_cmd.py` | `config` 组 |
共享辅助函数抽到 `cli_helpers.py`(或 `context.py` 旁):
- `default_config_path`, `default_artifact_path`, `resolve_legacy_default_input_path`
- `_load_or_create_config`, `_command_error`, `_review_plan_tui_streams_ok`
**预期:** `cli.py` 从 ~1941 行降至 ~300 行;**`vlm --help` 与子命令选项不变**。
### 3.6 延后(本计划不拆文件内容)
以下能减行数但工作量/风险更高,单列 **Phase 2**(可选后续计划):
- 拆分 `quarantine.py`1027 行)、`executor.py`833 行)、`planner.py`815 行)
- 统一 rollback/quarantine 的 `is_within_root`**安全增强**,非删功能)
- `io.py` 增加 `operation_type` 白名单(**更严校验**
---
## 4. 分阶段实施
### Phase 0 — 准备(0.5h
- [ ] 确认工作区干净或建立分支 `chore/functional-code-trim`
- [ ] 记录基线:`uv run pytest -q` → 517 passed
- [ ] 记录 `uv run vlm --help` 与子命令列表截图或文本(回归对比)
### Phase 1 — 删除零贡献代码(0.5–1h)
| 步骤 | 改动 |
|------|------|
| 1.1 | 删除 `src/vlm/exceptions.py` |
| 1.2 | 删除 `cli.py` `_fallback_plan_summary`L1332/L1451 改用 `preferred_plan_summary`;移除 `fallback_plan_summary` import |
| 1.3 | `pyproject.toml``[dev]` 去掉 `textual`README/CLAUDE 一行说明 TUI 安装方式 |
**验收:**
- [ ] `uv run pytest -q` 全绿
- [ ] `rg "exceptions|_fallback_plan_summary" src tests` 无匹配
### Phase 2 — 文档归档(0.5h
| 步骤 | 改动 |
|------|------|
| 2.1 | 创建 `docs/archive/2026-pre-baseline/README.md`(索引归档原因与日期) |
| 2.2 | `git mv` 第三节所列 markdown 到归档目录 |
| 2.3 | 更新 `README.md`:测试基线 **517**`CLAUDE.md` 补充 `by_reputation_quality_time` |
| 2.4 | `CHANGELOG.md` 增加条目:「文档归档 + 删除未使用 exceptions + CLI 摘要合并」 |
**验收:**
- [ ] 根目录仅保留现行文档(见 3.4
- [ ] 无断链:README 不引用已归档文件名(或改为 archive 链接)
### Phase 3 — CLI 模块化(12d
按 3.5 迁移;每迁一组命令跑一次 targeted tests
```bash
uv run pytest tests/test_cli_review_plan.py tests/test_cli_reports.py \
tests/test_cli_quarantine.py tests/test_cli_state.py tests/test_config.py -q
```
**验收:**
- [ ] 全量 `pytest -q` 517+ passed
- [ ] `uv run vlm --help` 与 Phase 0 命令列表一致
- [ ] `cli.py` 行数 &lt; 400(软目标)
### Phase 4 — 收尾与门禁(0.5h
- [ ] 更新 `AGENTS.md` / `skills/vlm-library-workflow/SKILL.md` 中的模块路径说明(若 CLI 拆分)
- [ ] PR 描述附:删除/归档清单、pytest 输出、`wc -l src/vlm/cli.py` 前后对比
- [ ] 不提交 `artifacts/``.nvimlog``.venv/`
---
## 5. 验证矩阵
| 检查项 | 命令/方法 |
|--------|-----------|
| 单元+集成测试 | `uv run pytest -q` |
| CLI 冒烟 | `uv run vlm --help``config validate``review-plan --help` |
| 可选 TUI 边界 | `uv run pytest tests/test_cli_review_plan.py -q` |
| 无死 import | `rg "vlm\.exceptions"` → 空 |
| 包可安装 | `uv pip install -e .` |
---
## 6. 风险与回滚
| 风险 | 等级 | 缓解 |
|------|------|------|
| 删除 `exceptions.py` 后未来 PR 又引入 import | 低 | PR 门禁 `rg exceptions` |
| `preferred_plan_summary``or _fallback` 空白语义差异 | 低 | 以 tests 为准;`test_plan_render` / report CLI 测试覆盖 |
| CLI 迁移遗漏 `pass_context` / 选项默认值 | 中 | 分命令迁移 + cli 集成测试 |
| 文档归档后外部链接失效 | 低 | archive README 写清迁移;根 README 不链旧文件 |
**回滚:** 按 Phase 逆序 revertPhase 1 可单独 revert 且不影响 Phase 3。
---
## 7. 成功标准(Definition of Done
1. **功能:** 所有现有 `vlm` 子命令、配置键、产物文件名与 schema 行为不变
2. **测试:** `pytest -q` 全绿,数量不低于 517(允许因补测略增)
3. **代码:** 无全仓库零引用 Python 模块;`cli.py` 仅负责注册与委托
4. **文档:** 单一事实来源 = `README` + `CHANGELOG` + `CLAUDE`/`AGENTS`;历史计划进 `docs/archive/`
5. **可维护性:** 新贡献者不再面对 6+ 份互相矛盾的 REVIEW/AUDIT 文档
---
## 8. 工作量估算
| Phase | 估时 | 可独立合并 |
|-------|------|------------|
| 0 准备 | 0.5h | — |
| 1 删死代码 | 0.51h | ✅ 建议首 PR |
| 2 文档归档 | 0.5h | ✅ 可与 Phase 1 同 PR |
| 3 CLI 拆分 | 12d | ✅ 单独 PR |
| 4 收尾 | 0.5h | 随 PR |
**合计:** 约 2–3 个工作日(含 review),若只做 Phase 1+2 约 **半天**
---
## 9. 建议 PR 拆分
| PR | 内容 | 标题示例 |
|----|------|----------|
| PR-1 | Phase 1 + 2 | `chore: remove unused code and archive stale docs` |
| PR-2 | Phase 3 | `refactor: extract remaining CLI commands to commands/` |
| PR-3(可选) | Phase 2 计划 3.6 | `refactor: split quarantine and align path guards` |
---
## 10. 执行后预期指标
| 指标 | 当前 | Phase 1+2 后 | Phase 3 后 |
|------|------|--------------|------------|
| `src/vlm/*.py` 模块数 | 36 | 35-exceptions | 35 + 4~5 command 模块 |
| `cli.py` 行数 | ~1941 | ~1935 | ~300400 |
| 根目录 *.md(审查类) | ~12 | 0(已归档) | 0 |
| pytest | 517 | 517 | 517 |
---
*本计划只覆盖「删无贡献 + 合重复 + 搬 CLI」;更深的安全加固与 domain 文件拆分见后续 `plans/2026-*-phase2-internal-split-v1.md`(待 Phase 13 完成后再写)。*