feat(governance): AI 治理事件處理鏈四軌交付(C/D/B/A)
Some checks failed
Code Review / ai-code-review (push) Successful in 48s
run-migration / migrate (push) Failing after 45s
CD Pipeline / tests (push) Successful in 3m46s
Type Sync Check / check-type-sync (push) Successful in 2m8s
CD Pipeline / build-and-deploy (push) Failing after 31m14s
CD Pipeline / post-deploy-checks (push) Has been skipped
Some checks failed
Code Review / ai-code-review (push) Successful in 48s
run-migration / migrate (push) Failing after 45s
CD Pipeline / tests (push) Successful in 3m46s
Type Sync Check / check-type-sync (push) Successful in 2m8s
CD Pipeline / build-and-deploy (push) Failing after 31m14s
CD Pipeline / post-deploy-checks (push) Has been skipped
【十二人專家團隊全景掃描 + 並行四軌實施】
統帥質疑「有讓 12-agent 一起協作嗎」後,依照團隊規則完成全鏈路交付:
onboarder + critic + db-expert + debugger + frontend-designer 並行掃描,
找到 6 大 Gap,再由 fullstack-engineer × 4、refactor-specialist 協作落地。
【Track C — trust_drift 雙寫整併】
兩條獨立寫 event_type=trust_drift 路徑互不呼叫,下游 consumer 拿到雙份資料
無法判定 source-of-truth。整併保留 governance_agent.check_trust_drift(功能
更全:auto-deprecate + Telegram + PG),TrustDriftDetector 降為純統計 lib,
W-6 watchdog 改呼叫 governance_agent。新增 TestSinglePgWritePerDriftScenario
驗證同一 drift 場景只觸發一次 PG 寫入。
變更:
- apps/api/src/services/trust_drift_detector.py(lib only,不再寫 PG)
- apps/api/tests/test_trust_drift_watchdog.py(W-6 改 mock governance_agent)
【Track D — governance_remediation_dispatch 派遣表】
ai_governance_events 是不可變 Event Sourcing,不能塞執行狀態。新建派遣表
作為投影層:1 event → 0..N dispatches,狀態可變、可重試、可審計。
- PgEnum 5 種 event_type + 7 階段狀態機(pending → dispatched → executing →
succeeded/failed/cancelled/skipped)
- 失敗重試 INSERT 新 row(不改舊 row 的 status,保留審計痕跡)
- Partial unique index ux_grd_one_active_per_event 強制「同事件唯一活躍」
- 4 個複合 index 支援 worker poll、去重查詢、觀測面板
- FK 對應 ai_governance_events / playbooks / incidents / approval_records
全部 SET NULL(avoid cascade lock,但 governance_event 用 RESTRICT)
變更:
- apps/api/src/db/models.py(GovernanceRemediationDispatch ORM class)
- apps/api/migrations/governance_remediation_dispatch_2026-05-03.sql
- apps/api/src/repositories/governance_remediation_dispatch_repo.py
(6 個 async 函式 + 3 個自訂例外:DispatchAlreadyActive /
InvalidStatusTransition / DispatchNotFound)
- apps/api/src/models/governance_dispatch.py(DecisionContextV1 等 4 schema)
- apps/api/tests/test_governance_remediation_dispatch.py(29 tests)
【Track B — /governance 頁面】
後端 PR1 三個 endpoint + 前端 PR2-5 完整三 Tab。
PR1 後端:
- GET /api/v1/ai/governance/events(events_tab,含 event_type/severity/
狀態/時間範圍篩選 + 分頁)
- GET /api/v1/ai/governance/queue(queue_tab,含 graceful fallback:
dispatch 表不存在時回 table_pending=True 不拋 500)
- GET /api/v1/ai/governance/summary(slo_tab 30d 違反時序圖)
- severity 映射規則寫死(critic 建議未來移 settings)
PR2-5 前端:
- /governance 路由 + AppLayout + Compliance Badge 橫幅 + PageTabs
- SLO Tab:3 KPI 卡片(Syne 28px + StatusOrb + 7d sparkline)+
30d 違反 stacked BarChart
- Events Tab:篩選列 + 表格 + inline 展開行(JSON / 修復建議 / 派遣記錄)
- Queue Tab:HITL 待辦卡片 + 信任度進度條 + 批准/拒絕按鈕(本 PR console.log)
- Sidebar 加入「AI 治理」入口(ShieldCheck icon)
- i18n 雙語完整(governance namespace + nav.governance)
- 7 個新元件:slo-kpi-card / slo-violation-chart / events-table /
events-filter-bar / event-detail-drawer / queue-item-card / queue-history-tabs
變更:
- apps/api/src/api/v1/ai_governance.py(router)
- apps/api/src/services/governance_query_service.py
- apps/api/src/models/governance.py(Pydantic V2 schemas)
- apps/api/tests/test_ai_governance_endpoints.py(21 tests)
- apps/web/src/app/[locale]/governance/(page + 3 tabs)
- apps/web/src/components/governance/(7 元件)
- apps/web/messages/{zh-TW,en}.json(governance namespace)
- apps/web/src/components/layout/sidebar.tsx(+1 行)
- apps/api/src/main.py(router include)
【Track A — GovernanceDispatcher 決策融合】
把治理事件接到 remediation 執行器,走北極星方向決策融合(LLM × Playbook trust
× MCP),符合「禁寫死規則」鐵律。
- 設計鐵律:DecisionFusionAdapter 是新增 wrapper,**不修改任何 Tier 3 檔**
(decision_manager / learning_service / trust_engine),只 consume 既有 API
- 三維融合公式:confidence = 0.4×llm + 0.3×playbook_trust + 0.3×mcp_consistency
(權重加 TODO 標明未來由 AI 自學調整)
- 三分支決策路徑:
confidence ≥ 0.85 → auto_dispatch(status=dispatched)
0.65 ≤ confidence < 0.85 → pending_approval(HITL)
confidence < 0.65 → skip + log
- decision_context JSONB 完整記錄三維輸入快照(給未來 fine-tune 用)
- poll 30s 掃 unresolved 事件,仿 governance loop 模式
- 重複事件擋去重(呼叫 get_active_for_event)
變更:
- apps/api/src/services/governance_dispatcher.py
- apps/api/src/services/decision_fusion_adapter.py
- apps/api/tests/test_governance_dispatcher.py(14 tests)
- apps/api/src/main.py(lifespan task 接 run_governance_dispatcher_loop)
【驗證】
1836 個 unit test 全過(29 skipped 為既有 PG integration env 問題)
【調度教訓 — 已記入 memory】
- vuln-verifier 應在 fullstack-engineer **之前**跑(避免並行讀到已修代碼誤判)
- critic 雙輪審查不可省(第二輪抓到 NaN sentinel + Prom rule 連鎖)
- 北極星「禁寫死規則」搭配 decision-fusion 確實實施
【未動 Tier 3 — 已驗證】
git diff 確認本 commit 完全沒改 decision_manager.py / learning_service.py /
trust_engine.py,只新增 wrapper service consume 既有 API。
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
124
apps/api/src/models/governance.py
Normal file
124
apps/api/src/models/governance.py
Normal file
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
Governance API Models — /governance 頁面 Pydantic Schemas
|
||||
=========================================================
|
||||
PR 1 後端 3 endpoint 的 request/response schema.
|
||||
|
||||
Endpoints:
|
||||
GET /api/v1/ai/governance/events — ai_governance_events 查詢
|
||||
GET /api/v1/ai/governance/queue — governance_remediation_dispatch 隊列(Track D 依賴表)
|
||||
GET /api/v1/ai/governance/summary — 30d SLO 違反時序統計
|
||||
|
||||
設計原則:
|
||||
- Pydantic V2,對齊 models/ 目錄
|
||||
- Severity 映射邏輯集中於此,Router / Service 直接用
|
||||
- 禁止硬編碼 IP 或內網位址
|
||||
|
||||
2026-05-02 ogt + Claude Sonnet 4.6 Asia/Taipei
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# =============================================================================
|
||||
# Severity 映射
|
||||
# =============================================================================
|
||||
|
||||
# critical: slo_violation / conservative_mode / governance_slo_data_gap
|
||||
# warning: trust_drift / kb_stale / knowledge_degradation / execution_blast_radius
|
||||
# info: 其他(含 replay_degraded / self_demotion / llm_hallucination 等)
|
||||
|
||||
_CRITICAL_TYPES: frozenset[str] = frozenset({
|
||||
"slo_violation",
|
||||
"conservative_mode",
|
||||
"governance_slo_data_gap",
|
||||
})
|
||||
|
||||
_WARNING_TYPES: frozenset[str] = frozenset({
|
||||
"trust_drift",
|
||||
"kb_stale",
|
||||
"knowledge_degradation",
|
||||
"execution_blast_radius",
|
||||
})
|
||||
|
||||
|
||||
def map_severity(event_type: str) -> Literal["critical", "warning", "info"]:
|
||||
"""將 event_type 映射為 severity 等級."""
|
||||
if event_type in _CRITICAL_TYPES:
|
||||
return "critical"
|
||||
if event_type in _WARNING_TYPES:
|
||||
return "warning"
|
||||
return "info"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Endpoint 1: events
|
||||
# =============================================================================
|
||||
|
||||
class GovernanceEvent(BaseModel):
|
||||
id: str
|
||||
event_type: str
|
||||
severity: Literal["critical", "warning", "info"]
|
||||
triggered_at: datetime
|
||||
resolved: bool
|
||||
resolved_at: datetime | None = None
|
||||
impact: str = Field(description="≤80 字摘要,從 details 抽取")
|
||||
details: dict
|
||||
remediation: str | None = None
|
||||
dispatch_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class GovernanceEventsResponse(BaseModel):
|
||||
items: list[GovernanceEvent]
|
||||
total: int
|
||||
page: int
|
||||
size: int
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Endpoint 2: queue
|
||||
# =============================================================================
|
||||
|
||||
class DispatchItem(BaseModel):
|
||||
id: str
|
||||
governance_event_id: str
|
||||
event_type: str
|
||||
dispatch_status: str
|
||||
proposed_action: str = Field(description="≤120 字動作摘要")
|
||||
playbook_id: str | None = None
|
||||
playbook_trust: float | None = Field(default=None, ge=0.0, le=1.0)
|
||||
created_at: datetime
|
||||
dispatched_at: datetime | None = None
|
||||
completed_at: datetime | None = None
|
||||
operator_note: str | None = None
|
||||
|
||||
|
||||
class GovernanceQueueResponse(BaseModel):
|
||||
items: list[DispatchItem]
|
||||
total: int
|
||||
page: int
|
||||
size: int
|
||||
table_pending: bool = Field(
|
||||
default=False,
|
||||
description="dispatch 表尚未建立時為 True",
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Endpoint 3: summary
|
||||
# =============================================================================
|
||||
|
||||
class DailyCount(BaseModel):
|
||||
date: str = Field(description="YYYY-MM-DD")
|
||||
total: int
|
||||
by_type: dict[str, int] = Field(description="{event_type: count}")
|
||||
|
||||
|
||||
class GovernanceSummaryResponse(BaseModel):
|
||||
compliance_rate: float = Field(description="0.0-1.0,1 - unresolved/total")
|
||||
total_events: int
|
||||
unresolved_count: int
|
||||
daily_counts: list[DailyCount]
|
||||
Reference in New Issue
Block a user