agentleFS
joserprietojoserprieto/ai-skills/skills/contract-first-clean-arch/SKILL.md

contract-first-clean-arch

Skill2 starsChanged 10 months agoMITView on GitHub

Use when starting a new backend or fullstack project, evaluating an existing project's architecture, migrating from code-first to contract-first, introducing Clean Architecture layers, setting up a type generation pipeline, or assessing architectural maturity. Also use when user says "contract-first", "clean architecture", "schema SSOT", "type generation", "ports and adapters", "hexagonal architecture", "architecture assessment", "dependency inversion", "composition root", "architecture evaluation", "contract-first clean arch", "screaming architecture", "vertical slicing", "criteria pattern", or "bounded contexts".

The file

Show its rules and text

We split this skill into the rules it gives an agent

14 rules. About 0 are common, 12 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈12

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    All types, models, validators, documentation, and client code must be derived from a single schema definition — never maintained …

    line 47
  2. Distinctive:

    Write the test first, then the code.

    line 69
  3. Distinctive:

    Every response from an external service must be parsed, validated against a schema, and handled with a fallback strategy.

    line 82
  4. Distinctive:

    When generating a project, follow this prescriptive sequence.

    line 115
  5. Distinctive:

    This is the "first" in "contract-first": Before writing any code or creating any directory structure, define YAML schemas (JSON Schema …

    line 141
  6. Very specific:

    Add a Makefile target:

    line 165
  7. Distinctive:

    Look at the schemas you wrote.

    line 179
  8. Distinctive:

    Only create subdirectories when the grouping reflects a real business boundary — never for organizational convenience alone.

    line 229
  9. Distinctive:

    Start with screaming slices derived from your contracts.

    line 257
  10. Distinctive:

    Create Object Mothers with faker for domain-meaningful test data.

    line 291
  11. Very specific:

    Test data is generated via Object Mothers with faker (see Step 8) — keeping domain-meaningful fixtures separate from test logic and making …

    line 368
  12. Distinctive:

    When applying Clean Architecture to a frontend project, adapt the layers:

    line 374
  13. Distinctive:

    Use this to evaluate any project.

    line 433
  14. Distinctive:

    When evaluating a project, score each sub-concern 1-5:

    line 472

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Contract-First + Clean Architecture

Opinionated, language-agnostic skill for building backend and fullstack projects with contract-first schemas as single source of truth, Clean Architecture layering, and screaming architecture that communicates business purpose through structure.

Snippets use TypeScript as notation — the patterns apply to any typed language. See the language equivalence table below for translations.

When to use

  • Starting a new project that exposes an API (REST, WebSocket, gRPC, GraphQL, events)
  • Migrating an existing codebase from code-first to contract-first
  • Introducing Clean Architecture layers into a flat/monolithic codebase
  • Evaluating architectural maturity of a project
  • Integrating external services (LLMs, third-party APIs, databases) with proper abstraction

When NOT to use

  • One-off scripts or throwaway prototypes with no future maintenance
  • Projects with fewer than 2 endpoints and no external integrations
  • Static sites or pure frontend projects with no backend

Core principles

These eight principles are non-negotiable regardless of language or framework.

1. Contracts are the single source of truth

All types, models, validators, documentation, and client code must be derived from a single schema definition — never maintained independently. Generation pipelines enforce this. Drift detection in CI verifies it.

Anti-pattern: Manually writing type definitions AND schema objects that represent the same data — they will diverge silently.

2. Dependencies point inward

Domain code has zero external dependencies. Application code depends only on domain abstractions. Infrastructure implements domain-defined interfaces. Only the composition root crosses all boundaries.

routes/handlers → use cases (application) → domain ← infrastructure
                                              ↑              |
                                              └──────────────┘
                                           (implements interfaces)

3. Tests drive design

Write the test first, then the code. If code is hard to test, the architecture is wrong. Port interfaces, constructor injection, and explicit use cases exist primarily to enable testing.

4. Domain entities encapsulate behavior

Entities are not data bags. They enforce invariants at construction, own their state transitions, and make invalid states unrepresentable through value objects and factories.

Domain-specific error hierarchies are mandatory. Every invalid transition or business rule violation must raise a domain-specific error — never a generic Error or Exception.

5. External service output is untrusted input

Every response from an external service must be parsed, validated against a schema, and handled with a fallback strategy. This applies regardless of protocol.

6. Architecture decisions are documented

ADRs provide governance, onboarding clarity, and a searchable record of why decisions were made.

7. The composition root is the single wiring point

One file, one place, assembles the entire dependency graph. Everything else receives its dependencies through constructors, factory parameters, or framework-native DI mechanisms.

See examples/snippets/composition-root.ts.

8. Semantic naming — no pattern names in code

Names describe WHAT a thing IS in the domain, never which pattern it implements. Suffixes like DTO, VO, Factory, Builder, Adapter, Handler, Wrapper, Helper, Manager, Utils, Impl are forbidden.

Allowed exceptions — where the pattern name IS the semantic name: *Repository, *Mother, *Faker, *EventBus.

Infrastructure adapters are named by technology + domain role: PostgresOrderRepository, StripePaymentGateway, KeycloakAuthService — NOT OrderRepositoryImpl or PaymentAdapter.

Entities follow Tell Don't Ask: expose behavior (order.confirm()), not accessors (order.getStatus()). The entity decides; the caller tells.

See examples/patterns/project-structure.md § Semantic naming.

Agent decision tree

When generating a project, follow this prescriptive sequence. Each step must be completed before the next.

Why contracts first — before even the directory structure?

In a code-first approach you write entities, then derive the API from them. The API becomes an accidental reflection of your internal model. In contract-first, you design the API boundary deliberately and THEN build internals to serve it. This has three concrete consequences:

  1. The schemas are concrete and validatable (YAML you can lint). Directory names are decisions you can change in seconds. Concrete before abstract.
  2. The schemas reveal the slices. When you write order.yaml, event.yaml, ticket.yaml, venue.yaml, the business groupings emerge naturally — you do not invent them, you discover them.
  3. An agent can derive structure from schemas programmatically. It cannot derive schemas from empty directory names. The SSOT must come first because everything else is derived from it.

Terminology note: In this skill, "use case" and "application service" are synonyms — both refer to the orchestration classes in application/. The directory name use-cases/ is forbidden (pattern name), but the concept is required.

TDD applies within every step: Steps 1-8 define the STRUCTURE. Within each step, write the test first, then the production code. The steps do not mean "build everything first, test last."

Step 1: Define contract schemas — the SSOT (Contract-First)

This is the "first" in "contract-first". Before writing any code or creating any directory structure, define YAML schemas (JSON Schema Draft 2020-12) for every entity the system will expose or consume.

The schemas reveal the domain. Writing order.yaml, event.yaml, ticket.yaml, venue.yaml forces you to think about what the system communicates — and the entities that emerge from the schemas naturally cluster into business capabilities that will become your screaming slices in Step 3.

See examples/contracts/schemas/ for real examples and examples/contracts/specs/ for OpenAPI and AsyncAPI specifications that reference those schemas.

Step 2: Set up generation pipeline

Generate types from schemas. The generated files are committed to the repo.

EcosystemToolCommand
TypeScriptjson-schema-to-typescriptnpx json-schema-to-typescript schemas/*.yaml -o generated/
Pythondatamodel-codegendatamodel-codegen --input schemas/ --output generated/models.py
Gogo-jsonschemago-jsonschema -p models schemas/*.yaml
Javajsonschema2pojoMaven/Gradle plugin in build
Rustschemafyschemafy schemas/order.yaml

Add a Makefile target:

generate-types:
  npx json-schema-to-typescript contracts/schemas/*.yaml -o contracts/generated/
  @echo "Types regenerated from contract schemas"

check-drift:
  $(MAKE) generate-types
  git diff --exit-code contracts/generated/ || (echo "DRIFT DETECTED" && exit 1)

Step 3: Derive screaming slices from the contracts

Look at the schemas you wrote. The entities cluster into business capabilities. Each cluster becomes a top-level directory that screams what it does.

Schemas written in Step 1:          Slices that emerge:
  event.yaml   ─┐
  venue.yaml    ─┤───────────>  src/catalog/
  event-status  ─┘
  order.yaml   ─┐
  ticket.yaml  ─┤───────────>  src/booking/
  order-status  ─┘
  Money, UUID   ─────────────>  src/shared/

The contracts REVEAL the structure — you do not invent it.

Step 4: Create layer structure per slice (Vertical Slicing)

Each slice is self-contained with its own layers. No shared services/ or repositories/ directory across slices. Dependencies ALWAYS point inward.

{slice}/
├── domain/               # Layer 0: ZERO imports from application/ or infrastructure/
│   ├── entities/         #   Aggregates with state machines and domain events
│   ├── value-objects/    #   Immutable, self-validating (Money, OrderId)
│   ├── ports/            #   Interfaces — define WHAT, never HOW
│   └── errors/           #   Domain-specific error hierarchy
├── application/          # Layer 1: imports ONLY from domain/
│   ├── purchase-order.ts #   Semantic name — NOT use-cases/purchase-order.ts
│   └── analyze-fit.ts    #   Each file orchestrates: load → mutate → persist → publish
└── infrastructure/       # Layer 2: IMPLEMENTS ports from domain/ports/
    ├── persistence/      #   SQL, in-memory, file
    ├── external/         #   ACL for third-party APIs
    └── messaging/        #   Event bus adapters

Note: application/ has NO use-cases/ subdirectory — that is a pattern name. Files go directly in application/ with semantic names. If a slice grows enough that application/ has many files, group by business sub-capability:

application/
├── purchase/             # "I handle the purchase flow"
│   ├── purchase-order.ts
│   └── refund-order.ts
└── discovery/            # "I handle search and browse"
    └── search-events.ts

Only create subdirectories when the grouping reflects a real business boundary — never for organizational convenience alone.

See examples/snippets/orchestration.ts for a concrete application service example.

The generated contract types (from Step 2) live in contracts/generated/ at the project root — NOT inside any slice. They are the API boundary shapes. Domain entities inside each slice are hand-written, with behavior and state machines that no code generator can produce. See examples/patterns/project-structure.md § Generated types vs domain entities for the mapping between them.

Screaming Architecture vs Vertical Slicing vs Bounded Context

These are three independent architectural decisions that often converge but are NOT synonyms:

ConceptDecidesQuestion it answers
Screaming ArchitectureHOW to name directories"What does this system do?"
Vertical SlicingWHAT each directory contains"Is this slice self-contained?"
Bounded Context (DDD)WHERE the model boundaries are"Where does the ubiquitous language change?"

In most projects, a screaming slice corresponds to a Bounded Context. But:

  • A BC can contain multiple slices (e.g., order-creation/ and order-fulfillment/ within the same Ordering BC)
  • A slice can exist without being a DDD Bounded Context (e.g., notification/ may be a technical slice, not a domain model boundary)

Start with screaming slices derived from your contracts. If the domain is complex enough to need DDD modeling, the BC boundaries will emerge from the ubiquitous language — not from the directory structure.

Step 5: Define port interfaces with Criteria pattern

For every external dependency, define a port interface in domain/ports/. Domain entities (written by hand) model the internal behavior. Port interfaces define the boundaries between the domain and the outside world.

CRITICAL: search operations MUST use the Criteria pattern — a domain value object for composable filters. NEVER add find_by_city(), find_by_capacity() methods to ports. That creates combinatorial explosion. One search(criteria) method covers all cases.

Adding a new filter = adding a field to Criteria. NOT changing the port signature.

See examples/snippets/port-interface.ts and examples/patterns/criteria-pattern.md.

Step 6: Implement infrastructure adapters

For each port, create at least TWO implementations:

  • In-memory (fake for tests)
  • Production (SQL, HTTP, SDK)

See examples/snippets/repository-implementation.ts and examples/snippets/acl-translation.ts.

Step 7: Wire in composition root

See examples/snippets/composition-root.ts. One file imports all concrete infrastructure. Override mechanism for tests.

Step 8: Build test infrastructure

Create Object Mothers with faker for domain-meaningful test data. Create stubs and spies for port interfaces.

See examples/snippets/object-mother.ts and examples/snippets/test-double-stub-spy.ts.

Language equivalence table

Snippets use TypeScript as notation. Apply this table for other languages:

ConceptTypeScriptPythonGoJava/KotlinRust
Port interfaceinterfaceABC + @abstractmethodinterface (implicit)interfacetrait
Value objectclass (readonly fields)@dataclass(frozen=True)struct (no setters)record / final classstruct (no mut)
Entityclass (private state)class (private attrs)struct + methodsclass (private fields)struct + impl
Async operationPromise<T>async/await (asyncio)goroutine + channelCompletableFuture<T>async fn -> impl Future
DI mechanismConstructor params__init__ params / Depends()func params / main()@Inject / constructorGenerics / main()
Error hierarchyclass extends Errorclass(DomainError)Custom error typesclass extends RuntimeExceptionenum implementing Error
File namingkebab-case.tssnake_case.pysnake_case.goPascalCase.javasnake_case.rs
Criteriainterface XxxCriteria@dataclass XxxCriteriastruct XxxCriteriarecord XxxCriteriastruct XxxCriteria
Test doubleclass implements Portclass(PortABC)struct + methodsclass implements Portstruct + impl Trait
Object MotherStatic factory methods@classmethodPackage-level funcsStatic factory methodsAssociated functions
Faker library@faker-js/fakerfakergo-fakerjavafaker / datafakerfake

Screaming architecture rules

Directory names communicate BUSINESS PURPOSE at every level — not technical patterns.

# BAD — pattern jargon at every level
src/
├── controllers/
├── services/
│   └── use-cases/        # ← pattern name inside pattern name
├── repositories/
├── dtos/                 # ← pattern suffix as directory
└── models/

# GOOD — screams business at the top, layers inside each slice
src/
├── catalog/              # "I manage events and venues"
│   ├── domain/
│   ├── application/      # Files here, not in use-cases/ subdir
│   └── infrastructure/
├── booking/              # "I handle reservations and payments"
│   ├── domain/
│   ├── application/
│   └── infrastructure/
└── shared/               # Cross-cutting value objects and ports

The rule applies at EVERY directory depth:

  • Top level: business capabilities (catalog/, booking/) — NOT frameworks
  • Second level: architectural layers (domain/, application/) — these are acceptable because they describe the dependency direction, not a pattern name
  • Inside layers: semantic names — purchase-order.ts, NOT use-cases/, NOT dtos/, NOT helpers/

Testing strategy

The testing strategy is NOT a methodology choice — it is a consequence of the architecture. Ports & adapters determines what is testable, how fast, and at what granularity. The distribution of tests emerges from the layers:

LayerWhat to testHowSpeed
DomainState machines, invariants, value objectsDirect calls, no DIMicroseconds
ApplicationBusiness operations through portsIn-memory doubles injectedMilliseconds
InfrastructureSQL, HTTP clients, serializationReal DB / API sandboxSeconds
E2ECritical user journeys onlyFull system wiredSeconds-minutes
ContractsSchema ↔ type driftCI pipelineSeconds

The key insight: the application layer tests are fast AND high-confidence because the architecture gives you injectable ports. Without ports & adapters, you would need real infrastructure for the same confidence level — making those tests slow and flaky. The architecture makes the testing strategy possible; the testing strategy does not dictate the architecture.

Test data is generated via Object Mothers with faker (see Step 8) — keeping domain-meaningful fixtures separate from test logic and making tests read as business scenarios: OrderMother.paid() instead of manual object construction.

Frontend adaptation

When applying Clean Architecture to a frontend project, adapt the layers:

Backend layerFrontend equivalentResponsibility
domain/domain/ (or rules/)Pure types + business rules, ZERO framework imports
domain/ports/domain/ports/Repository/service interfaces (inside domain/)
infrastructure/infrastructure/HTTP fetch implementations
application/stores/State management with DI (receives ports via factory)
api/components/UI components consuming stores + domain rules

Screaming slices apply equally: top-level directories are feature slices (event-discovery/, booking/), not technical layers.

Import rules within a slice:

components/ → stores/ → domain/ports/ → domain/
                             ↑
           infrastructure/ ──┘ (implements ports)

Components NEVER import from infrastructure/. Cross-slice imports go through ports only.

See examples/snippets/frontend-store-with-di.ts (React/Zustand-specific).

Project structure template

project-root/
├── contracts/                  # SSOT: schema definitions + generation
│   ├── schemas/                # Source schemas (YAML, JSON Schema Draft 2020-12)
│   ├── specs/                  # OpenAPI, AsyncAPI specs
│   └── generated/              # AUTO-GENERATED output (committed)
├── src/
│   ├── {slice}/                # Screaming: catalog/, booking/, notification/
│   │   ├── domain/
│   │   │   ├── entities/
│   │   │   ├── value-objects/
│   │   │   ├── ports/          # Interfaces with Criteria for search ops
│   │   │   └── errors/
│   │   ├── application/            # Semantic file names — NO use-cases/ subdir
│   │   └── infrastructure/
│   │       ├── persistence/
│   │       ├── external/       # ACLs for third-party APIs
│   │       └── messaging/
│   ├── shared/
│   │   ├── domain/             # Value objects (Money, IDs), EventBus port
│   │   └── infrastructure/     # Shared adapters (event bus, notifications)
│   ├── api/                    # Thin HTTP/gRPC handlers
│   └── composition-root.*     # Single wiring point
├── test/
│   ├── mothers/                # Object Mothers (use faker internally)
│   ├── doubles/                # Stubs + spies for port interfaces
│   └── contract/               # Schema ↔ type alignment tests
└── Makefile                    # generate-types, check-drift, test targets

Self-assessment checklist

Use this to evaluate any project. Each "no" identifies a specific gap:

#QuestionPrinciplePriority
1Are all types derived from a single schema source via code generation?Contract SSOTP1
2Does CI fail if generated files are stale (drift detection)?Drift ProtectionP1
3Can you swap any external dependency without modifying domain or application code?Dependency InversionP1
4Does every external service have a port interface with at least one test double?Port/AdapterP1
5Are application services explicit classes/functions, separate from HTTP handlers?App Layer ExplicitnessP2
6Do domain entities enforce their own invariants via guarded state transitions?Domain RichnessP2
7Are there value objects for domain identifiers and measurements?Value ObjectsP2
8Is there a composition root — one file where the dependency graph is assembled?Composition RootP1
9Do port search operations use the Criteria pattern (not combinatorial methods)?Criteria PatternP2
10Are there Object Mothers with faker for test data?Test MaintainabilityP2
11Is every architecture decision documented in an ADR?GovernanceP3
12Is the dev environment reproducible with a single command?DXP3
13Does CI enforce linting, type checking, testing, and contract validation?Quality GatesP2
14For external APIs: Is every response validated against a schema before use?External SafetyP1
15Does the directory structure scream business purpose, not framework names?Screaming ArchP2
16Are all names semantic (no DTO/VO/Helper/Impl suffixes)? Tell Don't Ask?Semantic NamingP2

Common mistakes

MistakeWhy it's wrongWhat to do instead
Writing types AND schemas independentlyThey diverge silentlyGenerate types FROM schemas
Business logic in route handlersUntestable, grows into god functionsExtract to application services with injected ports
Importing concrete services in domainViolates dependency ruleDefine port interfaces, inject via constructor
find_by_X() methods on repositoriesCombinatorial explosionCriteria pattern: one search(criteria) method
Layer-based top-level dirs (controllers/, services/)Hides business purposeScreaming slices (catalog/, booking/)
Tests that require real external servicesSlow, flaky, non-deterministicIn-memory fakes implementing port interfaces
Generic errors for domain violationsLoses business contextDomain error hierarchy with ubiquitous language
Coupling domain to ORM/frameworkDomain depends on infrastructurePure domain classes; map in infrastructure
No generation pipeline for contracts"Contract-first" in name onlyMakefile target: schema → types → drift check
Pattern names in classes (OrderDTO, PaymentAdapter, UserHelper)Hides domain intent behind jargonSemantic names: CreateOrderRequest, StripePaymentGateway, methods on User
Frontend components importing from infrastructure/Leaks HTTP details into UIComponents import stores + domain, never infrastructure

Scoring rubric

When evaluating a project, score each sub-concern 1-5:

ScoreMeaningEvidence
1AbsentNo evidence of the practice
2MinimalPartial or accidental implementation
3PartialIntentional but incomplete adoption
4SolidConsistent implementation with minor gaps
5ExemplaryComprehensive, documented, enforced in CI

Evaluation concerns

AreaSub-concerns to score
Contract-FirstContract SSOT, Type Generation, Drift Protection, Contract Testing
Clean ArchitectureDomain Layer, Application Layer, Infra Abstraction, Dependency Rule, Composition Root
Screaming ArchitectureBusiness-purpose dirs, Slice self-containment, No cross-slice shared services/
TestingLayer-appropriate tests, Isolation via ports, Contract tests, Object Mothers
DDDUbiquitous Language, Aggregates, Value Objects, Domain Events, Criteria
IntegrationACL pattern, External validation, Resilience patterns

Examples directory

See examples/ for complete working examples organized in three subdirectories:

  • contracts/ — Real YAML schemas (JSON Schema Draft 2020-12), OpenAPI 3.1.0, and AsyncAPI 3.0.0 specs
  • patterns/ — Language-agnostic architecture patterns (criteria, ACL, repository, strategy, infrastructure doubling)
  • snippets/ — Architecture patterns as TypeScript notation (entity, value object, port, repository, composition root, test doubles, Object Mother, frontend store)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.