Files
o2o-infinith-demo/.claude/hooks/watchdog_gate.py
T
Haewon KamandClaude Opus 5.5 4c2152bfaa fix: watchdog 게이트 훅을 오류 시 차단(fail-closed)하고 판정은 마지막 줄 "WATCHDOG: PASS" 만 인정한다
- 보안 검토 지적 반영: 훅 예외가 나면 초안 도구를 막는다, 기록 행·필드 타입 확인
- 판정 문자열은 결과 마지막 비어 있지 않은 줄이 정확히 WATCHDOG: PASS 일 때만 인정
- 남은 과제: 승인한 초안 본문 해시와 실제 초안 입력을 대조하는 바인딩(TOCTOU)은 별도 작업

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:48:39 +09:00

126 lines
4.9 KiB
Python

#!/usr/bin/env python3
"""Outlook 초안 생성·수정·발송 전에 view-mou-watchdog 검토 통과를 요구하는 PreToolUse 훅.
통과 조건: 가장 최근 view-mou-watchdog 결과(동기 결과 또는 백그라운드 task-notification)가 'WATCHDOG: PASS' 이고,
그 PASS 이후에 아직 다른 Outlook 초안 도구 호출이 없다 (검토 한 번에 초안 한 번).
"""
import json
import re
import sys
AGENT = "view-mou-watchdog"
OUTLOOK_PREFIX = "mcp__claude_ai_Microsoft_365__outlook_"
GATED = ("create_draft", "create_reply_draft", "create_reply_all_draft", "update_draft", "send_draft", "send_mail", "forward_mail")
def deny(reason):
print(json.dumps({
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "deny",
"permissionDecisionReason": reason,
}
}, ensure_ascii=False))
sys.exit(0)
def is_gated(name):
return name.startswith(OUTLOOK_PREFIX) and name[len(OUTLOOK_PREFIX):] in GATED
def result_text(item):
c = item.get("content")
if isinstance(c, str):
return c
if isinstance(c, list):
return "\n".join((x.get("text") or "") for x in c if isinstance(x, dict))
return ""
def verdict(text):
# 판정은 결과의 마지막 비어 있지 않은 줄이 정확히 "WATCHDOG: PASS" 일 때만 인정한다 (본문 중간 인용·FIX 혼재 차단)
lines = [l.strip() for l in text.replace("\\n", "\n").splitlines() if l.strip()]
if not lines:
return False
last = re.sub(r"[`*_<>/]|result", "", lines[-1]).strip()
return last == "WATCHDOG: PASS" and "WATCHDOG: FIX" not in text
def main():
payload = json.load(sys.stdin)
if not is_gated(payload.get("tool_name", "")):
sys.exit(0)
rows = []
with open(payload["transcript_path"], encoding="utf-8") as f:
for line in f:
line = line.strip()
if line:
try:
rows.append(json.loads(line))
except json.JSONDecodeError:
continue
# 검토 1회(PASS) = 초안 도구 1회. 백그라운드 검토 결과는 task-notification 으로 도착한다
watchdog_ids = set()
passed = False
for r in rows:
if not isinstance(r, dict):
continue
if r.get("isSidechain"):
continue
# 요청 사본 행은 앞선 도구 호출을 다시 담고 있어 순서를 흐트러뜨린다. 건너뛴다
if r.get("type") == "api-request-blob":
continue
# 최신 Claude Code 는 백그라운드 결과(task-notification)를 attachment.queued_command 로 기록한다
att = r.get("attachment") or {}
if att.get("type") == "queued_command":
prompt = att.get("prompt") or ""
if "<task-notification>" in prompt:
m = re.search(r"<tool-use-id>([^<]+)</tool-use-id>", prompt)
if m and m.group(1) in watchdog_ids:
passed = verdict(prompt)
continue
c = (r.get("message") or {}).get("content") if isinstance(r, dict) else None
if isinstance(c, str):
if "<task-notification>" in c:
m = re.search(r"<tool-use-id>([^<]+)</tool-use-id>", c)
if m and m.group(1) in watchdog_ids:
passed = verdict(c)
continue
if not isinstance(c, list):
continue
for x in c:
if not isinstance(x, dict):
continue
if x.get("type") == "tool_use":
inp = x.get("input") or {}
# 에이전트 정의가 아직 로드되지 않은 세션에서는 general-purpose 에 정의 파일을 넘기고 description 에 이름을 단다
if x.get("name") in ("Agent", "Task") and (
inp.get("subagent_type") == AGENT or AGENT in (inp.get("description") or "")
):
watchdog_ids.add(x.get("id"))
elif is_gated(x.get("name", "")):
passed = False
elif x.get("type") == "tool_result" and x.get("tool_use_id") in watchdog_ids:
text = result_text(x)
if "WATCHDOG:" in text:
passed = verdict(text)
if not passed:
deny(
"view-mou-watchdog 검토가 통과되지 않았습니다. 메일 초안을 만들거나 고치기 전에 "
"Agent(subagent_type='view-mou-watchdog')에 초안 전문과 근거 위치를 넘겨 검토받고, "
"'WATCHDOG: PASS'가 나온 뒤 다시 시도하세요. FIX면 정정한 초안으로 다시 검토받으세요."
)
sys.exit(0)
if __name__ == "__main__":
try:
main()
except SystemExit:
raise
except Exception as e: # 훅이 깨지면 막는 쪽으로 (fail-closed)
deny(f"watchdog 게이트 훅 오류로 초안 도구를 막았습니다: {type(e).__name__}: {e}")