# 模組化治理指南 > 目的:讓 EwoooC 後續功能不再回到「單一巨檔、分類不清、共用邏輯複製貼上」的狀態。 ## 分層規則 | 層級 | 放什麼 | 不放什麼 | |---|---|---| | `app.py` | Flask 初始化、Blueprint 註冊、啟動自檢、版本 | route 實作、DB 查詢、商業邏輯、排程任務 | | `routes/` | HTTP request/response、表單參數解析、權限 decorator、呼叫 service | 大量資料轉換、外部 API client、可重用計算 | | `services/` | 商業邏輯、AI pipeline、外部 API client、報表生成、可重用流程 | Flask request 物件、template rendering、route-only glue | | `database/` | ORM models、DB manager、schema helpers、migration baseline | HTTP/Telegram/AI side effect | | `utils/` | 無狀態純工具、字串/時間/安全 helper | 需要 DB/session/env-heavy 的流程 | | `templates/` | Jinja UI | Python business rule | ## 檔案尺寸規則 - 300 行以下:健康範圍。 - 300-600 行:可接受,但新增功能前要確認是否能抽 service/helper。 - 600-800 行:警戒範圍;PR/commit 需說明為何不拆。 - 800 行以上:技術債範圍;只能做 bugfix、安全修補、或「往外抽」的過渡改動。新增功能應先拆模組。 - 新增超過 800 行的 Python 檔案必須更新 `docs/memory/code_modularization_inventory_20260430.md`,否則 `tests/test_modularization_governance.py` 會失敗。 ## 新功能落點決策 1. 先問:這是 HTTP endpoint、商業流程、DB access、外部 API、還是純工具? 2. endpoint 只新增到對應 Blueprint,不新增到 `app.py`。 3. route 內超過 40 行的資料處理,優先抽到 `services/`。 4. 兩個以上 route 需要同一段邏輯時,第一次就抽 shared service,不複製貼上。 5. service 需要 DB 時,透過既有 `DatabaseManager` / repository-style helper,不在 route 裡反覆建立 engine。 6. AI 自動化、告警、自癒相關變更需同步檢查 `docs/AI_INTELLIGENCE_MODULE_SOT.md`。 ## 拆大檔順序 優先處理「又大又承擔多種責任」的檔案: 1. `routes/openclaw_bot_routes.py`:拆成 route、bot command service、learning/report service、scheduler hook。 2. `routes/sales_routes.py`:拆 dashboard/page routes、API routes、chart/query service。 3. `scheduler.py`:拆 task registry、crawler jobs、report jobs、notification jobs。 4. `routes/ai_routes.py` / `routes/vendor_routes.py`:把資料處理與整合邏輯移到 services。 5. `services/ppt_generator.py`:拆 deck orchestration、chart builders、slide templates。 ## Review 檢查表 - 是否新增 `@app.route`?若是,退回改 Blueprint。 - route 是否直接包含大量 SQL、DataFrame、AI prompt 組裝或外部 API 呼叫?若是,抽 service。 - 是否讓既有 >800 行檔案淨增加?若是,先抽模組或更新 inventory 與拆分計畫。 - 是否新增重複 cache / DB manager / Telegram / AI client 初始化?若是,改用既有 service。 - 是否需要更新 ADR、memory、SOT 或 guide?若是,本次 commit 一起更新。