A lot of people pay for Claude and still get buggy code. Usually the model is not the problem. They don't know how it works, so they can't control it.
In this post we follow one task from zero: you ask an agent to build a login page, and you want it done right. We start with how the AI works. We end with the tools I use every day to control my agents, with real examples from skills I built for myself.
After this post you can:
- explain how an LLM and an agent work, and why AI needs predictable checks
- control an agent with
CLAUDE.md, skills, MCP, hooks and subagents - keep your context small, write a spec with a clear "done when" line, and run loops with one leading agent
Setup#
I use Claude Code on a Mac here. If you use another machine, the install steps are in the official Claude Code docs.
On a Mac, open the Terminal app and run:
curl -fsSL https://claude.ai/install.sh | bash
Then type claude to start it. Congrats, you're done. Inside Claude Code, type /login to sign in and set up your account.
You just installed Claude Code. How do you sign in?
How AI works#
Words you need:
- LLM: Large Language Model, the "brain" you send text to.
- Inference: sending text to a trained model and getting text back.
- Token: a small piece of text, roughly one word.
- Context window: the limit of how much text the model can see at one time.
What we use every day is called LLM inference. A company (like Anthropic) trains a big model, and then we send it text and get text back. That "send and get back" part is inference.
LLM means Large Language Model. It's one small part of the big AI world:
At its base, an LLM is a predictor. It reads your input and predicts what the answer most likely looks like. That's also why it hallucinates (makes things up). The most likely answer is not always the true one, but it still sounds confident.
A simple case: ask it for a function from a library, and it can give you a function name that does not exist. The name looks real, and the answer sounds sure.
An LLM can also give a different answer each time. We call that probabilistic. So working with an LLM means putting gates around it: checks its output must pass (more in the Deterministic vs probabilistic chapter). Maybe one day models get smart enough that we don't need gates anymore, but I think that takes some time :)
What you send to the LLM is cut into tokens. A token is a small piece of text, roughly one word (sometimes part of a word).
Try it. Type any sentence and see how it gets cut into tokens:
The context is all the tokens the model can see at one time. The context window is the limit of how much context fits in one session (one conversation with the agent).
Every time you send a new message, the whole conversation is sent again, not only your last message. Watch the bar fill up:
This is why long sessions get slow, expensive and confused. The model re-reads everything, on every message.
A real example from my setup: I built a skill called /learning. A skill is a saved set of instructions for the agent (more in the Controlling the agent chapter). It keeps a small project memory in a .learning/ folder inside each repo:
- what the app does
- one short doc per module (one part of the app, like auth or payments)
- past decisions
- what happened in each session
The goal is simple. The next session already knows the codebase without re-reading it. So I don't waste context on reading the same files again and again. The docs are kept tiny on purpose (a module doc is max 40 lines), because everything the agent reads costs context.
Your chat with Claude is 2 hours long and getting slow. Why?
Why does an LLM sometimes make things up?
Congrats, you're now ahead of 50% of people. You know the basics of how it works, and you can share this in your group chat to sound smart.
Deterministic vs probabilistic#
Words you need:
- Probabilistic: the same input can give a different output each time.
- Deterministic: the same input always gives the same output.
- Gate: a deterministic check the AI's work must pass.
Everything an LLM gives you is probabilistic. Send the same prompt in two different sessions and you can get two different results.
Some people get good code and good UI from AI. Others pay for Claude Max 20x (the biggest paid Claude plan) and still get a lot of bugs. Why? The difference is the deterministic part.
Deterministic means: the same input always gives the same output. A linter (a tool that checks code for common mistakes) is deterministic. A unit test is deterministic. A calculator is deterministic. An LLM is not.
So you put deterministic checks around the AI. I call them gates: the AI's work must pass them.
Want to be sure your login page is not broken? Don't ask the AI "is it broken?". Run a linter and unit tests, and let them say pass or fail.
For UI, the gate can be a fixed list of rules, like your design guidelines, checked the same way every time. Now you get what you want, not what the AI wants.
Here is the same prompt sent to Claude again and again. The code changes every run. The test doesn't change, so it catches the bad ones:
function add(a, b) {
return a + b
}expect(add(2, 3)).toBe(5)
Quick quiz before we move on:
- A linter checking your code style
- Asking Claude "is my code broken?"
- A unit test: add(2, 3) must be 5
- Claude designing your landing page
- A calculator doing 12 × 7
Some examples from skills I built:
/calis my personal calorie tracker. I type "ayam geprek 1 porsi + 1 porsi nasi" (one plate of smashed fried chicken and one plate of rice). The AI splits it into food items and picks matching foods. But the AI never does the calorie math. A small CLI program (a command you run in the terminal) does the math, because math must be the same every time. The AI does the fuzzy part (reading my messy text), the code does the exact part./diet-reviewwrites a weekly review of my eating. Its rule: every number comes from the CLI, the AI is not allowed to invent a number./test-engineer-irfanis my testing workflow. I write the spec (the expected behaviour) first. Tests are made from the spec, not from the code, because tests made from code copy the code's bugs. Pass or fail comes only from real command output, never from the agent saying "verified".
In the /cal calorie tracker, who does the calorie math?
So when you start using AI, first think: what gates do I need so the output is what I expect? With those in place, you can start building your own software factory.
How an agent works#
Words you need:
- Tool: an action the agent can do, like read a file or run a command.
- Agent: an LLM that calls tools in a loop until the task is done.
- System prompt: instructions put at the very top, every time the agent runs.
Think of the LLM as a brain. It can think, but it can't move or touch anything. So we give it a body: tools. The LLM calls a tool, sees the result, thinks again, and repeats until the task is done. That loop is an agent.
- The LLM reads the task and decides what to do next.
- It calls a tool, like reading a file or running grep (a text search).
- The tool runs and returns a result.
- The LLM reads the result and thinks again.
- The loop stops when the task matches what you said finished looks like.
Here's an agent fixing a small bug:
An agent has three parts:
- System prompt: instructions put at the very top, every time the agent runs. Claude Code and Codex (OpenAI's coding agent) already set this up for you, but it's nice to know it's there.
- Tool calls: the list of actions the agent can do. In Claude Code that's things like reading files,
grep(search text),git, or any terminal command. - Loop: the agent repeats think, act, observe until the task is finished. You define what "finished" looks like.
Tools are where agents get dangerous, because now the AI can change real things. So I make my tools safe by design.
My /postgres-irfan-axi skill lets the agent work with my local Postgres database through a small CLI. Inside the tool there is a guard. DROP DATABASE is always refused. DROP TABLE and TRUNCATE stop and wait for my approval first.
query "SELECT * FROM users" -d app✓ read query, runs on the databaseexec "DROP TABLE orders" -d app✋ paused, exit 2: you must approve firstexec "DROP DATABASE app" -d app✗ refused, exit 3, alwaysThe tool is also careful with the database itself. Each call opens one database connection and closes it when done, so the agent never leaves connections open.
Same idea at my day job. I work with a big data warehouse (the database a company uses for reports). I made a skill so the agent can look up tables and check real values. It does that before it writes a query for me. The tool is read-only. Any write is refused by the tool itself, not by asking the AI nicely.
You never want the agent to drop your database. Where should that rule live?
When does the agent loop stop?
Controlling the agent#
Words you need:
CLAUDE.md: a rules file Claude Code reads at the start of every session.- Skill: a saved prompt for one specific task.
- MCP: a standard way for an agent to talk to other services.
- Hook: a command that runs on an event, every time.
- Subagent: an agent controlled by another agent, with its own clean context.
Now we know what an agent is made of. Next is controlling it. You've probably heard these words already, but maybe you don't know what they mean.
CLAUDE.md#
CLAUDE.md is a text file Claude Code reads at the start of every session. You put your rules there: how to test, what not to touch, how you want answers.
I keep one global file for every project. It holds my rules: security rules, "always run tests and lint before saying done", and how to report back to me. Each project can also have its own CLAUDE.md on top of it. A small one can look like this:
# Rules
- Always run tests and lint before saying done.
- Never put passwords or keys in the code.
- Answer short: the result first, then the details.
Skills#
A skill is just a bunch of text that tells the AI what to do. It's a prompt made for one specific task. I use a skill when I want one job always done the same way, like testing or E2E (end-to-end) checks. /test-engineer-irfan, /postgres-irfan-axi and /learning are all skills.
A skill is a file called SKILL.md in its own folder. The top part is its header: a name and a description. You call it by typing its name, like /review-sql:
---
name: review-sql
description: Check a SQL query before it runs. Use when the user asks to review SQL.
---
1. Read the query.
2. Make sure every WHERE column has an index.
3. Never run a DELETE without a WHERE.
The problem: skills don't scale well. The header of every installed skill is always pushed into the context, so the agent knows it exists. Install a lot of skills and your context gets full before you even start. Best practice is to install and use only the skills you need.
MCP#
MCP means Model Context Protocol. It's a standard way for an agent to talk to other services, like Figma or Slack. An MCP server is the small program that connects one service to the agent. MCP is good when you want to connect systems, or bring their data into your chat.
My take: if you're an engineer working in the terminal, you mostly don't need MCP. Use MCP only for data the terminal can't get.
That's why most of my tools are small CLIs instead of MCP servers: postgres-irfan-axi for my local database and taskboard for my own task board. The agent just runs them in the terminal.
My CLIs print a short format called TOON. It uses fewer tokens than JSON, so more of the context window is left for the real work. The same two rows look like this:
JSON: [{"id":1,"name":"Ana"},{"id":2,"name":"Budi"}]
TOON: users[2]{id,name}:
1,Ana
2,Budi
In TOON, [2] is the number of rows. {id,name} names the fields once, not on every row.
Try it. For each one, would you give the agent a terminal CLI or an MCP server?
- Your local Postgres database
- Files in your repo
- GitHub issues and pull requests
- A web app that only gives you an MCP server, no CLI or API
- Your git history
Hooks#
Hooks are commands that run on events. Every agent has events: before a prompt, after a tool runs, when the session ends, and so on. A hook runs on that event every time, the same way, so it's deterministic.
Example: after the agent writes code, don't ask an agent if the code works. Let a hook run the linter and unit tests. If you build agents, I really recommend adding hooks.
In Claude Code, hooks live in a settings file, like .claude/settings.json in your project. This one runs the linter after every file edit:
{
"hooks": {
"PostToolUse": [
{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "npm run lint" }] }
]
}
}
PostToolUse is the event after a tool runs. matcher picks which tools, here Edit and Write (the tools that change files).
Two hooks I use every day:
- In
/test-engineer-irfan, tests are locked by a hook, so the agent can't change them. Agents like to edit, skip or weaken tests to make them pass. A promise in the prompt doesn't stop that, a hook does. When the agent tries to touch a locked test, the hook blocks it. /learninginstalls hooks per repo. When a session starts, a hook loads the project memory. When the agent searches the code, a hook first checks the learning notes and shows what's already known. When the session ends, a hook reminds the agent to save what it learned.
SessionStart/learning loads the project memoryPreToolUse: grep/learning shows what is already known firstPreToolUse: edit a locked testtest lock BLOCKS the editPostToolUse: edit codelinter + unit tests runStop/learning reminds: save what you learned
Subagents#
A subagent is an agent controlled by another agent. The subagent doesn't have the parent's context, and the parent doesn't see the subagent's context. Each one has its own clean context.
That's great for running parallel jobs, like a group of agents each doing one piece. It also keeps the main session small, because the subagent reads the big files and only sends back a short result.
Two things I learned the hard way. First, a subagent doesn't see your chat. It also doesn't see the files the parent already read, or what my /learning hook loaded at session start. It does load CLAUDE.md. Two built-in helper agents, Explore and Plan, don't load it.
Everything else that matters has to be repeated in the handover prompt (the task message the parent gives the subagent).
Second, more agents is not always better. I cap mine at 4 running in parallel.
Your main agent read 10 files, then starts a subagent. What does the subagent see?
All five tools side by side#
| Tool | What it is | Good for |
|---|---|---|
CLAUDE.md | a text file read at the start of every session | your rules for every task |
| Skill | a prompt for one task, its header always in context | one job done one specific way |
| MCP | a standard way to talk to other services | data the terminal can't get |
| Hook | a command that runs on an event, every time | checks that must always run, like lint and tests |
| Subagent | an agent with its own clean context | parallel jobs and big reads |
Agents like to weaken tests to make them pass. What stops that every time?
Context#
Good tools are not enough. An agent still does bad work when it reads the wrong things or gets a vague task. It also does bad work when it stops because it feels done. The next three chapters fix those three problems.
Words you need:
- Context: everything the model can see at one time. On every message, the whole context is sent again.
/clear: starts a fresh chat./compact: replaces the old chat with a summary.
What is in the window before you type#
Your chat is only one part of the context. Before you type anything, Claude Code already loads:
- The system prompt: Claude Code's own instructions.
- Your
CLAUDE.mdfiles: the global one and the one in your project. - Skill headers: the name and description of every installed skill.
- MCP tool lists: every connected MCP server sends the list of tools it has.
Then, while the agent works, more goes in: every file it reads, every command output, and every message you send. Type /context in Claude Code to see what is in your window right now.
Why a full window hurts#
The model re-reads everything, on every message. So a big context is slow and expensive. It also gets harder for the model to follow the rules at the top. Those rules get lost under thousands of lines of logs and old file versions.
When I checked one day of my own sessions, some of them were re-reading 370k to 580k tokens on every message. That is a lot of money spent on reading the same things again.
Play with it. Turn things on and off, then try /compact and /clear:
Notice what /clear can't remove: the system prompt, CLAUDE.md, skills and MCP. Those load again in every new session. Only you can make them smaller (see "Keep the always-loaded stuff small" below).
You run /clear. What is still in the context window?
How I keep it clean#
-
One session per task. When a task (or one phase of a big task) is done, I run
/handoff, a command from my own setup. It writes a short note: the verdict (did it work or not), what changed, what's blocking, and what a human must check. The next session starts from that note instead of the whole old chat. -
/clearbetween unrelated tasks./clearstarts a fresh chat. -
/compactwhen a task is long./compactreplaces the old chat with a summary. Claude Code also compacts by itself when the window is almost full, but by then the session is already slow. -
Big reads go to subagents. A subagent reads the big files and long logs in its own context and sends back a short result (Controlling the agent chapter).
-
Give the end of a log, not the whole log. When an agent runs tests for me, it returns only four things:
- the command
- the exit code (0 means pass)
- the summary lines
- the path to the full log
I read the full log only when I need it.
-
Keep the always-loaded stuff small. A short
CLAUDE.md, only the skills I use, and CLIs (terminal commands) instead of MCP where the terminal can get the data. -
Small notes. My
/learningnotes (my own skill) follow the same idea: one doc per part of the app, max 40 lines each.
Writing specs#
Words you need:
- Spec: a prompt that leaves no gaps the agent has to guess.
- Done when: a check that says pass or fail, like a command.
- Plan mode: a Claude Code mode where the agent can only read and plan.
Every gap in your prompt gets filled with a guess. Each guess is probabilistic (Deterministic vs probabilistic chapter), so a vague prompt gives you a different result every run. A spec is a prompt that leaves no gaps the agent has to guess.
The parts of a spec#
- Goal: what to build and why.
- Rules: what to use, what not to touch, what is never allowed.
- Read first: the files and docs the agent needs.
- Done when: a check that says pass or fail, like a command. "Looks good" is not a check.
- Out of scope: what not to build yet, so the agent doesn't add extra work.
Here is our login page task as a vague prompt and as a spec:
Vague:
make a login page
Spec:
Goal: users sign in with email and password, so only members see the dashboard.
Rules: use the existing auth module. No new library. Never log passwords.
Read first: src/auth/ and docs/auth.md.
Done when: npm test and npm run lint pass, and a wrong password shows an error.
Out of scope: no sign-up page, no "forgot password" yet.
Tick the parts and watch the guesses go away:
make a login page
- Who signs in, and with what?
- What happens after login?
- Which library?
- Is it OK to log the password while debugging?
- Where is the existing code?
- How do I know I am finished?
- What if the password is wrong?
- Should I also build sign-up?
"Done when" is the most important line. It connects the spec to the deterministic checks from the Deterministic vs probabilistic chapter.
Which one is a real "done when" line?
Let the agent interview you first#
Writing a full spec alone is hard, because you don't know what you forgot. So I let the agent interview me before it writes any code. I use a skill called grilling for this (from Matt Pocock's skill set, an add-on, not built into Claude Code).
- The agent maps all the decisions the task needs.
- Facts in the code, files and docs it looks up by itself.
- Each round it asks every question it can, with its recommended answer first and the reason.
- You answer on a small web page. Only real decisions come to you.
- Then the agent writes a plan file from your answers.
- The agent maps all the decisions the task needs.
- Each round, it asks every question it can ask now. Each question comes with its recommended answer first and the reason behind it.
- Facts (what is in the code, the files, the docs) it looks up by itself. Only real decisions come to me.
- I answer on a small web page instead of in the chat. A page is easier for me to read, and the agent keeps working on other things while it waits.
Then the agent writes a plan file from my answers.
The Context to Loops chapters were first written after this interview. The agent reviewed the earlier chapters and asked me 6 questions on a page: split the post or not, which widgets, which title. It wrote nothing until I answered.
Claude Code also has a built-in plan mode (press Shift+Tab to switch to it). In plan mode the agent can only read and plan, not edit files.
The plan is the contract#
Once I approve the plan, it becomes the contract. The agent follows it and never adds work outside the plan by itself. If it finds work the plan doesn't cover, it stops and asks me. Small ideas it doesn't act on go in a "suggested, not done" list at the end.
The same idea works for tests. In my own /test-engineer-irfan skill, the expected values in a test come from the approved spec, never copied from what the code prints.
Loops and orchestration#
Words you need:
- Gate: a deterministic check the agent's work must pass, like tests, lint or build (Deterministic vs probabilistic chapter).
- Orchestrator: the one agent that splits the work, hands it out and checks the results.
- Handover: the task note the orchestrator gives to a subagent.
- Diff: the list of lines a change added or removed.
The outer loop#
In the How an agent works chapter you saw the agent loop: think, act, observe. That loop ends when the agent thinks it is done. But the agent's own "I am done" is only a guess.
So we add an outer loop around it. When the agent says "done", a deterministic gate runs (tests, lint, build). If the gate fails, the exact error goes back to the agent and it tries again.
For our login page, the gate is the "Done when" line from the spec: npm test and npm run lint must pass.
The loop I use is called ralph. It comes from the oh-my-claudecode plugin (an add-on for Claude Code). It keeps the agent working until the task is verified.
- The agent finishes its inner loop and says it is done.
- A deterministic gate runs: tests, lint, build.
- If the gate fails, the exact error goes back and the agent tries again.
- If a real command says pass, the loop stops. The task is verified.
- If the max number of tries is hit, the loop stops and a human looks at it.
A loop needs two ways to stop:
- The gate passes. A real command says pass.
- A limit is hit. If the spec is wrong, the agent can never pass. Without a limit, the loop spends tokens forever. So you set a max number of tries, then a human looks at it.
Run the loop. Then make the task impossible and run it again:
Your loop failed 5 times on the same error, and 5 is the limit. What happens next?
Orchestration: one agent leads, many agents work#
When a task is big, I split it across many agents. The rules I follow:
- Exactly one orchestrator. It doesn't do the big work itself. It splits the task into phases, hands each piece to a subagent, and checks the results.
- Every handover uses the same template: objective, hard rules, inputs, definition of done, and output format. That's a spec again. A subagent doesn't see the chat, so the important rules get repeated inside it.
- Max 4 agents at the same time. More work waits in a queue.
- Nobody approves their own work. The builder (the agent that wrote the code) checks its own diff first, but that isn't an approval. A separate review agent reads the diff.
- Review has limits too. Max 2 review rounds per phase, and a 60 minute time limit. If a problem is still not fixed when time is up, the result is BLOCKED (stopped, waiting for a human) and the agent asks me.
- Results are command output. A test result is the real output of
npm test, never an AI summary of it. - Phase by phase. Each phase is finished and verified before the next one starts. At the end there is a verdict document: what was done, what changed, and the test evidence.
Here is the whole flow:
When a gate fails, the orchestrator sends the error back to the agent that did that piece, and it tries again.
Now you be the orchestrator. Hand the tasks to your agents:
The widgets in the Context to Loops chapters were built the same way. One agent built them from a handover. A separate agent reviewed the diff. Tests, lint and build had to pass before I looked at it.
Recap#
The model is the probabilistic part, and you can't change that. What you control is everything around it.
| You can now | How |
|---|---|
| explain why an LLM can be wrong and still sound sure | it predicts the most likely answer, not the true one |
| explain why long sessions get slow | every message sends the whole chat again |
| put gates around the AI's work | linters, tests, and guards inside your tools |
| describe the agent loop | think, act, observe, until it matches "finished" |
| pick the right control | CLAUDE.md, skills, MCP, hooks or subagents |
| keep your context small | /clear, /handoff and subagents |
| write a spec | goal, rules, read first, done when, out of scope |
| plan before code | let the agent interview you, and treat the plan as the contract |
| stop every loop | the gate passes, or a limit is hit |
| run big work | one orchestrator, max 4 agents and a separate reviewer |
Try it:
- Before you start any task with AI, ask yourself what gates it needs. Then build those first.
- Before your next task with an agent, write the "done when" line first.
- Then decide what stops the loop: which command must pass, and what the limit is.
Read next: Claude Code token diet.