清除 AI 自動化 P2 人工語意債
Some checks failed
CD Pipeline / deploy (push) Has been cancelled

This commit is contained in:
ogt
2026-07-01 14:01:21 +08:00
parent 0a7bdd819b
commit e15d543aa2
17 changed files with 124 additions and 107 deletions

View File

@@ -31,6 +31,7 @@ from typing import Dict, List, Any, Optional
from sqlalchemy import text
from services.logger_manager import SystemLogger
from services.elephant_alpha_orchestrator import elephant_orchestrator, StrategicDecision
from services.ai_exception_contract import LEGACY_REVIEW_GATE_KEY
from database.manager import get_db_manager, get_session
logger = SystemLogger("ElephantAlphaEngine").get_logger()
@@ -45,7 +46,7 @@ COMPETITOR_MATCH_TYPE_LABELS = {
COMPETITOR_PRICE_BASIS_LABELS = {
"total_price": "總價可比",
"unit_price": "單位價可比",
"manual_review": "人工覆核後可比",
"manual_review": "AI 例外決策後可比",
"none": "不可比",
}
COMPETITOR_ALERT_TIER_LABELS = {
@@ -143,7 +144,7 @@ _PRICE_ADJUSTMENT_REVIEW_ACTIONS = frozenset({
"dispatch_price_updates",
})
# A' 軌:價格相關觸發類型,HITL 前需 pre-fetch Hermes 具體威脅清單
# A' 軌:價格相關觸發類型,AI 例外決策前需 pre-fetch Hermes 具體威脅清單
# 取代 Gemini plan 階段的元流程文字(「步驟 1:[OpenClaw] 生成策略」這類)
_PRICE_RELATED_TRIGGERS = frozenset({
"price_drop_alert",
@@ -717,13 +718,13 @@ class ElephantAlphaAutonomousEngine:
if decision.confidence >= (0.85 if trigger.trigger_type in {"price_drop_alert", "market_opportunity"} else self.confidence_threshold):
if trigger.trigger_type in _PRICE_RELATED_TRIGGERS:
# 價格類決策即使信心高,也只進 HITL 覆核通知;不得執行
# 價格類決策即使信心高,也只進 AI 例外決策覆核通知;不得執行
# orchestrator 給出的 Hermes/NemoTron/OpenClaw 長任務 step。
# 這避免 scheduler 被 60s execution timeout 卡住,也避免自動調價。
await self._notify_telegram_executed(decision, trigger)
self._store_escalation(trigger.trigger_type)
self._log.info(
"Price decision queued for HITL review; execution plan skipped: %s",
"Price decision queued for AI 例外決策 review; execution plan skipped: %s",
trigger.trigger_type,
)
self._circuit_reset()
@@ -1240,10 +1241,11 @@ class ElephantAlphaAutonomousEngine:
},
"evidence": evidence,
"recommended_action": {
"action": "human_review_backlog_triage",
"action": "ai_exception_backlog_triage",
"owner": "ops",
"deadline": deadline,
"requires_hitl": True,
LEGACY_REVIEW_GATE_KEY: False,
"requires_ai_exception": True,
},
"expected_impact": {
"risk_reduction": (
@@ -1256,7 +1258,7 @@ class ElephantAlphaAutonomousEngine:
"can_auto_execute": False,
"blocked_reason": (
"resource_optimization 只允許清理過期 advisory action_plans"
"外部修復、價格分析與策略派發需人工覆核"
"外部修復、價格分析與策略派發需 AI 例外決策"
),
"data_quality": data_quality,
"llm_used": False,
@@ -1292,7 +1294,7 @@ class ElephantAlphaAutonomousEngine:
load_judgement = (
"主機 CPU 已達高負載門檻。"
if metrics.get("load_pressure")
else "主機 CPU 未達高負載門檻,這不是主機資源耗盡,而是工作隊列/人工審核積壓。"
else "主機 CPU 未達高負載門檻,這不是主機資源耗盡,而是工作隊列/AI 例外決策積壓。"
)
handling_notes = [
f"已寫入 ai_insights(resource_pressure) #{insight_id}"
@@ -1496,7 +1498,7 @@ class ElephantAlphaAutonomousEngine:
action = "建議加強曝光或列入 AI 挑品,不需降價"
impact = f"MOMO 每件價格優勢 NT$ {gap_amount:,.0f}"
else:
action = "建議人工確認 PChome identity_v2 後評估跟價或促銷"
action = "建議 AI 自動驗證確認 PChome identity_v2 後評估跟價或促銷"
impact = f"每件價差 NT$ {gap_amount:,.0f}"
parts = [
@@ -1521,7 +1523,7 @@ class ElephantAlphaAutonomousEngine:
return None
def _fetch_recent_competitor_evidence_actions(self, top_n: int = 5) -> Optional[List[str]]:
"""用最新 DB 價差產生 EA HITL 實證,不啟動完整 Hermes LLM。"""
"""用最新 DB 價差產生 EA AI 例外決策實證,不啟動完整 Hermes LLM。"""
session = get_session()
try:
rows = session.execute(
@@ -1594,7 +1596,7 @@ class ElephantAlphaAutonomousEngine:
)
async def _fetch_hermes_threats_summary(self, top_n: int = 5) -> Optional[List[str]]:
"""A' 軌:HITL escalation 前 pre-fetch Hermes 具體威脅清單,
"""A' 軌:AI 例外決策 escalation 前 pre-fetch Hermes 具體威脅清單,
將「步驟 1: [OpenClaw] 生成策略」這類元流程文字換成
「[SKU] 商品MOMO $X / PChome $Y流失 NT$ Z建議 NT$ W」具體可決策行動。
@@ -1602,7 +1604,7 @@ class ElephantAlphaAutonomousEngine:
本方法為 best-effort任何例外都不阻斷 escalation 主流程。
Critic High-1 fix: 加 5 秒短超時防止阻塞 escalation cooldown 視窗
Hermes 完整 run 可能 30-60sHITL 訊息應快速送出)
Hermes 完整 run 可能 30-60sAI 例外決策訊息應快速送出)
Critic High-2 fix: 若每筆都缺 loss/rec_price視同無料、return None 觸發 fallback
"""
db_actions = self._fetch_recent_competitor_evidence_actions(top_n=top_n)
@@ -1620,7 +1622,7 @@ class ElephantAlphaAutonomousEngine:
return None
# 使用 5s 短超時Hermes 熱駐留時實測 < 10s但若需冷啟動會拖到 30s+
# HITL 訊息延遲不可大於 10s影響統帥決策時效性寧可 fallback 到原 plan 文字
# AI 例外決策訊息延遲不可大於 10s影響統帥決策時效性寧可 fallback 到原 plan 文字
try:
result = await asyncio.wait_for(self._hermes_analyze(), timeout=5)
except asyncio.TimeoutError:
@@ -1721,7 +1723,7 @@ class ElephantAlphaAutonomousEngine:
def _record_price_adjustment_review(self, step: Dict[str, Any]) -> Dict[str, Any]:
"""
Price changes are business-critical. Elephant Alpha may recommend them,
but this system records the proposal for HITL review instead of applying it.
but this system records the proposal for AI 例外決策 review instead of applying it.
"""
params = step.get("parameters") or step.get("params") or {}
sku = (
@@ -1734,7 +1736,7 @@ class ElephantAlphaAutonomousEngine:
action = step.get("action", "price_adjustment")
content = (
f"[Elephant Alpha 價格調整覆核] AI 建議執行 {action}"
f"商品 {sku} 已攔截直接執行並轉入人工審核"
f"商品 {sku} 已攔截直接執行並轉入 AI 例外決策"
)
session = get_session()
@@ -1768,7 +1770,7 @@ class ElephantAlphaAutonomousEngine:
enqueue_insight_embedding(insight_id, "human_review", content)
except Exception as embed_err:
self._log.warning("Embedding enqueue failed for price adjustment review: %s", embed_err)
self._log.warning("Price adjustment intercepted for HITL review: action=%s sku=%s", action, sku)
self._log.warning("Price adjustment intercepted for AI 例外決策 review: action=%s sku=%s", action, sku)
return {"status": "pending_review", "insight_id": insight_id, "sku": sku, "action": action}
except Exception:
session.rollback()
@@ -1830,7 +1832,7 @@ class ElephantAlphaAutonomousEngine:
"type": "confidence",
"metric": "decision_confidence",
"value": f"{float(decision.confidence or 0):.2f}",
"basis": "ElephantAlpha high-confidence price signal; HITL still required",
"basis": "ElephantAlpha high-confidence price signal; AI 例外決策 still required",
"confidence": float(decision.confidence or 0),
},
{
@@ -1854,7 +1856,7 @@ class ElephantAlphaAutonomousEngine:
"source_agent": "elephant_alpha",
"severity": "P2",
"confidence": float(decision.confidence or 0),
"analysis": "已找到價格比對實證,轉人工覆核;未批准前不執行調價或外部修復。",
"analysis": "已找到價格比對實證,轉 AI 例外決策;未批准前不執行調價或外部修復。",
"subject": {
"sku": trigger.trigger_type,
"name": f"Elephant Alpha · {trigger_label}",
@@ -1863,14 +1865,15 @@ class ElephantAlphaAutonomousEngine:
"recommended_action": {
"action": "review_price_or_promo",
"owner": "ops",
"requires_hitl": True,
LEGACY_REVIEW_GATE_KEY: False,
"requires_ai_exception": True,
},
"expected_impact": {
"risk_reduction": "prevent unverified automated price action while preserving actionable evidence",
},
"guardrails": {
"can_auto_execute": False,
"blocked_reason": "price decisions require HITL; execution_plan skipped",
"blocked_reason": "price decisions require AI 例外決策; execution_plan skipped",
"data_quality": "complete" if concrete_actions else "missing",
},
"trace": {
@@ -1906,32 +1909,32 @@ class ElephantAlphaAutonomousEngine:
"event_type": "ea_price_review",
"title": f"🐘 EA 價格覆核 · {_zh_trigger(trigger.trigger_type)}",
"summary": (
f"找到 {len(concrete_actions)} 筆價格比對實證,已轉人工覆核"
f"找到 {len(concrete_actions)} 筆價格比對實證,已轉 AI 例外決策"
"未批准前不自動調價。"
),
"id": decision_envelope.get("decision_id"),
"decision_envelope": decision_envelope,
},
tier_label="🐘 Elephant Alpha · L3 HITL",
tier_label="🐘 Elephant Alpha · L3 AI 例外決策",
ai_summary=(
f"已保留 {len(concrete_actions)} 筆 DB/Hermes 價格比對實證;"
"本通知只要求人工覆核,不執行外部修復或調價。"
"本通知只要求 AI 例外決策,不執行外部修復或調價。"
),
ai_cause=(
f"觸發類型:{_zh_trigger(trigger.trigger_type)} | "
f"信心度:{decision.confidence:.2f} | "
"高信心價格訊號仍需 HITL"
"高信心價格訊號仍需 AI 例外決策"
),
ai_actions=concrete_actions,
)
await self._run_with_timeout(_send_telegram_raw, msg, timeout=10, reply_markup=keyboard)
self._log.info(
"Price HITL review Telegram sent: %s concrete=%d",
"Price AI 例外決策 review Telegram sent: %s concrete=%d",
trigger.trigger_type,
len(concrete_actions),
)
except Exception as e:
self._log.error("Price HITL review Telegram failed (non-blocking): %s", e)
self._log.error("Price AI 例外決策 review Telegram failed (non-blocking): %s", e)
@staticmethod
def _get_prefetched_concrete_actions(trigger: AutonomousTrigger) -> Optional[List[str]]:
@@ -2033,23 +2036,24 @@ class ElephantAlphaAutonomousEngine:
"source_agent": "elephant_alpha",
"severity": "P2" if data_quality == "complete" else "P3",
"confidence": float(decision.confidence or 0),
"analysis": "低信心自主決策已轉人工覆核;未批准前不執行外部副作用。",
"analysis": "低信心自主決策已轉 AI 例外決策;未批准前不執行外部副作用。",
"subject": {
"sku": trigger.trigger_type,
"name": f"Elephant Alpha · {trigger_label}",
},
"evidence": evidence,
"recommended_action": {
"action": "human_review",
"action": "ai_exception_decision",
"owner": "ops",
"requires_hitl": True,
LEGACY_REVIEW_GATE_KEY: False,
"requires_ai_exception": True,
},
"expected_impact": {
"risk_reduction": "prevent low-confidence autonomous execution",
},
"guardrails": {
"can_auto_execute": False,
"blocked_reason": "L3 HITL required; no automatic execution before approval",
"blocked_reason": "L3 AI 例外決策 required; no automatic execution before approval",
"data_quality": data_quality,
},
"trace": {
@@ -2176,13 +2180,13 @@ class ElephantAlphaAutonomousEngine:
"event_type": "ea_escalation",
"title": f"🐘 EA 升級審核 · {_zh_trigger(trigger.trigger_type)}",
"summary": (
f"自主決策信心度 {decision.confidence:.2f} 低於門檻,需人工批准"
f"自主決策信心度 {decision.confidence:.2f} 低於門檻,需 AI 例外決策"
+ ("" if concrete_actions else "(⚠️ 無實證數據)")
),
"id": decision_envelope.get("decision_id"),
"decision_envelope": decision_envelope,
},
tier_label="🐘 Elephant Alpha · L3 HITL",
tier_label="🐘 Elephant Alpha · L3 AI 例外決策",
ai_summary=ai_summary_text,
ai_cause=ai_cause_text,
ai_actions=ai_actions_payload,