Don’t Use AI to Do a Tool’s Job
From the publisher’s feed, collected in the ZeroLabs newsroom.
The most important skill in agentic development isn’t prompting. It’s knowing when not to use AI at all.MidjourneyThere is a seductive idea at the center of the AI-assisted development movement: that with the right model and the right prompt, the AI can handle everything. Define your rules clearly enough, give it sufficient context, and it will follow your standards, respect your architecture, and make sound decisions autonomously.This is wrong, and the sooner we internalize that, the better our results will be.After nearly a year of building with Claude Code on multiple large scale production applications, I’ve arrived at a core philosophy that governs how I work with AI agents: don’t do something stochastically if it can be done deterministically. If a tool can enforce a rule, don’t ask the AI to remember it. If a script can verify an assumption, don’t trust the model to check. If a linter can catch an error, don’t rely on the agent’s judgment.This isn’t a limitation of current models that will be solved by the next generation. It’s a fundamental principle of sound engineering. We figured this out decades ago for human developers — we don’t ask people to remember the style guide, we run prettier. We don't trust developers to catch every bug, we write tests. The question isn't whether AI will eventually be reliable enough to follow instructions perfectly. The question is: why would we want it to, when deterministic tools already exist?The Stochastic TrapTo understand why this matters, we need to understand why relying on AI for enforceable rules fails.Many of my projects uses Supabase SaaS — a hosted remote database. No local Postgres. No Docker containers. No supabase start. This is documented in CLAUDE.md. It's injected into context before every relevant file edit. It's stated explicitly in the project standards. Despite all of that, the agent consistently suggests running supabase db reset --local or supabase start when troubleshooting migrations.After one particularly instructive session — where the agent suggested local database commands despite having just edited a migration file with “Fixed for Remote” in the comment header — I pushed it for an explanation. What it offered was remarkably honest:“Pattern Matching Over Comprehension: When I see ‘migration files need to be applied,’ my brain auto-completes to ‘suggest npx supabase db reset — local’ without actually thinking about YOUR setup.”“Not Reading What’s Right In Front Of Me: The migration file I just edited literally has the comment ‘Fixed for Remote’ in it. I read it, I even edited around it, and then I completely ignored what it meant.”“Defaulting to Documentation Examples: Most Supabase tutorials show local development workflows, so that’s what comes out of my mouth automatically without thinking about whether it applies to you.”This is a language model being transparent about how language models work. The training corpus is overwhelmingly dominated by local Supabase development workflows. When the model encounters “migration files need to be applied,” the statistical weight of thousands of training examples pulls it toward the local workflow regardless of what the project instructions say. The instruction is in the context window. The training data is in the weights. In a contest between the two, the weights have a gravitational advantage that grows as context gets longer and instructions drift further from the point of action.This is the stochastic trap: trusting a probabilistic system to enforce a deterministic rule. It will comply most of the time. It will fail unpredictably. And you won’t always catch it when it does.The solution isn’t to write better instructions. The solution is to recognize that this was never the AI’s job in the first place.The Principle: Right Tool for the Right JobThe principle itself is simple: every rule in your agentic workflow should be enforced by the most deterministic mechanism available.A rule like “don’t run local Supabase commands” is a pattern match on a string. That’s a job for grep, not Claude. A rule like "verify the port before curling localhost" is a state check. That's a job for a script, not an instruction. A rule like "stop retrying after three consecutive failures" is a counter. That's a job for a file on disk, not a language model's memory.This frees the AI to do what it’s actually good at: reasoning about ambiguous problems, generating creative solutions, understanding intent, navigating complex codebases. When we burden it with mechanical enforcement — remember this rule, check this assumption, don’t forget this constraint — we’re not just being inefficient. We’re using the wrong tool for the job, and the wrong tool fails in ways that are hard to detect and expensive to recover from.Claude Code’s hook system is where this principle becomes practical. Hooks let us run scripts that intercept tool calls before or after execution. A PreToolUse hook can inspect a bash command and block it, modify it, or inject additional context. A PostToolUse hook can inspect output and react. This is the exact same pattern as pre-commit hooks, CI checks, and linters — deterministic enforcement at the boundary between intent and action.Enforcement in PracticeLet me make this concrete with three hooks from my current Claude Code setup, each illustrating a different way to replace stochastic compliance with deterministic enforcement.Blocking: Making Wrong Actions ImpossibleFor the Supabase problem, a PreToolUse hook intercepts every Bash command and checks for patterns that imply local usage:# Excerpt from the larger script...if echo "$COMMAND" | grep -qE 'supabase\s+(start|stop|status)'; then cat BLOCKED: This project uses Supabase SaaS with a linked remote project.There is NO local Docker-based Supabase stack.The project is already linked via `supabase link`. Use these instead: supabase db push → push local migrations to remote supabase db pull → pull remote schema changes supabase db diff --linked → diff local vs remote schemaEOF exit 2fiThis is grep, not Claude. The rule is "don't run these commands." A regex can enforce that rule with 100% reliability. An instruction in a markdown file cannot. The AI's job was never to remember this constraint — it was to write good migration code. The hook handles the constraint so the AI can focus on what it's actually good at.The hook catches dozens of variants: the --local flag on any supabase command, supabase db reset without --linked, generating types without targeting the remote, Docker commands that imply a local Postgres, even psql connections to localhost. Each blocked pattern includes the correct alternative. The agent isn't just told "no" — it's told "here's what to do instead." And here's a key detail: the agent reads that rejection, learns from it in-context, and gets it right for the rest of the session. The deterministic tool actually makes the stochastic tool better by teaching it at the moment of maximum relevance.Gating: Requiring Verification Before ActionThe agent has a habit of hardcoding port numbers. It writes curl http://localhost:3000 without checking whether the dev server is actually running on port 3000. Sometimes the server is on 3001, or 5173, or isn't running at all. As a CLAUDE.md instruction, "verify ports before using them" was followed about 60% of the time — stochastic compliance with a deterministic rule.The verify-ports.py hook makes it a gate. It tracks a simple state machine: verification commands like lsof or server-start commands like npm run dev set a "verified" flag. Any subsequent command that references localhost: checks whether that port has been verified. If not:BLOCKED: You are using port(s) 3000 without verifying them first.Run `lsof -i -P -n | grep LISTEN` to discover the actual port,then retry your command with the verified port number.“Verify before using” is a precondition. Preconditions are the domain of assertions and gates, not instructions and hope. The hook transforms a suggestion into a requirement — the agent literally cannot use a port until it’s proven one exists. About 80 lines of Python replaced an unreliable cognitive burden with a deterministic invariant.Escalating: Stateful Intervention Over TimePerhaps the most expensive failure mode in agentic development is the infinite fix loop. The agent hits a build error, makes a change, gets the same error, makes another change, introduces a new error, and spirals for twenty tool calls before anyone notices it’s been making things worse for the last ten minutes. If you’ve worked with agentic coding tools on anything non-trivial, you’ve watched this happen.This is a counting problem. “Stop after too many failures” requires tracking state across multiple tool calls. Language models have no persistent memory between tool calls — each invocation starts fresh. A file on disk does.The failure-escalation.py hook implements two-tier escalation. At the first tier, after two failures with a similar command pattern, it injects: "Stop guessing. Your training knowledge may be stale. Search for the correct solution before retrying." At the second tier — three or more occurrences of the same error, a regression in error count, or five consecutive failures — it tells the agent to stop entirely:🛑 FAILURE ESCALATION — STOP:Reason: LOOPING: The same error has appeared 4 times.Your fixes are not resolving it.REQUIRED:1. Summarize what you've tried so far2. Explain what's failing and why your fixes haven't worked3. Ask the user how to proceedDo NOT continue attempting fixes autonomously.The hook normalizes command signatures to group similar attempts, tracks specific build error patterns to detect regressions, and stores state in a temp file with a 30-minute TTL so stale sessions don’t carry over. Success resets all counters. This is a counter, a diff, and a timer — all deterministic operations. The AI’s job is to fix the code. The hook’s job is to know when fixing isn’t working.Context Injection: The Right Information at the Right TimeNot every hook blocks something. Some solve a subtler problem: getting the right information to the agent at the right time.This matters because of how context windows actually work in practice. CLAUDE.md is read at the start of a session. Standards documents might be referenced early in a conversation. But by the time the agent is thirty tool calls deep into a complex task, those instructions are thousands of tokens away from the active context. They’re still technically in the window, but the model’s effective attention to them has degraded. Anyone who has worked with agentic tools on a long session has seen the pattern: the agent follows instructions beautifully for the first twenty minutes, then gradually drifts as context grows and the instructions recede.The underlying problem here is the same one we’ve been discussing — we’re asking the AI to do something a tool can do. Specifically, we’re asking the model to retrieve the right instruction from a long context at the moment it’s relevant. That’s an information retrieval task. We have deterministic tools for that.File-Aware Standards InjectionThe most sophisticated injection hook in my system is inject-standards.py. It fires on every file edit (Write|Edit|MultiEdit|Update) and injects the specific technical standards that are relevant to the file being modified — determined not by the model's judgment, but by a deterministic mapping of file path patterns to standards documents.The core of the hook is a routing table. Each entry maps a file path regex to a list of standards files:STANDARDS_MAP = [ # Pages (r'app/\[locale\]/.*page\.tsx$', [ 'component-patterns.md', 'architecture-principles.md', 'state-management.md', 'i18n.md', ]), # API Routes (r'app/api/.*route\.ts$', [ 'architecture-principles.md', 'error-handling.md', 'supabase.md', ]), # Components (r'components/.*\.tsx$', [ 'component-patterns.md', 'styling.md', 'accessibility.md', 'responsiveness.md', ]), # Database migrations (r'supabase/.*\.sql$', [ 'database-management.md', 'supabase.md', ]), # ... 30+ more patterns]When the agent edits a file, the hook matches the file path against this table and loads the relevant standards from disk. If the agent is editing a page component, it gets the component patterns, architecture principles, state management, and i18n standards. If it’s editing a migration file, it gets the database management and Supabase standards. If it’s editing a form component, it gets form validation and accessibility standards. The right standards arrive at the right time, every time, without the model needing to remember or retrieve anything.This is a large mapping — over thirty patterns covering pages, API routes, components, library code, types, migrations, i18n files, tests, config files, and more. Certain standards like type-safety.md and security.md are injected for every TypeScript and JavaScript file regardless of path. The mapping encodes institutional knowledge about which standards matter for which parts of the codebase — knowledge that would otherwise live in the model's fading memory of a CLAUDE.md it read at session start.The hook also solves a practical problem that comes with injecting context on every edit: deduplication. If the agent edits five .tsx component files in a row, injecting the same standards five consecutive times would waste context window. The hook tracks which standards have been injected and how many edit operations have occurred since, skipping any standard that was injected within the last ten edits. This keeps the context window efficient while ensuring the standards are always fresh enough to be relevant. A one-hour TTL resets the tracking entirely for new sessions.Before this hook, following project standards depended entirely on the model’s attention to instructions that were set at the start of a conversation. Standards compliance was high early in a session and degraded predictably as context grew. Now the relevant standards arrive adjacent to the action they govern, refreshed as needed, and the agent never has to rely on its memory of a document it read an hour ago.Injecting Standards for CLI CommandsThe same principle applies to Bash commands. A simpler hook, inject-db-standards.py, watches every Bash command for the word "supabase." When it finds it, it reads the project's supabase.md and database-management.md standards files and injects them as context for that specific tool call:if "supabase" in command: standards = [] for f in ["supabase.md", "database-management.md"]: try: with open(f"docs/standards/{f}") as fh: standards.append(fh.read()) except FileNotFoundError: passif standards: print(json.dumps({ "additionalContext": "\n\n".join(standards) }))Twelve lines of Python that replaced an entire category of frustration. Before this hook, the agent would read the Supabase standards at session start, follow them for a while, and then gradually revert to training-data defaults as the conversation grew. Now the standards arrive right before the agent executes each Supabase command, every single time, regardless of how deep into a session we are.Tracking State Across EditsThe ui-verification-reminder.py hook solves a different injection problem: maintaining awareness of accumulated changes over time.When the agent edits a .tsx or .css file, the hook appends that file path to a running list on disk and injects a reminder: "UI file changed. Remember: verify all UI changes with Playwright MCP screenshot before reporting task completion."if file_path.endswith(('.tsx', '.css')): with open(flag_file, "a") as f: f.write(file_path + "\n")print(json.dumps({ "additionalContext": "UI file changed. Remember: verify all UI " "changes with Playwright MCP screenshot before reporting " "task completion." }))This hook exists because of a specific and repeated failure mode. I’d ask the agent to fix a UI issue. It would make changes to three or four component files, then report the task complete — without ever checking whether the changes actually looked right in the browser. The CLAUDE.md instruction said to verify UI changes with Playwright. The agent followed this instruction reliably for the first few edits of a session, then gradually stopped as context grew.The hook is simple, but it’s doing something the model genuinely cannot do on its own: maintaining persistent, stateful awareness of which files have been touched across an entire session. Each edit re-triggers the reminder. The twentieth edit gets the same reminder as the first. The model’s attention to a session-start instruction fades over time; the hook’s doesn’t.The PatternThese hooks represent two variants of the same principle: content-aware injection (the right standards arrive based on what the agent is touching) and state-accumulated injection (reminders persist as changes accumulate). In both cases, we’re replacing a stochastic operation — the model retrieving the right information from a long context at the right moment — with a deterministic one.This is the difference between posting the safety rules at the entrance to the factory and posting them on the machine. The rules at the entrance get read once and gradually forgotten. The rules on the machine are there every time you reach for the controls.What Stays in CLAUDE.mdIf deterministic enforcement is so effective, why keep CLAUDE.md at all?Because not everything reduces to pattern matching. My CLAUDE.md still contains instructions for how to answer questions (explain why, not just what), when to use Playwright for visual testing, a troubleshooting protocol (“never ask the user to describe symptoms you can observe yourself”), and a directive to push back rather than agree sycophantically when I question a recommendation.These are judgment calls. They require understanding intent, weighing context, and applying nuance. This is exactly what language models are good at. The heuristic is: if it’s a repeated, mechanical violation, make it a hook. If it requires judgment, leave it as an instruction.The interesting result is what CLAUDE.md becomes when enforcement moves to hooks. It stops being a list of rules the agent might follow and starts being a description of how the agent should think — its priorities, its judgment calls, the values that can’t be reduced to grep. The mechanical rules get enforced mechanically. The space that's left is where AI actually excels.Principles for Building This SystemThe rejection message is the instruction. When a hook blocks an action, the denial reason becomes in-context learning — the deterministic tool teaching the stochastic one. Write rejection messages that include the correct alternative, not just “this is blocked.”Hooks compose like middleware. A single Bash matcher runs five hooks in sequence: log the tool name, check for dangerous kill patterns, verify ports, block local Supabase commands, and inject standards. Each is independent and can be added or removed without touching the others.State management matters. The failure escalation hook tracks state across tool calls using temp files. Session cleanup hooks clear stale state on startup. The 30-minute TTL was arrived at through experience: long enough to catch loops, short enough to not punish a fresh start.The system is imperfect, and that’s fine. Claude Code’s hook infrastructure has rough edges. MCP tool matchers don’t always fire reliably. Shell scripts need to consume stdin even if they don’t use the payload, or they’ll hang. The JSON output schema has changed. Building this system involved real debugging — wrong JSON formats, silent failures, matchers that worked for one tool but not another. But even imperfect deterministic enforcement is more reliable than perfect stochastic compliance.The Bottom LineThe most productive teams working with AI agents won’t be the ones with the best prompts. They’ll be the ones who most clearly understand the boundary between what AI should do and what tools should do.AI is extraordinary at reasoning, creativity, and navigating ambiguity. It is mediocre at remembering rules, maintaining state, and enforcing constraints. These aren’t the same category of task, and treating them as such — by writing longer and louder instructions — is the wrong response to a real problem.A linter doesn’t have a bad day. A pre-commit hook doesn’t forget the style guide halfway through a long PR. A grep doesn't get confused by training data. And a PreToolUse hook doesn't lose track of your project's database architecture after thirty tool calls.We are building the development workflows that will define how software gets made for the next decade. The developers and teams who build the smartest systems around their AI agents — not just the smartest prompts for them — will be the ones who win.Don’t ask your AI to do a tool’s job. Let it do its own.Don’t Use AI to Do a Tool’s Job was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.