AGENTS.md and ADR: the agent contract for every session
Phase 1 of the Harness Engineering series — context engineering. A deep dive into the four sources of truth the agent reads at start: AGENTS.md (working rules + Definition of Done + the retrieve rule), a per-agent addendum (CLAUDE.md / .cursorrules / system prompt), architecture.md (the layer & boundary map), and the ADR catalog (one decision = one markdown). Minimal templates and ready-to-copy bootstrap prompts — stack-agnostic, for any language and any agent.
IntermediateAI DevOps25 minAGENTS.md, CLAUDE.md, ADR, Claude Code
1
A context file is a session contract, not a README
If the agent writes code, its only source of truth is what lives in the repository. The chat, the ticket, the cloud doc — the agent doesn't see them at the start of a fresh session. Repo-first: any decision that should affect the agent's work is captured as a file in the repo.
Phase 1 gives the agent a contract it reads at the start of every session. It isn't one big file — it's four roles, following 'one artefact, one purpose': the working contract (AGENTS.md), a per-agent addendum (CLAUDE.md / .cursorrules / system prompt), the architecture map (architecture.md), and the decision catalog (ADRs). The contract is short and links to sources of truth rather than duplicating their content. The overview of the whole environment is in the series hub; here we go deep on this one phase.
AGENTS.md — contract for any agent
Working rules, Definition of Done, the retrieve rule, check commands
Per-agent addendum (CLAUDE.md / .cursorrules)
Tool specifics: skills, modes, MCP — on top of the shared contract
architecture.md — layer & boundary map
Domains, layers, dependency directions, what is NOT in this repo
docs/decisions/ — the ADR catalog
One decision = one markdown: why this and not that
Machine over text, but text beats nothing. Phase 1 is still text (conventions, not barriers), yet without it the agent re-invents the architecture from scratch every session. The barriers of phase 3 lean directly on this map.
2
AGENTS.md: working rules + Definition of Done + the retrieve rule
AGENTS.md is the shared contract for any coding agent (Claude Code, Codex, Cursor, whatever comes next). Keep it short (≤100 lines): it's a map, not an encyclopedia. Structure: what this project is in one paragraph; the stack as a single list; where the truth lives (links to architecture.md, decisions/, the ExecPlan template, the environment audit); working rules; check commands; explicit prohibitions.
Two sections carry most of the weight. The Definition of Done is one checklist for 'what done means': what must be green (formatter, linter, type-check, tests, build), whether the affected docs were updated, whether a new decision got an ADR. And the retrieve rule: before working on a given boundary the agent must first read the lessons accumulated for it and the related ADRs — this is the seam the lessons-ledger plugs into later. Take the concrete commands from the project manifest (package.json, pyproject.toml, build.gradle, Cargo.toml — whichever applies); don't invent them.
The minimum for AGENTS.md
The project in one paragraph + the stack as one list
Links to sources of truth (architecture.md, decisions/, ExecPlan)
Working rules: one thread = one task, atomic commits, update docs when behavior changes
Definition of Done: what must be green + an ADR for any new decision
Retrieve rule: read the boundary lessons and ADRs BEFORE the task
Check commands — copy from the manifest, do not invent
Phase 1: Context Engineering. Прочитай аудит среды и состояния
проекта (docs/audit/), затем создай AGENTS.md в корне репо.
Принципы:
- Файл короткий (<= 100 строк). Это КАРТА, а не энциклопедия.
- AGENTS.md — общий контракт для любых кодинг-агентов.
- Содержит ССЫЛКИ на источники правды в docs/, не дубль контента.
Структура AGENTS.md:
1. Какой это проект, в одном абзаце.
2. Стек (один список).
3. Где лежит правда: ссылки на docs/architecture.md,
docs/decisions/, docs/templates/ExecPlan.md, аудит среды.
4. Working rules:
- один тред = одна задача
- для крупных задач — ExecPlan
- коммиты атомарные
- обновляй документацию, если меняешь описанное в ней поведение
- не используй инструменты, не зафиксированные в аудите среды
5. Definition of Done: чек-лист, что значит «готово» —
форматтер/линтер/тайп-чек/тесты/билд зелёные, доки обновлены,
на новое архитектурное решение заведён ADR.
6. Retrieve-правило: перед задачей на конкретной границе сначала
прочитай накопленные по ней уроки и связанные ADR.
7. Команды проверки. Бери КОНКРЕТНЫЕ команды из манифеста проекта
(package.json, pyproject.toml, build.gradle, Cargo.toml — что
применимо). Не выдумывай команды, которых нет.
8. Что НЕ делать: явные запреты, специфичные для проекта.
The Definition of Done is a convention while it lives only in text. Phase 3's goal is to move as many of its items as possible into machine barriers (pre-commit + CI): what the machine checks, the agent can't skip; what stays as text rests on its discipline alone.
3
A per-agent addendum: CLAUDE.md / .cursorrules / system prompt
AGENTS.md is for any agent. But each tool has its own mechanics that don't belong in the shared contract: for Claude Code that's skills, plan mode and connected MCP servers; for Cursor it's the .cursorrules format and its rules; for a homegrown agent it's the system prompt. The principle: shared → AGENTS.md, tool specifics → that tool's addendum. Don't duplicate: the addendum links to AGENTS.md, it doesn't rewrite it.
The addendum is short too (≤100 lines) and answers narrow questions: which skills exist and for which procedures; which mode to use for which tasks (e.g. plan mode for non-trivial ones); which MCP servers are connected and why. If tomorrow the team adopts a second agent, you write a second addendum and leave the shared contract untouched. That is stack- and agent-agnosticism in practice.
Agent / environment
Addendum file
What goes in (specifics)
Claude Code
CLAUDE.md
Skills, plan mode, connected MCP servers
Cursor
.cursorrules / .cursor/rules
Rules in Cursor format, path-scoped rules
Codex / GitHub agent
AGENTS.md is already native
An extra section if the tool has its own hooks
Homegrown agent
system prompt in the repo
Preamble: 'read AGENTS.md first'
A duplication test: if a line in the addendum could move verbatim into AGENTS.md without losing meaning, it belongs in AGENTS.md. Only what is meaningless to another tool stays in the addendum.
4
ADRs: one decision = one markdown
An ADR (Architecture Decision Record) captures one architectural decision in one markdown file: context, the decision itself, consequences, alternatives considered, status. The naming format is `NNNN-short-name.md` inside `docs/decisions/`. An ADR answers the question the agent asks most often — 'why is this done this way and not another?' — and thereby stops it from 'improving' something that was chosen on purpose.
The most valuable part of this phase is retroactive documentation. Walk the codebase and, for each implicit decision that already lives in the code but is written down nowhere, create an ADR with status Discovered (not Proposed): the framework choice, the state-management pattern, the testing approach, how modules are organized, the API data format, error handling. At least 3, at most 10 — no more, so you don't drown. It's the cheapest adoption in the whole series: one markdown in 15–20 minutes, and the decision stops being tribal knowledge. The template below copies as-is.
# NNNN. <Краткое имя решения / Short decision name>
- **Status / Статус:** Discovered | Proposed | Accepted | Superseded
- **Date / Дата:** YYYY-MM-DD
- **Authors / Авторы:** <...>
## Context / Контекст
Что заставило принимать решение: ограничения, силы, проблема.
What forced the decision: constraints, forces, the problem.
## Decision / Решение
Что именно решили. Один абзац, в настоящем времени.
What exactly was decided. One paragraph, present tense.
## Consequences / Последствия
Что стало проще, что — сложнее. Что теперь нельзя делать.
What got easier, what got harder. What is now off-limits.
## Alternatives Considered / Рассмотренные альтернативы
Какие варианты отвергли и почему. Без этого ADR бесполезен.
Which options were rejected and why. Without this an ADR is useless.
The most important section is Alternatives Considered. An ADR without rejected options doesn't stop the agent: it can't see the choice was deliberate, so it 'fixes' what shouldn't be fixed. A Discovered status honestly says 'this is already how it's done', not 'this was perfectly intended'.
5
architecture.md: the layer & boundary map
architecture.md is the map the agent navigates by and that a boundary linter will later defend. Five sections: a top-level map (business domains, no implementation); the layer model (technical layers and dependency directions — for each: what's allowed, what's forbidden); external integrations (what we talk to: APIs, DBs, queues); cross-cutting concerns (where auth, logging, errors, config live); and an explicit 'what is NOT in this repo' section — so the agent doesn't try to solve neighboring systems' problems here.
The layer model is the key section: on phase 3 it becomes the config of a boundary linter (in JS/TS, e.g. eslint-plugin-boundaries or dependency-cruiser; in Python — import-linter; in Java — ArchUnit; in Go — internal packages and depguard). While it's still a convention, mark it 'Discovered, not enforced yet'. And an iron rule: if data is missing, don't invent. Put '?' and a TODO. An incomplete architecture map beats an invented one: the agent will silently rely on the invented map and propagate the mistake.
UI / entry points
allowed
Application / use cases
allowed
Domain / business logic
forbidden
Infrastructure: API, DB, queues
The arrows on the map are the future linter config. A domain layer depending on infrastructure directly is the most common violation the agent makes 'on the way'; pin the direction in words here so phase 3 can mechanize it with a check.
6
Rollout order and what comes next
The order inside phase 1 goes from map to contract, because AGENTS.md links to architecture.md and decisions/. (1) architecture.md — the layer map; (2) ADRs: README + template + retroactive Discovered records for what's already in the code; (3) AGENTS.md — the shared contract linking to (1) and (2) + the Definition of Done + the retrieve rule; (4) the addendum for your agent (CLAUDE.md / .cursorrules / system prompt). Each file ≤100 lines, the phase ends in a single PR.
Phase 1's Definition of Done: architecture.md exists; docs/decisions/ holds a README, a template and ≥3 ADRs; AGENTS.md and the addendum are each ≤100 lines. And an honest boundary: context files are conventions — they rest on discipline. 'Written in the rules' ≠ 'actually followed' until you turn it into a barrier. So the next mandatory step for big tasks is the ExecPlan (phase 2), and the machine barriers under the layer model and the DoD are built in phase 3.
Definition of Done — phase 1
architecture.md exists: domains, layer model, integrations, "what is NOT here"
docs/decisions/: README + template + ≥3 ADRs (Discovered for what is already in code)
AGENTS.md ≤100 lines: working rules + Definition of Done + the retrieve rule
Per-agent addendum ≤100 lines, links to AGENTS.md
Inventing architecture instead of "?" and TODO where unclear
Treating context files as barriers: they are conventions; barriers are phase 3
Don't try to make the map perfect on the first pass. An incomplete architecture.md with honest '?' already pays off on the very first task, and the gaps fill in with retroactive ADRs as you go.
Result
You've assembled the phase-1 contract the agent reads at the start of every session: an AGENTS.md with working rules, a Definition of Done and the retrieve rule; a per-agent addendum (CLAUDE.md / .cursorrules / system prompt) that doesn't duplicate the shared contract; an architecture.md whose layer and boundary map is ready to become a linter config; and an ADR catalog where one decision = one markdown, including retroactive Discovered records. These are still conventions, not barriers — but without them the agent re-invents the architecture from scratch. Next: the ExecPlan for multi-hour tasks (phase 2) and the machine barriers under this map (phase 3).