[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XGZCMX0YF4TDW6F7HPVQC":3,"skill-same:01M72XGZCMX0YF4TDW6F7HPVQC":51},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":28,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M72XGZCMX0YF4TDW6F7HPVQC","architecture-patterns",null,"Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.","steph-frtech\u002Fclaude-code-up","steph-frtech","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F198466323?v=4","01M72XD213FVQA2QXRGTJFKHE1","01M72XD227AANJ993SQTNZB1CK",1,"MIT","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fbackend-development\u002Fskills\u002Farchitecture-patterns\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: architecture-patterns\ndescription: Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use this skill when designing clean architecture for a new microservice, when refactoring a monolith to use bounded contexts, when implementing hexagonal or onion architecture patterns, or when debugging dependency cycles between application layers.\n---\n\n# Architecture Patterns\n\nMaster proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.\n\n**Given:** a service boundary or module to architect.\n**Produces:** layered structure with clear dependency rules, interface definitions, and test boundaries.\n\n## When to Use This Skill\n\n- Designing new backend services or microservices from scratch\n- Refactoring monolithic applications where business logic is entangled with ORM models or HTTP concerns\n- Establishing bounded contexts before splitting a system into services\n- Debugging dependency cycles where infrastructure code bleeds into the domain layer\n- Creating testable codebases where use-case tests do not require a running database\n- Implementing domain-driven design tactical patterns (aggregates, value objects, domain events)\n\n## Core Concepts\n\n### 1. Clean Architecture (Uncle Bob)\n\n**Layers (dependency flows inward):**\n\n- **Entities**: Core business models, no framework imports\n- **Use Cases**: Application business rules, orchestrate entities\n- **Interface Adapters**: Controllers, presenters, gateways — translate between use cases and external formats\n- **Frameworks & Drivers**: UI, database, external services — all at the outermost ring\n\n**Key Principles:**\n\n- Dependencies point inward only; inner layers know nothing about outer layers\n- Business logic is independent of frameworks, databases, and delivery mechanisms\n- Every layer boundary is crossed via an abstract interface\n- Testable without UI, database, or external services\n\n### 2. Hexagonal Architecture (Ports and Adapters)\n\n**Components:**\n\n- **Domain Core**: Business logic lives here, framework-free\n- **Ports**: Abstract interfaces that define how the core interacts with the outside world (driving and driven)\n- **Adapters**: Concrete implementations of ports (PostgreSQL adapter, Stripe adapter, REST adapter)\n\n**Benefits:**\n\n- Swap implementations without touching the core (e.g., replace PostgreSQL with DynamoDB)\n- Use in-memory adapters in tests — no Docker required\n- Technology decisions deferred to the edges\n\n### 3. Domain-Driven Design (DDD)\n\n**Strategic Patterns:**\n\n- **Bounded Contexts**: Isolate a coherent model for one subdomain; avoid sharing a single model across the whole system\n- **Context Mapping**: Define how contexts relate (Anti-Corruption Layer, Shared Kernel, Open Host Service)\n- **Ubiquitous Language**: Every term in code matches the term used by domain experts\n\n**Tactical Patterns:**\n\n- **Entities**: Objects with stable identity that change over time\n- **Value Objects**: Immutable objects identified by their attributes (Email, Money, Address)\n- **Aggregates**: Consistency boundaries; only the root is accessible from outside\n- **Repositories**: Persist and reconstitute aggregates; abstract over the storage mechanism\n- **Domain Events**: Capture things that happened inside the domain; used for cross-aggregate coordination\n\n## Clean Architecture — Directory Structure\n\n```\napp\u002F\n├── domain\u002F           # Entities, value objects, interfaces\n│   ├── entities\u002F\n│   │   ├── user.py\n│   │   └── order.py\n│   ├── value_objects\u002F\n│   │   ├── email.py\n│   │   └── money.py\n│   └── interfaces\u002F   # Abstract ports (no implementations)\n│       ├── user_repository.py\n│       └── payment_gateway.py\n├── use_cases\u002F        # Application business rules\n│   ├── create_user.py\n│   ├── process_order.py\n│   └── send_notification.py\n├── adapters\u002F         # Concrete implementations\n│   ├── repositories\u002F\n│   │   ├── postgres_user_repository.py\n│   │   └── redis_cache_repository.py\n│   ├── controllers\u002F\n│   │   └── user_controller.py\n│   └── gateways\u002F\n│       ├── stripe_payment_gateway.py\n│       └── sendgrid_email_gateway.py\n└── infrastructure\u002F   # Framework wiring, config, DI container\n    ├── database.py\n    ├── config.py\n    └── logging.py\n```\n\n**Dependency rule in one sentence:** every `import` statement in `domain\u002F` and `use_cases\u002F` must point only toward `domain\u002F`; nothing in those layers may import from `adapters\u002F` or `infrastructure\u002F`.\n\n## Clean Architecture — Core Implementation\n\n```python\n# domain\u002Fentities\u002Fuser.py\nfrom dataclasses import dataclass\nfrom datetime import datetime\n\n@dataclass\nclass User:\n    \"\"\"Core user entity — no framework dependencies.\"\"\"\n    id: str\n    email: str\n    name: str\n    created_at: datetime\n    is_active: bool = True\n\n    def deactivate(self):\n        self.is_active = False\n\n    def can_place_order(self) -> bool:\n        return self.is_active\n\n\n# domain\u002Finterfaces\u002Fuser_repository.py\nfrom abc import ABC, abstractmethod\nfrom typing import Optional\nfrom domain.entities.user import User\n\nclass IUserRepository(ABC):\n    \"\"\"Port: defines contract, no implementation details.\"\"\"\n\n    @abstractmethod\n    async def find_by_id(self, user_id: str) -> Optional[User]: ...\n\n    @abstractmethod\n    async def find_by_email(self, email: str) -> Optional[User]: ...\n\n    @abstractmethod\n    async def save(self, user: User) -> User: ...\n\n    @abstractmethod\n    async def delete(self, user_id: str) -> bool: ...\n\n\n# use_cases\u002Fcreate_user.py\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import Optional\nimport uuid\nfrom domain.entities.user import User\nfrom domain.interfaces.user_repository import IUserRepository\n\n@dataclass\nclass CreateUserRequest:\n    email: str\n    name: str\n\n@dataclass\nclass CreateUserResponse:\n    user: Optional[User]\n    success: bool\n    error: Optional[str] = None\n\nclass CreateUserUseCase:\n    \"\"\"Use case: orchestrates business logic, no HTTP or DB details.\"\"\"\n\n    def __init__(self, user_repository: IUserRepository):\n        self.user_repository = user_repository\n\n    async def execute(self, request: CreateUserRequest) -> CreateUserResponse:\n        existing = await self.user_repository.find_by_email(request.email)\n        if existing:\n            return CreateUserResponse(user=None, success=False, error=\"Email already exists\")\n\n        user = User(\n            id=str(uuid.uuid4()),\n            email=request.email,\n            name=request.name,\n            created_at=datetime.now(),\n        )\n        saved_user = await self.user_repository.save(user)\n        return CreateUserResponse(user=saved_user, success=True)\n\n\n# adapters\u002Frepositories\u002Fpostgres_user_repository.py\nfrom domain.interfaces.user_repository import IUserRepository\nfrom domain.entities.user import User\nfrom typing import Optional\nimport asyncpg\n\nclass PostgresUserRepository(IUserRepository):\n    \"\"\"Adapter: PostgreSQL implementation of the user port.\"\"\"\n\n    def __init__(self, pool: asyncpg.Pool):\n        self.pool = pool\n\n    async def find_by_id(self, user_id: str) -> Optional[User]:\n        async with self.pool.acquire() as conn:\n            row = await conn.fetchrow(\"SELECT * FROM users WHERE id = $1\", user_id)\n            return self._to_entity(row) if row else None\n\n    async def find_by_email(self, email: str) -> Optional[User]:\n        async with self.pool.acquire() as conn:\n            row = await conn.fetchrow(\"SELECT * FROM users WHERE email = $1\", email)\n            return self._to_entity(row) if row else None\n\n    async def save(self, user: User) -> User:\n        async with self.pool.acquire() as conn:\n            await conn.execute(\n                \"\"\"\n                INSERT INTO users (id, email, name, created_at, is_active)\n                VALUES ($1, $2, $3, $4, $5)\n                ON CONFLICT (id) DO UPDATE\n                SET email = $2, name = $3, is_active = $5\n                \"\"\",\n                user.id, user.email, user.name, user.created_at, user.is_active,\n            )\n        return user\n\n    async def delete(self, user_id: str) -> bool:\n        async with self.pool.acquire() as conn:\n            result = await conn.execute(\"DELETE FROM users WHERE id = $1\", user_id)\n            return result == \"DELETE 1\"\n\n    def _to_entity(self, row) -> User:\n        return User(\n            id=row[\"id\"], email=row[\"email\"], name=row[\"name\"],\n            created_at=row[\"created_at\"], is_active=row[\"is_active\"],\n        )\n\n\n# adapters\u002Fcontrollers\u002Fuser_controller.py\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom pydantic import BaseModel\nfrom use_cases.create_user import CreateUserUseCase, CreateUserRequest\n\nrouter = APIRouter()\n\nclass CreateUserDTO(BaseModel):\n    email: str\n    name: str\n\n@router.post(\"\u002Fusers\")\nasync def create_user(\n    dto: CreateUserDTO,\n    use_case: CreateUserUseCase = Depends(get_create_user_use_case),\n):\n    \"\"\"Controller handles HTTP only — no business logic lives here.\"\"\"\n    response = await use_case.execute(CreateUserRequest(email=dto.email, name=dto.name))\n    if not response.success:\n        raise HTTPException(status_code=400, detail=response.error)\n    return {\"user\": response.user}\n```\n\n## Hexagonal Architecture — Ports and Adapters\n\n```python\n# Core domain service — no infrastructure dependencies\nclass OrderService:\n    def __init__(\n        self,\n        order_repository: OrderRepositoryPort,\n        payment_gateway: PaymentGatewayPort,\n        notification_service: NotificationPort,\n    ):\n        self.orders = order_repository\n        self.payments = payment_gateway\n        self.notifications = notification_service\n\n    async def place_order(self, order: Order) -> OrderResult:\n        if not order.is_valid():\n            return OrderResult(success=False, error=\"Invalid order\")\n\n        payment = await self.payments.charge(amount=order.total, customer=order.customer_id)\n        if not payment.success:\n            return OrderResult(success=False, error=\"Payment failed\")\n\n        order.mark_as_paid()\n        saved_order = await self.orders.save(order)\n        await self.notifications.send(\n            to=order.customer_email,\n            subject=\"Order confirmed\",\n            body=f\"Order {order.id} confirmed\",\n        )\n        return OrderResult(success=True, order=saved_order)\n\n\n# Ports (driving and driven interfaces)\nclass OrderRepositoryPort(ABC):\n    @abstractmethod\n    async def save(self, order: Order) -> Order: ...\n\nclass PaymentGatewayPort(ABC):\n    @abstractmethod\n    async def charge(self, amount: Money, customer: str) -> PaymentResult: ...\n\nclass NotificationPort(ABC):\n    @abstractmethod\n    async def send(self, to: str, subject: str, body: str): ...\n\n\n# Production adapter: Stripe\nclass StripePaymentAdapter(PaymentGatewayPort):\n    def __init__(self, api_key: str):\n        import stripe\n        stripe.api_key = api_key\n        self._stripe = stripe\n\n    async def charge(self, amount: Money, customer: str) -> PaymentResult:\n        try:\n            charge = self._stripe.Charge.create(\n                amount=amount.cents, currency=amount.currency, customer=customer\n            )\n            return PaymentResult(success=True, transaction_id=charge.id)\n        except self._stripe.error.CardError as e:\n            return PaymentResult(success=False, error=str(e))\n\n\n# Test adapter: no external dependencies\nclass MockPaymentAdapter(PaymentGatewayPort):\n    async def charge(self, amount: Money, customer: str) -> PaymentResult:\n        return PaymentResult(success=True, transaction_id=\"mock-txn-123\")\n```\n\n## DDD — Value Objects and Aggregates\n\n```python\n# Value Objects: immutable, validated at construction\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Email:\n    value: str\n\n    def __post_init__(self):\n        if \"@\" not in self.value or \".\" not in self.value.split(\"@\")[-1]:\n            raise ValueError(f\"Invalid email: {self.value}\")\n\n@dataclass(frozen=True)\nclass Money:\n    amount: int   # cents\n    currency: str\n\n    def __post_init__(self):\n        if self.amount \u003C 0:\n            raise ValueError(\"Money amount cannot be negative\")\n        if self.currency not in {\"USD\", \"EUR\", \"GBP\"}:\n            raise ValueError(f\"Unsupported currency: {self.currency}\")\n\n    def add(self, other: \"Money\") -> \"Money\":\n        if self.currency != other.currency:\n            raise ValueError(\"Currency mismatch\")\n        return Money(self.amount + other.amount, self.currency)\n\n\n# Aggregate root: enforces all invariants for its cluster of entities\nclass Order:\n    def __init__(self, id: str, customer_id: str):\n        self.id = id\n        self.customer_id = customer_id\n        self.items: list[OrderItem] = []\n        self.status = OrderStatus.PENDING\n        self._events: list[DomainEvent] = []\n\n    def add_item(self, product: Product, quantity: int):\n        if self.status != OrderStatus.PENDING:\n            raise ValueError(\"Cannot modify a submitted order\")\n        item = OrderItem(product=product, quantity=quantity)\n        self.items.append(item)\n        self._events.append(ItemAddedEvent(order_id=self.id, item=item))\n\n    @property\n    def total(self) -> Money:\n        totals = [item.subtotal() for item in self.items]\n        return sum(totals[1:], totals[0]) if totals else Money(0, \"USD\")\n\n    def submit(self):\n        if not self.items:\n            raise ValueError(\"Cannot submit an empty order\")\n        if self.status != OrderStatus.PENDING:\n            raise ValueError(\"Order already submitted\")\n        self.status = OrderStatus.SUBMITTED\n        self._events.append(OrderSubmittedEvent(order_id=self.id))\n\n    def pop_events(self) -> list[DomainEvent]:\n        events, self._events = self._events, []\n        return events\n\n\n# Repository: persist and reconstitute aggregates\nclass OrderRepository(ABC):\n    @abstractmethod\n    async def find_by_id(self, order_id: str) -> Optional[Order]: ...\n\n    @abstractmethod\n    async def save(self, order: Order) -> None: ...\n    # Implementations persist events via pop_events() after writing state\n```\n\n## Testing — In-Memory Adapters\n\nThe hallmark of correctly applied Clean Architecture is that every use case can be exercised in a plain unit test with no real database, no Docker, and no network:\n\n```python\n# tests\u002Funit\u002Ftest_create_user.py\nimport asyncio\nfrom typing import Dict, Optional\nfrom domain.entities.user import User\nfrom domain.interfaces.user_repository import IUserRepository\nfrom use_cases.create_user import CreateUserUseCase, CreateUserRequest\n\n\nclass InMemoryUserRepository(IUserRepository):\n    def __init__(self):\n        self._store: Dict[str, User] = {}\n\n    async def find_by_id(self, user_id: str) -> Optional[User]:\n        return self._store.get(user_id)\n\n    async def find_by_email(self, email: str) -> Optional[User]:\n        return next((u for u in self._store.values() if u.email == email), None)\n\n    async def save(self, user: User) -> User:\n        self._store[user.id] = user\n        return user\n\n    async def delete(self, user_id: str) -> bool:\n        return self._store.pop(user_id, None) is not None\n\n\nasync def test_create_user_succeeds():\n    repo = InMemoryUserRepository()\n    use_case = CreateUserUseCase(user_repository=repo)\n\n    response = await use_case.execute(CreateUserRequest(email=\"alice@example.com\", name=\"Alice\"))\n\n    assert response.success\n    assert response.user.email == \"alice@example.com\"\n    assert response.user.id is not None\n\n\nasync def test_duplicate_email_rejected():\n    repo = InMemoryUserRepository()\n    use_case = CreateUserUseCase(user_repository=repo)\n\n    await use_case.execute(CreateUserRequest(email=\"alice@example.com\", name=\"Alice\"))\n    response = await use_case.execute(CreateUserRequest(email=\"alice@example.com\", name=\"Alice2\"))\n\n    assert not response.success\n    assert \"already exists\" in response.error\n```\n\n## Troubleshooting\n\n### Use case tests require a running database\n\nBusiness logic has leaked into the infrastructure layer. Move all database calls behind an `IRepository` interface and inject an in-memory implementation in tests (see Testing section above). The use case constructor must accept the abstract port, not the concrete class.\n\n### Circular imports between layers\n\nA common symptom is `ImportError: cannot import name X` between `use_cases` and `adapters`. This happens when a use case imports a concrete adapter class instead of the abstract port. Enforce the rule: `use_cases\u002F` imports only from `domain\u002F` (entities and interfaces). It must never import from `adapters\u002F` or `infrastructure\u002F`.\n\n### Framework decorators appearing in domain entities\n\nIf SQLAlchemy `Column()` or Pydantic `Field()` annotations appear on domain entities, the entity is no longer pure. Create a separate ORM model in `adapters\u002Frepositories\u002F` and map to\u002Ffrom the domain entity in the repository's `_to_entity()` method.\n\n### All logic ending up in controllers\n\nWhen the controller grows beyond HTTP parsing and response formatting, extract the logic into a use case class. A controller method should do three things only: parse the request, call a use case, map the response.\n\n### Value objects raising errors too late\n\nValidate invariants in `__post_init__` (Python) or the constructor so an invalid `Email` or `Money` cannot be constructed at all. This surfaces bad data at the boundary, not deep inside business logic.\n\n### Context bleed across bounded contexts\n\nIf the `Order` context is importing `User` entities from the `Identity` context, introduce an Anti-Corruption Layer. The `Order` context should hold its own lightweight `CustomerId` value object and only call the `Identity` context through an explicit interface.\n\n## Advanced Patterns\n\nFor detailed DDD bounded context mapping, full multi-service project trees, Anti-Corruption Layer implementations, and Onion Architecture comparisons, see:\n\n- [`references\u002Fadvanced-patterns.md`](references\u002Fadvanced-patterns.md)\n\n## Related Skills\n\n- `microservices-patterns` — Apply these architecture patterns when decomposing a monolith into services\n- `cqrs-implementation` — Use Clean Architecture as the structural foundation for CQRS command\u002Fquery separation\n- `saga-orchestration` — Sagas require well-defined aggregate boundaries, which DDD tactical patterns provide\n- `event-store-design` — Domain events produced by aggregates feed directly into an event store\n","# Architecture Patterns\n\nMaster proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.\n\n**Given:** a service boundary or module to architect.\n**Produces:** layered structure with clear dependency rules, interface definitions, and test boundaries.\n\n## When to Use This Skill\n\n- Designing new backend services or microservices from scratch\n- Refactoring monolithic applications where business logic is entangled with ORM models or HTTP concerns\n- Establishing bounded contexts before splitting a system into services\n- Debugging dependency cycles where infrastructure code bleeds into the domain layer\n- Creating testable codebases where use-case tests do not require a running database\n- Implementing domain-driven design tactical patterns (aggregates, value objects, domain events)\n\n## Core Concepts\n\n### 1. Clean Architecture (Uncle Bob)\n\n**Layers (dependency flows inward):**\n\n- **Entities**: Core business models, no framework imports\n- **Use Cases**: Application business rules, orchestrate entities\n- **Interface Adapters**: Controllers, presenters, gateways — translate between use cases and external formats\n- **Frameworks & Drivers**: UI, database, external services — all at the outermost ring\n\n**Key Principles:**\n\n- Dependencies point inward only; inner layers know nothing about outer layers\n- Business logic is independent of frameworks, databases, and delivery mechanisms\n- Every layer boundary is crossed via an abstract interface\n- Testable without UI, database, or external services\n\n### 2. Hexagonal Architecture (Ports and Adapters)\n\n**Components:**\n\n- **Domain Core**: Business logic lives here, framework-free\n- **Ports**: Abstract interfaces that define how the core interacts with the outside world (driving and driven)\n- **Adapters**: Concrete implementations of ports (PostgreSQL adapter, Stripe adapter, REST adapter)\n\n**Benefits:**\n\n- Swap implementations without touching the core (e.g., replace PostgreSQL with DynamoDB)\n- Use in-memory adapters in tests — no Docker required\n- Technology decisions deferred to the edges\n\n### 3. Domain-Driven Design (DDD)\n\n**Strategic Patterns:**\n\n- **Bounded Contexts**: Isolate a coherent model for one subdomain; avoid sharing a single model across the whole system\n- **Context Mapping**: Define how contexts relate (Anti-Corruption Layer, Shared Kernel, Open Host Service)\n- **Ubiquitous Language**: Every term in code matches the term used by domain experts\n\n**Tactical Patterns:**\n\n- **Entities**: Objects with stable identity that change over time\n- **Value Objects**: Immutable objects identified by their attributes (Email, Money, Address)\n- **Aggregates**: Consistency boundaries; only the root is accessible from outside\n- **Repositories**: Persist and reconstitute aggregates; abstract over the storage mechanism\n- **Domain Events**: Capture things that happened inside the domain; used for cross-aggregate coordination\n\n## Clean Architecture — Directory Structure\n\n```\napp\u002F\n├── domain\u002F           # Entities, value objects, interfaces\n│   ├── entities\u002F\n│   │   ├── user.py\n│   │   └── order.py\n│   ├── value_objects\u002F\n│   │   ├── email.py\n│   │   └── money.py\n│   └── interfaces\u002F   # Abstract ports (no implementations)\n│       ├── user_repository.py\n│       └── payment_gateway.py\n├── use_cases\u002F        # Application business rules\n│   ├── create_user.py\n│   ├── process_order.py\n│   └── send_notification.py\n├── adapters\u002F         # Concrete implementations\n│   ├── repositories\u002F\n│   │   ├── postgres_user_repository.py\n│   │   └── redis_cache_repository.py\n│   ├── controllers\u002F\n│   │   └── user_controller.py\n│   └── gateways\u002F\n│       ├── stripe_payment_gateway.py\n│       └── sendgrid_email_gateway.py\n└── infrastructure\u002F   # Framework wiring, config, DI container\n    ├── database.py\n    ├── config.py\n    └── logging.py\n```\n\n**Dependency rule in one sentence:** every `import` statement in `domain\u002F` and `use_cases\u002F` must point only toward `domain\u002F`; nothing in those layers may import from `adapters\u002F` or `infrastructure\u002F`.\n\n## Clean Architecture — Core Implementation\n\n```python\n# domain\u002Fentities\u002Fuser.py\nfrom dataclasses import dataclass\nfrom datetime import datetime\n\n@dataclass\nclass User:\n    \"\"\"Core user entity — no framework dependencies.\"\"\"\n    id: str\n    email: str\n    name: str\n    created_at: datetime\n    is_active: bool = True\n\n    def deactivate(self):\n        self.is_active = False\n\n    def can_place_order(self) -> bool:\n        return self.is_active\n\n\n# domain\u002Finterfaces\u002Fuser_repository.py\nfrom abc import ABC, abstractmethod\nfrom typing import Optional\nfrom domain.entities.user import User\n\nclass IUserRepository(ABC):\n    \"\"\"Port: defines contract, no implementation details.\"\"\"\n\n    @abstractmethod\n    async def find_by_id(self, user_id: str) -> Optional[User]: ...\n\n    @abstractmethod\n    async def find_by_email(self, email: str) -> Optional[User]: ...\n\n    @abstractmethod\n    async def save(self, user: User) -> User: ...\n\n    @abstractmethod\n    async def delete(self, user_id: str) -> bool: ...\n\n\n# use_cases\u002Fcreate_user.py\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom typing import Optional\nimport uuid\nfrom domain.entities.user import User\nfrom domain.interfaces.user_repository import IUserRepository\n\n@dataclass\nclass CreateUserRequest:\n    email: str\n    name: str\n\n@dataclass\nclass CreateUserResponse:\n    user: Optional[User]\n    success: bool\n    error: Optional[str] = None\n\nclass CreateUserUseCase:\n    \"\"\"Use case: orchestrates business logic, no HTTP or DB details.\"\"\"\n\n    def __init__(self, user_repository: IUserRepository):\n        self.user_repository = user_repository\n\n    async def execute(self, request: CreateUserRequest) -> CreateUserResponse:\n        existing = await self.user_repository.find_by_email(request.email)\n        if existing:\n            return CreateUserResponse(user=None, success=False, error=\"Email already exists\")\n\n        user = User(\n            id=str(uuid.uuid4()),\n            email=request.email,\n            name=request.name,\n            created_at=datetime.now(),\n        )\n        saved_user = await self.user_repository.save(user)\n        return CreateUserResponse(user=saved_user, success=True)\n\n\n# adapters\u002Frepositories\u002Fpostgres_user_repository.py\nfrom domain.interfaces.user_repository import IUserRepository\nfrom domain.entities.user import User\nfrom typing import Optional\nimport asyncpg\n\nclass PostgresUserRepository(IUserRepository):\n    \"\"\"Adapter: PostgreSQL implementation of the user port.\"\"\"\n\n    def __init__(self, pool: asyncpg.Pool):\n        self.pool = pool\n\n    async def find_by_id(self, user_id: str) -> Optional[User]:\n        async with self.pool.acquire() as conn:\n            row = await conn.fetchrow(\"SELECT * FROM users WHERE id = $1\", user_id)\n            return self._to_entity(row) if row else None\n\n    async def find_by_email(self, email: str) -> Optional[User]:\n        async with self.pool.acquire() as conn:\n            row = await conn.fetchrow(\"SELECT * FROM users WHERE email = $1\", email)\n            return self._to_entity(row) if row else None\n\n    async def save(self, user: User) -> User:\n        async with self.pool.acquire() as conn:\n            await conn.execute(\n                \"\"\"\n                INSERT INTO users (id, email, name, created_at, is_active)\n                VALUES ($1, $2, $3, $4, $5)\n                ON CONFLICT (id) DO UPDATE\n                SET email = $2, name = $3, is_active = $5\n                \"\"\",\n                user.id, user.email, user.name, user.created_at, user.is_active,\n            )\n        return user\n\n    async def delete(self, user_id: str) -> bool:\n        async with self.pool.acquire() as conn:\n            result = await conn.execute(\"DELETE FROM users WHERE id = $1\", user_id)\n            return result == \"DELETE 1\"\n\n    def _to_entity(self, row) -> User:\n        return User(\n            id=row[\"id\"], email=row[\"email\"], name=row[\"name\"],\n            created_at=row[\"created_at\"], is_active=row[\"is_active\"],\n        )\n\n\n# adapters\u002Fcontrollers\u002Fuser_controller.py\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom pydantic import BaseModel\nfrom use_cases.create_user import CreateUserUseCase, CreateUserRequest\n\nrouter = APIRouter()\n\nclass CreateUserDTO(BaseModel):\n    email: str\n    name: str\n\n@router.post(\"\u002Fusers\")\nasync def create_user(\n    dto: CreateUserDTO,\n    use_case: CreateUserUseCase = Depends(get_create_user_use_case),\n):\n    \"\"\"Controller handles HTTP only — no business logic lives here.\"\"\"\n    response = await use_case.execute(CreateUserRequest(email=dto.email, name=dto.name))\n    if not response.success:\n        raise HTTPException(status_code=400, detail=response.error)\n    return {\"user\": response.user}\n```\n\n## Hexagonal Architecture — Ports and Adapters\n\n```python\n# Core domain service — no infrastructure dependencies\nclass OrderService:\n    def __init__(\n        self,\n        order_repository: OrderRepositoryPort,\n        payment_gateway: PaymentGatewayPort,\n        notification_service: NotificationPort,\n    ):\n        self.orders = order_repository\n        self.payments = payment_gateway\n        self.notifications = notification_service\n\n    async def place_order(self, order: Order) -> OrderResult:\n        if not order.is_valid():\n            return OrderResult(success=False, error=\"Invalid order\")\n\n        payment = await self.payments.charge(amount=order.total, customer=order.customer_id)\n        if not payment.success:\n            return OrderResult(success=False, error=\"Payment failed\")\n\n        order.mark_as_paid()\n        saved_order = await self.orders.save(order)\n        await self.notifications.send(\n            to=order.customer_email,\n            subject=\"Order confirmed\",\n            body=f\"Order {order.id} confirmed\",\n        )\n        return OrderResult(success=True, order=saved_order)\n\n\n# Ports (driving and driven interfaces)\nclass OrderRepositoryPort(ABC):\n    @abstractmethod\n    async def save(self, order: Order) -> Order: ...\n\nclass PaymentGatewayPort(ABC):\n    @abstractmethod\n    async def charge(self, amount: Money, customer: str) -> PaymentResult: ...\n\nclass NotificationPort(ABC):\n    @abstractmethod\n    async def send(self, to: str, subject: str, body: str): ...\n\n\n# Production adapter: Stripe\nclass StripePaymentAdapter(PaymentGatewayPort):\n    def __init__(self, api_key: str):\n        import stripe\n        stripe.api_key = api_key\n        self._stripe = stripe\n\n    async def charge(self, amount: Money, customer: str) -> PaymentResult:\n        try:\n            charge = self._stripe.Charge.create(\n                amount=amount.cents, currency=amount.currency, customer=customer\n            )\n            return PaymentResult(success=True, transaction_id=charge.id)\n        except self._stripe.error.CardError as e:\n            return PaymentResult(success=False, error=str(e))\n\n\n# Test adapter: no external dependencies\nclass MockPaymentAdapter(PaymentGatewayPort):\n    async def charge(self, amount: Money, customer: str) -> PaymentResult:\n        return PaymentResult(success=True, transaction_id=\"mock-txn-123\")\n```\n\n## DDD — Value Objects and Aggregates\n\n```python\n# Value Objects: immutable, validated at construction\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Email:\n    value: str\n\n    def __post_init__(self):\n        if \"@\" not in self.value or \".\" not in self.value.split(\"@\")[-1]:\n            raise ValueError(f\"Invalid email: {self.value}\")\n\n@dataclass(frozen=True)\nclass Money:\n    amount: int   # cents\n    currency: str\n\n    def __post_init__(self):\n        if self.amount \u003C 0:\n            raise ValueError(\"Money amount cannot be negative\")\n        if self.currency not in {\"USD\", \"EUR\", \"GBP\"}:\n            raise ValueError(f\"Unsupported currency: {self.currency}\")\n\n    def add(self, other: \"Money\") -> \"Money\":\n        if self.currency != other.currency:\n            raise ValueError(\"Currency mismatch\")\n        return Money(self.amount + other.amount, self.currency)\n\n\n# Aggregate root: enforces all invariants for its cluster of entities\nclass Order:\n    def __init__(self, id: str, customer_id: str):\n        self.id = id\n        self.customer_id = customer_id\n        self.items: list[OrderItem] = []\n        self.status = OrderStatus.PENDING\n        self._events: list[DomainEvent] = []\n\n    def add_item(self, product: Product, quantity: int):\n        if self.status != OrderStatus.PENDING:\n            raise ValueError(\"Cannot modify a submitted order\")\n        item = OrderItem(product=product, quantity=quantity)\n        self.items.append(item)\n        self._events.append(ItemAddedEvent(order_id=self.id, item=item))\n\n    @property\n    def total(self) -> Money:\n        totals = [item.subtotal() for item in self.items]\n        return sum(totals[1:], totals[0]) if totals else Money(0, \"USD\")\n\n    def submit(self):\n        if not self.items:\n            raise ValueError(\"Cannot submit an empty order\")\n        if self.status != OrderStatus.PENDING:\n            raise ValueError(\"Order already submitted\")\n        self.status = OrderStatus.SUBMITTED\n        self._events.append(OrderSubmittedEvent(order_id=self.id))\n\n    def pop_events(self) -> list[DomainEvent]:\n        events, self._events = self._events, []\n        return events\n\n\n# Repository: persist and reconstitute aggregates\nclass OrderRepository(ABC):\n    @abstractmethod\n    async def find_by_id(self, order_id: str) -> Optional[Order]: ...\n\n    @abstractmethod\n    async def save(self, order: Order) -> None: ...\n    # Implementations persist events via pop_events() after writing state\n```\n\n## Testing — In-Memory Adapters\n\nThe hallmark of correctly applied Clean Architecture is that every use case can be exercised in a plain unit test with no real database, no Docker, and no network:\n\n```python\n# tests\u002Funit\u002Ftest_create_user.py\nimport asyncio\nfrom typing import Dict, Optional\nfrom domain.entities.user import User\nfrom domain.interfaces.user_repository import IUserRepository\nfrom use_cases.create_user import CreateUserUseCase, CreateUserRequest\n\n\nclass InMemoryUserRepository(IUserRepository):\n    def __init__(self):\n        self._store: Dict[str, User] = {}\n\n    async def find_by_id(self, user_id: str) -> Optional[User]:\n        return self._store.get(user_id)\n\n    async def find_by_email(self, email: str) -> Optional[User]:\n        return next((u for u in self._store.values() if u.email == email), None)\n\n    async def save(self, user: User) -> User:\n        self._store[user.id] = user\n        return user\n\n    async def delete(self, user_id: str) -> bool:\n        return self._store.pop(user_id, None) is not None\n\n\nasync def test_create_user_succeeds():\n    repo = InMemoryUserRepository()\n    use_case = CreateUserUseCase(user_repository=repo)\n\n    response = await use_case.execute(CreateUserRequest(email=\"alice@example.com\", name=\"Alice\"))\n\n    assert response.success\n    assert response.user.email == \"alice@example.com\"\n    assert response.user.id is not None\n\n\nasync def test_duplicate_email_rejected():\n    repo = InMemoryUserRepository()\n    use_case = CreateUserUseCase(user_repository=repo)\n\n    await use_case.execute(CreateUserRequest(email=\"alice@example.com\", name=\"Alice\"))\n    response = await use_case.execute(CreateUserRequest(email=\"alice@example.com\", name=\"Alice2\"))\n\n    assert not response.success\n    assert \"already exists\" in response.error\n```\n\n## Troubleshooting\n\n### Use case tests require a running database\n\nBusiness logic has leaked into the infrastructure layer. Move all database calls behind an `IRepository` interface and inject an in-memory implementation in tests (see Testing section above). The use case constructor must accept the abstract port, not the concrete class.\n\n### Circular imports between layers\n\nA common symptom is `ImportError: cannot import name X` between `use_cases` and `adapters`. This happens when a use case imports a concrete adapter class instead of the abstract port. Enforce the rule: `use_cases\u002F` imports only from `domain\u002F` (entities and interfaces). It must never import from `adapters\u002F` or `infrastructure\u002F`.\n\n### Framework decorators appearing in domain entities\n\nIf SQLAlchemy `Column()` or Pydantic `Field()` annotations appear on domain entities, the entity is no longer pure. Create a separate ORM model in `adapters\u002Frepositories\u002F` and map to\u002Ffrom the domain entity in the repository's `_to_entity()` method.\n\n### All logic ending up in controllers\n\nWhen the controller grows beyond HTTP parsing and response formatting, extract the logic into a use case class. A controller method should do three things only: parse the request, call a use case, map the response.\n\n### Value objects raising errors too late\n\nValidate invariants in `__post_init__` (Python) or the constructor so an invalid `Email` or `Money` cannot be constructed at all. This surfaces bad data at the boundary, not deep inside business logic.\n\n### Context bleed across bounded contexts\n\nIf the `Order` context is importing `User` entities from the `Identity` context, introduce an Anti-Corruption Layer. The `Order` context should hold its own lightweight `CustomerId` value object and only call the `Identity` context through an explicit interface.\n\n## Advanced Patterns\n\nFor detailed DDD bounded context mapping, full multi-service project trees, Anti-Corruption Layer implementations, and Onion Architecture comparisons, see:\n\n- [`references\u002Fadvanced-patterns.md`](references\u002Fadvanced-patterns.md)\n\n## Related Skills\n\n- `microservices-patterns` — Apply these architecture patterns when decomposing a monolith into services\n- `cqrs-implementation` — Use Clean Architecture as the structural foundation for CQRS command\u002Fquery separation\n- `saga-orchestration` — Sagas require well-defined aggregate boundaries, which DDD tactical patterns provide\n- `event-store-design` — Domain events produced by aggregates feed directly into an event store\n",{"name":5,"description":7},"main","900bb95bbe72cdb94af6f5a620aa5081264b7b6d",".claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fbackend-development\u002Fskills\u002Farchitecture-patterns",0,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up#readme","https:\u002F\u002Fgithub.com\u002Fsteph-frtech","2026-05-16 00:03:30",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add steph-frtech\u002Fclaude-code-up --skill architecture-patterns",{"tool":37,"command":38},"bunx","bunx skills add steph-frtech\u002Fclaude-code-up --skill architecture-patterns",{"tool":40,"command":41},"pnpm","pnpm dlx skills add steph-frtech\u002Fclaude-code-up --skill architecture-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fbackend-development\u002Fskills\u002Farchitecture-patterns\u002FSKILL.md",true,[45],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"references\u002Fadvanced-patterns.md","REFERENCE","参考文档",15329,"https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fmarketplaces\u002Fwshobson\u002Fplugins\u002Fbackend-development\u002Fskills\u002Farchitecture-patterns\u002Freferences\u002Fadvanced-patterns.md",[52,59,66,73,80,87],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":18},"01M72Y1BY6X8TX3DS19Y04NEBQ","example","One-line summary of what this skill does","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002Fskills\u002Fexample\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":18},"01M72Y1A38EYR8S9P1MBYDAQTW","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__writing-plans\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M72Y174QSV1B5NV1E4KWHQBR","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__using-git-worktrees\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M72Y14SQRHHMKG316HGB2CGK","test-driven-development","Use when implementing any feature or bugfix, before writing implementation code","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__test-driven-development\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M72Y127BCPRH3BRKPJC3Q3G2","systematic-debugging","Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__systematic-debugging\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M72Y1090GJA6B67KPD60WPHH","subagent-driven-development","Use when executing implementation plans with independent tasks in the current session","https:\u002F\u002Fgithub.com\u002Fsteph-frtech\u002Fclaude-code-up\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fsuperpowers__subagent-driven-development\u002FSKILL.md",[],[]]