Clean Architecture — boundaries e Dependency Rule

Definition

Este conceito destila o livro clean-architecture 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 Architecture — boundaries e Dependency Rule. Ver detalhes completos do mini na seção “Regras originais (mini)” abaixo, extraída verbatim de raw/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 bias como 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 rule em critério de pronto da issue (especificacao-de-issues-para-agentes) e em item do Final checklist que 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).

Regras originais (mini) — transcrição verbatim

Fonte: raw/vibecoding/articles/agent-rules-books.md seção ## clean-architecture — conteúdo mini extraído via https://raw.githubusercontent.com/mattpocock/agent-rules-books/main/clean-architecture/clean-architecture.mini.md em 2026-08-29. Transcrição fiel; não substitui a leitura do livro.

OBEY Clean Architecture by Robert C. Martin
 
## When to use
 
Use when adding, changing, reviewing, or refactoring code whose business rules should survive changes in frameworks, databases, delivery mechanisms, services, devices, vendors, deployment shape, or schedule pressure.
 
## Primary bias to correct
 
Do not let details become the architecture. Business policy stays independent, dependencies point inward, and volatile mechanisms remain replaceable.
 
## Decision rules
 
- Preserve independent business rules, inward dependencies, testability, and replaceable details even when the immediate feature would be shorter without them.
- Source dependencies must point inward toward higher-level policy. Domain and use cases must not import frameworks, databases, web handlers, queues, external service clients, UI types, or other details.
- Put enterprise rules and invariants in entities or equivalent domain objects; put application-specific orchestration in focused use cases.
- Pass plain request and response models across use-case boundaries. Do not pass web requests, framework contexts, ORM rows, database-bound structures, or framework response objects into or out of core policy.
- Treat frameworks, databases, web delivery, messaging, filesystems, clocks, service clients, networks, devices, and vendors as outer-layer details behind ports, gateways, presenters, mappers, or adapters.
- Inner layers own the interfaces they need; outer layers implement them. Object construction and concrete wiring belong in the composition root or other outer-layer main component.
- Keep adapters humble. Controllers, endpoints, presenters, gateway adapters, service listeners, and hardware adapters translate external formats to use-case calls and back; they do not own business decisions.
- Organize by use case, feature, or business capability before generic technical buckets. The structure should reveal domain intent and application actions.
- Choose boundaries by volatility, policy importance, substitution value, testability, and cost. Use the lightest enforceable boundary, including partial boundaries, when full deployment or runtime separation is too expensive.
- Do not merge unrelated use cases or eliminate duplication when sharing would couple actors, change reasons, team ownership, deployment needs, or release pressure.
- Use structured code, dependency inversion, role-sized interfaces, substitutable implementations, controlled mutation, acyclic components, and stability-directed dependencies to protect policy from volatile details.
- Enforce boundaries with package structure, dependency rules, build constraints, tests, visibility, or narrow APIs. A diagram, service split, package name, or shared `common` folder is not enough.
- Test entities, use cases, and boundary contracts first, without the real framework, database, network, external service, or target hardware. Test adapters separately at the seams.
- Preserve behavior while improving dependency direction. Prefer incremental boundary extraction over rewrites, and call out architectural debt when it cannot be fixed safely now.
 
## Trigger rules
 
- When urgent delivery would skip architecture, state the future change, test, replacement, or operational cost before accepting the shortcut.
- When framework annotations, request/response objects, serializers, ORM rows, schemas, vendor SDKs, config, environment reads, device registers, or transport formats enter core policy, move translation outward.
- When controllers, jobs, handlers, views, presenters, gateways, repositories, SQL, service listeners, scripts, or hardware adapters contain business branching or validation, move the rule inward.
- When a use case instantiates infrastructure, calls a volatile dependency directly, or depends on a concrete implementation, introduce a policy-owned port and wire the concrete detail at the edge.
- When a `*Service`, utility folder, shared module, base package, or generic `core` package becomes an escape hatch, split by use case, role, or ownership and restore dependency direction.
- When an adapter bypasses a use case, a presenter reads persistence directly, or infrastructure is both imported by and importing inward code, restore the intended boundary.
- When service boundaries, process boundaries, remote calls, deployment boundaries, or embedded hardware appear, still verify source dependencies, data ownership, I/O cost, and policy independence.
- When tests need the framework, database, network, service, or hardware to verify business rules, move tests to use cases/entities with fakes or add a stable boundary contract.
- When a compromise is unavoidable, keep it at the outermost layer possible, document the violation, avoid normalizing it, and preserve a path to separation.
 
## Final checklist
 
- Business rules independent from frameworks, databases, UI, services, devices, and vendors?
- Dependencies point inward, with ports owned by inner policy and concrete details outside?
- Entities guard invariants and focused use cases orchestrate one application action?
- Boundaries explicit and enforced in code, tests, packages, or build rules?
- Controllers, presenters, gateways, service listeners, and adapters humble?
- Structure reveals use cases and business capabilities instead of generic technical buckets?
- Core tests run fast without real delivery, persistence, network, external service, or hardware?
- Details remain replaceable without rewriting business rules?

Sources