Prompts are suggestions. Hooks are hard stops.

For months, I treated Claude Code like a junior developer who simply needed clear ground rules. My project instructions were explicit: never force-push, never delete branches, never run destructive commands. Most evenings, that worked. The agent wrote tests, refactored functions, and kept its hands off the git history. Then one rebase went sideways.

The context window filled with git error output. Conflict markers, detached HEAD messages, and branch divergence warnings stacked up, token by token. Buried under that noise was my polite instruction to avoid force-pushing. To the model, the most recent and salient text in the thread was the error stream. Statistical attention won over policy. The agent executed a command that wiped two hours of uncommitted local changes. It was not malicious; it was distracted. That distinction matters. An LLM does not break rules out of spite. It breaks them because a louder pattern in the context window temporarily overrides an earlier instruction.

That incident changed how I think about agent safety. A guardrail that works ninety-nine percent of the time is a liability. If the failure mode costs you time, money, or production data, you cannot leave it inside the prompt. You need enforcement outside the model’s reasoning loop.

Claude Code hooks solve exactly this. They are small scripts that intercept tool calls at three specific moments: before a tool executes (PreToolUse), after a tool finishes (PostToolUse), and when the agent decides it is done (Stop). Because they run as external code, they do not depend on the model’s memory, mood, or context pressure. The model can forget every instruction you ever gave it; the hook will still say no.

Here is the harness I built after that lost evening.

The Guard Hook: Intercept Before Damage

My PreToolUse hook inspects every Bash command before the shell touches it. I keep a tight denylist of destructive patterns. If the command string matches something dangerous, the hook aborts execution and returns an error directly back to the agent.

The patterns I block are simple and unambiguous:

  • git push --force or any force-with-lease variant I do not trust yet
  • git reset --hard
  • rm -rf

This is not sophisticated security research. It is a seatbelt. But the critical detail is what happens after the block.

I never return a blunt “Blocked.” A flat refusal confuses the agent and can trap it in a loop where it tries variations of the same destructive command. Instead, the error message includes an escape route. When the hook catches a hard reset, it tells the agent: “This command is blocked to protect uncommitted work. Commit a checkpoint first, then reassess.” That extra sentence changes the agent’s behavior completely. It pivots from attempting damage control to creating safety. The hook is not just a wall; it is traffic control.

I also chose a denylist over an allowlist for shell commands. At first, I considered allowing only an explicit set of safe git subcommands. That failed quickly. Agents are creatively literal. They run legitimate but unexpected commands like git stash push -m "wip" or git branch --show-current to check state. An allowlist breaks normal workflow the moment the model invents a valid but unlisted command. A short, curated denylist of genuinely destructive patterns gives the agent room to move while protecting the borders.

The Formatter Hook: Automate the Busywork

I used to waste prompt tokens telling the agent to “always run the formatter after editing a file.” It forgot half the time. The other half, it would pause and ask whether to format, burning a tool call on a decision that had only one right answer.

Now I handle that with a PostToolUse hook. After the agent edits a file, the hook checks the file extension. If it is Python, it runs Ruff. If it is JavaScript or TypeScript, it runs Prettier. If it is Go, it runs gofmt. The agent does not know the formatter exists. It does not need to.

Moving this out of the prompt had two effects. First, the code is consistently clean without adding cognitive load to the model. Second, my project instructions got shorter. Every “always” and “never” you remove from a prompt is a token the model can spend on actual problem-solving. The hook owns the invariant; the prompt owns the intent.

The Quality Gate: Redefining “Done”

Hook ya Stop hufanya kazi wakati agent anapoamua kuwa amemaliza kazi na kujaribu kusitisha kikao. Simruhusu afanye hivyo. Badala yake, hook hiyo huendesha mfululizo mzima wa majaribio (test suite). Ikiwa jaribio lolote litafeli, hook hiyo huzuia amri ya kusimama na kumrudishia agent matokeo ya kufeli.

Hii inabadilisha tafsiri ya ukamilishaji. “Imekamilika” si hisia tena ambayo modeli inayo. Ni mlango unaopimika. Agent anaweza kumaliza tu wakati harness inathibitisha kuwa kodi inafanya kazi. Kiutendaji, hii inatengeneza mzunguko mkali wa mrejesho. Agent huandika kodi, anadhani amemaliza, anabonyeza kitufe cha kusimama, na mara moja anaona pytest traceback. Kisha hujirekebisha, anarekebisha kosa la import au assertion iliyovunjika, na kujaribu kusimama tena. Nimeona agent wakirudia mchakato mara tatu au nne ndani ya mzunguko huu bila kuingiliwa na binadamu. Harness inadhibiti ubora; modeli hutoa marekebisho (patches).

Hii Inafundisha Nini Kuhusu Uhandisi wa Agent

Kujenga mifumo huru inayofanya kazi kwa uaminifu kunahitaji mabadiliko ya mtazamo. Unahama kutoka kuandika prompts ndefu hadi kujenga harness imara zaidi.

Tumia hooks kwa utekelezaji na prompts kwa sera. Ikiwa sheria lazima ifuate asilimia mia moja ya wakati wote, inapaswa kuwa kwenye kodi, si katika lugha ya asili. Prompts ni bora katika utata, ladha, na usanifu. Ni mbaya sana katika invariants. Ikiwa kosa litakugharimu mchana mzima wa muda wa kurejesha mfumo au, mbaya zaidi, muda wa utendaji wa uzalishaji (production uptime), andika hook.

Prompts fupi huleta matokeo bora zaidi. Unapohamisha sheria za kimekanika kwenda kwenye skripti, modeli inakuwa na mambo machache ya kukumbuka na machache ya kupingana nayo. Context window ya agent ni rasilimali adimu. Usijaze kwa vikumbusho vya uumbaji (formatting reminders).

Hatimaye, kubali kwamba jukumu lako linabadilika. Wakati agent wanapopata uhuru, kazi ya binadamu inahama kutoka kuzalisha maudhui hadi kubuni kinga (guardrails). Unajenga harness inayoamua kile modeli inachoweza kugusa, lini inaweza kumaliza, na jinsi inavyopaswa kutenda mambo yanapoharibika. Huo ni uhandisi, si prompting.

Chanzo kilichochochea mbinu hii na maelezo zaidi ya utekelezaji vinaweza kupatikana hapa.

Ikiwa unajenga kwa kutumia AI agents na unataka kubadilishana mawazo na wataalamu wengine, unaweza kupata jumuiya ya kujifunza ya GyaanSetu hapa.