@zimezone/z-command 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/package.json +4 -1
  2. package/templates/agents/api-documenter.agent.md +161 -0
  3. package/templates/agents/architect-review.agent.md +146 -0
  4. package/templates/agents/arm-cortex-expert.agent.md +288 -0
  5. package/templates/agents/backend-architect.agent.md +309 -0
  6. package/templates/agents/backend-security-coder.agent.md +152 -0
  7. package/templates/agents/bash-pro.agent.md +285 -0
  8. package/templates/agents/c-pro.agent.md +35 -0
  9. package/templates/agents/c4-code.agent.md +320 -0
  10. package/templates/agents/c4-component.agent.md +227 -0
  11. package/templates/agents/c4-container.agent.md +248 -0
  12. package/templates/agents/c4-context.agent.md +235 -0
  13. package/templates/agents/conductor-validator.agent.md +245 -0
  14. package/templates/agents/csharp-pro.agent.md +38 -0
  15. package/templates/agents/customer-support.agent.md +148 -0
  16. package/templates/agents/database-admin.agent.md +142 -0
  17. package/templates/agents/database-architect.agent.md +238 -0
  18. package/templates/agents/database-optimizer.agent.md +144 -0
  19. package/templates/agents/debugger.agent.md +30 -0
  20. package/templates/agents/deployment-engineer.agent.md +0 -0
  21. package/templates/agents/devops-troubleshooter.agent.md +138 -0
  22. package/templates/agents/django-pro.agent.md +159 -0
  23. package/templates/agents/docs-architect.agent.md +77 -0
  24. package/templates/agents/dotnet-architect.agent.md +175 -0
  25. package/templates/agents/dx-optimizer.agent.md +63 -0
  26. package/templates/agents/elixir-pro.agent.md +38 -0
  27. package/templates/agents/error-detective.agent.md +32 -0
  28. package/templates/agents/event-sourcing-architect.agent.md +42 -0
  29. package/templates/agents/fastapi-pro.agent.md +171 -0
  30. package/templates/agents/firmware-analyst.agent.md +330 -0
  31. package/templates/agents/frontend-security-coder.agent.md +149 -0
  32. package/templates/agents/haskell-pro.agent.md +37 -0
  33. package/templates/agents/hr-pro.agent.md +105 -0
  34. package/templates/agents/incident-responder.agent.md +190 -0
  35. package/templates/agents/ios-developer.agent.md +198 -0
  36. package/templates/agents/java-pro.agent.md +156 -0
  37. package/templates/agents/javascript-pro.agent.md +35 -0
  38. package/templates/agents/julia-pro.agent.md +187 -0
  39. package/templates/agents/legal-advisor.agent.md +49 -0
  40. package/templates/agents/malware-analyst.agent.md +272 -0
  41. package/templates/agents/mermaid-expert.agent.md +39 -0
  42. package/templates/agents/minecraft-bukkit-pro.agent.md +104 -0
  43. package/templates/agents/mobile-security-coder.agent.md +163 -0
  44. package/templates/agents/monorepo-architect.agent.md +44 -0
  45. package/templates/agents/observability-engineer.agent.md +228 -0
  46. package/templates/agents/performance-engineer.agent.md +167 -0
  47. package/templates/agents/php-pro.agent.md +43 -0
  48. package/templates/agents/posix-shell-pro.agent.md +284 -0
  49. package/templates/agents/quant-analyst.agent.md +32 -0
  50. package/templates/agents/reference-builder.agent.md +167 -0
  51. package/templates/agents/reverse-engineer.agent.md +202 -0
  52. package/templates/agents/risk-manager.agent.md +41 -0
  53. package/templates/agents/ruby-pro.agent.md +35 -0
  54. package/templates/agents/rust-pro.agent.md +156 -0
  55. package/templates/agents/sales-automator.agent.md +35 -0
  56. package/templates/agents/scala-pro.agent.md +60 -0
  57. package/templates/agents/search-specialist.agent.md +59 -0
  58. package/templates/agents/security-auditor.agent.md +138 -0
  59. package/templates/agents/seo-authority-builder.agent.md +116 -0
  60. package/templates/agents/seo-cannibalization-detector.agent.md +103 -0
  61. package/templates/agents/seo-content-auditor.agent.md +63 -0
  62. package/templates/agents/seo-content-planner.agent.md +88 -0
  63. package/templates/agents/seo-content-refresher.agent.md +98 -0
  64. package/templates/agents/seo-content-writer.agent.md +76 -0
  65. package/templates/agents/seo-keyword-strategist.agent.md +75 -0
  66. package/templates/agents/seo-meta-optimizer.agent.md +72 -0
  67. package/templates/agents/seo-snippet-hunter.agent.md +94 -0
  68. package/templates/agents/seo-structure-architect.agent.md +88 -0
  69. package/templates/agents/service-mesh-expert.agent.md +41 -0
  70. package/templates/agents/sql-pro.agent.md +146 -0
  71. package/templates/agents/tdd-orchestrator.agent.md +183 -0
  72. package/templates/agents/temporal-python-pro.agent.md +349 -0
  73. package/templates/agents/terraform-specialist.agent.md +137 -0
  74. package/templates/agents/test-automator.agent.md +203 -0
  75. package/templates/agents/threat-modeling-expert.agent.md +44 -0
  76. package/templates/agents/tutorial-engineer.agent.md +118 -0
  77. package/templates/agents/ui-ux-designer.agent.md +188 -0
  78. package/templates/agents/ui-visual-validator.agent.md +192 -0
  79. package/templates/agents/vector-database-engineer.agent.md +43 -0
  80. package/templates/skills/angular-migration/SKILL.md +410 -0
  81. package/templates/skills/api-design-principles/SKILL.md +528 -0
  82. package/templates/skills/api-design-principles/assets/api-design-checklist.md +155 -0
  83. package/templates/skills/api-design-principles/assets/rest-api-template.py +182 -0
  84. package/templates/skills/api-design-principles/references/graphql-schema-design.md +583 -0
  85. package/templates/skills/api-design-principles/references/rest-best-practices.md +408 -0
  86. package/templates/skills/architecture-decision-records/SKILL.md +428 -0
  87. package/templates/skills/architecture-patterns/SKILL.md +494 -0
  88. package/templates/skills/async-python-patterns/SKILL.md +694 -0
  89. package/templates/skills/auth-implementation-patterns/SKILL.md +634 -0
  90. package/templates/skills/changelog-automation/SKILL.md +552 -0
  91. package/templates/skills/code-review-excellence/SKILL.md +520 -0
  92. package/templates/skills/competitive-landscape/SKILL.md +479 -0
  93. package/templates/skills/context-driven-development/SKILL.md +385 -0
  94. package/templates/skills/cost-optimization/SKILL.md +274 -0
  95. package/templates/skills/cqrs-implementation/SKILL.md +554 -0
  96. package/templates/skills/data-quality-frameworks/SKILL.md +587 -0
  97. package/templates/skills/data-storytelling/SKILL.md +453 -0
  98. package/templates/skills/database-migration/SKILL.md +424 -0
  99. package/templates/skills/dbt-transformation-patterns/SKILL.md +561 -0
  100. package/templates/skills/debugging-strategies/SKILL.md +527 -0
  101. package/templates/skills/defi-protocol-templates/SKILL.md +454 -0
  102. package/templates/skills/dependency-upgrade/SKILL.md +409 -0
  103. package/templates/skills/deployment-pipeline-design/SKILL.md +359 -0
  104. package/templates/skills/distributed-tracing/SKILL.md +438 -0
  105. package/templates/skills/dotnet-backend-patterns/SKILL.md +815 -0
  106. package/templates/skills/dotnet-backend-patterns/assets/repository-template.cs +523 -0
  107. package/templates/skills/dotnet-backend-patterns/assets/service-template.cs +336 -0
  108. package/templates/skills/dotnet-backend-patterns/references/dapper-patterns.md +544 -0
  109. package/templates/skills/dotnet-backend-patterns/references/ef-core-best-practices.md +355 -0
  110. package/templates/skills/e2e-testing-patterns/SKILL.md +547 -0
  111. package/templates/skills/employment-contract-templates/SKILL.md +507 -0
  112. package/templates/skills/error-handling-patterns/SKILL.md +636 -0
  113. package/templates/skills/event-store-design/SKILL.md +437 -0
  114. package/templates/skills/fastapi-templates/SKILL.md +567 -0
  115. package/templates/skills/git-advanced-workflows/SKILL.md +400 -0
  116. package/templates/skills/github-actions-templates/SKILL.md +333 -0
  117. package/templates/skills/go-concurrency-patterns/SKILL.md +655 -0
  118. package/templates/skills/grafana-dashboards/SKILL.md +369 -0
  119. package/templates/skills/helm-chart-scaffolding/SKILL.md +544 -0
  120. package/templates/skills/helm-chart-scaffolding/assets/Chart.yaml.template +42 -0
  121. package/templates/skills/helm-chart-scaffolding/assets/values.yaml.template +185 -0
  122. package/templates/skills/helm-chart-scaffolding/references/chart-structure.md +500 -0
  123. package/templates/skills/helm-chart-scaffolding/scripts/validate-chart.sh +244 -0
  124. package/templates/skills/javascript-testing-patterns/SKILL.md +1025 -0
  125. package/templates/skills/langchain-architecture/SKILL.md +338 -0
  126. package/templates/skills/llm-evaluation/SKILL.md +471 -0
  127. package/templates/skills/microservices-patterns/SKILL.md +595 -0
  128. package/templates/skills/modern-javascript-patterns/SKILL.md +911 -0
  129. package/templates/skills/monorepo-management/SKILL.md +622 -0
  130. package/templates/skills/nextjs-app-router-patterns/SKILL.md +544 -0
  131. package/templates/skills/nodejs-backend-patterns/SKILL.md +1020 -0
  132. package/templates/skills/nx-workspace-patterns/SKILL.md +452 -0
  133. package/templates/skills/openapi-spec-generation/SKILL.md +1028 -0
  134. package/templates/skills/paypal-integration/SKILL.md +467 -0
  135. package/templates/skills/pci-compliance/SKILL.md +466 -0
  136. package/templates/skills/postgresql/SKILL.md +204 -0
  137. package/templates/skills/projection-patterns/SKILL.md +490 -0
  138. package/templates/skills/prometheus-configuration/SKILL.md +392 -0
  139. package/templates/skills/prompt-engineering-patterns/SKILL.md +201 -0
  140. package/templates/skills/prompt-engineering-patterns/assets/few-shot-examples.json +106 -0
  141. package/templates/skills/prompt-engineering-patterns/assets/prompt-template-library.md +246 -0
  142. package/templates/skills/prompt-engineering-patterns/references/chain-of-thought.md +399 -0
  143. package/templates/skills/prompt-engineering-patterns/references/few-shot-learning.md +369 -0
  144. package/templates/skills/prompt-engineering-patterns/references/prompt-optimization.md +414 -0
  145. package/templates/skills/prompt-engineering-patterns/references/prompt-templates.md +470 -0
  146. package/templates/skills/prompt-engineering-patterns/references/system-prompts.md +189 -0
  147. package/templates/skills/prompt-engineering-patterns/scripts/optimize-prompt.py +279 -0
  148. package/templates/skills/python-packaging/SKILL.md +870 -0
  149. package/templates/skills/python-performance-optimization/SKILL.md +869 -0
  150. package/templates/skills/python-testing-patterns/SKILL.md +907 -0
  151. package/templates/skills/rag-implementation/SKILL.md +403 -0
  152. package/templates/skills/react-modernization/SKILL.md +513 -0
  153. package/templates/skills/react-native-architecture/SKILL.md +671 -0
  154. package/templates/skills/react-state-management/SKILL.md +429 -0
  155. package/templates/skills/risk-metrics-calculation/SKILL.md +555 -0
  156. package/templates/skills/rust-async-patterns/SKILL.md +517 -0
  157. package/templates/skills/secrets-management/SKILL.md +346 -0
  158. package/templates/skills/security-requirement-extraction/SKILL.md +677 -0
  159. package/templates/skills/shellcheck-configuration/SKILL.md +454 -0
  160. package/templates/skills/similarity-search-patterns/SKILL.md +558 -0
  161. package/templates/skills/slo-implementation/SKILL.md +329 -0
  162. package/templates/skills/sql-optimization-patterns/SKILL.md +493 -0
  163. package/templates/skills/stripe-integration/SKILL.md +442 -0
  164. package/templates/skills/tailwind-design-system/SKILL.md +666 -0
  165. package/templates/skills/temporal-python-testing/SKILL.md +158 -0
  166. package/templates/skills/temporal-python-testing/resources/integration-testing.md +455 -0
  167. package/templates/skills/temporal-python-testing/resources/local-setup.md +553 -0
  168. package/templates/skills/temporal-python-testing/resources/replay-testing.md +462 -0
  169. package/templates/skills/temporal-python-testing/resources/unit-testing.md +328 -0
  170. package/templates/skills/terraform-module-library/SKILL.md +249 -0
  171. package/templates/skills/terraform-module-library/references/aws-modules.md +63 -0
  172. package/templates/skills/threat-mitigation-mapping/SKILL.md +745 -0
  173. package/templates/skills/track-management/SKILL.md +593 -0
  174. package/templates/skills/typescript-advanced-types/SKILL.md +717 -0
  175. package/templates/skills/uv-package-manager/SKILL.md +831 -0
  176. package/templates/skills/vector-index-tuning/SKILL.md +521 -0
  177. package/templates/skills/wcag-audit-patterns/SKILL.md +555 -0
  178. package/templates/skills/workflow-orchestration-patterns/SKILL.md +316 -0
  179. package/templates/skills/workflow-patterns/SKILL.md +623 -0
  180. package/templates/agents/game-developer.agent.md +0 -57
  181. package/templates/agents/kubernetes-specialist.agent.md +0 -56
  182. package/templates/agents/market-researcher.agent.md +0 -47
@@ -0,0 +1,494 @@
1
+ ---
2
+ name: architecture-patterns
3
+ description: Implement proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design. Use when architecting complex backend systems or refactoring existing applications for better maintainability.
4
+ ---
5
+
6
+ # Architecture Patterns
7
+
8
+ Master proven backend architecture patterns including Clean Architecture, Hexagonal Architecture, and Domain-Driven Design to build maintainable, testable, and scalable systems.
9
+
10
+ ## When to Use This Skill
11
+
12
+ - Designing new backend systems from scratch
13
+ - Refactoring monolithic applications for better maintainability
14
+ - Establishing architecture standards for your team
15
+ - Migrating from tightly coupled to loosely coupled architectures
16
+ - Implementing domain-driven design principles
17
+ - Creating testable and mockable codebases
18
+ - Planning microservices decomposition
19
+
20
+ ## Core Concepts
21
+
22
+ ### 1. Clean Architecture (Uncle Bob)
23
+
24
+ **Layers (dependency flows inward):**
25
+
26
+ - **Entities**: Core business models
27
+ - **Use Cases**: Application business rules
28
+ - **Interface Adapters**: Controllers, presenters, gateways
29
+ - **Frameworks & Drivers**: UI, database, external services
30
+
31
+ **Key Principles:**
32
+
33
+ - Dependencies point inward
34
+ - Inner layers know nothing about outer layers
35
+ - Business logic independent of frameworks
36
+ - Testable without UI, database, or external services
37
+
38
+ ### 2. Hexagonal Architecture (Ports and Adapters)
39
+
40
+ **Components:**
41
+
42
+ - **Domain Core**: Business logic
43
+ - **Ports**: Interfaces defining interactions
44
+ - **Adapters**: Implementations of ports (database, REST, message queue)
45
+
46
+ **Benefits:**
47
+
48
+ - Swap implementations easily (mock for testing)
49
+ - Technology-agnostic core
50
+ - Clear separation of concerns
51
+
52
+ ### 3. Domain-Driven Design (DDD)
53
+
54
+ **Strategic Patterns:**
55
+
56
+ - **Bounded Contexts**: Separate models for different domains
57
+ - **Context Mapping**: How contexts relate
58
+ - **Ubiquitous Language**: Shared terminology
59
+
60
+ **Tactical Patterns:**
61
+
62
+ - **Entities**: Objects with identity
63
+ - **Value Objects**: Immutable objects defined by attributes
64
+ - **Aggregates**: Consistency boundaries
65
+ - **Repositories**: Data access abstraction
66
+ - **Domain Events**: Things that happened
67
+
68
+ ## Clean Architecture Pattern
69
+
70
+ ### Directory Structure
71
+
72
+ ```
73
+ app/
74
+ ├── domain/ # Entities & business rules
75
+ │ ├── entities/
76
+ │ │ ├── user.py
77
+ │ │ └── order.py
78
+ │ ├── value_objects/
79
+ │ │ ├── email.py
80
+ │ │ └── money.py
81
+ │ └── interfaces/ # Abstract interfaces
82
+ │ ├── user_repository.py
83
+ │ └── payment_gateway.py
84
+ ├── use_cases/ # Application business rules
85
+ │ ├── create_user.py
86
+ │ ├── process_order.py
87
+ │ └── send_notification.py
88
+ ├── adapters/ # Interface implementations
89
+ │ ├── repositories/
90
+ │ │ ├── postgres_user_repository.py
91
+ │ │ └── redis_cache_repository.py
92
+ │ ├── controllers/
93
+ │ │ └── user_controller.py
94
+ │ └── gateways/
95
+ │ ├── stripe_payment_gateway.py
96
+ │ └── sendgrid_email_gateway.py
97
+ └── infrastructure/ # Framework & external concerns
98
+ ├── database.py
99
+ ├── config.py
100
+ └── logging.py
101
+ ```
102
+
103
+ ### Implementation Example
104
+
105
+ ```python
106
+ # domain/entities/user.py
107
+ from dataclasses import dataclass
108
+ from datetime import datetime
109
+ from typing import Optional
110
+
111
+ @dataclass
112
+ class User:
113
+ """Core user entity - no framework dependencies."""
114
+ id: str
115
+ email: str
116
+ name: str
117
+ created_at: datetime
118
+ is_active: bool = True
119
+
120
+ def deactivate(self):
121
+ """Business rule: deactivating user."""
122
+ self.is_active = False
123
+
124
+ def can_place_order(self) -> bool:
125
+ """Business rule: active users can order."""
126
+ return self.is_active
127
+
128
+ # domain/interfaces/user_repository.py
129
+ from abc import ABC, abstractmethod
130
+ from typing import Optional, List
131
+ from domain.entities.user import User
132
+
133
+ class IUserRepository(ABC):
134
+ """Port: defines contract, no implementation."""
135
+
136
+ @abstractmethod
137
+ async def find_by_id(self, user_id: str) -> Optional[User]:
138
+ pass
139
+
140
+ @abstractmethod
141
+ async def find_by_email(self, email: str) -> Optional[User]:
142
+ pass
143
+
144
+ @abstractmethod
145
+ async def save(self, user: User) -> User:
146
+ pass
147
+
148
+ @abstractmethod
149
+ async def delete(self, user_id: str) -> bool:
150
+ pass
151
+
152
+ # use_cases/create_user.py
153
+ from domain.entities.user import User
154
+ from domain.interfaces.user_repository import IUserRepository
155
+ from dataclasses import dataclass
156
+ from datetime import datetime
157
+ import uuid
158
+
159
+ @dataclass
160
+ class CreateUserRequest:
161
+ email: str
162
+ name: str
163
+
164
+ @dataclass
165
+ class CreateUserResponse:
166
+ user: User
167
+ success: bool
168
+ error: Optional[str] = None
169
+
170
+ class CreateUserUseCase:
171
+ """Use case: orchestrates business logic."""
172
+
173
+ def __init__(self, user_repository: IUserRepository):
174
+ self.user_repository = user_repository
175
+
176
+ async def execute(self, request: CreateUserRequest) -> CreateUserResponse:
177
+ # Business validation
178
+ existing = await self.user_repository.find_by_email(request.email)
179
+ if existing:
180
+ return CreateUserResponse(
181
+ user=None,
182
+ success=False,
183
+ error="Email already exists"
184
+ )
185
+
186
+ # Create entity
187
+ user = User(
188
+ id=str(uuid.uuid4()),
189
+ email=request.email,
190
+ name=request.name,
191
+ created_at=datetime.now(),
192
+ is_active=True
193
+ )
194
+
195
+ # Persist
196
+ saved_user = await self.user_repository.save(user)
197
+
198
+ return CreateUserResponse(
199
+ user=saved_user,
200
+ success=True
201
+ )
202
+
203
+ # adapters/repositories/postgres_user_repository.py
204
+ from domain.interfaces.user_repository import IUserRepository
205
+ from domain.entities.user import User
206
+ from typing import Optional
207
+ import asyncpg
208
+
209
+ class PostgresUserRepository(IUserRepository):
210
+ """Adapter: PostgreSQL implementation."""
211
+
212
+ def __init__(self, pool: asyncpg.Pool):
213
+ self.pool = pool
214
+
215
+ async def find_by_id(self, user_id: str) -> Optional[User]:
216
+ async with self.pool.acquire() as conn:
217
+ row = await conn.fetchrow(
218
+ "SELECT * FROM users WHERE id = $1", user_id
219
+ )
220
+ return self._to_entity(row) if row else None
221
+
222
+ async def find_by_email(self, email: str) -> Optional[User]:
223
+ async with self.pool.acquire() as conn:
224
+ row = await conn.fetchrow(
225
+ "SELECT * FROM users WHERE email = $1", email
226
+ )
227
+ return self._to_entity(row) if row else None
228
+
229
+ async def save(self, user: User) -> User:
230
+ async with self.pool.acquire() as conn:
231
+ await conn.execute(
232
+ """
233
+ INSERT INTO users (id, email, name, created_at, is_active)
234
+ VALUES ($1, $2, $3, $4, $5)
235
+ ON CONFLICT (id) DO UPDATE
236
+ SET email = $2, name = $3, is_active = $5
237
+ """,
238
+ user.id, user.email, user.name, user.created_at, user.is_active
239
+ )
240
+ return user
241
+
242
+ async def delete(self, user_id: str) -> bool:
243
+ async with self.pool.acquire() as conn:
244
+ result = await conn.execute(
245
+ "DELETE FROM users WHERE id = $1", user_id
246
+ )
247
+ return result == "DELETE 1"
248
+
249
+ def _to_entity(self, row) -> User:
250
+ """Map database row to entity."""
251
+ return User(
252
+ id=row["id"],
253
+ email=row["email"],
254
+ name=row["name"],
255
+ created_at=row["created_at"],
256
+ is_active=row["is_active"]
257
+ )
258
+
259
+ # adapters/controllers/user_controller.py
260
+ from fastapi import APIRouter, Depends, HTTPException
261
+ from use_cases.create_user import CreateUserUseCase, CreateUserRequest
262
+ from pydantic import BaseModel
263
+
264
+ router = APIRouter()
265
+
266
+ class CreateUserDTO(BaseModel):
267
+ email: str
268
+ name: str
269
+
270
+ @router.post("/users")
271
+ async def create_user(
272
+ dto: CreateUserDTO,
273
+ use_case: CreateUserUseCase = Depends(get_create_user_use_case)
274
+ ):
275
+ """Controller: handles HTTP concerns only."""
276
+ request = CreateUserRequest(email=dto.email, name=dto.name)
277
+ response = await use_case.execute(request)
278
+
279
+ if not response.success:
280
+ raise HTTPException(status_code=400, detail=response.error)
281
+
282
+ return {"user": response.user}
283
+ ```
284
+
285
+ ## Hexagonal Architecture Pattern
286
+
287
+ ```python
288
+ # Core domain (hexagon center)
289
+ class OrderService:
290
+ """Domain service - no infrastructure dependencies."""
291
+
292
+ def __init__(
293
+ self,
294
+ order_repository: OrderRepositoryPort,
295
+ payment_gateway: PaymentGatewayPort,
296
+ notification_service: NotificationPort
297
+ ):
298
+ self.orders = order_repository
299
+ self.payments = payment_gateway
300
+ self.notifications = notification_service
301
+
302
+ async def place_order(self, order: Order) -> OrderResult:
303
+ # Business logic
304
+ if not order.is_valid():
305
+ return OrderResult(success=False, error="Invalid order")
306
+
307
+ # Use ports (interfaces)
308
+ payment = await self.payments.charge(
309
+ amount=order.total,
310
+ customer=order.customer_id
311
+ )
312
+
313
+ if not payment.success:
314
+ return OrderResult(success=False, error="Payment failed")
315
+
316
+ order.mark_as_paid()
317
+ saved_order = await self.orders.save(order)
318
+
319
+ await self.notifications.send(
320
+ to=order.customer_email,
321
+ subject="Order confirmed",
322
+ body=f"Order {order.id} confirmed"
323
+ )
324
+
325
+ return OrderResult(success=True, order=saved_order)
326
+
327
+ # Ports (interfaces)
328
+ class OrderRepositoryPort(ABC):
329
+ @abstractmethod
330
+ async def save(self, order: Order) -> Order:
331
+ pass
332
+
333
+ class PaymentGatewayPort(ABC):
334
+ @abstractmethod
335
+ async def charge(self, amount: Money, customer: str) -> PaymentResult:
336
+ pass
337
+
338
+ class NotificationPort(ABC):
339
+ @abstractmethod
340
+ async def send(self, to: str, subject: str, body: str):
341
+ pass
342
+
343
+ # Adapters (implementations)
344
+ class StripePaymentAdapter(PaymentGatewayPort):
345
+ """Primary adapter: connects to Stripe API."""
346
+
347
+ def __init__(self, api_key: str):
348
+ self.stripe = stripe
349
+ self.stripe.api_key = api_key
350
+
351
+ async def charge(self, amount: Money, customer: str) -> PaymentResult:
352
+ try:
353
+ charge = self.stripe.Charge.create(
354
+ amount=amount.cents,
355
+ currency=amount.currency,
356
+ customer=customer
357
+ )
358
+ return PaymentResult(success=True, transaction_id=charge.id)
359
+ except stripe.error.CardError as e:
360
+ return PaymentResult(success=False, error=str(e))
361
+
362
+ class MockPaymentAdapter(PaymentGatewayPort):
363
+ """Test adapter: no external dependencies."""
364
+
365
+ async def charge(self, amount: Money, customer: str) -> PaymentResult:
366
+ return PaymentResult(success=True, transaction_id="mock-123")
367
+ ```
368
+
369
+ ## Domain-Driven Design Pattern
370
+
371
+ ```python
372
+ # Value Objects (immutable)
373
+ from dataclasses import dataclass
374
+ from typing import Optional
375
+
376
+ @dataclass(frozen=True)
377
+ class Email:
378
+ """Value object: validated email."""
379
+ value: str
380
+
381
+ def __post_init__(self):
382
+ if "@" not in self.value:
383
+ raise ValueError("Invalid email")
384
+
385
+ @dataclass(frozen=True)
386
+ class Money:
387
+ """Value object: amount with currency."""
388
+ amount: int # cents
389
+ currency: str
390
+
391
+ def add(self, other: "Money") -> "Money":
392
+ if self.currency != other.currency:
393
+ raise ValueError("Currency mismatch")
394
+ return Money(self.amount + other.amount, self.currency)
395
+
396
+ # Entities (with identity)
397
+ class Order:
398
+ """Entity: has identity, mutable state."""
399
+
400
+ def __init__(self, id: str, customer: Customer):
401
+ self.id = id
402
+ self.customer = customer
403
+ self.items: List[OrderItem] = []
404
+ self.status = OrderStatus.PENDING
405
+ self._events: List[DomainEvent] = []
406
+
407
+ def add_item(self, product: Product, quantity: int):
408
+ """Business logic in entity."""
409
+ item = OrderItem(product, quantity)
410
+ self.items.append(item)
411
+ self._events.append(ItemAddedEvent(self.id, item))
412
+
413
+ def total(self) -> Money:
414
+ """Calculated property."""
415
+ return sum(item.subtotal() for item in self.items)
416
+
417
+ def submit(self):
418
+ """State transition with business rules."""
419
+ if not self.items:
420
+ raise ValueError("Cannot submit empty order")
421
+ if self.status != OrderStatus.PENDING:
422
+ raise ValueError("Order already submitted")
423
+
424
+ self.status = OrderStatus.SUBMITTED
425
+ self._events.append(OrderSubmittedEvent(self.id))
426
+
427
+ # Aggregates (consistency boundary)
428
+ class Customer:
429
+ """Aggregate root: controls access to entities."""
430
+
431
+ def __init__(self, id: str, email: Email):
432
+ self.id = id
433
+ self.email = email
434
+ self._addresses: List[Address] = []
435
+ self._orders: List[str] = [] # Order IDs, not full objects
436
+
437
+ def add_address(self, address: Address):
438
+ """Aggregate enforces invariants."""
439
+ if len(self._addresses) >= 5:
440
+ raise ValueError("Maximum 5 addresses allowed")
441
+ self._addresses.append(address)
442
+
443
+ @property
444
+ def primary_address(self) -> Optional[Address]:
445
+ return next((a for a in self._addresses if a.is_primary), None)
446
+
447
+ # Domain Events
448
+ @dataclass
449
+ class OrderSubmittedEvent:
450
+ order_id: str
451
+ occurred_at: datetime = field(default_factory=datetime.now)
452
+
453
+ # Repository (aggregate persistence)
454
+ class OrderRepository:
455
+ """Repository: persist/retrieve aggregates."""
456
+
457
+ async def find_by_id(self, order_id: str) -> Optional[Order]:
458
+ """Reconstitute aggregate from storage."""
459
+ pass
460
+
461
+ async def save(self, order: Order):
462
+ """Persist aggregate and publish events."""
463
+ await self._persist(order)
464
+ await self._publish_events(order._events)
465
+ order._events.clear()
466
+ ```
467
+
468
+ ## Resources
469
+
470
+ - **references/clean-architecture-guide.md**: Detailed layer breakdown
471
+ - **references/hexagonal-architecture-guide.md**: Ports and adapters patterns
472
+ - **references/ddd-tactical-patterns.md**: Entities, value objects, aggregates
473
+ - **assets/clean-architecture-template/**: Complete project structure
474
+ - **assets/ddd-examples/**: Domain modeling examples
475
+
476
+ ## Best Practices
477
+
478
+ 1. **Dependency Rule**: Dependencies always point inward
479
+ 2. **Interface Segregation**: Small, focused interfaces
480
+ 3. **Business Logic in Domain**: Keep frameworks out of core
481
+ 4. **Test Independence**: Core testable without infrastructure
482
+ 5. **Bounded Contexts**: Clear domain boundaries
483
+ 6. **Ubiquitous Language**: Consistent terminology
484
+ 7. **Thin Controllers**: Delegate to use cases
485
+ 8. **Rich Domain Models**: Behavior with data
486
+
487
+ ## Common Pitfalls
488
+
489
+ - **Anemic Domain**: Entities with only data, no behavior
490
+ - **Framework Coupling**: Business logic depends on frameworks
491
+ - **Fat Controllers**: Business logic in controllers
492
+ - **Repository Leakage**: Exposing ORM objects
493
+ - **Missing Abstractions**: Concrete dependencies in core
494
+ - **Over-Engineering**: Clean architecture for simple CRUD