Coverage for .claude/hooks/moai/lib/tool.py: 0.00%
19 statements
« prev ^ index » next coverage.py v7.11.3, created at 2025-11-19 08:00 +0900
« prev ^ index » next coverage.py v7.11.3, created at 2025-11-19 08:00 +0900
1#!/usr/bin/env python3
2"""Tool usage handlers
4PreToolUse, PostToolUse event handling
5"""
7from lib import HookPayload, HookResult
8from lib.checkpoint import create_checkpoint, detect_risky_operation
11def handle_pre_tool_use(payload: HookPayload) -> HookResult:
12 """PreToolUse event handler (Event-Driven Checkpoint integration)
14 Automatically creates checkpoints before dangerous operations.
15 Called before using the Claude Code tool, it notifies the user when danger is detected.
17 Args:
18 payload: Claude Code event payload
19 (includes tool, arguments, cwd keys)
21 Returns:
22 HookResult(
23 system_message=checkpoint creation notification (when danger is detected);
24 continue_execution=True (always continue operation)
25 )
27 Checkpoint Triggers:
28 - Bash: rm -rf, git merge, git reset --hard
29 - Edit/Write: CLAUDE.md, config.json
30 - MultiEdit: ≥10 files
32 Examples:
33 Bash tool (rm -rf) detection:
34 → "🛡️ Checkpoint created: before-delete-20251015-143000"
36 Notes:
37 - Return continue_execution=True even after detection of danger (continue operation)
38 - Work continues even when checkpoint fails (ignores)
39 - Transparent background operation
41 """
42 tool_name = payload.get("tool", "")
43 tool_args = payload.get("arguments", {})
44 cwd = payload.get("cwd", ".")
46 # Dangerous operation detection (best-effort)
47 try:
48 is_risky, operation_type = detect_risky_operation(tool_name, tool_args, cwd)
49 # Create checkpoint when danger is detected
50 if is_risky:
51 checkpoint_branch = create_checkpoint(cwd, operation_type)
52 if checkpoint_branch != "checkpoint-failed":
53 system_message = (
54 f"🛡️ Checkpoint created: {checkpoint_branch}\n Operation: {operation_type}"
55 )
56 return HookResult(system_message=system_message, continue_execution=True)
57 except Exception:
58 # Do not fail the hook if risk detection errors out
59 pass
61 return HookResult(continue_execution=True)
64def handle_post_tool_use(payload: HookPayload) -> HookResult:
65 """PostToolUse event handler (default implementation)"""
66 return HookResult()
69__all__ = ["handle_pre_tool_use", "handle_post_tool_use"]