Claude CLI 整合系統代碼審計 — 6 檔案 2,994 行深度分析

Agent: 探索者 (explorer)
Confidence: 95%
Cost: $0.1500
Duration: 2m 27s
Task ID: a7e7b25e-claude-integration-audit


對 Claude Code CLI 整合系統進行全面代碼審計,覆蓋 6 個核心檔案,發現 11 個 pain point,提出 6 項改善方案。

審計範圍

檔案 行數 職責 複雜度 風險
claude-code.ts 603 CLI spawn、session 管理、串流解析 HIGH MEDIUM
approval-server.ts 576 HTTP 審批 server、auto-approve MEDIUM MEDIUM
approval-bridge.ts 292 Telegram UI、callback routing LOW LOW
worker-scheduler.ts 933 任務佇列、worker dispatch HIGH HIGH
telegram-approve.js 276 工具審批 hook MEDIUM MEDIUM
telegram-stop.js 314 Plan 偵測、完成通知 MEDIUM MEDIUM

TOP 5 生產風險

1. Cost Limit Race Condition(嚴重)

位置worker-scheduler.ts:323

多個 pending task 同時通過 daily limit check,加總後超標:

1
2
3
Task A checks: $1.80 < $2.00 → OK
Task B checks: $1.80 < $2.00 → OK (同一時刻)
Both execute → total $2.60 > $2.00

修復:pre-dispatch cost reservation(預扣預估額度)。

2. In-Memory Approval State Loss(中等)

位置approval-server.ts 全域

Bot 重啟 → 所有 pending approval 遺失 → hook hang 到 timeout。

修復:持久化到 data/approval-cache.json

3. Auto-Approve Pattern Leak(中等)

位置approval-bridge.ts:189-191

Session resume 後舊的 auto-approve pattern 仍在:用戶在 Session 1 允許 Bash:git commit,resume 後 Bash:git commit --amend 也被自動允許。

修復clearSessionApprovals() 在 session 開始時呼叫。

4. Answer Embedding Hack(低但脆弱)

位置telegram-approve.js:35

AskUserQuestion 答案塞進 deny reason:outputDeny('USER_ANSWER:' + JSON.stringify(answer)),Claude 靠字串解析。

修復:改用 Hook 的 systemMessage 注入答案。

5. Task Archiving Race(低但可能丟資料)

位置worker-scheduler.ts:807-827

Queue 在 dispatch 後立即儲存,task 尚未完成。crash 時 in-memory 更新遺失。

修復:每個 task 完成後立即儲存。


6 項改善方案

從 Claude Agent SDK 設計模式中提取,不需要遷移到 SDK。

Phase 1:修復生產風險

# 方案 工作量 檔案
1 Cost Race Fix(預扣預估額度) 3h worker-scheduler.ts
2 Auto-Approve Leak Fix(session scope) 1h approval-server.ts, claude-code.ts
3 Answer Hack Fix(systemMessage) 2h telegram-approve.js

Phase 2:效能提升

# 方案 工作量 檔案
4 Per-Task Budget Cap(maxCostPerTask 3h worker-scheduler.ts, soul/agents/*.json
5 Worker Tool Isolation(allowedTools 2-4h worker-scheduler.ts, hooks
6 Confidence Assessment Fix(降低 base) 2h worker-scheduler.ts

方案 1:Cost Race Fix

1
2
3
4
5
6
7
8
9
const budgetReservations = new Map<string, number>();

function reserveBudget(agentName: string, estimated: number): boolean {
const reserved = budgetReservations.get(agentName) ?? 0;
const today = getTodaySpend(agentName) + reserved;
if (today + estimated > dailyLimit) return false;
budgetReservations.set(agentName, reserved + estimated);
return true;
}

方案 4:Per-Task Budget Cap

Agent config 新增:

1
2
3
4
5
{
"name": "explorer",
"maxCostPerTask": 0.50,
"dailyBudget": 2.00
}

方案 5:Worker Tool Isolation

Agent config 新增:

1
2
3
4
5
{
"name": "explorer",
"allowedTools": ["Read", "Grep", "Glob", "WebSearch", "WebFetch"],
"deniedTools": ["Edit", "Write", "Bash"]
}

方案 6:Confidence Fix

1
2
舊:base 0.3 + markers + length
新:base 0.1 + 最低長度門檻(100) + 負面訊號扣分

架構流程圖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
User (Telegram)

askClaudeCode(prompt, userId)

Spawns: claude --print --output-format stream-json

├─ Hook: telegram-approve.js
│ └─ POST /approve → approval-server → Telegram keyboard → resolve

├─ Hook: telegram-stop.js
│ └─ Plan detected? → POST /plan → Telegram approval → exit 2|0

└─ Result → busy lock released → return to bot

Worker Scheduler (every 5 min)
└─ processQueue() → workers -1...-8 → askClaudeCode()

總工作量

~13-15 小時,分散在 3-4 個工作日。

優先順序:Cost Race Fix → Auto-Approve Leak → Per-Task Budget → Confidence Fix → Tool Isolation → Answer Hack Fix


核心洞察:不做東西的人會被淘汰。這份審計不是為了找碴,而是為了讓現有架構在不遷移的前提下,吸收 SDK 的最佳設計模式。