Clean Code — legibilidade e raciocínio local
Definition
Este conceito destila o livro clean-code em regras executáveis para agentes de IA, conforme publicado no repositório agent-rules-books (v0.5, MIT, fork de ciembor/agent-rules-books). Cada livro tem 3 formatos (full canônico, mini recomendado, nano compacto); esta página documenta o mini — o formato usado no dia a dia para instruir Codex, Cursor e Claude Code sem estourar a janela de contexto.
Ponto de partida: Clean Code — legibilidade e raciocínio local. Ver detalhes completos do
minina seção “Regras originais (mini)” abaixo, extraída verbatim deraw/vibecoding/articles/agent-rules-books.md.
Quando usar
Extraído do header ## When to use do mini (tradução e adaptação para founder/PM não-técnico abaixo; original em inglês mantido na seção final):
- Use quando a dimensão que este livro governa for o risco principal da tarefa do agente (legibilidade, arquitetura, legado, dados, etc.).
- Prefira este livro como contrato verificável em vez de pedir genérico tipo “faça bem feito” — ver hub regras-de-agentes-a-partir-de-livros para escolher entre os 14.
Viés principal a corrigir e regras de decisão
O mini organiza as regras em ## Primary bias to correct e ## Decision rules. Para o founder, isso vira checklist de revisão do plano e do PR:
- Leia o
Primary biascomo o erro que o agente comete quando só recebe instrução vaga (ex.: “código que roda não é código limpo” em Clean Code; “complexidade acidental” em Philosophy of SD). - Transforme cada
Decision ruleem critério de pronto da issue (especificacao-de-issues-para-agentes) e em item doFinal checklistque você cobra no review.
Consulte a transcrição completa na seção final e marque na issue quais regras desta página se aplicam (ex.: scoped rules só em src/domain/** para DDD, só em src/infra/** para Release It!).
Gatilhos (Trigger rules)
Os Trigger rules do mini indicam quando o agente deve quebrar a tarefa em passos menores ou trocar de padrão (ex.: “quando função mistura setup/validação/computação/efeito, separe fases” — Clean Code; “quando boundary vaza framework para dentro, fortaleça adapter” — Clean Code/Clean Architecture). Para o founder, são sinais para pedir ao agente: “pare, proponha plano antes de codar” (plan-first-com-agentes-de-ia).
Checklist final para o founder cobrar do agente
O mini fecha com ## Final checklist — perguntas que você faz no PR sem precisar ler o livro:
- O leitor consegue seguir a mudança localmente, sem pular arquivos?
- Nomes/APIs carregam significado sem comentário narrativo?
- Mutação é explícita e o caminho feliz permanece legível?
- Detalhes de framework/persistência/vendor ficaram atrás de boundaries?
- Pelo menos um smell foi removido na área tocada, sem alargar o escopo silenciosamente?
- Testes protegem o contrato mudado e foram efetivamente rodados?
Adapte o checklist ao livro: para DDIA troque por “timeout/retry/circuit breaker definidos?”; para DDD troque por “linguagem ubíqua respeitada? aggregate protege invariantes?”.
Implications
Para o founder/PM não-técnico, esta página transforma conhecimento de livro — normalmente inacessível sem 300+ páginas de leitura — em instrução operacional colável no AGENTS.md/skills. Em vez de torcer para o agente “saber” o livro, você cola 30 regras testáveis e mede no vibe-coded-crap (74/100 com mini vs 46/100 só citando o título). Isso conecta agents-md-como-instrucao-operacional (zona 60-150 linhas, pointers), plan-first-com-agentes-de-ia (plano melhora com regras concretas) e ciclo-issue-branch-pr-merge (PR só mergea se passa no checklist).
Related Concepts
- clean-code-e-regras-de-legibilidade
- regras-de-agentes-a-partir-de-livros
- especificacao-de-issues-para-agentes
- agents-md-como-instrucao-operacional
- agent-rules-books — repositório fonte desta coleção
- vibe-coding — prática onde estas regras são aplicadas
Regras originais (mini) — transcrição verbatim
Fonte:
raw/vibecoding/articles/agent-rules-books.mdseção## clean-code— conteúdominiextraído viahttps://raw.githubusercontent.com/mattpocock/agent-rules-books/main/clean-code/clean-code.mini.mdem 2026-08-29. Transcrição fiel; não substitui a leitura do livro.
OBEY Clean Code by Robert C. Martin
## When to use
Use when readability, local reasoning, and maintainable code shape are the main concerns, especially during everyday implementation and review.
## Primary bias to correct
Working code is not automatically clean code.
## Decision rules
- Treat cleanliness as part of delivery. Preserve behavior, leave touched code cleaner within scope, and do not add mess because the schedule is tight or a rewrite is promised.
- Write for local reasoning. A reader should understand the path without reconstructing hidden state, wide jumps, or naming trivia.
- Use precise names and one term per concept. Rename code when vocabulary hides intent, overloads meaning, or forces comments to compensate.
- Keep functions small, focused, and at one level of abstraction. Tell the story top-down so intent appears before detail.
- Keep parameters few and meaningful. Avoid boolean flags, output parameters, and grab-bag argument lists; model the concept instead.
- Separate commands from queries and eliminate hidden side effects. A function that answers should not also mutate behind the reader's back.
- Keep the happy path readable. Isolate error handling, invalid-state handling, and cleanup; prefer explicit optionality or typed results over null-like sentinel flow when the language supports it.
- Expose behavior rather than raw representation. Avoid train-wreck access, utility dumping grounds, and classes or modules with mixed responsibilities.
- Keep construction, framework, persistence, transaction, security, and vendor details outside business behavior.
- Make public APIs small, explicit, and hard to misuse. Encode boundary logic, required order, and likely changes where readers can see them.
- Use comments only for rationale, constraints, warnings, or external contracts. Do not narrate code instead of improving it.
- Treat tests as production code: readable, deterministic, aligned with the behavior or contract they protect, and backed by proportionate validation before calling the change done.
- Let design emerge through tests, duplication removal, expressiveness, and minimal structure; do not add needless abstractions or infrastructure.
- When touching code, remove the smell that most increases change cost, but do not silently broaden the task beyond the smallest cleanup that makes the requested change safe.
## Trigger rules
- When a function mixes setup, validation, computation, and side effects, split the phases.
- When a comment explains control flow, simplify names or structure before keeping the comment.
- When a function both mutates and answers, or hides a mode switch behind a flag, separate the responsibilities.
- When duplication, repeated switches, or primitive clusters appear, name the concept with an argument object, polymorphism, special case, or other small abstraction.
- When a boundary leaks framework, vendor, or persistence quirks inward, add or strengthen a local adapter.
- When async or concurrency enters, isolate threading policy, minimize shared mutable state, define shutdown, and test timing-sensitive behavior.
- When fixing a bug or changing behavior, add or update the test that protects the intended contract.
- When cleanup starts spreading into unrelated areas, cut back to the smallest refactor that keeps the requested change safe and readable.
## Final checklist
- Can a reader follow the change locally?
- Are names and APIs carrying the meaning without narration?
- Is mutation explicit and the happy path still clear?
- Did framework, persistence, vendor, and construction details stay behind boundaries?
- Did I remove at least one smell from the touched area?
- Do tests protect the changed behavior or contract?
- Did I actually run the relevant tests or checks for this change?