devhive 0.1.21__tar.gz → 0.1.22__tar.gz

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 (95) hide show
  1. devhive-0.1.22/MANIFEST.in +2 -0
  2. devhive-0.1.22/PKG-INFO +101 -0
  3. devhive-0.1.22/README.md +78 -0
  4. devhive-0.1.22/community_skills/architecture-patterns/SKILL.md +37 -0
  5. devhive-0.1.22/community_skills/architecture-patterns/resources/implementation-playbook.md +479 -0
  6. devhive-0.1.21/devhive/skills/developer/backend-architect.md → devhive-0.1.22/community_skills/backend-arthitect/SKILL.md +33 -9
  7. devhive-0.1.21/devhive/skills/developer/backend-security-coder.md → devhive-0.1.22/community_skills/backend-security-coder/SKILL.md +23 -21
  8. devhive-0.1.22/community_skills/docker-expert/SKILL.md +406 -0
  9. devhive-0.1.22/community_skills/frontend-design/SKILL.md +42 -0
  10. devhive-0.1.22/community_skills/frontend-developer/SKILL.md +171 -0
  11. devhive-0.1.22/community_skills/theme-factory/SKILL.md +59 -0
  12. devhive-0.1.22/community_skills/theme-factory/theme-showcase.pdf +0 -0
  13. devhive-0.1.22/community_skills/theme-factory/themes/arctic-frost.md +19 -0
  14. devhive-0.1.22/community_skills/theme-factory/themes/botanical-garden.md +19 -0
  15. devhive-0.1.22/community_skills/theme-factory/themes/desert-rose.md +19 -0
  16. devhive-0.1.22/community_skills/theme-factory/themes/forest-canopy.md +19 -0
  17. devhive-0.1.22/community_skills/theme-factory/themes/golden-hour.md +19 -0
  18. devhive-0.1.22/community_skills/theme-factory/themes/midnight-galaxy.md +19 -0
  19. devhive-0.1.22/community_skills/theme-factory/themes/modern-minimalist.md +19 -0
  20. devhive-0.1.22/community_skills/theme-factory/themes/ocean-depths.md +19 -0
  21. devhive-0.1.22/community_skills/theme-factory/themes/sunset-boulevard.md +19 -0
  22. devhive-0.1.22/community_skills/theme-factory/themes/tech-innovation.md +19 -0
  23. devhive-0.1.22/devhive.egg-info/PKG-INFO +101 -0
  24. devhive-0.1.22/devhive.egg-info/SOURCES.txt +48 -0
  25. devhive-0.1.22/devhive.egg-info/entry_points.txt +2 -0
  26. devhive-0.1.22/devhive.egg-info/requires.txt +1 -0
  27. devhive-0.1.22/devhive.egg-info/top_level.txt +1 -0
  28. devhive-0.1.22/devhive_cli/__init__.py +1 -0
  29. devhive-0.1.22/devhive_cli/main.py +79 -0
  30. devhive-0.1.22/setup.py +33 -0
  31. devhive-0.1.22/skills/devhive_architect/SKILL.md +52 -0
  32. devhive-0.1.22/skills/devhive_auditor/SKILL.md +39 -0
  33. devhive-0.1.22/skills/devhive_backender/SKILL.md +26 -0
  34. devhive-0.1.22/skills/devhive_dba/SKILL.md +25 -0
  35. devhive-0.1.22/skills/devhive_designer/SKILL.md +25 -0
  36. devhive-0.1.22/skills/devhive_devops/SKILL.md +26 -0
  37. devhive-0.1.22/skills/devhive_explorer/SKILL.md +53 -0
  38. devhive-0.1.22/skills/devhive_frontender/SKILL.md +26 -0
  39. devhive-0.1.22/skills/devhive_orchestrator/SKILL.md +51 -0
  40. devhive-0.1.22/skills/devhive_perf/SKILL.md +25 -0
  41. devhive-0.1.22/skills/devhive_proposal/SKILL.md +46 -0
  42. devhive-0.1.22/skills/devhive_qa/SKILL.md +44 -0
  43. devhive-0.1.22/skills/devhive_releaser/SKILL.md +28 -0
  44. devhive-0.1.22/skills/devhive_sast/SKILL.md +44 -0
  45. devhive-0.1.22/skills/devhive_taskplanner/SKILL.md +85 -0
  46. devhive-0.1.22/skills/devhive_techwriter/SKILL.md +25 -0
  47. devhive-0.1.22/skills/devhive_workflow.md +43 -0
  48. devhive-0.1.21/PKG-INFO +0 -9
  49. devhive-0.1.21/README.md +0 -245
  50. devhive-0.1.21/devhive/__init__.py +0 -1
  51. devhive-0.1.21/devhive/agents/__init__.py +0 -10
  52. devhive-0.1.21/devhive/agents/architect.py +0 -19
  53. devhive-0.1.21/devhive/agents/archivist.py +0 -19
  54. devhive-0.1.21/devhive/agents/auditor.py +0 -18
  55. devhive-0.1.21/devhive/agents/base_agent.py +0 -104
  56. devhive-0.1.21/devhive/agents/ceo.py +0 -95
  57. devhive-0.1.21/devhive/agents/developer.py +0 -34
  58. devhive-0.1.21/devhive/agents/explorer.py +0 -24
  59. devhive-0.1.21/devhive/agents/proposal.py +0 -19
  60. devhive-0.1.21/devhive/agents/qa.py +0 -34
  61. devhive-0.1.21/devhive/agents/task_agent.py +0 -79
  62. devhive-0.1.21/devhive/cli.py +0 -335
  63. devhive-0.1.21/devhive/core/__init__.py +0 -0
  64. devhive-0.1.21/devhive/core/artifact_manager.py +0 -141
  65. devhive-0.1.21/devhive/core/context_optimizer.py +0 -384
  66. devhive-0.1.21/devhive/core/context_router.py +0 -286
  67. devhive-0.1.21/devhive/core/dependency_manager.py +0 -278
  68. devhive-0.1.21/devhive/core/llm.py +0 -119
  69. devhive-0.1.21/devhive/core/memory_store.py +0 -363
  70. devhive-0.1.21/devhive/core/project_state_manager.py +0 -64
  71. devhive-0.1.21/devhive/core/prompt_builder.py +0 -355
  72. devhive-0.1.21/devhive/core/task_orchestrator.py +0 -428
  73. devhive-0.1.21/devhive/core/task_queue.py +0 -305
  74. devhive-0.1.21/devhive/server.py +0 -801
  75. devhive-0.1.21/devhive/skills/auditor/owasp_security_audit.md +0 -11
  76. devhive-0.1.21/devhive/skills/auditor/performance_bottlenecks.md +0 -10
  77. devhive-0.1.21/devhive/skills/explorer/edge_case_hunter.md +0 -13
  78. devhive-0.1.21/devhive/skills/explorer/nfr_checklist.md +0 -10
  79. devhive-0.1.21/devhive/skills/global/inclusive_language.md +0 -7
  80. devhive-0.1.21/devhive/skills/global/json_strictness.md +0 -7
  81. devhive-0.1.21/devhive/skills/global/security_mandates.md +0 -7
  82. devhive-0.1.21/devhive/utils/__init__.py +0 -0
  83. devhive-0.1.21/devhive/utils/filesystem.py +0 -71
  84. devhive-0.1.21/devhive/utils/validation.py +0 -167
  85. devhive-0.1.21/devhive.egg-info/PKG-INFO +0 -9
  86. devhive-0.1.21/devhive.egg-info/SOURCES.txt +0 -48
  87. devhive-0.1.21/devhive.egg-info/entry_points.txt +0 -3
  88. devhive-0.1.21/devhive.egg-info/requires.txt +0 -2
  89. devhive-0.1.21/devhive.egg-info/top_level.txt +0 -1
  90. devhive-0.1.21/pyproject.toml +0 -25
  91. devhive-0.1.21/setup.py +0 -21
  92. devhive-0.1.21/tests/test_parallel_development.py +0 -368
  93. {devhive-0.1.21 → devhive-0.1.22}/LICENSE +0 -0
  94. {devhive-0.1.21 → devhive-0.1.22}/devhive.egg-info/dependency_links.txt +0 -0
  95. {devhive-0.1.21 → devhive-0.1.22}/setup.cfg +0 -0
@@ -0,0 +1,2 @@
1
+ recursive-include skills *
2
+ recursive-include community_skills *
@@ -0,0 +1,101 @@
1
+ Metadata-Version: 2.4
2
+ Name: devhive
3
+ Version: 0.1.22
4
+ Summary: CLI to manage DevHive skills and autonomous AI agents for OpenCode.
5
+ Home-page: https://github.com/ramBlanco/devhive
6
+ Author: ramBlanco
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: click>=8.0.0
14
+ Dynamic: author
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: home-page
19
+ Dynamic: license-file
20
+ Dynamic: requires-dist
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # DevHive: Skill-Driven Development (SDD) for OpenCode
25
+
26
+ DevHive is a fully autonomous AI software development pipeline designed specifically as a set of Skills and a dedicated Agent for **OpenCode**.
27
+
28
+ It replaces complex background servers and in-memory states with a transparent, predictable, and local **Skill-Driven Development (SDD)** architecture. DevHive uses your file system (`.devhive/specs/`) as its database, generating readable Markdown files at each step of the software lifecycle.
29
+
30
+ ## The Pipeline
31
+
32
+ DevHive is composed of specialized Agent Skills that work sequentially:
33
+
34
+ 1. **`devhive-explorer`**: Analyzes the request and writes `.devhive/specs/01-exploration.md`
35
+ 2. **`devhive-proposal`**: Creates acceptance criteria in `02-proposal.md`
36
+ 3. **`devhive-architect`**: Designs the system architecture, DB schemas, and UX/UI design system in `03-architecture.md`
37
+ 4. **`devhive-taskplanner`**: Breaks the architecture into actionable items across 8 different domains in `04-tasks.md`
38
+ 5. **`devhive-designer`**: Implements the base UI/UX configuration (CSS vars, Tailwind configs) under `## Design Tasks`
39
+ 6. **`devhive-devops`**: Writes Infrastructure as Code (IaC) (Terraform, CDK, Docker) and checks off `## Infrastructure Tasks`
40
+ 7. **`devhive-dba`**: Creates DB schemas, migrations, and seeders under `## Data Tasks`
41
+ 8. **`devhive-backender`**: Initializes the project, writes APIs and server logic, and checks off `## Backend Tasks`
42
+ 9. **`devhive-frontender`**: Writes UI components and client-side logic, and checks off `## Frontend Tasks`
43
+ 10. **`devhive-perf`**: Writes load testing scripts (k6, artillery) under `## Performance Tasks`
44
+ 11. **`devhive-techwriter`**: Writes API docs (Swagger) and updates README under `## Documentation Tasks`
45
+ 12. **`devhive-releaser`**: Bumps package versions, writes CHANGELOG, and creates local git tags under `## Release Tasks`
46
+ 13. **`devhive-sast`**: Performs a Static Application Security Testing (SAST) scan and writes `05-sast-report.md`
47
+ 14. **`devhive-qa`**: Writes test cases and test plans in `06-qa-plan.md`
48
+ 15. **`devhive-auditor`**: Performs a final check and writes `07-audit.md`
49
+
50
+ All of this is managed by the **`devhive-orchestrator`** skill.
51
+
52
+ ## Installation
53
+
54
+ DevHive is available as a Python package via PyPI. You can install it globally to manage your OpenCode skills across all your environments.
55
+
56
+ ```bash
57
+ pip install devhive
58
+ ```
59
+
60
+ Once installed, you can use the CLI to setup or update your DevHive environment:
61
+
62
+ ```bash
63
+ # Install all official and community skills into OpenCode
64
+ devhive install
65
+
66
+ # Update your existing skills to the latest versions
67
+ devhive update-skill
68
+ ```
69
+
70
+ ## Usage (The `@devhive` Agent)
71
+
72
+ Instead of using OpenCode as a general assistant, invoke the dedicated `@devhive` agent. This agent is hardwired to immediately start the SDD pipeline.
73
+
74
+ ```
75
+ @devhive Build a script that converts CSV to JSON running on AWS Lambda.
76
+ ```
77
+
78
+ The agent will automatically load the orchestrator skill and start the 10-phase pipeline!
79
+
80
+ ### Continuous Mode
81
+ By default, the orchestrator will pause and ask for your approval after writing each specification file (e.g., after writing the architecture design). If you want it to run entirely autonomously without stopping, you can add the "continuous mode" flag to your prompt:
82
+
83
+ ```
84
+ @devhive Build a React landing page. Run in continuous mode with no pauses.
85
+ ```
86
+
87
+ Or permanently enable it for the project by creating a flag file:
88
+ ```bash
89
+ mkdir -p .devhive
90
+ touch .devhive/continuous
91
+ ```
92
+
93
+ ## Why SDD (Skill-Driven Development)?
94
+
95
+ - **Zero Setup**: No Python servers, no MCP configuration, no background processes.
96
+ - **Local Memory**: The entire state of the project is readable by humans in `.devhive/specs/`. You can edit `02-proposal.md` manually, and the Architect will adapt to your changes.
97
+ - **Modular**: Need a different architectural approach? You can just tweak the prompt inside `skills/devhive_architect/SKILL.md`.
98
+
99
+ ## License
100
+
101
+ MIT License.
@@ -0,0 +1,78 @@
1
+ # DevHive: Skill-Driven Development (SDD) for OpenCode
2
+
3
+ DevHive is a fully autonomous AI software development pipeline designed specifically as a set of Skills and a dedicated Agent for **OpenCode**.
4
+
5
+ It replaces complex background servers and in-memory states with a transparent, predictable, and local **Skill-Driven Development (SDD)** architecture. DevHive uses your file system (`.devhive/specs/`) as its database, generating readable Markdown files at each step of the software lifecycle.
6
+
7
+ ## The Pipeline
8
+
9
+ DevHive is composed of specialized Agent Skills that work sequentially:
10
+
11
+ 1. **`devhive-explorer`**: Analyzes the request and writes `.devhive/specs/01-exploration.md`
12
+ 2. **`devhive-proposal`**: Creates acceptance criteria in `02-proposal.md`
13
+ 3. **`devhive-architect`**: Designs the system architecture, DB schemas, and UX/UI design system in `03-architecture.md`
14
+ 4. **`devhive-taskplanner`**: Breaks the architecture into actionable items across 8 different domains in `04-tasks.md`
15
+ 5. **`devhive-designer`**: Implements the base UI/UX configuration (CSS vars, Tailwind configs) under `## Design Tasks`
16
+ 6. **`devhive-devops`**: Writes Infrastructure as Code (IaC) (Terraform, CDK, Docker) and checks off `## Infrastructure Tasks`
17
+ 7. **`devhive-dba`**: Creates DB schemas, migrations, and seeders under `## Data Tasks`
18
+ 8. **`devhive-backender`**: Initializes the project, writes APIs and server logic, and checks off `## Backend Tasks`
19
+ 9. **`devhive-frontender`**: Writes UI components and client-side logic, and checks off `## Frontend Tasks`
20
+ 10. **`devhive-perf`**: Writes load testing scripts (k6, artillery) under `## Performance Tasks`
21
+ 11. **`devhive-techwriter`**: Writes API docs (Swagger) and updates README under `## Documentation Tasks`
22
+ 12. **`devhive-releaser`**: Bumps package versions, writes CHANGELOG, and creates local git tags under `## Release Tasks`
23
+ 13. **`devhive-sast`**: Performs a Static Application Security Testing (SAST) scan and writes `05-sast-report.md`
24
+ 14. **`devhive-qa`**: Writes test cases and test plans in `06-qa-plan.md`
25
+ 15. **`devhive-auditor`**: Performs a final check and writes `07-audit.md`
26
+
27
+ All of this is managed by the **`devhive-orchestrator`** skill.
28
+
29
+ ## Installation
30
+
31
+ DevHive is available as a Python package via PyPI. You can install it globally to manage your OpenCode skills across all your environments.
32
+
33
+ ```bash
34
+ pip install devhive
35
+ ```
36
+
37
+ Once installed, you can use the CLI to setup or update your DevHive environment:
38
+
39
+ ```bash
40
+ # Install all official and community skills into OpenCode
41
+ devhive install
42
+
43
+ # Update your existing skills to the latest versions
44
+ devhive update-skill
45
+ ```
46
+
47
+ ## Usage (The `@devhive` Agent)
48
+
49
+ Instead of using OpenCode as a general assistant, invoke the dedicated `@devhive` agent. This agent is hardwired to immediately start the SDD pipeline.
50
+
51
+ ```
52
+ @devhive Build a script that converts CSV to JSON running on AWS Lambda.
53
+ ```
54
+
55
+ The agent will automatically load the orchestrator skill and start the 10-phase pipeline!
56
+
57
+ ### Continuous Mode
58
+ By default, the orchestrator will pause and ask for your approval after writing each specification file (e.g., after writing the architecture design). If you want it to run entirely autonomously without stopping, you can add the "continuous mode" flag to your prompt:
59
+
60
+ ```
61
+ @devhive Build a React landing page. Run in continuous mode with no pauses.
62
+ ```
63
+
64
+ Or permanently enable it for the project by creating a flag file:
65
+ ```bash
66
+ mkdir -p .devhive
67
+ touch .devhive/continuous
68
+ ```
69
+
70
+ ## Why SDD (Skill-Driven Development)?
71
+
72
+ - **Zero Setup**: No Python servers, no MCP configuration, no background processes.
73
+ - **Local Memory**: The entire state of the project is readable by humans in `.devhive/specs/`. You can edit `02-proposal.md` manually, and the Architect will adapt to your changes.
74
+ - **Modular**: Need a different architectural approach? You can just tweak the prompt inside `skills/devhive_architect/SKILL.md`.
75
+
76
+ ## License
77
+
78
+ MIT License.
@@ -0,0 +1,37 @@
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
+ ## Use this skill when
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
+ ## Do not use this skill when
21
+
22
+ - You only need small, localized refactors
23
+ - The system is primarily frontend with no backend architecture changes
24
+ - You need implementation details without architectural design
25
+
26
+ ## Instructions
27
+
28
+ 1. Clarify domain boundaries, constraints, and scalability targets.
29
+ 2. Select an architecture pattern that fits the domain complexity.
30
+ 3. Define module boundaries, interfaces, and dependency rules.
31
+ 4. Provide migration steps and validation checks.
32
+
33
+ Refer to `resources/implementation-playbook.md` for detailed patterns, checklists, and templates.
34
+
35
+ ## Resources
36
+
37
+ - `resources/implementation-playbook.md` for detailed patterns, checklists, and templates.
@@ -0,0 +1,479 @@
1
+ # Architecture Patterns Implementation Playbook
2
+
3
+ This file contains detailed patterns, checklists, and code samples referenced by the skill.
4
+
5
+ ## Core Concepts
6
+
7
+ ### 1. Clean Architecture (Uncle Bob)
8
+
9
+ **Layers (dependency flows inward):**
10
+
11
+ - **Entities**: Core business models
12
+ - **Use Cases**: Application business rules
13
+ - **Interface Adapters**: Controllers, presenters, gateways
14
+ - **Frameworks & Drivers**: UI, database, external services
15
+
16
+ **Key Principles:**
17
+
18
+ - Dependencies point inward
19
+ - Inner layers know nothing about outer layers
20
+ - Business logic independent of frameworks
21
+ - Testable without UI, database, or external services
22
+
23
+ ### 2. Hexagonal Architecture (Ports and Adapters)
24
+
25
+ **Components:**
26
+
27
+ - **Domain Core**: Business logic
28
+ - **Ports**: Interfaces defining interactions
29
+ - **Adapters**: Implementations of ports (database, REST, message queue)
30
+
31
+ **Benefits:**
32
+
33
+ - Swap implementations easily (mock for testing)
34
+ - Technology-agnostic core
35
+ - Clear separation of concerns
36
+
37
+ ### 3. Domain-Driven Design (DDD)
38
+
39
+ **Strategic Patterns:**
40
+
41
+ - **Bounded Contexts**: Separate models for different domains
42
+ - **Context Mapping**: How contexts relate
43
+ - **Ubiquitous Language**: Shared terminology
44
+
45
+ **Tactical Patterns:**
46
+
47
+ - **Entities**: Objects with identity
48
+ - **Value Objects**: Immutable objects defined by attributes
49
+ - **Aggregates**: Consistency boundaries
50
+ - **Repositories**: Data access abstraction
51
+ - **Domain Events**: Things that happened
52
+
53
+ ## Clean Architecture Pattern
54
+
55
+ ### Directory Structure
56
+
57
+ ```
58
+ app/
59
+ ├── domain/ # Entities & business rules
60
+ │ ├── entities/
61
+ │ │ ├── user.py
62
+ │ │ └── order.py
63
+ │ ├── value_objects/
64
+ │ │ ├── email.py
65
+ │ │ └── money.py
66
+ │ └── interfaces/ # Abstract interfaces
67
+ │ ├── user_repository.py
68
+ │ └── payment_gateway.py
69
+ ├── use_cases/ # Application business rules
70
+ │ ├── create_user.py
71
+ │ ├── process_order.py
72
+ │ └── send_notification.py
73
+ ├── adapters/ # Interface implementations
74
+ │ ├── repositories/
75
+ │ │ ├── postgres_user_repository.py
76
+ │ │ └── redis_cache_repository.py
77
+ │ ├── controllers/
78
+ │ │ └── user_controller.py
79
+ │ └── gateways/
80
+ │ ├── stripe_payment_gateway.py
81
+ │ └── sendgrid_email_gateway.py
82
+ └── infrastructure/ # Framework & external concerns
83
+ ├── database.py
84
+ ├── config.py
85
+ └── logging.py
86
+ ```
87
+
88
+ ### Implementation Example
89
+
90
+ ```python
91
+ # domain/entities/user.py
92
+ from dataclasses import dataclass
93
+ from datetime import datetime
94
+ from typing import Optional
95
+
96
+ @dataclass
97
+ class User:
98
+ """Core user entity - no framework dependencies."""
99
+ id: str
100
+ email: str
101
+ name: str
102
+ created_at: datetime
103
+ is_active: bool = True
104
+
105
+ def deactivate(self):
106
+ """Business rule: deactivating user."""
107
+ self.is_active = False
108
+
109
+ def can_place_order(self) -> bool:
110
+ """Business rule: active users can order."""
111
+ return self.is_active
112
+
113
+ # domain/interfaces/user_repository.py
114
+ from abc import ABC, abstractmethod
115
+ from typing import Optional, List
116
+ from domain.entities.user import User
117
+
118
+ class IUserRepository(ABC):
119
+ """Port: defines contract, no implementation."""
120
+
121
+ @abstractmethod
122
+ async def find_by_id(self, user_id: str) -> Optional[User]:
123
+ pass
124
+
125
+ @abstractmethod
126
+ async def find_by_email(self, email: str) -> Optional[User]:
127
+ pass
128
+
129
+ @abstractmethod
130
+ async def save(self, user: User) -> User:
131
+ pass
132
+
133
+ @abstractmethod
134
+ async def delete(self, user_id: str) -> bool:
135
+ pass
136
+
137
+ # use_cases/create_user.py
138
+ from domain.entities.user import User
139
+ from domain.interfaces.user_repository import IUserRepository
140
+ from dataclasses import dataclass
141
+ from datetime import datetime
142
+ import uuid
143
+
144
+ @dataclass
145
+ class CreateUserRequest:
146
+ email: str
147
+ name: str
148
+
149
+ @dataclass
150
+ class CreateUserResponse:
151
+ user: User
152
+ success: bool
153
+ error: Optional[str] = None
154
+
155
+ class CreateUserUseCase:
156
+ """Use case: orchestrates business logic."""
157
+
158
+ def __init__(self, user_repository: IUserRepository):
159
+ self.user_repository = user_repository
160
+
161
+ async def execute(self, request: CreateUserRequest) -> CreateUserResponse:
162
+ # Business validation
163
+ existing = await self.user_repository.find_by_email(request.email)
164
+ if existing:
165
+ return CreateUserResponse(
166
+ user=None,
167
+ success=False,
168
+ error="Email already exists"
169
+ )
170
+
171
+ # Create entity
172
+ user = User(
173
+ id=str(uuid.uuid4()),
174
+ email=request.email,
175
+ name=request.name,
176
+ created_at=datetime.now(),
177
+ is_active=True
178
+ )
179
+
180
+ # Persist
181
+ saved_user = await self.user_repository.save(user)
182
+
183
+ return CreateUserResponse(
184
+ user=saved_user,
185
+ success=True
186
+ )
187
+
188
+ # adapters/repositories/postgres_user_repository.py
189
+ from domain.interfaces.user_repository import IUserRepository
190
+ from domain.entities.user import User
191
+ from typing import Optional
192
+ import asyncpg
193
+
194
+ class PostgresUserRepository(IUserRepository):
195
+ """Adapter: PostgreSQL implementation."""
196
+
197
+ def __init__(self, pool: asyncpg.Pool):
198
+ self.pool = pool
199
+
200
+ async def find_by_id(self, user_id: str) -> Optional[User]:
201
+ async with self.pool.acquire() as conn:
202
+ row = await conn.fetchrow(
203
+ "SELECT * FROM users WHERE id = $1", user_id
204
+ )
205
+ return self._to_entity(row) if row else None
206
+
207
+ async def find_by_email(self, email: str) -> Optional[User]:
208
+ async with self.pool.acquire() as conn:
209
+ row = await conn.fetchrow(
210
+ "SELECT * FROM users WHERE email = $1", email
211
+ )
212
+ return self._to_entity(row) if row else None
213
+
214
+ async def save(self, user: User) -> User:
215
+ async with self.pool.acquire() as conn:
216
+ await conn.execute(
217
+ """
218
+ INSERT INTO users (id, email, name, created_at, is_active)
219
+ VALUES ($1, $2, $3, $4, $5)
220
+ ON CONFLICT (id) DO UPDATE
221
+ SET email = $2, name = $3, is_active = $5
222
+ """,
223
+ user.id, user.email, user.name, user.created_at, user.is_active
224
+ )
225
+ return user
226
+
227
+ async def delete(self, user_id: str) -> bool:
228
+ async with self.pool.acquire() as conn:
229
+ result = await conn.execute(
230
+ "DELETE FROM users WHERE id = $1", user_id
231
+ )
232
+ return result == "DELETE 1"
233
+
234
+ def _to_entity(self, row) -> User:
235
+ """Map database row to entity."""
236
+ return User(
237
+ id=row["id"],
238
+ email=row["email"],
239
+ name=row["name"],
240
+ created_at=row["created_at"],
241
+ is_active=row["is_active"]
242
+ )
243
+
244
+ # adapters/controllers/user_controller.py
245
+ from fastapi import APIRouter, Depends, HTTPException
246
+ from use_cases.create_user import CreateUserUseCase, CreateUserRequest
247
+ from pydantic import BaseModel
248
+
249
+ router = APIRouter()
250
+
251
+ class CreateUserDTO(BaseModel):
252
+ email: str
253
+ name: str
254
+
255
+ @router.post("/users")
256
+ async def create_user(
257
+ dto: CreateUserDTO,
258
+ use_case: CreateUserUseCase = Depends(get_create_user_use_case)
259
+ ):
260
+ """Controller: handles HTTP concerns only."""
261
+ request = CreateUserRequest(email=dto.email, name=dto.name)
262
+ response = await use_case.execute(request)
263
+
264
+ if not response.success:
265
+ raise HTTPException(status_code=400, detail=response.error)
266
+
267
+ return {"user": response.user}
268
+ ```
269
+
270
+ ## Hexagonal Architecture Pattern
271
+
272
+ ```python
273
+ # Core domain (hexagon center)
274
+ class OrderService:
275
+ """Domain service - no infrastructure dependencies."""
276
+
277
+ def __init__(
278
+ self,
279
+ order_repository: OrderRepositoryPort,
280
+ payment_gateway: PaymentGatewayPort,
281
+ notification_service: NotificationPort
282
+ ):
283
+ self.orders = order_repository
284
+ self.payments = payment_gateway
285
+ self.notifications = notification_service
286
+
287
+ async def place_order(self, order: Order) -> OrderResult:
288
+ # Business logic
289
+ if not order.is_valid():
290
+ return OrderResult(success=False, error="Invalid order")
291
+
292
+ # Use ports (interfaces)
293
+ payment = await self.payments.charge(
294
+ amount=order.total,
295
+ customer=order.customer_id
296
+ )
297
+
298
+ if not payment.success:
299
+ return OrderResult(success=False, error="Payment failed")
300
+
301
+ order.mark_as_paid()
302
+ saved_order = await self.orders.save(order)
303
+
304
+ await self.notifications.send(
305
+ to=order.customer_email,
306
+ subject="Order confirmed",
307
+ body=f"Order {order.id} confirmed"
308
+ )
309
+
310
+ return OrderResult(success=True, order=saved_order)
311
+
312
+ # Ports (interfaces)
313
+ class OrderRepositoryPort(ABC):
314
+ @abstractmethod
315
+ async def save(self, order: Order) -> Order:
316
+ pass
317
+
318
+ class PaymentGatewayPort(ABC):
319
+ @abstractmethod
320
+ async def charge(self, amount: Money, customer: str) -> PaymentResult:
321
+ pass
322
+
323
+ class NotificationPort(ABC):
324
+ @abstractmethod
325
+ async def send(self, to: str, subject: str, body: str):
326
+ pass
327
+
328
+ # Adapters (implementations)
329
+ class StripePaymentAdapter(PaymentGatewayPort):
330
+ """Primary adapter: connects to Stripe API."""
331
+
332
+ def __init__(self, api_key: str):
333
+ self.stripe = stripe
334
+ self.stripe.api_key = api_key
335
+
336
+ async def charge(self, amount: Money, customer: str) -> PaymentResult:
337
+ try:
338
+ charge = self.stripe.Charge.create(
339
+ amount=amount.cents,
340
+ currency=amount.currency,
341
+ customer=customer
342
+ )
343
+ return PaymentResult(success=True, transaction_id=charge.id)
344
+ except stripe.error.CardError as e:
345
+ return PaymentResult(success=False, error=str(e))
346
+
347
+ class MockPaymentAdapter(PaymentGatewayPort):
348
+ """Test adapter: no external dependencies."""
349
+
350
+ async def charge(self, amount: Money, customer: str) -> PaymentResult:
351
+ return PaymentResult(success=True, transaction_id="mock-123")
352
+ ```
353
+
354
+ ## Domain-Driven Design Pattern
355
+
356
+ ```python
357
+ # Value Objects (immutable)
358
+ from dataclasses import dataclass
359
+ from typing import Optional
360
+
361
+ @dataclass(frozen=True)
362
+ class Email:
363
+ """Value object: validated email."""
364
+ value: str
365
+
366
+ def __post_init__(self):
367
+ if "@" not in self.value:
368
+ raise ValueError("Invalid email")
369
+
370
+ @dataclass(frozen=True)
371
+ class Money:
372
+ """Value object: amount with currency."""
373
+ amount: int # cents
374
+ currency: str
375
+
376
+ def add(self, other: "Money") -> "Money":
377
+ if self.currency != other.currency:
378
+ raise ValueError("Currency mismatch")
379
+ return Money(self.amount + other.amount, self.currency)
380
+
381
+ # Entities (with identity)
382
+ class Order:
383
+ """Entity: has identity, mutable state."""
384
+
385
+ def __init__(self, id: str, customer: Customer):
386
+ self.id = id
387
+ self.customer = customer
388
+ self.items: List[OrderItem] = []
389
+ self.status = OrderStatus.PENDING
390
+ self._events: List[DomainEvent] = []
391
+
392
+ def add_item(self, product: Product, quantity: int):
393
+ """Business logic in entity."""
394
+ item = OrderItem(product, quantity)
395
+ self.items.append(item)
396
+ self._events.append(ItemAddedEvent(self.id, item))
397
+
398
+ def total(self) -> Money:
399
+ """Calculated property."""
400
+ return sum(item.subtotal() for item in self.items)
401
+
402
+ def submit(self):
403
+ """State transition with business rules."""
404
+ if not self.items:
405
+ raise ValueError("Cannot submit empty order")
406
+ if self.status != OrderStatus.PENDING:
407
+ raise ValueError("Order already submitted")
408
+
409
+ self.status = OrderStatus.SUBMITTED
410
+ self._events.append(OrderSubmittedEvent(self.id))
411
+
412
+ # Aggregates (consistency boundary)
413
+ class Customer:
414
+ """Aggregate root: controls access to entities."""
415
+
416
+ def __init__(self, id: str, email: Email):
417
+ self.id = id
418
+ self.email = email
419
+ self._addresses: List[Address] = []
420
+ self._orders: List[str] = [] # Order IDs, not full objects
421
+
422
+ def add_address(self, address: Address):
423
+ """Aggregate enforces invariants."""
424
+ if len(self._addresses) >= 5:
425
+ raise ValueError("Maximum 5 addresses allowed")
426
+ self._addresses.append(address)
427
+
428
+ @property
429
+ def primary_address(self) -> Optional[Address]:
430
+ return next((a for a in self._addresses if a.is_primary), None)
431
+
432
+ # Domain Events
433
+ @dataclass
434
+ class OrderSubmittedEvent:
435
+ order_id: str
436
+ occurred_at: datetime = field(default_factory=datetime.now)
437
+
438
+ # Repository (aggregate persistence)
439
+ class OrderRepository:
440
+ """Repository: persist/retrieve aggregates."""
441
+
442
+ async def find_by_id(self, order_id: str) -> Optional[Order]:
443
+ """Reconstitute aggregate from storage."""
444
+ pass
445
+
446
+ async def save(self, order: Order):
447
+ """Persist aggregate and publish events."""
448
+ await self._persist(order)
449
+ await self._publish_events(order._events)
450
+ order._events.clear()
451
+ ```
452
+
453
+ ## Resources
454
+
455
+ - **references/clean-architecture-guide.md**: Detailed layer breakdown
456
+ - **references/hexagonal-architecture-guide.md**: Ports and adapters patterns
457
+ - **references/ddd-tactical-patterns.md**: Entities, value objects, aggregates
458
+ - **assets/clean-architecture-template/**: Complete project structure
459
+ - **assets/ddd-examples/**: Domain modeling examples
460
+
461
+ ## Best Practices
462
+
463
+ 1. **Dependency Rule**: Dependencies always point inward
464
+ 2. **Interface Segregation**: Small, focused interfaces
465
+ 3. **Business Logic in Domain**: Keep frameworks out of core
466
+ 4. **Test Independence**: Core testable without infrastructure
467
+ 5. **Bounded Contexts**: Clear domain boundaries
468
+ 6. **Ubiquitous Language**: Consistent terminology
469
+ 7. **Thin Controllers**: Delegate to use cases
470
+ 8. **Rich Domain Models**: Behavior with data
471
+
472
+ ## Common Pitfalls
473
+
474
+ - **Anemic Domain**: Entities with only data, no behavior
475
+ - **Framework Coupling**: Business logic depends on frameworks
476
+ - **Fat Controllers**: Business logic in controllers
477
+ - **Repository Leakage**: Exposing ORM objects
478
+ - **Missing Abstractions**: Concrete dependencies in core
479
+ - **Over-Engineering**: Clean architecture for simple CRUD