What does this solve?
Claude Code agents (they are also called subagents) are individual executors whom the main session launches for a specific subtask and receives a short summary from them instead of the entire draft output. The pain here is simple: searching the repository, reading logs and searching through files fills the context with garbage, after which the agent loses the original task and begins to argue with itself. The subagent grinds the volume in its window and returns the paragraph. The second benefit is rights: the scout is given read only, and he physically cannot break anything in the working tree.
How it works
Agent file
The description is in the markdown file: .claude/agents/<имя>.md for project agents, ~/.claude/agents/<имя>.md for personal.
---
name: explorer
description: Read-only разведчик по кодовой базе — найти файлы, проследить поток вызовов, ответить «где происходит X». Диспетчить перед правкой незнакомого модуля и когда нужен список всех вызовов символа.
model: sonnet
tools: Read, Glob, Grep, Bash
---
Ты ищешь и читаешь код, ничего не меняя. Файлы адресуются абсолютными путями,
git запускается как `git -C <корень> ...`.
Чего не делать: не править файлы, не ставить зависимости, не запускать сборку и тесты.
Формат ответа: сначала список найденного строками вида `путь:строка — что там`,
потом три-пять строк вывода. Содержимое файлов целиком не пересказывать.
Header margins: name — name to call, description — when this agent is dispatched, tools —white list of tools, model —which model works (value inherit takes the parent session model). The body of the file works as a system prompt for the executor.
What happens when you call
- The main session formulates the task in text and transfers it to the subagent.
- The subagent starts with a clean context: he sees his system prompt and the received statement. He does not see the history of the main dialogue.
- Works with its tools in as many steps as necessary.
- Only the final text is given out. Intermediate readings, greps and dead ends do not fall into the main context.
Point 2 is the source of most failures. The subagent does not know what the conversation was about, does not see the already open files and cannot ask the person again. Everything you need fits into the statement: absolute paths, branch names, readiness criteria, response format.
How to calculate savings
A subagent is beneficial where there is a lot of text at the input and little output: forty files, a thousand lines of log, a diff of five hundred lines - and back ten lines of output. The difference between input and output remains in someone else's window and is not transferred to the main context.
The opposite situation - the input is a couple of lines, the output is a long code, which you then still need to edit in the dialog - does not provide savings: the code will arrive in the main context in its entirety, plus the launch of a separate agent will be paid for.
White list of tools
tools: Read, Glob, Grep means that the agent will not write to the file, even if it decides that it is necessary. The ruling agent is added Edit, Write, Bash. The minimum set not only saves nerves: the agent does not waste steps on tools that are not useful to him, and does not go away to fix something that he was not asked to do.
Model for the task
Mechanical work - collecting a list, marking it according to the rules, renaming it according to a template - makes the model simpler. Reasoning about the cause of the bug and analysis of someone else's patch - the eldest. Field model solves this once in the agent description, and not every time by hand when starting.
Batch instead of fan-out
On the task of “processing many elements of the same type,” the temptation is to run an agent per element. Each agent pays for its own system prompt, its own setup and its own warm-up, and the total expense is a multiple of that of the same amount of work, distributed in batches: one agent takes a stack of elements and returns the total result for them. Fan-out for one element is justified only where the elements are expensive and independent, and the result for each is needed in a separate text.
How to connect
- Create a directory in the repository:
mkdir -p .claude/agents
- Write an agent for a specific job:
cat > .claude/agents/reviewer.md <<'EOF'
---
name: reviewer
description: Ревью диффа текущей ветки на предмет ошибок и лишних правок. Диспетчить перед созданием MR и при просьбах «посмотри мой дифф», «проверь ветку».
model: inherit
tools: Read, Glob, Grep, Bash
---
Читаешь дифф ветки относительно базовой и файлы вокруг него, ничего не меняя.
Ищешь: сломанную логику, потерянные при мерже куски, правки, не относящиеся
к задаче, секреты в коде, изменения в файлах окружения.
Формат ответа: список замечаний, каждое строкой `файл:строка — что не так — чем грозит`.
Порядок — от блокеров к мелочам. Если замечаний нет, ответить одной строкой «замечаний нет».
EOF
- Trim
toolsto a minimum. For the researcher - reading and searching; for the ruler - plus a record, and better in a separate working tree. - Specify the return format. This is the most important field of the body: the main session will receive only text, and everything that is not included in the format will be lost.
- Check the call with an explicit request: “use the reviewer agent on the current branch.”
- Commit
.claude/agents/—then the whole team has an agent.
Useful scripts
- Reconnaissance for an unfamiliar module: directory map, entry points, who is calling whom - read only.
- Diff reviewer: reads the entire thread, returns comments with coordinates
файл:строка. - Collector of excerpts from logs: thousands of lines as input, dozens of relevant ones as output.
- Independent reviewer of the patch: he did not see how the patch was written, and therefore does not defend it.
- Mass marking of cards, letters or tickets according to the rules - in batches.
- The same checklist for several services in parallel, each service to its own agent.
Limitations
- The subagent does not see the dialogue and does not ask clarifying questions. An unsaid statement gives confidently done the wrong job.
- Return - text. Details that are not included in the response format are lost forever: there is nothing to ask again from the terminated agent.
- Debugging is more difficult than usual. The steps are not visible, but the result is visible; a bad answer is sorted out by re-running with a narrower formulation.
- Savings are not free: the system prompt and setup are paid for at each launch, so a small task through an agent is more expensive than the same task directly.
- Multiple ruling agents in the same work tree are in conflict. One should write to files, the rest should read.
- The subagent does not replace the work plan: the main session builds a chain of five dependent steps, the agent takes one step.
- A metric or conclusion that comes from an agent cannot be retold further without selective verification with the original source: the agent answers confidently even in case of an error.
How to check the result
- Run one task with and without an agent, compare what remains in the main context (
/context) and how many steps it took to complete. - Check permission boundaries: ask the read-only agent to change something. Refusal should come from the level of tools, and not from the politeness of the model.
- Read the return with your eyes and ask: would this text be enough for a person who has not seen the source? What was not enough was to edit the response format in the agent’s body, and not the statement every time.
- Give a deliberately incomplete production and see what comes back. The agent, who silently thinks out what is missing, requires a more stringent prompt with an explicit “if there is a lack of data, return a question, not a guess.”
- Check two or three links selectively
файл:строкаfrom the answer with real files. An error in coordinates means that the agent is retelling from memory, and not from what he read.
One line rule: a subagent is justified where there is a lot of text at the input, and a short output at the output, and everything necessary for the work is included in the statement.
