今日已更新 143 条资讯 | 累计 40588 条内容
关于我们

The Hook System — Blocking AI Mistakes with Structure

Sungsoo Youn 2026年09月07日 05:22 1 次阅读 来源:Dev.to

This is chapter 4 of my book **Building Autonomous AI Agents with Claude Code * — a field guide to turning Claude Code from a coding assistant into an agent that remembers, verifies its own work, and knows when to stop. Everything below is from a system I actually run every day on one Windows PC.* 1. A Hook Is a Safety Mechanism Outside the AI A rules file is something the AI tries to follow ; a hook is something the system uses to make it be followed . This difference is bigger than it looks. Rules get buried as context grows longer, get skipped when things are urgent, and "just this once" exceptions pile up. Hooks don't do that. Point Timing Typical use UserPromptSubmit Right after the user types input Automatic context injection (record summaries, related rules) PreToolUse Right before a tool runs Blocking dangerous actions (gates) PostToolUse Right after a tool runs After-the-fact checks (contamination detection, follow-up procedure reminders) Stop When the response ends Quality gates (forbidden-word detection, verification requirements) Registration happens in one place, the settings file. { "hooks" : { "PreToolUse" : [ { "matcher" : "Write|Edit" , "hooks" : [{ "type" : "command" , "command" : "python C:/hooks/record_gate.py" }] } ] } } 2. Pattern A — The Blocking Hook (Gate) This is a gate that blocks "attempts to modify a file without reading the records first." What follows is a shortened version of one actually in use. import json , sys , time from pathlib import Path STATE = Path ( tempfile . gettempdir ()) / " read_state.json " REQUIRED = [ " memory/diary.md " , " memory/mistakes.md " ] payload = json . load ( sys . stdin ) # hooks receive the tool call on stdin tool = payload . get ( " tool_name " , "" ) if tool == " Read " : state = json . loads ( STATE . read_text ()) if STATE . exists () else {} state [ payload [ " tool_input " ][ " file_path " ]] = time . time () STATE . write_text ( json . dumps ( state )) sys . exit ( 0 ) state = json . loads ( STA

本文内容来源于互联网,版权归原作者所有
查看原文