An agent today can be assembled in an evening: a long prompt, a couple of tools, and he does something. The difficulties begin later: the behavior cannot be verified, any edit of the prompt breaks something, and the question “why did he do that?” no answer.
In this article we will look at how to design an agent as an engineering object: with specifications, tests, restrictions and metrics. The approach is compiled from Spec-Driven Development (SDD), models of agent maturity and autonomy, and the practices of teams that have already implemented agents in development.
For whom: developers and team leads who are already working with Claude Code, Cursor or another agent and want to make their own for a specific team task.
End-to-end example: agent reviewer who checks the pull request for compliance with the feature specification (spec.md) and leaves a report. It is useful in itself, and all layers are clearly visible on it: reading data, actions with consequences, escalation to a person. Example files are given in Claude Code format, but the approach is transferable to any tool.
What you get at the end: six artifact files (constitution, agent spec, skills, reference examples, access rules, metrics).
Contents
First look for something ready
Most likely, someone has already solved your problem and registered it as an agent or skill. Taking something ready-made and adapting it to suit you is faster than writing from scratch.
Where to look - from reliable to noisy:
Official catalogs of your tool. For Claude Code - plugin marketplaces (
/plugin) and anthropics/skills.Search GitHub code by file structure. Agents and skills have standard paths, so this is more accurate than the description:
path:.claude/agents review,filename:SKILL.md "spec",path:.agents/skills, or from the terminalgh search code "spec compliance" --filename SKILL.md.Skill collections - for example, obra/superpowers, garrytan/gstack, addyosmani/agent‑skills. They are also useful because you can see how the work is divided between agents.
Awesome lists and articles - only as a source of candidates: they are often written by the authors of the tools themselves.
How to select:
Character | Good | Bad |
|---|---|---|
Activity | Commits for the last 1–3 months | Year without changes |
License | MIT, Apache-2.0 | No license or restriction (Commons Clause) |
Target | One narrow task, clear output format | “Does everything” |
Permissions | Tools are limited, reading is separated from actions | Full access, |
Verifiability | There are tests or evals of the skill itself | README only |
Installation | Files inside the project | Global installation, git hooks, daemons, |
Stars are a weak signal: Popular repositories have a lot of listings and marketing.
How to use. Someone else's skill is an instruction that the agent will carry out with your rights, that is, essentially a code. Read it in its entirety, copy it to the repository and adapt it to your own rules. Test with 10–20 of your own examples and commit to a version. You will almost always have to add restrictions (prohibitions, limits, journal) yourself - how to do this is described in step 5.
If there is no ready-made agent or you need your own agent, read on. Let's figure out how to design it from scratch so that it can be tested and limited.
Why do agents break down?
Most homemade agents are prompts that have been given tools. It has no written purpose, no boundaries, and no way to check the outcome. This is called agent-washing: a chatbot or text generator poses as an agent.
A good filter is the five criteria for a “real” agent. They are convenient to use as technical specifications: each criterion is then covered by a specific file.
Criterion | How to close | Step |
|---|---|---|
There is an explicit specification of the task and action boundaries, rather than just a system prompt |
| 1, 3 |
Success criteria are separate from the agent and verified by someone else | Benchmark set and tests | 4 |
There is a path of escalation when going beyond the limits of confidence | Section “Escalation” in the spec | 3 |
The level of autonomy is explicitly named and confirmed by metrics | Level R0–R5 in the spec, metrics at launch | 1, 6 |
Reproducing and testing the result | Reference examples, activity log | 4, 5 |
A textbook example of what happens without these criteria is the Replit incident in July 2025. During a user-declared code freeze, the agent deleted the product database and then incorrectly reported that rollback was not possible (AI Incident Database, #1152). The prohibition existed only as a text, and the only check on the agent was the agent himself.
Agent architecture at a glance

The agent does not act directly: any action goes through external rules and a separate skill with narrow rights, and everything controversial goes to the person. Next, we will analyze each block step by step.
Step 1. One goal, mode and level of autonomy
The agent must have one goal, which can be stated in one sentence. If it doesn't work out, you have multiple agents: several small and clearly limited agents are more reliable than one large one with hidden logic.
For our example:
Goal. For each FR/NFR requirement from
spec.mdsay whether it is implemented in the PR, and find behavior in the code that is not in the spec.
Next, select the mode and permission level. The R0–R5 scale from the whitepaper “AI-Disrupt PDLC” (Sber, v2.0, section 4.3) is convenient: it describes what an agent can do in a specific environment.
Level | What is allowed | When applicable |
|---|---|---|
R0 | Read Only | Prod without verified evals |
R1 | Only suggestions, the person decides | Critical sales paths |
R2 | Actions in the PR review thread | Standard development |
R3 | Automatic merging when passing evals | Standardized templates |
R4 | Multiple sessions with checkpoints | Long tested scripts |
R5 | Full autonomy | Isolated sandbox only |
The level is set not for the agent as a whole, but for the environment: the same agent can be R1 in production, R3 in the branch and R5 in the sandbox. The more critical the task and the higher the risk, the lower the level.
The new agent starts at R1–R2, even if the target is R4. Each stage must be passed and confirmed with metrics, and not declared: “jumping levels” is one of the most common implementation mistakes.
Our reviewer works in assistant mode on R1: he prepares a report, and a person makes the decision on the merge. An agent can neither approve nor reject a PR.
Step 2. Constitution and three levels of prompt
One long prompt that is ruled in its entirety is the main source of regressions. Divide it by how often each part changes:
Level | What's inside | How often does it change | Where does he live |
|---|---|---|---|
1. Constitution | Role, boundaries, sacred rules | Rarely, via code review | Agent description body |
2. Context | Spec features, project constitution, diff | For each launch; is loaded and not written by hand | Repository files, MCP |
3. Instructions | Specific task of this call | Every call | User request or CI |
Division has two effects. The first is security: editing the context does not affect the rules of the constitution. The second is money: the stable part can be cached. How much this reduces the cost of requests in your case needs to be measured: the figures from other people’s presentations differ greatly.
In Claude Code, an agent can be described as a subagent - a markdown file with a frontmatter. The body of the file is the agent's constitution:
---
name: spec-reviewer
description: Checks a pull request against the feature spec (specs/<feature>/spec.md) and returns a compliance report. Use after implementation, before human review. Read-only.
tools: Read, Grep, Glob
model: sonnet
maxTurns: 20
---
# Роль
Ты — ревьюер соответствия спецификации. Ты не оцениваешь стиль и не предлагаешь рефакторинг.
# Входные данные
Вызывающий передаёт тебе два пути:
- SPEC — файл спецификации, например specs/010-pager/spec.md
- PACKAGE — пакет для ревью (коммиты + дифф), собранный scripts/review-package.sh
Если одного из путей нет или файл не читается — остановись и сообщи об этом.
# Границы
- Только чтение. Не меняй код, тесты и спеку.
- Не одобряй и не отклоняй PR — решение за человеком.
- Каждое утверждение подкрепляй ссылкой file:line из пакета.
# Как работать
1. Прочитай SPEC и выпиши все требования FR-xxx и NFR-xxx / SC-xxx.
2. Прочитай PACKAGE один раз.
3. Для каждого требования поставь статус: implemented / partial / not_implemented /
needs_human (нельзя проверить по диффу).
4. Отдельно перечисли поведение в диффе, которого нет ни в одном требовании.
5. Найди не менее пяти конкретных расхождений или явно объясни, почему их нет.
# Эскалация
Верни только раздел «Эскалация» без статусов, если:
- в SPEC есть [NEEDS CLARIFICATION];
- дифф затрагивает больше 30 файлов.
# Формат ответа
## Статусы
| Требование | Статус | Где (file:line) | Комментарий |
## Незаявленное поведение
- file:line — что делает код
## Вопросы к автору
- ...Please note the tools field: the reviewer does not physically receive recording tools. The prohibition “don’t change the code” is duplicated not by text, but by setting - we will return to this principle in step 5.
And one more rule of thumb: don’t inflate a constant context. Put everything that is not needed for every call into skills, which are loaded as needed, and make sure that each rule has one owner.
Step 3. Specification of the agent and his skills
The constitution tells the agent how to behave. A specification is a document for people: what an agent does, what data it works with, what rights it has, and when it must stop. It is read for review and behavior is checked using it.
Main architectural decision: reading and actions are separated. The agent reads the data through MCP or files - reading has no side effects. Any action with consequences goes through a separate skill with its own specification: inputs, outputs, rights, code. Then each action of the agent can be separately limited and verified.
What the reviewer checks: spec.md features. This is what such a file looks like in a real project: pamburus/hl is a log viewer for Rust (about 3.3 thousand stars), the features of which are maintained through the Spec Kit. Below are verbatim fragments of specs/010-pager/spec.md (commit fbfb7f6, MIT, © 2020 Pavel Ivanov); […] are my omissions. The full file contains 9 user stories, 71 requirements, and three refinement sessions.
# Feature Specification: Pager Integration and Configuration
**Feature Branch**: `010-pager`
**Created**: 2025-01-15
**Status**: Draft
**Input**: User description: "Add feature describing how pager is handled, with configurable pager profiles, priority-based selection, and role-specific arguments for view and follow modes"
## Clarifications
[…]
### Session 2026-02-15
- Q: How should the application execute the pager program to prevent security vulnerabilities? → A: Execute pager directly from PATH without shell, validate it's executable before spawning
- Q: What should the user experience be when the specified pager program is not found or cannot be executed? → A: Write error to stderr, fall back to direct stdout (disable paging)
[…]
- Q: What exit code should the application use when the pager crashes or is killed unexpectedly? → A: Exit with code 141 (SIGPIPE convention, matching broken pipe)
[…]
## User Scenarios & Testing *(mandatory)*
[…]
### User Story 3 - Graceful Exit When Pager Closes (Priority: P1)
When a user closes the pager (e.g., pressing 'q' in less), the application should detect the pager exit and terminate gracefully without error messages or hanging processes.
**Why this priority**: Critical for user experience - users expect quitting the pager to cleanly exit the application. Hanging or error messages create confusion and frustration.
**Independent Test**: Can be tested by running the application with large input, closing the pager, and verifying the application exits with status code 0.
**Acceptance Scenarios**:
1. **Given** the application is running with output piped to a pager, **When** the user quits the pager normally, **Then** the application process terminates within 1 second with exit code 0
2. **Given** the application is in follow mode with a pager enabled via profile configuration, **When** the user quits the pager, **Then** the application stops monitoring and exits cleanly
3. **Given** the pager crashes or is killed unexpectedly, **When** the application detects the abnormal exit, **Then** the application writes the error message "hl: pager killed" to stderr, resets ANSI color/formatting codes, restores terminal echo mode, and exits with code 141
4. **Given** the user quits the pager while the application is still writing output, **When** the write to pager's stdin fails with broken pipe error, **Then** the application stops processing and exits gracefully with exit code 0 without logging an error
[…]
### Edge Cases
[…]
- How should SIGPIPE be handled when user quits pager early?
- Ignore SIGPIPE signal, treat write errors (broken pipe) as normal termination condition, exit gracefully with status code 0
[…]
## Requirements *(mandatory)*
### Functional Requirements
[…]
- **FR-002**: System MUST launch a pager automatically when stdout is a TTY, no output file is specified, and paging mode is "auto" (default)
- **FR-003**: System MUST provide a `--paging` command-line option accepting values `auto`, `always`, or `never` with `auto` as the default
[…]
- **FR-004a**: System MUST disable paging when output is explicitly directed to a file via `--output` or `-o` option
[…]
- **FR-005**: System MUST execute the pager program directly from PATH without shell interpretation to prevent command injection vulnerabilities
[…]
- **FR-005b**: System MUST validate that the specified pager executable exists and has execute permissions before attempting to spawn the process
[…]
## Success Criteria *(mandatory)*
### Measurable Outcomes
[…]
- **SC-001a**: Pager interface appears immediately (within 100ms) after application launch when paging is enabled
- **SC-002**: Application exits within 1 second of pager termination in 100% of normal cases
[…]
- **SC-006**: Test coverage for pager-related code must not be less than the current test coverage on the target branchWhat's happening here - in blocks:
Head (Feature Branch, Status, Input) connects the spec with the branch and preserves the original statement of the problem in the words of the author.
Clarifications - Clarify step Q&A log with session dates. The solution is not lost in the chat, but turns into a requirement: the answer about running “without shell” became FR-005, about checking executability - FR-005b, about code 141 - scenario 3 in User Story 3.
User Story carries three things that are not in a regular ticket: the reason for priority (Why this priority), an independent test (Independent Test) and acceptance scripts Given/When/Then with numbers (1 second, exit codes 0 and 141, the exact text of the error).
Edge Cases record behavior in abnormal situations - this is where the agent most often “thinks it through.”
Functional Requirements in the form “System MUST...” with numbers. It's not EARS, but the main feature is the same: each requirement can be verified and referenced by number. It is these numbers that the reviewer puts in his status table.
Success Criteria - measurable results (100 ms, 1 second 100% of the time, coverage not lower than current).
What this spec doesn’t include: a business result hypothesis and a human validation map. To work with agents in your team, it is worth adding them.
It is with this file that the reviewer checks the diff. If in PR the pager began to be launched via sh -c, this is a violation of FR-005. If there is a new option that is not in any of the requirements, it is undeclared behavior. Both cases will occur in the reference example in step 4.
Now the agent himself.
Our reviewer's spec (docs/agents/spec-reviewer.md):
# Агент: spec-reviewer
## Цель
Для каждого требования из spec.md сказать, реализовано ли оно в PR,
и найти поведение, которого нет в спеке.
## Режим и разрешения
Ассистирующий, R1: агент только предлагает, решение о слиянии — за человеком.
## Входные данные (только чтение)
- specs/<фича>/spec.md — из репозитория
- Пакет для ревью — scripts/review-package.sh <BASE> <HEAD> <файл>
- Описание PR — gh pr view <номер> --json title,body (токен только на чтение)
- constitution.md проекта
## Выход
Отчёт по шаблону: таблица требование → статус → file:line;
незаявленное поведение; вопросы к автору.
## Действия (скилы)
- post-review-comment — опубликовать отчёт комментарием в PR
(вызывает оркестратор, не сам ревьюер)
## Запрещено
- Менять файлы, делать коммиты, одобрять / отклонять / сливать PR
- Читать .env и secrets/
## Эскалация к человеку
- spec.md содержит [NEEDS CLARIFICATION]
- Дифф больше 30 файлов
- Требование нельзя проверить по диффу → статус needs_human, а не догадка
## Ограничения
- maxTurns: 20 в определении субагента
- В CI: claude -p ... --max-turns 30 --max-budget-usd 2The review package assembles the deterministic script scripts/review-package.sh. This is a simplified version of the review-package script from obra/superpowers (MIT, © 2025 Jesse Vincent) - the original is shown in the superpowers section below. The link to the plan file has been removed and a limit on the number of files has been added:
#!/usr/bin/env bash
# scripts/review-package.sh BASE HEAD OUTFILE
# Based on obra/superpowers skills/subagent-driven-development/scripts/review-package
# (MIT License, Copyright (c) 2025 Jesse Vincent)
set -euo pipefail
if [ $# -ne 3 ]; then
echo "usage: review-package.sh BASE HEAD OUTFILE" >&2
exit 2
fi
base=$1; head=$2; out=$3
max_files=${MAX_FILES:-30}
git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; }
git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; }
git merge-base --is-ancestor "$base" "$head" || { echo "HEAD is not a descendant of BASE" >&2; exit 3; }
[ "$(git rev-list --count "${base}..${head}")" -gt 0 ] || { echo "empty commit range" >&2; exit 3; }
files=$(git diff --name-only "${base}..${head}" | wc -l | tr -d ' ')
[ "$files" -le "$max_files" ] || { echo "too many files: $files > $max_files, escalate to a human" >&2; exit 4; }
mkdir -p "$(dirname "$out")"
{
echo "# Review package: ${base}..${head}"
echo; echo "## Commits"; git log --oneline "${base}..${head}"
echo; echo "## Files changed"; git diff --stat "${base}..${head}"
echo; echo "## Diff"; git diff -U10 "${base}..${head}"
} > "$out"
echo "wrote $out: $files file(s)"How to launch. In an interactive Claude Code session, just ask: “Use the spec-reviewer subagent. SPEC=specs/010-pager/spec.md PACKAGE=.review/pr-412.diff.” In CI it’s like this (you need a full history, for example fetch-depth: 0, and a token GH_TOKEN with rights to read PR):
PR=412
git fetch origin "pull/$PR/head"
BASE=$(gh pr view "$PR" --json baseRefOid -q .baseRefOid)
HEAD=$(gh pr view "$PR" --json headRefOid -q .headRefOid)
scripts/review-package.sh "$BASE" "$HEAD" ".review/pr-$PR.diff"
claude -p "Use the spec-reviewer subagent. SPEC=specs/010-pager/spec.md PACKAGE=.review/pr-$PR.diff. Print only the report." \
--max-turns 30 --max-budget-usd 2 > ".review/pr-$PR.md"Publishing a report is a separate step, through the skill below or directly using its script.
And a skill for a single action with consequences (.claude/skills/post-review-comment/SKILL.md):
---
name: post-review-comment
description: Publishes a saved spec-reviewer report as a comment on a pull request. Use only when the report file already exists.
argument-hint: <pr-number> <report-file>
allowed-tools: Bash(${CLAUDE_SKILL_DIR}/scripts/post_review_comment.sh *)
---
Опубликуй отчёт одной командой:
`${CLAUDE_SKILL_DIR}/scripts/post_review_comment.sh <номер PR> <файл отчёта>`
- Не вызывай `gh` напрямую и не меняй аргументы скрипта.
- Если скрипт завершился с ошибкой — покажи её человеку и остановись.
- Верни ссылку на комментарий, которую напечатал скрипт.Script next to the skill (.claude/skills/post-review-comment/scripts/post_review_comment.sh, don't forget chmod +x):
#!/usr/bin/env bash
# Публикует отчёт spec-reviewer комментарием к PR. Только комментарий: без approve, review и merge.
set -euo pipefail
pr="${1:?usage: post_review_comment.sh <pr-number> <report-file>}"
report="${2:?usage: post_review_comment.sh <pr-number> <report-file>}"
[[ "$pr" =~ ^[0-9]+$ ]] || { echo "PR number must be numeric: $pr" >&2; exit 2; }
[ -s "$report" ] || { echo "report file is missing or empty: $report" >&2; exit 2; }
size=$(wc -c < "$report")
[ "$size" -le 65000 ] || { echo "report is too large: $size bytes (max 65000)" >&2; exit 2; }
gh pr comment "$pr" --body-file "$report"The action is wrapped in a script deliberately. We write the logic that should be predictable (validation, format, API call) in deterministic code. LLM leaves where analysis and formulation are needed.
The reviewer himself does not use this skill: he only has Read, Grep and Glob. It returns a report, and the orchestrator publishes it - the main session or CI step. Thus, analysis and action are distributed among different performers with different rights.
MCP, API or CLI: through which an agent can work with external systems
MCP is not the only way. If the agent can run commands in the terminal (Claude Code, Codex CLI, Cursor in agent mode and others), it can work through the usual CLI tools: gh, glab, kubectl, aws, psql, jq. Our publishing skill works like this: inside there is a call gh pr comment.
Method | Strengths | Weaknesses | When to choose |
|---|---|---|---|
MCP server | Typed tools, server-side authorization, works even where there is no terminal | Descriptions of tools provide context; need a server and its support | Reading data from systems without CLI; agents without command line access |
API via your script | Full control: input validation, output format, repeats | The script needs to be written and tested | Actions with consequences where predictability is needed |
CLI tool | Nothing needs to be unwrapped; models know popular CLIs well; the output can be easily filtered through | Broad rights by default; The CLI runs under your credentials | Agent with a terminal and a common tool with a good CLI |
Rules for working via CLI:
Allow specific commands, not the entire tool. Terminal access is the broadest of the agent's rights. In Claude Code, rules are specified by command prefix: allow
Bash(gh pr view *)andBash(gh pr diff *), denyBash(gh pr merge *)(see step 5).Individual tokens. The CLI takes the token under which it is authorized. For the agent, set your token via an environment variable (for
gh-GH_TOKEN) with minimal rights, and not a personal developer session.Non-interactive mode and machine output. Use flags like
--json,--yes,--no-pagerand limit the volume (--limit,head): long output wastes context, and an interactive request will hang the agent.Output is data, not instructions. The text of an issue, comment, or log may contain an attempt at prompt injection. Prohibitions in access settings protect against this as well.
Wrap actions with consequences in a script. The agent calls
scripts/post_review_comment.sh, and does not assemble the commandghitself. Then exactly one script can be allowed, and its logic is checked by regular tests.
A typical scheme for our reviewer: reading PR via gh pr view --json and gh pr diff (or MCP with a read-only token), the only action is through a script skill, everything else is prohibited by the settings.
Step 4. Acceptance criteria and reference examples
An agent should not evaluate himself. The marking of the “correct answer” is done by a person in advance, and the comparison is performed by a script. This is the same principle as in SDD: acceptance criteria are encoded in tests, rather than described in words.
Reviewer acceptance criteria (added to agent spec):
WHEN the requirement is implemented and covered by the test, THE SHALL agent set the status “implemented” with a link to the code and test.
IF there is no code in the diff for the requirement, THEN THE SHALL agent put “not implemented” and not “partially”.
IF code adds a behavior that is not in the spec, THEN THE SHALL agent list it in the “undeclared behavior” section.
IF spec.md contains
[NEEDS CLARIFICATION], THEN THE agent SHALL stop and escalate without setting statuses.
A set of reference examples. Take 10-20 already merged PRs from your repository, for which there is a spec, and mark them up manually. Add several “traps”: PR with unnecessary behavior, PR without tests, spec with [NEEDS CLARIFICATION].
# evals/spec-reviewer/case-007.yaml
pr: 412 # PR с доработкой пейджера
spec: specs/010-pager/spec.md
expected:
FR-003: implemented
FR-004a: implemented
FR-005: not_implemented # пейджер запускается через sh -c
undeclared:
- "новая опция --pager-timeout" # в спеке нет такого требования
must_escalate: falseThe script runs the agent through all the examples and counts two numbers: the share of correct statuses and the number of false “implemented” statuses. The second is more important: a false “everything is fine” is more dangerous than a false alarm. The set is run with every change in constitution, skills or model - just like tests are run when the code is changed.
Separately check out escalations: the whitepaper “AI‑Disrupt PDLC” separates them into a class of their own, evals. Ambiguous cases are included in the set, and it is checked that the agent stops and does not guess. The quality of a reviewer is measured by the percentage of matches with a person; The whitepaper sets a goal of no lower than 80–85%.
And one more EPAM observation: a reviewing agent without an explicit attitude is prone to optimism and approves of almost everything. Add an adversarial attitude to the reviewer’s constitution: “find at least five specific discrepancies or justify why there are none.”
Add the result of each launch to evidence bundle (Evidence Bundle): report, evals results, call log and token consumption. With it, a person checks not “by eye”, but according to the facts.
If the same example fails and you have to edit the prompt for the third time, stop: most likely, the agent spec or the target itself is inaccurate.
Step 5. Constraints: rules in the code, not in the prompt
A prohibition in a prompt is a request that the model can ignore. Real constraints are checked outside of the agent's decision and physically block the action. This is called Policy as Code.
It is worth distinguishing from rules as Guardian agents—agents who check other agents. The whitepaper “AI‑Disrupt PDLC” (section 4.5) describes their maturity on a scale T1–T5:
Level | What does a protective agent do |
|---|---|
T1 · Review | Looks at the agent's output and prepares a report for the human |
T2 · Verification | Actively checks with tests and evals, issues pass/fail |
T3 · Redirect | Sends risky actions to a person for approval |
T4 · Lock | Stops risky actions |
T5 · Correction | Corrects violations himself, for example, publishes a PR with a correction |
Our spec-reviewer is a T1-level Guardian for agents who write code. But the reviewer himself also needs external rules: any agent with real rights must work under prohibitions that are checked outside of his decision. Confirmations for each step are a poor substitute for such bans: according to Anthropic data cited in the whitepaper, after 20 or more requests per session, the accuracy of confirmations drops from 85% to 55%. The solution is to reduce the number of requests: set strict bans and combine low-risk actions into batch confirmations.
For our reviewer at Claude Code, such prohibitions are set in .claude/settings.json of the project:
{
"permissions": {
"allow": [
"Bash(gh pr view *)",
"Bash(gh pr diff *)",
"Bash(scripts/review-package.sh *)"
],
"deny": [
"Read(./.env)",
"Read(./secrets/**)",
"Bash(git push *)",
"Bash(gh pr merge *)",
"Bash(gh pr review *)"
]
}
}Even if someone accidentally changes the constitution, the PR agent will not be able to approve or suppress it. For the exact syntax of the rules, check the documentation for your version of the tool; For complex checks, hooks are used that fire before the tool is called.
Other limiters:
Separate credentials. The agent does not work under your token: MCP has a read-only token, the publishing script has a comment-only token.
Step limit. In a non-interactive run, limit the number of moves the agent can take (in Claude Code, flag
--max-turns) to prevent it from getting stuck.Budget. Spending limit and alerts from the model provider; stop due to consumption, even if the agent is working “correctly”.
Log. Each run saves the input, tool calls, and output - for example, as a CI artifact. Without this, there is nothing to investigate the agent's mistake.
Step 6. Launch and metrics
We launch the agent next to the regular process, and not instead of it. On R1, the reviewer writes a report, and the person conducts his review as usual and notes where the agent made a mistake.
Before the launch, take a baseline: average time to the first PR review, the share of PRs that were returned for revision due to non-compliance with the requirements, the number of defects “misunderstood” after the release.
Metric | What does show? | How to count |
|---|---|---|
Outcome Validation Rate | Share of reports with which the human reviewer agreed without edits | True/false mark under each report |
False “implemented” | Agent's Most Dangerous Mistake | Human marking + reference set |
Proportion of escalations | Too little - agent guesses; too much - useless | Run log |
Time to first review and percentage of improvements | Real effect for the team | Comparison with baseline |
Cost per PR | Does the agent pay off | Provider billing / PR number |
Don’t count “how many reports an agent has written”: volume creates the illusion of productivity, and the percentage of those not redone shows the real one.
When to increase autonomy. When the metrics are stable for several weeks, and there are no false “implemented” ones, you can switch to R2: the agent himself publishes a report in PR through the skill, and the decision about the merger remains with the PR reviewer. Set the thresholds in advance, before the launch, so as not to adjust them to the result.
Check any change in the agent (new version of the prompt, different model) against the reference set and based on metrics, and not based on the feeling “it seems to be better.” Return the agent's incidents and errors to his spec and to his set of examples - this way the spec becomes more accurate over time.
Example from an open source project: obra/superpowers
The closest thing to the described reviewer is the subagent-driven-development skill from the obra/superpowers repository (MIT license, about 299 thousand stars as of October 2026). In it, one subagent implements the task from the plan, and the other checks the diff for compliance with the specification. The repository was found among GitHub projects with the most popular AGENTS.md files.
What's in the article | As in superpowers | Coincide |
|---|---|---|
Single goal: spec compliance + undeclared behavior | Spec Compliance Section: Missing / Extra / Misunderstood | yes |
Reviewer only reads | Review is read‑only, working tree and branch are prohibited from touching | yes |
Analysis and action by different performers | The controller is active, the reviewer only returns a report | yes |
Adversarial setup | "Don't trust the performer's report", every comment with file:line | yes |
Escalation instead of guesswork | Status ⚠️ “cannot be checked by diff”; 4 stopping conditions (irreversible, safety, off-branch action, broken plan) | yes |
Evidence Package and Journal | Script | yes |
Step limit and budget | No more than 5 rounds of corrections per task; the cheapest suitable model for each role | yes |
Testing the agent itself using examples | Skill tests via subagents ( | partially |
Prohibitions by access settings (deny) | Prohibitions only in text in the prompt | no |
Publishing a report in PR and metrics | The report remains inside the session, there are no quality metrics | no |
7 out of 10 elements match completely and one more partially matches. What is missing is what the article brings out from the prompt: prohibitions in settings and metrics.
Below are verbatim excerpts from the repository (commit 5 bf4e78, MIT, © 2025 Jesse Vincent); […] are my omissions. Full files: task‑reviewer‑prompt.md and scripts/review-package.
Task reviewer prompt (task-reviewer-prompt.md, fragments):
# Task Reviewer Prompt Template
Use this template when dispatching a task reviewer subagent. The reviewer
reads the task's diff once and returns two verdicts: spec compliance and
code quality.
**Purpose:** Verify one task's implementation matches its requirements (nothing
more, nothing less) and is well-built (clean, tested, maintainable)
[…]
Your review is read-only on this checkout. Do not mutate the working
tree, the index, HEAD, or branch state in any way.
[…]
## Do Not Trust the Report
Treat the implementer's report as unverified claims about the code. It
may be incomplete, inaccurate, or optimistic. Verify the claims against
the diff. Design rationales in the report are claims too: "left it per
YAGNI," "kept it simple deliberately," or any other justification is the
implementer grading their own work. Judge the code on its merits — a
stated rationale never downgrades a finding's severity.
[…]
## Part 1: Spec Compliance
Compare the diff against What Was Requested:
- **Missing:** requirements they skipped, missed, or claimed without
implementing
- **Extra:** features that weren't requested, over-engineering, unneeded
"nice to haves"
- **Misunderstood:** right feature built the wrong way, wrong problem
solved
[…]
If a requirement cannot be verified from this diff alone (it lives in
unchanged code or spans tasks), report it as a ⚠️ item instead of
broadening your search.
[…]
## Output Format
### Spec Compliance
- ✅ Spec compliant | ❌ Issues found: [what's missing/extra/misunderstood,
with file:line references]
- ⚠️ Cannot verify from diff: [requirements you could not verify from the
diff alone, and what the controller should check — report alongside the
✅/❌ verdict for everything you could verify]Explanation:
Purpose sets one goal and its boundaries at once: “nothing more, nothing less” - both incompleteness and excess are considered an error.
read‑only - the reviewer is prohibited from touching the working tree, index, HEAD and branches. Here it is a prohibition by text; in our agent the same thing is secured by the
settingtools: Read, Grep, Glob.Do Not Trust the Report - adversarial attitude: the performer's report and its justifications are unverified statements and do not reduce the seriousness of the observation.
Spec Compliance - three categories: Missing (not done or declared without implementation), Extra (undeclared behavior) and Misunderstood (done wrong or wrong). In our agent they correspond to the not_implemented statuses, the “Undeclared Behavior” section and partial.
⚠️ Cannot verify - escalation instead of guessing: if the requirement cannot be verified by diff, the reviewer does not expand the search, but passes the question to the controller. For us this is the status needs_human.
Package script for review (scripts/review-package, in full):
#!/usr/bin/env bash
# Generate a review package: commit list, stat summary, and the net
# diff with extended context, written to a file the reviewer reads in one
# call. Using the recorded per-task BASE (not HEAD~1) keeps multi-commit
# tasks intact.
#
# Usage: review-package PLAN_FILE BASE HEAD [OUTFILE]
# Default OUTFILE: <repo-root>/.superpowers/sdd/<plan-basename>/review-<base7>..<head7>.diff
# (named per range, so a re-review after fixes gets a distinct fresh file).
set -euo pipefail
if [ $# -lt 3 ] || [ $# -gt 4 ]; then
echo "usage: review-package PLAN_FILE BASE HEAD [OUTFILE]" >&2
exit 2
fi
plan=$1
base=$2
head=$3
[ -f "$plan" ] || { echo "no such plan file: $plan" >&2; exit 2; }
git rev-parse --verify --quiet "$base" >/dev/null || { echo "bad BASE: $base" >&2; exit 2; }
git rev-parse --verify --quiet "$head" >/dev/null || { echo "bad HEAD: $head" >&2; exit 2; }
# Range guards (exit 3): a wrong-branch HEAD yields a range that is empty or
# not rooted at BASE; either would silently produce a bogus review package.
git merge-base --is-ancestor "$base" "$head" || { echo "HEAD is not a descendant of BASE: ${base}..${head}" >&2; exit 3; }
[ "$(git rev-list --count "${base}..${head}")" -gt 0 ] || { echo "empty commit range: ${base}..${head}" >&2; exit 3; }
if [ $# -eq 4 ]; then
out=$4
else
# Invoke via bash rather than direct exec: some extractors (Python zipfile)
# strip Unix exec bits when unpacking marketplace packages (#2040).
dir=$("${BASH:-bash}" "$(cd "$(dirname "$0")" && pwd)/sdd-workspace" "$plan")
out="$dir/review-$(git rev-parse --short "$base")..$(git rev-parse --short "$head").diff"
fi
{
echo "# Review package: ${base}..${head}"
echo
echo "## Commits"
git log --oneline "${base}..${head}"
echo
echo "## Files changed"
git diff --stat "${base}..${head}"
echo
echo "## Diff"
git diff -U10 "${base}..${head}"
} > "$out"
commits=$(git rev-list --count "${base}..${head}")
echo "wrote ${out}: ${commits} commit(s), $(wc -c < "$out" | tr -d ' ') bytes"Explanation: the script is a deterministic part that is not trusted by the model. Range checks prevent a package from being collected from someone else's branch or from an empty one: such a package would give the reviewer a false picture without any error. Everything the reviewer reads - the list of commits, statistics and a diff with 10 lines of context - lies in one file, and he reads it once. A simplified version for our agent without connection to the plan is in step 3.
Fuse and log. The controller gives no more than five rounds of “fix + re-review” per task. Rounds 1–3 are led by the previous performer, 4–5 by a new performer on a stronger model. After the fifth round, the remaining comments are sorted out and recorded in a decision. Each step is recorded in the plan log, like this:
# SDD ledger — plan: specs/010-pager/plan.md
Task 3: fix round 2/5 (2 addressed, 1 open — FR-005b нет проверки прав на запуск; commits a1b2c3d..e4f5a6b)
Task 3: Ruling: код выхода 141 берём из Clarifications спеки, не из плана — спека главнее — если неверно, правка в одной функции
Task 3: completeTo bring the example up to the diagram in the article, add three things to it. The first is the deny rules in .claude/settings.json from step 5: now the ban on changing a branch rests only on the prompt text. The second is the skill of publishing a report in PR. The third is taking into account the metrics from step 6, marking the reviewer's result (Approved / Needs fixes) as correct or incorrect.
Common mistakes
Error | Why is dangerous | What to do |
|---|---|---|
One agent for all tasks | Behavior cannot be verified or constrained | Several small agents with one goal each |
Prohibitions only in the prompt | The agent can ignore them | Duplicate with access settings and hooks |
Agent evaluates himself | Self-report instead of testing | Human marking and reference set |
Immediately high autonomy | Errors end up in production before they are noticed | Start at R1, increase in metrics |
One long prompt with no versions | Any edit breaks something else, there is nowhere to roll back | Three levels, git, review, reference set |
Volume metrics | Illusion of Productivity | Share of results without rework |
Conclusion
Your own agent is not a prompt, but a set of artifacts: a goal and level of autonomy, a constitution, a spec with skills, reference examples, limiters in the code and metrics. Each artifact lives in a repository, undergoes review and changes in the same way as code. Then the question “why did the agent do this?” there is an answer, and its change can be verified.
Start with a reading agent and an assistive mode, like the reviewer in this article: the cost of an error is low, and you can work on it the entire cycle - from specs to metrics.
Sources and what to read
GitHub Spec Kit - cycle Constitution → Specify → Plan → Tasks → Implement.
Inside Spec‑Driven Development: what the Spec Kit is capable of and Introducing SDD into existing projects - the experience of EPAM teams.
Rewrote the project in a week with Claude Code - skills and subagent reviewers.
The Agentic SDLC Handbook - agent management and security in development.
Claude Code: documentation - subagents, skills, access settings, hooks.
AI Incident Database, No. 1152 - Incident Replit.
AI‑Disrupt PDLC, full version 2.0 (Sber, June 2026, PDF, 175 pp.) - R0-R5 scale (section 4.3), Guardian T1-T5 (4.5), evals and Evidence Bundle (2.11).
EPAM: Designing Autonomous AI Agents - Multi-Agent Swarm for UI Development (April 2026) - single-responsibility agents and adversarial reviewers.
💬 Discussion 0
BBCode & Emoji supportedParticipate in discussions, ask authors questions, and share benchmarks by joining the ProArena engineering community.