OBEY Clean Architecture by Robert C. Martin
Purpose
This repository must follow Clean Architecture.
When writing, modifying, or reviewing code, prefer decisions that preserve:
- independent business rules
- inward-pointing dependencies
- framework independence
- database independence
- UI independence
- testability
- replaceable details
Treat this file as a binding implementation policy: MUST is binding, SHOULD is a strong default, and MUST NOT is forbidden.
Non-Negotiable Rules
Follow the Dependency Rule
- Source code dependencies must point inward, toward higher-level policies.
- Inner layers must not import or depend on outer layers.
- Business rules must not depend on frameworks, web handlers, database drivers, UI libraries, queues, external services, or other details.
Keep Business Rules Pure
- Entities and use cases must contain business policy.
- Business rules must not read web requests, environment variables, framework context, database-bound structures, or database rows directly.
- Pass plain data into use cases through request models or arguments.
Treat Frameworks as Details
- Frameworks are tools, not the foundation of the design.
- Keep framework annotations, decorators, controllers, routes, middleware, serializers, and database artifacts at the edges.
- Do not let framework types leak into core policies.
Treat the Database as a Detail
- Do not shape the domain model around tables.
- Use gateways to isolate persistence.
- Business rules must work without a real database.
Treat the Web as a Detail
- Controllers and endpoints translate delivery input into input models for use cases.
- Use cases must not know about web transport, status codes, cookies, headers, or routing.
- Presenters or response mappers translate use case output for delivery mechanisms.
Use Explicit Boundaries
- Define interfaces at architectural seams.
- External systems, persistence, messaging, file systems, clocks, and service clients must sit behind boundaries.
- Prefer adapters over direct calls from policy code to implementation details.
Organize by Use Case
- Prefer feature and use-case oriented structure over generic technical buckets.
- The architecture should scream the domain and application intent.
- Avoid codebases dominated by generic technical buckets that do not reveal use cases or business purpose.
Use Cases Must Orchestrate
- A use case coordinates entities and gateways.
- A use case should not contain delivery concerns, database concerns, or presentation formatting concerns.
- A use case should represent one application action.
Entities Must Guard Invariants
- Critical domain rules belong in entities or equivalent domain objects.
- Entities must protect invariants and consistency.
- Do not leave core rules in controllers, jobs, handlers, or database scripts.
Outer Layers May Depend on Inner Layers, Never the Reverse
- Controllers may depend on use cases.
- Gateways may implement interfaces defined by the use case or domain layer.
- Presenters may implement output boundaries owned by inner layers.
- Never invert this relationship accidentally.
Required Layer Responsibilities
Domain Layer
Contains:
- entities
- enterprise business rules
- domain invariants
- core business rules
These may be implemented with plain objects, functions, modules, or other structures. Clean Architecture requires independent business rules; it does not require a specific domain modeling style.
Must:
- be framework free
- be persistence ignorant
- be delivery mechanism agnostic
- avoid annotations and infrastructure imports where possible
Must not:
- import web libraries
- import database access types
- import external service clients
- perform I/O
- read configuration directly
Application Layer
Contains:
- use cases
- input models
- output models
- ports and boundaries
- orchestration logic
Must:
- depend on domain abstractions and models
- define interfaces for required external behavior
- coordinate workflows explicitly
Must not:
- contain controller logic
- contain database access details
- return framework response types
- format UI strings unless explicitly part of a presenter boundary
Interface Adapters Layer
Contains:
- controllers
- presenters
- view models
- gateway adapters
- mappers between external and internal models
Must:
- translate between external formats and internal models
- depend inward on application and domain code
- isolate framework and vendor details
Must not:
- move business policy out of the use case or domain layer
- bypass use cases to call gateways directly unless explicitly justified by architecture
Infrastructure Layer
Contains:
- framework bootstrap
- object graph and component wiring
- database access details
- external service integrations
- message bus clients
- filesystem implementations
- network clients
Must:
- remain replaceable
- implement interfaces owned by inner layers
- stay at the outermost edge
Must not:
- define business rules
- dictate domain shapes
- leak vendor types inward
Code Generation Rules
When generating code, always apply the following.
1. Define the Use Case First
For every non-trivial feature:
- identify the use case
- define the input
- define the output
- define required ports
- keep orchestration in one place
Prefer this order:
- domain rule or entity behavior
- use case
- boundary interfaces
- presenter contract
- gateway contract
- adapters
- framework wiring
2. Use Plain Models at Boundaries
- Use request and response models owned by the application layer.
- Do not pass database-bound entities, web requests, or framework-bound data structures into core logic.
- Do not return framework objects from use cases.
3. Create Ports for Volatile Dependencies
Introduce interfaces for:
- gateways
- mailers
- payment providers
- message publishers
- storage providers
- clocks
- ID generators
- transaction runners if needed
Do not call volatile details directly from core use cases.
4. Keep Wiring in the Main Component
- Object construction belongs in the composition root.
- Do not instantiate infrastructure dependencies inside use cases or entities.
- Use explicit construction, factories, or composition in the outer layer.
5. Prefer Stable Dependencies
- Inner layers own the abstractions they need.
- Outer layers implement those abstractions.
- Avoid shared "common" packages that create sideways coupling.
6. Keep Boundaries Visible
- When in doubt, introduce a boundary sooner.
- Partial boundaries are acceptable if they preserve future extraction options.
- Use interfaces, request models, and output models to avoid coupling to details.
Architecture Heuristics
Dependency Direction
Always verify:
- Does this import point inward?
- Is a high-level policy depending on a low-level detail?
- Is a framework or vendor type leaking into a core layer?
- Is an adapter bypassing the intended boundary?
If yes, refactor.
Policy vs Detail
When placing code, ask:
- Is this business policy?
- Is this orchestration?
- Is this translation?
- Is this infrastructure?
Put the code in the highest-level place that matches its responsibility.
Stable Core, Replaceable Edge
Prefer designs where you can replace:
- web framework
- persistence technology
- message broker
- job runner
- cloud vendor
- serializer
- UI
without rewriting business rules.
Feature First Structure
Prefer:
- feature/use-case names
- business-capability/use-case names
- names that reveal the application's use cases
Over:
- generic controller, service, or gateway buckets
- generic technical buckets
Technical subfolders are acceptable only when they do not obscure use-case ownership.
Architecture Economics and Priority
- Treat architecture as a way to keep future change cost proportional to the scope of change.
- Do not sacrifice important architectural work merely because urgent feature work is louder.
- Preserve options around frameworks, databases, delivery mechanisms, and deployment topology until evidence justifies commitment.
- Choose boundaries by volatility, policy importance, substitution value, testability, and cost.
- Do not overbuild boundaries whose cost exceeds the option value they preserve.
- Revisit architecture when change shape, team ownership, deployment needs, or operational constraints reveal rising cost.
Paradigm and Component Rules
- Use structured programming to make behavior decomposable and testable.
- Use polymorphism to invert dependencies when high-level policy must not know low-level details.
- Use immutability or controlled mutation when it protects policy from accidental state coupling.
- Apply SRP by separating code that changes for different actors or reasons.
- Apply the Open-Closed Principle by protecting stable policy from volatile extension details.
- Apply LSP by ensuring substitutable implementations preserve caller expectations.
- Apply ISP by keeping interfaces focused on what each client actually needs.
- Apply DIP by making source dependencies point toward stable policy and abstractions.
- Group components by cohesion and release pressure; do not group unrelated policy just because it shares a technical layer.
- Avoid component cycles; break cycles before they harden into deployment or test bottlenecks.
- Balance stability and abstraction: stable components should not depend on unstable details, and abstract components should have concrete reason to exist.
Boundary Cost, Deployment, and Operations
- A boundary may be a source boundary, deployment boundary, process boundary, service boundary, or partial boundary.
- Choose the lightest boundary that preserves the needed independence.
- Use partial boundaries when a full deployment/runtime split is too expensive but future separation is valuable.
- Keep development, deployment, operation, and maintenance concerns visible without letting them own business policy.
- Do not combine unrelated use cases just because operational wiring is easier.
- Do not eliminate duplication when the shared code would couple use cases that change for different actors.
- Make architectural boundaries enforceable through package structure, tests, dependency rules, or build constraints.
Services, Distribution, and Embedded Boundaries
- A service is not automatically an architectural boundary; source dependencies and data ownership still decide coupling.
- Remote calls must be treated as I/O boundaries, not as local method calls.
- Keep service listeners humble: translate external messages into use case calls and return through output boundaries.
- Keep embedded and hardware details behind interfaces so policy can be tested without the target device.
- Do not let real-time, firmware, database, web, or framework concerns pull policy outward.
Naming Rules
- Name modules and packages after business capabilities or use cases.
- Name use cases with action verbs from the application's use cases.
- Name ports by the role they play for the use case.
- Name adapters by the external detail or delivery mechanism they adapt.
- Avoid vague technical names when a use case, policy, boundary, presenter, controller, gateway, or entity role is more precise.
- If a class is named
Service, justify why it is not a use case, adapter, or domain object.
Testing Rules
Core Tests First
Prioritize tests for:
- entities
- use cases
- boundary contracts
These tests must:
- run without the real framework
- run without the real database
- run without the network
- run fast and deterministically
Adapter Tests
Test adapters separately for:
- mapping correctness
- gateway behavior
- controller translation
- presenter formatting
- integration with framework or external service
Do not use slow integration tests as a substitute for testing business rules.
Test Through Supported Boundaries
- Avoid reaching private internals when a public use case boundary exists.
- Prefer testing use cases with fakes or mocks for ports.
- Use integration tests only where architectural seams meet real details.
Forbidden Patterns
Do not generate or keep code that does any of the following unless explicitly required and justified.
Framework Leakage
- domain entities annotated with database or web framework metadata when avoidable
- use cases depending on
Request, Response, controller base classes, framework sessions, or middleware objects
- application layer importing serializer or database base classes
Database Leakage
- use cases returning table rows or database-bound entities
- domain rules embedded in gateway implementations or database access
- domain objects designed primarily around persistence convenience
Controller-Centric Logic
- controllers containing branching business rules
- controllers performing validation that belongs to business policy
- controllers calling gateways directly instead of use cases
God Services
- large
*Service classes that create, fetch, validate, persist, publish, and present everything
- services that own unrelated use cases
- application services that become dumping grounds
Layer Bypass
- controllers bypassing use cases to call gateways
- presenters reading directly from databases
- infrastructure code importing inward and also being imported by domain code
Direction Violations
- gateway interfaces defined in infrastructure and consumed by core policy
- entities importing adapters
- use cases depending on concrete implementations
Utility Dumping Grounds
- generic utility, shared, base, or core folders used as architecture escape hatches
- generic abstractions with no clear ownership
- convenience modules that hide bad dependency direction
Refactoring Rules
When modifying existing code:
Move business rules inward
- Extract domain logic from controllers, handlers, views, gateway classes, and jobs.
Introduce boundaries around details
- Wrap external services, database access, message buses, filesystem operations, and clocks.
Replace concrete dependencies with ports
- Define interfaces in inner layers.
- Implement them in outer layers.
Separate translation from policy
- Request parsing, data mapping, serialization, and presentation formatting belong outside core business rules.
Break up god services
- Split by use case.
- Give each use case one clear application action.
Eliminate framework coupling from tests
- Rewrite tests to target use cases and entities directly where possible.
Preserve behavior while improving direction
- Refactor incrementally.
- Prefer safe boundary extraction over large rewrites.
Output Expectations
When asked to implement a feature, default to producing:
- a domain model or entity if business invariants exist
- a focused use case
- input and output models if needed
- ports/interfaces for external dependencies
- adapters for web, persistence, or messaging details
- composition root wiring outside the use case
When asked to modify existing code:
- keep or improve dependency direction
- avoid adding framework dependencies to inner layers
- call out architectural debt explicitly if it cannot be fixed safely now
When asked to review code:
- identify boundary violations
- identify dependency rule violations
- identify framework leakage
- identify misplaced business rules
- identify god services and layer bypass
- propose concrete refactorings toward Clean Architecture
Review Checklist
Before finalizing any change, verify:
- Are business rules independent from frameworks?
- Are use cases independent from delivery and persistence details?
- Do source dependencies point inward?
- Are controllers thin?
- Are gateways just persistence adapters?
- Are entities guarding domain invariants?
- Are ports owned by inner layers?
- Is composition happening at the edge?
- Can core tests run without the web framework and database?
- Does the project structure reflect the domain and use cases?
- Did we avoid generic utility dumping grounds?
- Did we avoid creating another god service?
- Did we keep details replaceable?
If any answer is no, revise the design before shipping.
Preferred Default Shapes
Preferred feature shape
- domain
- application
- adapters
- infrastructure
Or, if feature-oriented:
- feature/domain
- feature/application
- feature/adapters
- feature/infrastructure
Preferred use case shape
- request model
- use case
- output boundary or response model
- ports
- adapter implementations outside
Preferred dependency pattern
- inner layer defines interface
- outer layer implements interface
- composition root wires them together
When Tradeoffs Are Necessary
If constraints force a compromise:
- keep the compromise at the outermost layer possible
- document the boundary violation clearly in code comments or review notes
- avoid normalizing the compromise into the core architecture
- preserve a future path to separation
Choose the design that minimizes long-term coupling, not the one that is only shortest today.
Final Instruction
When uncertain, choose the option that:
- keeps business rules independent
- points dependencies inward
- isolates details behind boundaries
- improves testability
- makes replacement of frameworks, databases, and delivery mechanisms easier
If a proposed change conflicts with these priorities, reject it and propose a cleaner architectural alternative.
1---
2name: book-clean-architecture-full
3description: >-
4 Clean Architecture (Robert C. Martin) — Full rules — comprehensive mandatory coding standards. Use when asked to apply Clean Architecture principles or review code against Clean Architecture standards.
5origin: "github.com/ciembor/agent-rules-books (MIT)"
6license: MIT
7version: "1.0.0"
8compatibility: "yana-ai >= 0.14.0"
9metadata:
10 source: https://skillmd.com/skills/yanacuti1121/book-clean-architecture-full
11---
12
13# OBEY Clean Architecture by Robert C. Martin
14
15## Purpose
16
17This repository must follow **Clean Architecture**.
18When writing, modifying, or reviewing code, prefer decisions that preserve:
19- independent business rules
20- inward-pointing dependencies
21- framework independence
22- database independence
23- UI independence
24- testability
25- replaceable details
26
27Treat this file as a binding implementation policy: `MUST` is binding, `SHOULD` is a strong default, and `MUST NOT` is forbidden.
28
29---
30
31## Non-Negotiable Rules
32
331. **Follow the Dependency Rule**
34 - Source code dependencies must point inward, toward higher-level policies.
35 - Inner layers must not import or depend on outer layers.
36 - Business rules must not depend on frameworks, web handlers, database drivers, UI libraries, queues, external services, or other details.
37
382. **Keep Business Rules Pure**
39 - Entities and use cases must contain business policy.
40 - Business rules must not read web requests, environment variables, framework context, database-bound structures, or database rows directly.
41 - Pass plain data into use cases through request models or arguments.
42
433. **Treat Frameworks as Details**
44 - Frameworks are tools, not the foundation of the design.
45 - Keep framework annotations, decorators, controllers, routes, middleware, serializers, and database artifacts at the edges.
46 - Do not let framework types leak into core policies.
47
484. **Treat the Database as a Detail**
49 - Do not shape the domain model around tables.
50 - Use gateways to isolate persistence.
51 - Business rules must work without a real database.
52
535. **Treat the Web as a Detail**
54 - Controllers and endpoints translate delivery input into input models for use cases.
55 - Use cases must not know about web transport, status codes, cookies, headers, or routing.
56 - Presenters or response mappers translate use case output for delivery mechanisms.
57
586. **Use Explicit Boundaries**
59 - Define interfaces at architectural seams.
60 - External systems, persistence, messaging, file systems, clocks, and service clients must sit behind boundaries.
61 - Prefer adapters over direct calls from policy code to implementation details.
62
637. **Organize by Use Case**
64 - Prefer feature and use-case oriented structure over generic technical buckets.
65 - The architecture should scream the domain and application intent.
66 - Avoid codebases dominated by generic technical buckets that do not reveal use cases or business purpose.
67
688. **Use Cases Must Orchestrate**
69 - A use case coordinates entities and gateways.
70 - A use case should not contain delivery concerns, database concerns, or presentation formatting concerns.
71 - A use case should represent one application action.
72
739. **Entities Must Guard Invariants**
74 - Critical domain rules belong in entities or equivalent domain objects.
75 - Entities must protect invariants and consistency.
76 - Do not leave core rules in controllers, jobs, handlers, or database scripts.
77
7810. **Outer Layers May Depend on Inner Layers, Never the Reverse**
79 - Controllers may depend on use cases.
80 - Gateways may implement interfaces defined by the use case or domain layer.
81 - Presenters may implement output boundaries owned by inner layers.
82 - Never invert this relationship accidentally.
83
84---
85
86## Required Layer Responsibilities
87
88### Domain Layer
89Contains:
90- entities
91- enterprise business rules
92- domain invariants
93- core business rules
94
95These may be implemented with plain objects, functions, modules, or other structures. Clean Architecture requires independent business rules; it does not require a specific domain modeling style.
96
97Must:
98- be framework free
99- be persistence ignorant
100- be delivery mechanism agnostic
101- avoid annotations and infrastructure imports where possible
102
103Must not:
104- import web libraries
105- import database access types
106- import external service clients
107- perform I/O
108- read configuration directly
109
110### Application Layer
111Contains:
112- use cases
113- input models
114- output models
115- ports and boundaries
116- orchestration logic
117
118Must:
119- depend on domain abstractions and models
120- define interfaces for required external behavior
121- coordinate workflows explicitly
122
123Must not:
124- contain controller logic
125- contain database access details
126- return framework response types
127- format UI strings unless explicitly part of a presenter boundary
128
129### Interface Adapters Layer
130Contains:
131- controllers
132- presenters
133- view models
134- gateway adapters
135- mappers between external and internal models
136
137Must:
138- translate between external formats and internal models
139- depend inward on application and domain code
140- isolate framework and vendor details
141
142Must not:
143- move business policy out of the use case or domain layer
144- bypass use cases to call gateways directly unless explicitly justified by architecture
145
146### Infrastructure Layer
147Contains:
148- framework bootstrap
149- object graph and component wiring
150- database access details
151- external service integrations
152- message bus clients
153- filesystem implementations
154- network clients
155
156Must:
157- remain replaceable
158- implement interfaces owned by inner layers
159- stay at the outermost edge
160
161Must not:
162- define business rules
163- dictate domain shapes
164- leak vendor types inward
165
166---
167
168## Code Generation Rules
169
170When generating code, always apply the following.
171
172### 1. Define the Use Case First
173For every non-trivial feature:
174- identify the use case
175- define the input
176- define the output
177- define required ports
178- keep orchestration in one place
179
180Prefer this order:
1811. domain rule or entity behavior
1822. use case
1833. boundary interfaces
1844. presenter contract
1855. gateway contract
1866. adapters
1877. framework wiring
188
189### 2. Use Plain Models at Boundaries
190- Use request and response models owned by the application layer.
191- Do not pass database-bound entities, web requests, or framework-bound data structures into core logic.
192- Do not return framework objects from use cases.
193
194### 3. Create Ports for Volatile Dependencies
195Introduce interfaces for:
196- gateways
197- mailers
198- payment providers
199- message publishers
200- storage providers
201- clocks
202- ID generators
203- transaction runners if needed
204
205Do not call volatile details directly from core use cases.
206
207### 4. Keep Wiring in the Main Component
208- Object construction belongs in the composition root.
209- Do not instantiate infrastructure dependencies inside use cases or entities.
210- Use explicit construction, factories, or composition in the outer layer.
211
212### 5. Prefer Stable Dependencies
213- Inner layers own the abstractions they need.
214- Outer layers implement those abstractions.
215- Avoid shared "common" packages that create sideways coupling.
216
217### 6. Keep Boundaries Visible
218- When in doubt, introduce a boundary sooner.
219- Partial boundaries are acceptable if they preserve future extraction options.
220- Use interfaces, request models, and output models to avoid coupling to details.
221
222---
223
224## Architecture Heuristics
225
226### Dependency Direction
227Always verify:
228- Does this import point inward?
229- Is a high-level policy depending on a low-level detail?
230- Is a framework or vendor type leaking into a core layer?
231- Is an adapter bypassing the intended boundary?
232
233If yes, refactor.
234
235### Policy vs Detail
236When placing code, ask:
237- Is this business policy?
238- Is this orchestration?
239- Is this translation?
240- Is this infrastructure?
241
242Put the code in the highest-level place that matches its responsibility.
243
244### Stable Core, Replaceable Edge
245Prefer designs where you can replace:
246- web framework
247- persistence technology
248- message broker
249- job runner
250- cloud vendor
251- serializer
252- UI
253without rewriting business rules.
254
255### Feature First Structure
256Prefer:
257- feature/use-case names
258- business-capability/use-case names
259- names that reveal the application's use cases
260
261Over:
262- generic controller, service, or gateway buckets
263- generic technical buckets
264
265Technical subfolders are acceptable only when they do not obscure use-case ownership.
266
267---
268
269## Architecture Economics and Priority
270
2711. Treat architecture as a way to keep future change cost proportional to the scope of change.
2722. Do not sacrifice important architectural work merely because urgent feature work is louder.
2733. Preserve options around frameworks, databases, delivery mechanisms, and deployment topology until evidence justifies commitment.
2744. Choose boundaries by volatility, policy importance, substitution value, testability, and cost.
2755. Do not overbuild boundaries whose cost exceeds the option value they preserve.
2766. Revisit architecture when change shape, team ownership, deployment needs, or operational constraints reveal rising cost.
277
278---
279
280## Paradigm and Component Rules
281
2821. Use structured programming to make behavior decomposable and testable.
2832. Use polymorphism to invert dependencies when high-level policy must not know low-level details.
2843. Use immutability or controlled mutation when it protects policy from accidental state coupling.
2854. Apply SRP by separating code that changes for different actors or reasons.
2865. Apply the Open-Closed Principle by protecting stable policy from volatile extension details.
2876. Apply LSP by ensuring substitutable implementations preserve caller expectations.
2887. Apply ISP by keeping interfaces focused on what each client actually needs.
2898. Apply DIP by making source dependencies point toward stable policy and abstractions.
2909. Group components by cohesion and release pressure; do not group unrelated policy just because it shares a technical layer.
29110. Avoid component cycles; break cycles before they harden into deployment or test bottlenecks.
29211. Balance stability and abstraction: stable components should not depend on unstable details, and abstract components should have concrete reason to exist.
293
294---
295
296## Boundary Cost, Deployment, and Operations
297
2981. A boundary may be a source boundary, deployment boundary, process boundary, service boundary, or partial boundary.
2992. Choose the lightest boundary that preserves the needed independence.
3003. Use partial boundaries when a full deployment/runtime split is too expensive but future separation is valuable.
3014. Keep development, deployment, operation, and maintenance concerns visible without letting them own business policy.
3025. Do not combine unrelated use cases just because operational wiring is easier.
3036. Do not eliminate duplication when the shared code would couple use cases that change for different actors.
3047. Make architectural boundaries enforceable through package structure, tests, dependency rules, or build constraints.
305
306---
307
308## Services, Distribution, and Embedded Boundaries
309
3101. A service is not automatically an architectural boundary; source dependencies and data ownership still decide coupling.
3112. Remote calls must be treated as I/O boundaries, not as local method calls.
3123. Keep service listeners humble: translate external messages into use case calls and return through output boundaries.
3134. Keep embedded and hardware details behind interfaces so policy can be tested without the target device.
3145. Do not let real-time, firmware, database, web, or framework concerns pull policy outward.
315
316---
317
318## Naming Rules
319
320- Name modules and packages after business capabilities or use cases.
321- Name use cases with action verbs from the application's use cases.
322- Name ports by the role they play for the use case.
323- Name adapters by the external detail or delivery mechanism they adapt.
324- Avoid vague technical names when a use case, policy, boundary, presenter, controller, gateway, or entity role is more precise.
325- If a class is named `Service`, justify why it is not a use case, adapter, or domain object.
326
327---
328
329## Testing Rules
330
331### Core Tests First
332Prioritize tests for:
333- entities
334- use cases
335- boundary contracts
336
337These tests must:
338- run without the real framework
339- run without the real database
340- run without the network
341- run fast and deterministically
342
343### Adapter Tests
344Test adapters separately for:
345- mapping correctness
346- gateway behavior
347- controller translation
348- presenter formatting
349- integration with framework or external service
350
351Do not use slow integration tests as a substitute for testing business rules.
352
353### Test Through Supported Boundaries
354- Avoid reaching private internals when a public use case boundary exists.
355- Prefer testing use cases with fakes or mocks for ports.
356- Use integration tests only where architectural seams meet real details.
357
358---
359
360## Forbidden Patterns
361
362Do not generate or keep code that does any of the following unless explicitly required and justified.
363
364### Framework Leakage
365- domain entities annotated with database or web framework metadata when avoidable
366- use cases depending on `Request`, `Response`, controller base classes, framework sessions, or middleware objects
367- application layer importing serializer or database base classes
368
369### Database Leakage
370- use cases returning table rows or database-bound entities
371- domain rules embedded in gateway implementations or database access
372- domain objects designed primarily around persistence convenience
373
374### Controller-Centric Logic
375- controllers containing branching business rules
376- controllers performing validation that belongs to business policy
377- controllers calling gateways directly instead of use cases
378
379### God Services
380- large `*Service` classes that create, fetch, validate, persist, publish, and present everything
381- services that own unrelated use cases
382- application services that become dumping grounds
383
384### Layer Bypass
385- controllers bypassing use cases to call gateways
386- presenters reading directly from databases
387- infrastructure code importing inward and also being imported by domain code
388
389### Direction Violations
390- gateway interfaces defined in infrastructure and consumed by core policy
391- entities importing adapters
392- use cases depending on concrete implementations
393
394### Utility Dumping Grounds
395- generic utility, shared, base, or core folders used as architecture escape hatches
396- generic abstractions with no clear ownership
397- convenience modules that hide bad dependency direction
398
399---
400
401## Refactoring Rules
402
403When modifying existing code:
404
4051. **Move business rules inward**
406 - Extract domain logic from controllers, handlers, views, gateway classes, and jobs.
407
4082. **Introduce boundaries around details**
409 - Wrap external services, database access, message buses, filesystem operations, and clocks.
410
4113. **Replace concrete dependencies with ports**
412 - Define interfaces in inner layers.
413 - Implement them in outer layers.
414
4154. **Separate translation from policy**
416 - Request parsing, data mapping, serialization, and presentation formatting belong outside core business rules.
417
4185. **Break up god services**
419 - Split by use case.
420 - Give each use case one clear application action.
421
4226. **Eliminate framework coupling from tests**
423 - Rewrite tests to target use cases and entities directly where possible.
424
4257. **Preserve behavior while improving direction**
426 - Refactor incrementally.
427 - Prefer safe boundary extraction over large rewrites.
428
429---
430
431## Output Expectations
432
433When asked to implement a feature, default to producing:
434- a domain model or entity if business invariants exist
435- a focused use case
436- input and output models if needed
437- ports/interfaces for external dependencies
438- adapters for web, persistence, or messaging details
439- composition root wiring outside the use case
440
441When asked to modify existing code:
442- keep or improve dependency direction
443- avoid adding framework dependencies to inner layers
444- call out architectural debt explicitly if it cannot be fixed safely now
445
446When asked to review code:
447- identify boundary violations
448- identify dependency rule violations
449- identify framework leakage
450- identify misplaced business rules
451- identify god services and layer bypass
452- propose concrete refactorings toward Clean Architecture
453
454---
455
456## Review Checklist
457
458Before finalizing any change, verify:
459
460- Are business rules independent from frameworks?
461- Are use cases independent from delivery and persistence details?
462- Do source dependencies point inward?
463- Are controllers thin?
464- Are gateways just persistence adapters?
465- Are entities guarding domain invariants?
466- Are ports owned by inner layers?
467- Is composition happening at the edge?
468- Can core tests run without the web framework and database?
469- Does the project structure reflect the domain and use cases?
470- Did we avoid generic utility dumping grounds?
471- Did we avoid creating another god service?
472- Did we keep details replaceable?
473
474If any answer is no, revise the design before shipping.
475
476---
477
478## Preferred Default Shapes
479
480### Preferred feature shape
481- domain
482- application
483- adapters
484- infrastructure
485
486Or, if feature-oriented:
487- feature/domain
488- feature/application
489- feature/adapters
490- feature/infrastructure
491
492### Preferred use case shape
493- request model
494- use case
495- output boundary or response model
496- ports
497- adapter implementations outside
498
499### Preferred dependency pattern
500- inner layer defines interface
501- outer layer implements interface
502- composition root wires them together
503
504---
505
506## When Tradeoffs Are Necessary
507
508If constraints force a compromise:
509- keep the compromise at the outermost layer possible
510- document the boundary violation clearly in code comments or review notes
511- avoid normalizing the compromise into the core architecture
512- preserve a future path to separation
513
514Choose the design that minimizes long-term coupling, not the one that is only shortest today.
515
516---
517
518## Final Instruction
519
520When uncertain, choose the option that:
5211. keeps business rules independent
5222. points dependencies inward
5233. isolates details behind boundaries
5244. improves testability
5255. makes replacement of frameworks, databases, and delivery mechanisms easier
526
527If a proposed change conflicts with these priorities, reject it and propose a cleaner architectural alternative.