# Hooks Examples (Unit 5) This directory demonstrates hook patterns across Claude Code, Codex, OpenCode, and Pi. ## Hook Lifecycle ``` User prompt │ ├─[UserPromptSubmit hook]─► log / inject context ▼ Model reasoning │ ├─[PreToolUse hook]─► allow, deny, rewrite args ▼ Tool executes │ ├─[PostToolUse hook]─► log, analyze, post-process ▼ Model continues │ └─[Stop / SessionEnd hooks]─► persist, notify, tear down ``` ## Claude Code — `.claude/settings.json` ```json { "hooks": { "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "command": "python .claude/hooks/guard_bash.py" } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "python .claude/hooks/run_linter.py" } ] } ], "Stop": [ { "hooks": [ { "type": "command", "command": "python .claude/hooks/notify_done.py" } ] } ] } } ``` ## OpenCode — `.opencode/plugins/activity-logger.ts` ```typescript export default { "tool.execute.before": async (input, output) => { console.log(`[HOOK] Before tool: ${input.tool}`); // Block dangerous commands if (input.tool === "bash" && input.args?.command?.includes("rm -rf")) { throw new Error("Blocked: dangerous command"); } }, "tool.execute.after": async (input, output) => { console.log(`[HOOK] After tool: ${input.tool} -> ${output.result?.slice(0, 100)}`); }, "event": async ({ event }) => { if (event.type === "session.idle") { console.log("[HOOK] Session ended"); } } }; ``` ## Guardrail Example — `.claude/hooks/guard_bash.py` ```python import json, sys payload = json.load(sys.stdin) command = payload.get("tool_input", {}).get("command", "") BLOCKED = ["rm -rf /", "rm -rf ~", "~/.ssh/", "chmod 777"] for pattern in BLOCKED: if pattern in command: print(json.dumps({"decision": "deny", "reason": f"Blocked: {pattern}"})) sys.exit(0) print(json.dumps({"decision": "allow"})) ``` ## Three Patterns 1. **Observability** — Log every tool call, prompt, and stop event to a dashboard. 2. **Guardrails** — Inspect commands before execution; deny unsafe actions. 3. **Automation** — Run linters, formatters, tests automatically after file edits. ## Agent Activity Dashboard A Gradio app that receives hook events over HTTP and visualizes tool calls, prompts, and sessions in real time. See `hooks/dashboard.py`.