Coverage for src/moai_adk/templates/.claude/hooks/moai/lib/tool.py: 26.32%

19 statements  

« prev     ^ index     » next       coverage.py v7.11.3, created at 2025-11-20 09:47 +0900

1#!/usr/bin/env python3 

2"""Tool usage handlers 

3 

4PreToolUse, PostToolUse event handling 

5""" 

6 

7from lib import HookPayload, HookResult 

8from lib.checkpoint import create_checkpoint, detect_risky_operation 

9 

10 

11def handle_pre_tool_use(payload: HookPayload) -> HookResult: 

12 """PreToolUse event handler (Event-Driven Checkpoint integration) 

13 

14 Automatically creates checkpoints before dangerous operations. 

15 Called before using the Claude Code tool, it notifies the user when danger is detected. 

16 

17 Args: 

18 payload: Claude Code event payload 

19 (includes tool, arguments, cwd keys) 

20 

21 Returns: 

22 HookResult( 

23 system_message=checkpoint creation notification (when danger is detected); 

24 continue_execution=True (always continue operation) 

25 ) 

26 

27 Checkpoint Triggers: 

28 - Bash: rm -rf, git merge, git reset --hard 

29 - Edit/Write: CLAUDE.md, config.json 

30 - MultiEdit: ≥10 files 

31 

32 Examples: 

33 Bash tool (rm -rf) detection: 

34 → "🛡️ Checkpoint created: before-delete-20251015-143000" 

35 

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 

40 

41 """ 

42 tool_name = payload.get("tool", "") 

43 tool_args = payload.get("arguments", {}) 

44 cwd = payload.get("cwd", ".") 

45 

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 

60 

61 return HookResult(continue_execution=True) 

62 

63 

64def handle_post_tool_use(payload: HookPayload) -> HookResult: 

65 """PostToolUse event handler (default implementation)""" 

66 return HookResult() 

67 

68 

69__all__ = ["handle_pre_tool_use", "handle_post_tool_use"]