Files
awoooi/docs/ARCHITECTURE_CODE_REVIEW.md
OG T 7478dc0254 feat(phase6-9): Complete modular architecture and Agent Teams
Phase 6.4 - Modular Architecture:
- Add lewooogo-brain adapters for LLM providers
- Add lewooogo-data dual memory (Redis + PostgreSQL)
- Implement consensus engine for multi-agent decisions
- Add incident memory service for historical context

Phase 9 - Agent Teams (Claude Agent SDK):
- Add base agent class with Claude Sonnet 4 integration
- Implement action planner, blast radius, and security agents
- Add agent API endpoints and proposal workflow
- Integrate ADR-009 OpenClaw Agent Teams architecture

DevOps & CI/CD:
- Add GitHub Actions CI/CD workflows (ci.yaml, cd.yaml)
- Add pre-commit hooks and secrets baseline
- Add docker-compose for local development
- Update Kubernetes network policies

Frontend Improvements:
- Add auto-healing error boundary component
- Update i18n messages for agent features
- Enhance dual-state incident card with execution feedback

Documentation:
- Add 7 ADRs covering MCP, design system, architecture decisions
- Update ARCHITECTURE_MEMORY.md with modular design
- Add GLOBAL_RULES.md and SOUL.md for project identity

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-03-23 18:40:36 +08:00

175 lines
8.6 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AWOOOI 專案架構與程式碼審查報告 (Architecture & Code Review)
## 1. 專案總覽 (Project Overview)
AWOOOI 是一個由 AI 驅動的智能運維平台 (AI+WOOO Intelligent Operations Platform)主打「Zero-Touch Ops. Human-Centric Decisions」。專案採用 Turborepo 建構的 Monorepo 架構,包含四大核心支柱:**Privacy Shield (隱私保護)**、**GraphRAG (拓撲感知情報)**、**Multi-Sig & Dry-Run (多重簽核與防禦)**、以及 **Progressive Autonomy (漸進式自治)**
### 技術棧 (Tech Stack)
- **Backend (apps/api)**: FastAPI, Python 3.11+, PostgreSQL, Redis, structlog, OpenTelemetry。
- **Frontend (apps/web)**: Next.js 14, React 18, Tailwind CSS, Zustand, React-Query。
- **Workspace**: pnpm + Turborepo抽出共用模組 `@awoooi/lewooogo-core`
---
## 2. 核心架構審查 (Architecture Review)
### 2.1 Backend (leWOOOgo Engine)
API 服務設計為高度模組化的 BFF (Backend For Frontend) 架構,並嚴格遵循四大鐵律 (Async-First, CORS Whitelist, Pydantic Config, Structured Logging)。
- **可觀測性先行**: 於 `main.py`OpenTelemetry 的初始化被置於啟動流程與 Middleware 的最前方,確保 Request 全生命週期的追蹤,這是極其優秀的企業級實踐。
- **生命週期管理 (Lifespan)**: 妥善利用 FastAPI 的 `@asynccontextmanager` 來管理資料庫連線、HTTP Clients Pooling 以及 SSE Publisher 的啟動與優雅關閉 (Graceful Shutdown)避免資源洩漏Memory Leaks
### 2.2 Frontend (Web App)
- **狀態管理**: 採用 `zustand` 進行元件外部的狀態管理 (`agent.store.ts`),特別針對 Server-Sent Events (SSE) 實作了專屬的 Buffer 累積機制。這能有效防止 TCP 封包切斷導致後端流式輸出的 JSON 解析錯誤,這在串流顯示 AI 思考過程 (Thinking Stream) 時非常關鍵。
- **嚴謹的環境變數字典**: 程式碼中 (如 `getApiBaseUrl`) 嚴格禁止了 Fallback IP 的濫用,強制拋出錯誤並依賴 `NEXT_PUBLIC_API_URL`,這確保了開發、測試與生產環境的絕對隔離。
---
## 3. 核心模組程式碼深潛審查 (Core Modules Deep Dive)
### 3.1 Multi-Sig Engine (`approval.py`)
- **亮點**: 實作了極具資安意識的 **TOCTOU (Time-of-Check to Time-of-Use) 防護**。在收集完所有高權限使用者的簽章、準備真正執行指令前,系統會強制對目標資源再次呼叫 `dry_run_engine.evaluate` 來檢查狀態是否發生過偏移。
- **合規性稽核**: 當發生 TOCTOU 衝突時,系統不會鴕鳥心態地直接清空簽章,而是將審批狀態明確標記為 `VOIDED` 並保留所有簽核歷史,完全符合金融與企業環境對資安稽核 (Audit Trail) 的要求。
- **設計模式**: 採用清晰的 In-Memory 狀態機與 Strategy Pattern 來實作不同風險層級 (Risk Matrix) 的簽核門檻。
### 3.2 GraphRAG Engine (`graph_rag.py`)
- **亮點**: 實作了強大且雙向的圖形遍歷演算法 (BFS-based traversal)。
- **Blast Radius (向上追溯)**: 準確計算「若特定服務掛掉,哪些上游服務將作為受災戶被連帶波及」。
- **Root Cause (向下追溯)**: 當服務報錯時,從異常節點往下找尋發生故障的根本原因,並具備優先權排序演算法 (DB > CACHE > QUEUE)。
- **效能考量**: 演算法中引入了 `max_depth` 限制,防止在大型 Kubernetes 叢集中發生圖遍歷的無限遞迴擴散,顯示出高度的工程成熟度。
---
## 4. 總結與改進建議 (Conclusion & Recommendations)
AWOOOI 的整體程式碼品質極高,充分展現了「企業級系統」應有的嚴謹度,特別是在異常處理、資安防護與微服務架構解耦上做得很到位。
**未來潛在改善點 (Tech Debt & Roadmap)**
1. **狀態持久化 (Persistence)**: 目前 `MultiSigEngine``TopologyGraph` 皆依賴 In-Memory (`dict`) 作為儲存。進入 Phase 4/5 生產環境硬化時,應盡快置換為 Redis (用於分散式鎖與簽核狀態共用) 與 Graph Database (如 Neo4j) 以應對多實例高可用部署 (Horizontal Scaling)。
2. **容錯與重試恢復 (Resilience)**: 在前端 SSE 串流部分,雖然處理了 AbortController 手動中斷,但可考慮加入對底層網路不穩時的自動重連機制與 Exponential Backoff 策略,進一步提升運維戰情室的體驗韌性。
---
## 5. 優化方案與解決策略 (Optimization Solutions)
### 5.1 問題與解決方案對照表
| # | 類別 | 問題 | 解決方案 | 優先級 | 規劃狀態 |
|---|------|------|----------|--------|----------|
| **1** | 狀態持久化 | `MultiSigEngine` 使用 In-Memory `dict` | 改用 **Redis** 實作分散式鎖與簽核狀態共用 | 🔴 P0 | ⚪ Phase 6.1.1 |
| **2** | 狀態持久化 | `TopologyGraph` 使用 In-Memory `dict` | 導入 **Neo4j / Redis Graph** 支援多實例 HA | 🔴 P0 | ⚪ Phase 6.1.2 |
| **3** | 容錯機制 | SSE 串流無自動重連 | 加入 **Exponential Backoff** + Auto-Reconnect | 🟡 P1 | ✅ ADR-004 已規劃 |
| **4** | 水平擴展 | 單實例限制 | Redis 分散式鎖 + Sticky Session 或 Redis Pub/Sub | 🟡 P1 | ⚪ Phase 6.3 |
> **備註**: 第 3 項 SSE 容錯機制已在 [ADR-004](adr/ADR-004-state-management.md) 定義完整規格 (Line 228-236),待驗證實作狀態。
---
### 5.2 詳細解決方案 (Implementation Details)
#### 5.2.1 Redis 狀態持久化 (Multi-Sig Engine)
```python
# apps/api/src/services/multi_sig_redis.py
import redis.asyncio as redis
from pydantic import BaseModel
from datetime import datetime
class ApprovalState(BaseModel):
request_id: str
status: str # PENDING | APPROVED | VOIDED
signatures: list[dict]
created_at: datetime
async def save_approval(r: redis.Redis, state: ApprovalState):
key = f"approval:{state.request_id}"
await r.hset(key, mapping=state.model_dump_json())
await r.expire(key, 86400 * 7) # 7 days TTL for audit
```
#### 5.2.2 Neo4j 圖資料庫 (GraphRAG Engine)
```python
# apps/api/src/services/graph_rag_neo4j.py
from neo4j import AsyncGraphDatabase
async def get_blast_radius(driver, service_id: str, max_depth: int = 5):
query = """
MATCH path = (s:Service {id: $service_id})<-[:DEPENDS_ON*1..$max_depth]-(affected)
RETURN affected.id, length(path) as depth
ORDER BY depth
"""
async with driver.session() as session:
result = await session.run(query, service_id=service_id, max_depth=max_depth)
return [record async for record in result]
```
#### 5.2.3 SSE 自動重連 + Exponential Backoff
```typescript
// apps/web/src/hooks/useSSEReconnect.ts
import { useState, useCallback } from 'react';
export function useSSEWithReconnect(url: string) {
const [retryCount, setRetryCount] = useState(0);
const maxRetries = 5;
const connect = useCallback(() => {
const eventSource = new EventSource(url);
eventSource.onerror = () => {
eventSource.close();
if (retryCount < maxRetries) {
const delay = Math.min(1000 * Math.pow(2, retryCount), 30000);
setTimeout(() => {
setRetryCount(prev => prev + 1);
connect();
}, delay);
}
};
eventSource.onopen = () => setRetryCount(0);
return eventSource;
}, [url, retryCount]);
return { connect, retryCount };
}
```
---
### 5.3 實作優先順序 (Implementation Roadmap)
| Phase | 項目 | 預估工時 | 狀態 | 對應任務 |
|-------|------|----------|------|----------|
| **Phase 6.1.1** | Redis Multi-Sig 持久化 | 2 天 | ⚪ 規劃中 | 簽核狀態 + TTL 7d |
| **Phase 6.1.2** | Neo4j GraphRAG 遷移 | 3 天 | ⚪ 規劃中 | Blast Radius 查詢 |
| **Phase 6.1.3** | Redis 分散式鎖 | 1 天 | ⚪ 規劃中 | Redlock 演算法 |
| **Phase 6.2** | SSE 容錯驗證 | 1.5 天 | ✅ ADR-004 | 驗證 Backoff/Heartbeat |
| **Phase 6.3** | 水平擴展 | 3 天 | ⚪ 規劃中 | Redis Pub/Sub + Sticky Session |
> **依賴**: Phase 6 需等待 Phase 5 (OpenClaw 實體化) 完成後執行。
---
## 6. 審查結論 (Review Conclusion)
本次架構審查確認 AWOOOI 具備企業級系統的核心素質,主要技術債集中於 **狀態持久化****水平擴展** 兩大領域。
### 關鍵發現
| 類別 | 結論 |
|------|------|
| **SSE 容錯** | ✅ 已在 ADR-004 完整規劃,待驗證實作 |
| **狀態持久化** | ⚪ 新需求,已納入 Phase 6.1 |
| **水平擴展** | ⚪ 新需求,已納入 Phase 6.3 |
### 執行順序
```
Phase 5 (OpenClaw 實體化) → Phase 6 (架構硬化)
↓ ↓
Telegram Gateway Redis + Neo4j + HA
```
**審查日期**: 2026-03-22
**審查人員**: Claude Code (Architecture Review Agent)
**更新紀錄**: Phase 6 任務已同步至 `memory/project_phases.md`