Первая попытка ускорить написание кода с помощью LLM состоялась в середине 2025 года. Результат не впечатлил: тогда шла работа над libadbmdns — реализацией mDNS на Rust. Сгенерированный код даже не компилировался.

К LLM вернулись в январе 2026 года. На этот раз получилось значительно лучше. Модель не только написала сложный класс индексированной бинарной кучи, но и смогла указать на неочевидный баг в крейте polling, связанный с реализацией IOCP в Windows.

Однако качество кода оставляло желать лучшего: спагетти-код без комментариев и структуры. Выигрыш в скорости съедался временем, которое пришлось бы тратить на доведение кода до продакшен-уровня — работать с LLM в таком виде было нерационально.

Итерации и повторение одного и того же

В марте 2026 года в дело пошли агентные IDE — Antigravity и плагин Claude Code для VS Code. Появилась возможность «итерировать» по «застейдженному» коду. По сути, это выглядело как ревью кода бесконечно терпеливого junior-разработчика: приходилось раз за разом объяснять «не используй магические числа», «добавь короткий комментарий, поясняющий логику» или «используй короткие имена функций».

Качество кода заметно выросло — стало близко к тому, что получилось бы написать вручную. Но процесс был утомительным: одни и те же замечания приходилось повторять в каждой новой сессии.

agent.md приходит на помощь

При запуске сессии агентная среда загружает файл agent.md и подставляет его в промпт. Это идеальное место для тонкой настройки предпочтений по стилю кода. Как только одно и то же замечание повторялось из раза в раз, оно отправлялось прямиком в этот файл.

Итоговая версия agent.md может послужить отправной точкой для тех, кому нужен подобный файл. Достаточно положить его в корень проекта. Как вариант, gemini.md/claude.md можно сделать симлинками на agent.md, чтобы правила действовали везде.

# FAB's AGENT.MD

- When writing something intended for human consumption, (comment, commit message, reply to prompt) use as few words as possible. Pick every word meticulously to reduce the volume to a strict minimum. Be down to the point. Less is more.

- Avoid superlatives and praise. Stop telling me I am absolutely right. Give me the cold hard truth.

- Avoid magic numbers and strings by extracting recurring or meaningful values into descriptive constants (const) or enums. Keep self-explanatory, one-off values inline to avoid clutter. If a value comes from a spec (e.g. HTTP 200 OK), use a constant regardless.

- Reduce code indentation. Avoid Arrow Anti-Pattern. Leverage early return and continue.

- Keep function names short. Less than 30 characters.

- Use enums instead of booleans for function parameters.

- Let the reader of the code breathe. Add empty lines between logical blocks of code.

- Add a small, to the point, comment to explain *what* the block does and *why*. Use examples when possible. Propose ASCII drawings to explain complete systems.

- Treat member visibility changes as a breaking design shift. Keep all fields and functions private unless external access is strictly required by the design. Prompt the user for explicit approval before changing any access modifier from private to internal or public.

- Program to levels of abstraction. Lower-level mechanics (e.g., raw hardware I/O, sector parsing, direct socket streams) must be encapsulated in a dedicated driver/abstraction layer. Expose clean, high-level APIs to the rest of the application so calling code works with domain concepts, not raw implementation details.

- Don't touch blocks of code unrelated to the feature you implement. e.g. Don't add comments to a block of code if you did not create it or modify it. As much as possible try to minimize the number of changed lines when implementing a feature.

- Strictly adhere to the layered boundary hierarchy: each layer may only communicate with its immediate neighbor directly below it. Never "punch holes" through layers (e.g., controllers or UI components must never directly call database queries, raw hardware drivers, or low-level network clients; always route through the intermediate service/abstraction layer).

- Always use {}, even on a one-line "if" statement.

When you write a commit message, follow these 7 rules:
Rule 1: Separate the subject line from the body with a single blank line.
Rule 2: Limit the subject line to 50 characters (72 is the absolute hard limit).
Rule 3: Capitalize the first letter of the subject line.
Rule 4: Do not end the subject line with a period.
Rule 5: Use the imperative mood in the subject line (e.g., "Fix bug," "Add feature," 
        not "Fixed" or "Adds"). Test formula: It must complete the sentence: "If applied,
        this commit will [your subject line here]".
Rule 6: Wrap the body text manually at 72 characters to prevent Git formatting issues.
Rule 7: Use the body to explain what and why vs. how. Assume the code explains the how;
        the message must explain the context and reasoning. 

- If the prompt indicates that a bug is being fixed, don't write the fix right away. First write the test. Observe it failing. Then write the fix. And observe the test passing.        

Этот приём заметно улучшил качество генерируемого кода, но не стал волшебной таблеткой, избавляющей от необходимости читать код. LLM регулярно галлюцинируют, и доверять им нельзя. Проверка и итерации по-прежнему занимают немало времени, но теперь основное внимание уходит на архитектуру и дизайн, а не на стиль кода.

Как бороться с «размытием» контекста

Существует раздражающее явление, известное как «размытие контекста» или «размытие внимания» (context dilution / attention dilution), описанное в статье Lost in the Middle. По мере роста контекста модель начинает уделять меньше внимания инструкциям в середине контекста, отдавая приоритет тому, что находится в начале и в конце. Причины этого явления пока не до конца изучены. Найдено лишь два способа минимизировать эффект.

  1. Держать контекст коротким — начинать новую сессию под каждую фичу.
  2. Явно просить агента перезагрузить agent.md. Обычно достаточно фразы «Reload agent.md», когда заметно падение качества кода.

Автообновление agent.md

Открывать редактор каждый раз, когда нужно добавить новое правило, необязательно. Проще попросить самого агента обновить agent.md.