К основному содержанию
скилл CX Codex

clean-architecture · giuseppe-trisciuoglio, developer-kit-python — скилл для Claude Code

Скилл clean-architecture для Claude Code задаёт шаблоны слоистой архитектуры Python-бэкенда на FastAPI или Flask: домен, сценарии, порты и адаптеры, репозитории. Разделяет код по слоям.

MIT ★ 372 обновлён 2026-09-10

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-python@developer-kit
Открыть на GitHub

Что делает clean-architecture

Скилл задаёт скелет приложения по правилу зависимостей: домен внутри, инфраструктура снаружи. В доменном слое — сущности, value objects, доменные события и интерфейсы репозиториев. Выше идут сценарии использования, затем адаптеры с реализациями репозиториев и контроллерами, в конце инфраструктура с подключением к базе и контейнером внедрения зависимостей.

Работа идёт по шагам: сначала структура каталогов, потом домен, сценарии, адаптеры, инфраструктура, точка входа и тесты. В примерах есть value object Email на frozen dataclass с проверкой в __post_init__, сущность User с фабричным методом create() и порт IUserRepository на ABC. Тесты разносятся по слоям: сценарии с подставными репозиториями, адаптеры на тестовой базе.

Инструменты у скилла — Read, Write, Edit, Glob, Grep и Bash, так что он создаёт файлы и может запускать команды в проекте. Всё описание рассчитано на Python с FastAPI или Flask, а в адаптерах примеры опираются на async-сессии SQLAlchemy. В проекте на другом языке шаблоны придётся переписывать самому.

Какие задачи решает

  • разложить слипшийся модуль на домен, сценарии и адаптеры
  • вынести бизнес-логику из роутеров FastAPI
  • описать порт репозитория и подменить его в тестах
  • собрать value object с валидацией в __post_init__
  • протестировать сценарий без базы и HTTP

Примеры запросов агенту

  • Разложи текущий каталог app/ по слоям Clean Architecture и покажи новое дерево файлов
  • Сделай сущность Order с value object Money и портом репозитория на ABC
  • Напиши сценарий использования для регистрации пользователя с внедрением репозитория через конструктор

Как установить clean-architecture

1Через маркетплейс плагинов

/plugin marketplace add giuseppe-trisciuoglio/developer-kit
/plugin install developer-kit-python@developer-kit

Команда ставит плагин developer-kit-python целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill clean-architecture -a claude-code

3Вручную: положить файлы

~/.claude/skills/clean-architecture/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/clean-architecture/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о clean-architecture

Как установить clean-architecture в Claude Code?

Через маркетплейс: сначала /plugin marketplace add giuseppe-trisciuoglio/developer-kit, потом /plugin install developer-kit-python@developer-kit.

Что делает clean-architecture?

Даёт шаблоны слоёв для Python-приложения: сущности и value objects, сценарии использования, порты и адаптеры, репозитории. Плюс порядок шагов и примеры кода для каждого слоя.

Для какого стека подходит скилл?

Для Python-бэкенда на FastAPI или Flask. Примеры используют dataclasses, ABC и async-сессии SQLAlchemy в адаптерах.

Исходный текст

SKILL.md · MIT
---
name: clean-architecture
description: Provides implementation patterns for Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design in Python applications with FastAPI or Flask. Use when designing maintainable backends with separation of concerns, implementing repository patterns, creating entities/value objects/aggregates, or structuring domain logic independent of frameworks for testability.
allowed-tools: Read, Write, Edit, Glob, Grep, Bash
---

# Clean Architecture, DDD & Hexagonal Architecture for Python

## Overview

This skill provides comprehensive guidance for implementing Clean Architecture, Hexagonal Architecture (Ports & Adapters), and Domain-Driven Design patterns in Python applications. It focuses on creating maintainable, testable, and framework-independent business logic through proper separation of concerns.

### Core Concepts

**Layered Architecture (Clean Architecture)** - Dependencies flow inward, inner layers know nothing about outer layers:

```
+-------------------------------------+
|  Infrastructure (Frameworks, DB)   |  <- Outer layer
+-------------------------------------+
|  Adapters (Controllers, Repos)     |
+-------------------------------------+
|  Use Cases (Application Logic)     |
+-------------------------------------+
|  Domain (Entities, Value Objects)  |  <- Inner layer
+-------------------------------------+
```

**Layers:**
- **Domain**: Entities, value objects, domain events, repository interfaces
- **Use Cases**: Application business rules, orchestrate domain objects
- **Adapters**: Interface implementations (controllers, repositories, gateways)
- **Infrastructure**: Framework configuration, database connections, external clients

**Hexagonal Architecture (Ports & Adapters)**
- **Ports**: Abstract interfaces defining what the application needs
- **Adapters**: Concrete implementations of ports
- **Domain Core**: Business logic with no external dependencies

**Domain-Driven Design Tactical Patterns**
- **Entities**: Objects with identity and lifecycle
- **Value Objects**: Immutable objects defined by attributes
- **Aggregates**: Consistency boundaries with aggregate roots
- **Repositories**: Persistence abstraction for aggregates
- **Domain Events**: Capture significant occurrences in the domain

## When to Use

- Designing new Python backend systems with separation of concerns
- Refactoring tightly coupled code into layered architectures
- Implementing domain-driven design with bounded contexts
- Creating testable business logic independent of frameworks
- Building applications with FastAPI or Flask using clean patterns
- Setting up repository patterns with SQLAlchemy or async databases
- Implementing use case patterns with proper dependency injection

## Instructions

### 1. Define the Project Structure

Create the layered directory structure following the dependency rule:

```
myapp/
+-- domain/                    # Inner layer - no external deps
|   +-- entities/             # Business entities
|   +-- value_objects/        # Immutable value objects
|   +-- events/               # Domain events
|   +-- repositories/         # Abstract repository interfaces (ports)
+-- use_cases/                # Application layer
+-- adapters/                 # Interface adapters
|   +-- repositories/         # Repository implementations
|   +-- controllers/          # API controllers
+-- infrastructure/           # Framework & external concerns
|   +-- database.py          # Database configuration
|   +-- container.py         # Dependency injection container
|   +-- config.py            # Application settings
+-- main.py                  # Application entry point
```

### 2. Implement the Domain Layer

Start from the innermost layer with no external dependencies:

1. Create Value Objects using frozen dataclasses with validation in `__post_init__`
2. Define Entities with identity, behavior, and factory methods (e.g., `create()`)
3. Define Repository Interfaces (Ports) as abstract base classes with abstract methods
4. Keep all domain logic in entities - avoid anemic models

### 3. Implement the Use Cases Layer

Create application-specific business rules:

1. Define Request/Response dataclasses for input/output
2. Create Use Case classes that receive repository interfaces via constructor injection
3. Implement the `execute()` method that orchestrates domain objects
4. Handle validation and business errors, returning appropriate responses

### 4. Implement the Adapter Layer

Create concrete implementations of domain interfaces:

1. Implement Repository classes that extend domain interfaces
2. Use SQLAlchemy async sessions or other ORM tools
3. Map between domain entities and database models
4. Create Controllers (FastAPI routers) that invoke use cases

### 5. Implement the Infrastructure Layer

Configure frameworks and external dependencies:

1. Set up database connections and session management
2. Configure the dependency injection container
3. Wire all components together
4. Define application settings and configuration

### 6. Create the Application Entry Point

Build the FastAPI or Flask application:

1. Initialize the DI container and wire modules
2. Configure application lifespan (startup/shutdown)
3. Register routers and middleware
4. Export the application factory function

### 7. Write Tests

Test each layer in isolation:

1. Unit test use cases with mocked repositories
2. Unit test domain entities and value objects
3. Integration test adapters with test databases
4. End-to-end test the full application stack

## Examples

### Example 1: Domain Layer - Value Object & Entity

```python
# domain/value_objects/email.py
from dataclasses import dataclass
import re

@dataclass(frozen=True)
class Email:
    value: str
    def __post_init__(self):
        if not re.match(r'^[\w\.-]+@[\w\.-]+\.\w+$', self.value):
            raise ValueError(f"Invalid email: {self.value}")
    def __str__(self) -> str:
        return self.value


# domain/entities/user.py
from dataclasses import dataclass, field
from datetime import datetime
from uuid import UUID, uuid4
from domain.value_objects.email import Email

@dataclass
class User:
    email: Email
    name: str
    id: UUID = field(default_factory=uuid4)
    is_active: bool = True
    created_at: datetime = field(default_factory=datetime.utcnow)

    def deactivate(self) -> None:
        self.is_active = False

    def can_login(self) -> bool:
        return self.is_active

    @classmethod
    def create(cls, email: Email, name: str) -> "User":
        return cls(email=email, name=name)
```

### Example 2: Repository Port (Interface)

```python
# domain/repositories/user_repository.py
from abc import ABC, abstractmethod
from typing import Optional
from uuid import UUID
from domain.entities.user import User
from domain.value_objects.email import Email

class IUserRepository(ABC):
    @abstractmethod
    async def find_by_id(self, user_id: UUID) -> Optional[User]: ...
    @abstractmethod
    async def find_by_email(self, email: Email) -> Optional[User]: ...
    @abstractmethod
    async def save(self, user: User) -> User: ...
    @abstractmethod
    async def delete(self, user_id: UUID) -> bool: ...
```

### Example 3: Use Case Layer

```python
# use_cases/create_user.py
from dataclasses import dataclass
from typing import Optional
from uuid import UUID
from domain.entities.user import User
from domain.value_objects.email import Email
from domain.repositories.user_repository import IUserRepository

@dataclass
class CreateUserRequest:
    email: str
    name: str

@dataclass
class CreateUserResponse:
    user_id: Optional[UUID]
    success: bool
    error_message: Optional[str] = None

class CreateUserUseCase:
    def __init__(self, user_repository: IUserRepository):
        self._user_repository = user_repository

    async def execute(self, request: CreateUserRequest) -> CreateUserResponse:
        try:
            email = Email(request.email)
        except ValueError as e:
            return CreateUserResponse(None, False, str(e))
        if await self._user_repository.find_by_email(email):
            return CreateUserResponse(None, False, "Email already registered")
        user = User.create(email=email, name=request.name)
        saved = await self._user_repository.save(user)
        return CreateUserResponse(saved.id, True)
```

### Example 4: Adapter Layer - Repository Implementation

```python
# adapters/repositories/sqlalchemy_user_repository.py
from typing import Optional
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from domain.entities.user import User
from domain.value_objects.email import Email
from domain.repositories.user_repository import IUserRepository

class SQLAlchemyUserRepository(IUserRepository):
    def __init__(self, session: AsyncSession):
        self._session = session

    async def find_by_id(self, user_id: UUID) -> Optional[User]:
        result = await self._session.execute(
            select(UserModel).where(UserModel.id == user_id)
        )
        row = result.scalar_one_or_none()
        return self._to_entity(row) if row else None

    async def find_by_email(self, email: Email) -> Optional[User]:
        result = await self._session.execute(
            select(UserModel).where(UserModel.email == str(email))
        )
        row = result.scalar_one_or_none()
        return self._to_entity(row) if row else None

    async def save(self, user: User) -> User:
        model = UserModel(
            id=user.id, email=str(user.email), name=user.name,
            is_active=user.is_active, created_at=user.created_at
        )
        self._session.add(model)
        await self._session.commit()
        return user

    def _to_entity(self, model) -> User:
        return User(
            id=model.id, email=Email(model.email), name=model.name,
            is_active=model.is_active, created_at=model.created_at
        )
```

### Example 5: Dependency Injection Container

```python
# infrastructure/container.py
from dependency_injector import containers, providers
from adapters.repositories.sqlalchemy_user_repository import SQLAlchemyUserRepository
from use_cases.create_user import CreateUserUseCase
from infrastructure.database import get_session

class Container(containers.DeclarativeContainer):
    db_session = providers.Factory(get_session)
    user_repository = providers.Factory(SQLAlchemyUserRepository, session=db_session)
    create_user_use_case = providers.Factory(
        CreateUserUseCase, user_repository=user_repository
    )
```

### Example 6: FastAPI Controller

```python
# adapters/controllers/user_controller.py
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, EmailStr
from use_cases.create_user import CreateUserUseCase, CreateUserRequest
from infrastructure.container import Container
from dependency_injector.wiring import inject, Provide

router = APIRouter(prefix="/users", tags=["users"])

class CreateUserInput(BaseModel):
    email: EmailStr
    name: str

@router.post("/", status_code=status.HTTP_201_CREATED)
@inject
async def create_user(
    data: CreateUserInput,
    use_case: CreateUserUseCase = Depends(Provide[Container.create_user_use_case])
):
    request = CreateUserRequest(email=data.email, name=data.name)
    response = await use_case.execute(request)
    if not response.success:
        raise HTTPException(status_code=400, detail=response.error_message)
    return {"id": str(response.user_id)}
```

### Example 7: Application Entry Point

```python
# main.py
from fastapi import FastAPI
from contextlib import asynccontextmanager
from adapters.controllers import user_controller
from infrastructure.container import Container
from infrastructure.database import init_db

@asynccontextmanager
async def lifespan(app: FastAPI):
    await init_db()
    yield

def create_app() -> FastAPI:
    container = Container()
    container.wire(modules=[user_controller])
    app = FastAPI(title="Clean Architecture API", lifespan=lifespan)
    app.container = container
    app.include_router(user_controller.router)
    return app

app = create_app()
```

### Example 8: Unit Testing Use Cases

```python
# tests/unit/test_create_user_use_case.py
import pytest
from unittest.mock import AsyncMock
from use_cases.create_user import CreateUserUseCase, CreateUserRequest
from domain.entities.user import User
from domain.value_objects.email import Email

@pytest.fixture
def mock_repository():
    return AsyncMock()

@pytest.fixture
def use_case(mock_repository):
    return CreateUserUseCase(user_repository=mock_repository)

@pytest.mark.asyncio
async def test_create_user_success(use_case, mock_repository):
    mock_repository.find_by_email.return_value = None
    mock_repository.save.return_value = User(
        email=Email("[email protected]"), name="Test User"
    )
    request = CreateUserRequest(email="[email protected]", name="Test User")
    response = await use_case.execute(request)
    assert response.success is True
    assert response.user_id is not None

@pytest.mark.asyncio
async def test_create_user_duplicate_email(use_case, mock_repository):
    mock_repository.find_by_email.return_value = AsyncMock()
    request = CreateUserRequest(email="[email protected]", name="Test User")
    response = await use_case.execute(request)
    assert response.success is False
    assert "already registered" in response.error_message
```

## Best Practices

1. **Dependency Rule**: Dependencies must always point inward toward the domain - never outward
2. **Immutable Value Objects**: Always use frozen dataclasses for value objects with validation in `__post_init__`
3. **Rich Domain Models**: Put business logic in entities, not in services or use cases
4. **Use Cases as Orchestrators**: Use cases coordinate workflows but domain objects make decisions
5. **Async by Default**: Use async/await for all I/O operations to support modern async frameworks
6. **Pydantic at Boundary**: Use Pydantic models only at the API boundary, never in domain layer
7. **Repository per Aggregate**: Create one repository per aggregate root, not per entity
8. **Factory Methods**: Use `@classmethod` factory methods like `create()` for entity construction with invariants
9. **Dependency Injection**: Inject dependencies through constructors for testability
10. **Structured Responses**: Return structured response objects from use cases, not raw entities

## Constraints and Warnings

### Architecture Constraints

- **Dependency Rule**: Dependencies must always point inward toward the domain - never outward
- **Framework Independence**: Domain layer must have no framework dependencies (no FastAPI, SQLAlchemy, Pydantic imports)
- **Interface Segregation**: Keep repository interfaces focused and small - avoid god interfaces
- **Repository per Aggregate**: Create one repository per aggregate root, not per entity

### Implementation Constraints

- **Immutable Value Objects**: Always use frozen dataclasses for value objects
- **Rich Domain Models**: Put business logic in entities, not in services or use cases
- **Use Cases as Orchestrators**: Use cases coordinate workflows but domain objects make decisions
- **Async by Default**: Use async/await for all I/O operations to support modern async frameworks
- **Pydantic at Boundary**: Use Pydantic models only at the API boundary, not in domain layer

### Common Pitfalls to Avoid

- **Anemic Domain Models**: Entities with only getters/setters and no behavior violate DDD principles
- **Leaky Abstractions**: ORM models leaking into domain layer creates tight coupling
- **Fat Controllers**: Business logic in controllers instead of use cases defeats the architecture
- **Missing Abstractions**: Direct database calls in use cases break the dependency rule
- **Circular Dependencies**: Be careful with imports between layers - use dependency injection to avoid
- **Over-Engineering**: Not every CRUD app needs full DDD - evaluate complexity before applying

## References

- `references/python-clean-architecture.md` - Python-specific patterns including Result type, Specification pattern, Event Bus, and manual DI
- `references/fastapi-implementation.md` - Complete FastAPI example with middleware, Docker setup, and integration tests

© Giuseppe Trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Похожие скиллы

Все скиллы по теме «Бэкенд и API» →

Сначала — clean-architecture от других авторов.

clean-architecture wondelai Скилл clean-architecture держит бизнес-правила отдельно от фреймворка и базы: исходники зависят только от внутренних слоёв, и это проверяется по чек-листу. CX Codex +1 8 000установок clean-architecture codewithmukesh Скилл clean-architecture для .NET-проектов: раскладывает код по четырём слоям, следит за направлением зависимостей и подсказывает, где живут use case-хендлеры. CX Codex +1 4 200установок clean-architecture ciembor Скилл clean-architecture для Claude Code применяет правила чистой архитектуры к решениям о границах между бизнес-логикой и техническими деталями. Агент подключает его при работе с зависимостями, сценариями использования и слоями приложения. CX Codex +1 645установок clean-architecture giuseppe-trisciuoglio Проектирование многоуровневых Java 21+ приложений на Spring Boot 3.5+. Отделяет бизнес-логику от фреймворка через Clean Architecture, Hexagonal Architecture и Domain-Driven Design. CX Codex +1 4 200установок clean-architecture pproenca Скилл clean-architecture с 42 правилами из книги Роберта Мартина: подсказывает агенту, куда направлять зависимости и где проводить границы слоёв. CX Codex +1 2 100установок python-clean-architecture MKToronto Плагин python-clean-architecture внедряет принципы чистой архитектуры в проекты на Python и FastAPI. Он проверяет слои приложения, находит сильную связанность и генерирует каркасы сервисов. ★ 11звёзд репо architecture-patterns OrchestKit Скилл architecture-patterns проверяет соблюдение чистой архитектуры, деление бэкенда на слои и глубину вложенности папок. Включается при проектировании границ сервисов и рефакторинге. CX Codex +1 236установок architecture-advisor codewithmukesh Скилл architecture-advisor задаёт вопросы про домен, команду и срок жизни системы, а потом советует архитектуру для .NET-проекта. Пригодится до того, как разложить решение по папкам. CX Codex +1 4 000установок go-backend-clean-architecture rebyteai-template Скилл go-backend-clean-architecture разворачивает в проекте шаблон Go-бэкенда на Gin с MongoDB, JWT-авторизацией и слоями Clean Architecture — от клонирования до запуска. CX Codex +1 105установок Python Security Scan sugarforever Скилл Python Security Scan проверяет код на Python, Flask, Django и FastAPI на уязвимости OWASP Top 10, утечки секретов и уязвимые зависимости. Пригодится перед релизом и во время аудита безопасности. CX Codex +1 553установок android-clean-architecture affaan-m Скилл android-clean-architecture подсказывает агенту, как раскладывать Android- и KMP-проект по слоям: модули, зависимости, UseCase, репозитории, работа с Room, SQLDelight и Ktor. CX Codex +1 7 200установок

Из того же набора191

Весь набор →
nestjs-security-expert Субагент nestjs-security-expert для Claude Code помогает настраивать аутентификацию и защищать NestJS API. Подключается при работе с JWT, ролями, OAuth и уязвимостями. CX Codex ★ 372звёзд репо php-software-architect-expert php-software-architect-expert — субагент для Claude Code, который разбирает архитектуру PHP-проектов. Его подключают для проверки Clean Architecture, DDD и решений по структуре кода. CX Codex ★ 372звёзд репо typescript-refactor-expert Субагент typescript-refactor-expert проводит рефакторинг кода на TypeScript и современном JavaScript без изменения поведения программы. Применяет принципы SOLID и чистой архитектуры после написания фич. CX Codex ★ 372звёзд репо speckit.verify Команда speckit.verify проверяет готовность реализации по задачам, спецификации, тестам и качеству кода. Запускайте после /speckit.implement. CX Codex +1 ★ 372звёзд репо python-security-expert Субагент python-security-expert для Claude Code проверяет безопасность Python-приложений. Подключается к запросам на аудит, DevSecOps или внедрение требований безопасности. CX Codex ★ 372звёзд репо java-software-architect-review Субагент java-software-architect-review проверяет архитектуру Java-проекта на соответствие Clean Architecture и DDD, а также оценивает Spring Boot. Подключайте его при проектировании или ревью архитектуры. CX Codex ★ 372звёзд репо java-documentation-specialist Субагент java-documentation-specialist для Claude Code разбирает код на Spring Boot и пишет документацию по эндпоинтам, схеме БД и архитектуре. Помогает объяснить Java-проект другим. CX Codex ★ 372звёзд репо devkit.github.review-pr Команда devkit.github.review-pr проводит аудит пулл-реквеста в GitHub перед слиянием: разбирает дифф, ищет секреты и оценивает архитектуру с безопасностью. CX Codex +1 ★ 372звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой