@moon791017/neo-skills 1.1.7 → 1.1.8

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.
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
 
12
12
  目前專案提供:
13
13
 
14
- - `skills/`:22 個內建專家技能。
14
+ - `skills/`:23 個內建專家技能。
15
15
  - `bin/install-skills.js`:同步技能到 Antigravity CLI 全域技能目錄。
16
16
  - `bin/install-system-instructions.js`:把系統提示詞安裝到 Claude Code、Copilot CLI、Codex 或 Antigravity 的指導檔。
17
17
  - `scripts/check-skills-syntax.py`:非互動式技能結構驗證工具。
@@ -41,6 +41,7 @@
41
41
  | DevOps | `neo-azure-pipelines` | 建立、審查、除錯或現代化 Azure Pipelines YAML,尤其是 .NET build、Azure App Service 或 IIS 部署。 |
42
42
  | 需求釐清 | `neo-clarification` | 將模糊、情緒化、片段式、截圖式需求轉成規格、驗收條件或釐清問題。 |
43
43
  | Code Review | `neo-code-review` | 進行程式碼審查、PR/diff review、bug 風險掃描、安全性、效能或可維護性檢查。 |
44
+ | 系統架構 | `neo-clean-architecture` | 設計、實作、審查或重構符合 Clean Architecture 原則的系統,劃分層級並排除特定技術依賴。 |
44
45
  | C# | `neo-csharp` | 撰寫、審查、除錯或現代化 C#/.NET 程式碼,包含語言版本、NRT、records、pattern matching 與 async。 |
45
46
  | C# | `neo-csharp-interface-generator` | 從 C# class 產生或更新 interface,並安全建立、追加或替換 interface block。 |
46
47
  | .NET | `neo-dotnet` | 廣泛 .NET 問題或尚未確定子領域時,先偵測 SDK/project shape 並導向合適技能。 |
@@ -147,6 +148,7 @@ npx -p @moon791017/neo-skills install-system-instructions \
147
148
  | 設計 Azure Pipelines CI/CD | `neo-azure-pipelines` | `幫我建立 .NET 專案的 Azure Pipelines CI` |
148
149
  | 審查目前變更 | `neo-code-review` | `請 review 目前 git diff` |
149
150
  | 釐清模糊需求 | `neo-clarification` | `把這些零散需求整理成規格與待確認問題` |
151
+ | 設計乾淨架構 | `neo-clean-architecture` | `幫我用 Clean Architecture 設計訂單管理模組` |
150
152
  | 寫 TypeScript 型別 | `neo-typescript` | `幫我設計這個 API response 的泛型型別` |
151
153
  | 建 Vue 3 元件 | `neo-vue` | `幫我重構這個 SFC,避免響應式踩坑` |
152
154
  | 改善 AI 開發流程 | `neo-agent-harness` | `評估這個專案讓 coding agent 協作的可靠度` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@moon791017/neo-skills",
3
- "version": "1.1.7",
3
+ "version": "1.1.8",
4
4
  "type": "module",
5
5
  "description": "Neo Skills: A Universal AI Agent Skills Extension",
6
6
  "homepage": "https://neo-blog-iota.vercel.app/",
@@ -0,0 +1,116 @@
1
+ ---
2
+ name: neo-clean-architecture
3
+ description: >
4
+ Use this skill when the user wants to design, implement, review, or refactor software systems conforming to Clean Architecture principles.
5
+ It structures code into Domain, Application, Infrastructure, and Presentation/API layers, enforcing inward-only dependencies.
6
+ It advocates rich domain models, CQRS, and the Result pattern, operating on technology-neutral concepts without database or framework bindings.
7
+ metadata:
8
+ pattern: reviewer-generator
9
+ domain: architecture
10
+ ---
11
+
12
+ # Clean Architecture
13
+
14
+ Design and review software systems using Clean Architecture. The core objective is separating concerns based on their rate of change, directing all source code dependencies inward toward the Domain core.
15
+
16
+ ## Gotchas
17
+ * **Anemic Models**: Entities that are mere data containers (only getters/setters) leak business logic. Entities must protect their invariants. State changes must go through explicit, business-oriented methods.
18
+ * **Pointless Value Objects**: Avoid wrapping primitives (e.g., string, number) unless they encapsulate validation (e.g., email format) or behavior (e.g., auto-slug generation).
19
+ * **Deep Object Graphs**: Do not nest full entities for associations. Loading a parent entity will trigger database performance issues. Reference other aggregates using IDs instead.
20
+ * **Dependency Leakage**: Repository interfaces must reside in the Application layer, with implementations in Infrastructure. Never return query streams (e.g., `IQueryable`) to Application, as it leaks database concerns.
21
+ * **Exception Control Flow**: Do not throw runtime exceptions for expected business failures (e.g., duplicate title, user not found). Use the Result pattern for flow control.
22
+
23
+ ---
24
+
25
+ ## Workflow Checklist
26
+
27
+ Progress:
28
+ - [ ] Step 1: Analyze Core & Boundaries (See `references/design_principles.md`).
29
+ - [ ] Step 2: Design Domain Layer (Build entities and value objects; protect invariants).
30
+ - [ ] Step 3: Design Application Layer (Define use case handlers, CQRS inputs, and repository interfaces).
31
+ - [ ] Step 4: Implement Outer Layers (Implement database mapping, external services, and API controllers).
32
+ - [ ] Step 5: Audit Architecture Health (Use `assets/review_checklist.md` to scan code).
33
+
34
+ ---
35
+
36
+ ## Detailed Guidelines
37
+
38
+ ### Step 1 — Analyze Core & Boundaries
39
+ 1. Categorize business rules:
40
+ - Domain Layer: Core rules that would exist even without a computer system.
41
+ - Application Layer: System orchestration, workflows, and protocols.
42
+ - Outer Layers (Infrastructure/Presentation): Delivery mechanisms and persistence details.
43
+ 2. Read [design_principles.md](references/design_principles.md) for architectural details.
44
+
45
+ ### Step 2 — Design Domain Layer
46
+ 1. Entities: Keep setters private or read-only.
47
+ 2. Domain Methods: Expose semantic operations (e.g., `updateContent()`, `addTag()`) that validate rules inside the entity.
48
+ 3. Associations: Keep aggregates decoupled by referencing other aggregate roots via ID only.
49
+
50
+ ### Step 3 — Design Application Layer
51
+ 1. Separate write operations (Commands) from read operations (Queries) using **CQRS**.
52
+ 2. Define technology-neutral interfaces (e.g., `IUserRepository`), keeping database or network specifics out of Application.
53
+ 3. Wrap use case outcomes in a **Result** type containing success/failure status, value, error type, and message. Refer to [layer_specifications.md](references/layer_specifications.md) for concepts mapping.
54
+
55
+ ### Step 4 — Implement Infrastructure & Presentation
56
+ 1. **Infrastructure**: Implement interfaces defined in Application. Configure ORM/database mappings, value conversions, and call external services.
57
+ 2. **Presentation/API**: Handle transmission protocols (e.g., HTTP, gRPC). Map request payload to Command/Query, dispatch it to Application, and translate the Result into appropriate responses (e.g., HTTP 200, 201, 400, 404, 409).
58
+
59
+ ---
60
+
61
+ ## Output Templates
62
+
63
+ ### 1. Architecture Blueprint Template
64
+ ```markdown
65
+ # [System Name] Clean Architecture Blueprint
66
+
67
+ ## 1. Domain Layer
68
+ * **Entities & Aggregate Roots**:
69
+ - `EntityName` (ID-association explanation)
70
+ * **Value Objects**:
71
+ - `ValueObjectName` (Validation and behavior description)
72
+
73
+ ## 2. Application Layer
74
+ * **Use Cases (CQRS / Handlers)**:
75
+ - `CreateSomethingCommand` & Handler
76
+ - `GetSomethingQuery` & Handler
77
+ * **External Interfaces (Gateways / Repositories)**:
78
+ - `ISomethingRepository` (Interface methods)
79
+
80
+ ## 3. Infrastructure Layer
81
+ * **Persistence Configurations**:
82
+ - `SomethingRepository` implementation notes
83
+ - Value Object persistence mapping rules
84
+
85
+ ## 4. Presentation / API Layer
86
+ * **Contracts (Request/Response)**:
87
+ - `CreateSomethingRequest` -> `SomethingResponse`
88
+ * **Route & Status Code Mappings**:
89
+ - `POST /api/something` -> `201 Created` / `400 Bad Request` / `409 Conflict`
90
+ ```
91
+
92
+ ### 2. Architecture Review Template
93
+ ```markdown
94
+ # Clean Architecture Review — [Project Name]
95
+
96
+ ## Health Score: [Score]/10
97
+ [Brief architectural health assessment]
98
+
99
+ ## Findings & Recommendations
100
+ ### 🔴 Critical (Dependency Violation / Invariant Leakage)
101
+ * **Location**: `path/to/file.ext#L12-30`
102
+ * **Problem**: [Description of the clean architecture violation]
103
+ * **Remediation**:
104
+ ```[language]
105
+ // Corrected code snippet
106
+ ```
107
+
108
+ ### 🟡 Warning (Anemic Model / Pointless Wrapping)
109
+ * **Location**: `path/to/file.ext`
110
+ * **Problem**: [Issue description]
111
+ * **Remediation**: [Code or prose description]
112
+
113
+ ### 🟢 Info (Structural / Pipeline Enhancements)
114
+ * **Location**: `path/to/file.ext`
115
+ * **Remediation**: [Suggestion details]
116
+ ```
@@ -0,0 +1,93 @@
1
+ # [System Name] — Clean Architecture Design Blueprint
2
+
3
+ This document specifies the architectural layout for [System Name], conforming to inward-only dependency rules of Clean Architecture.
4
+
5
+ ---
6
+
7
+ ## 1. Domain Layer
8
+
9
+ The Domain layer is independent of databases, web frameworks, and libraries.
10
+
11
+ ### 1.1 Entities
12
+
13
+ #### Entity: `[EntityName]`
14
+ * **Description**: [E.g., Represents a registered user account]
15
+ * **Core Attributes** (Read-Only):
16
+ - `id`: UniqueIdentifier
17
+ - `[PropertyName]`: [PropertyType]
18
+ * **Invariants & Operations**:
19
+ - `[MethodName]([parameters])`: [Explain what state changes are made and which invariants are verified]
20
+ - `constructor([parameters])`: [Initial validation rules upon instantiation]
21
+
22
+ ### 1.2 Value Objects
23
+
24
+ #### Value Object: `[ValueObjectName]`
25
+ * **Description**: [E.g., Format-validated email address]
26
+ * **Attributes**:
27
+ - `value`: String
28
+ * **Validation & Formatting**:
29
+ - [Explain formatting rules or auto-slug generation rules]
30
+
31
+ ---
32
+
33
+ ## 2. Application Layer
34
+
35
+ Defines use cases, structures input commands/queries, and declares repository interfaces.
36
+
37
+ ### 2.1 Use Cases (CQRS)
38
+
39
+ #### Command / Query: `[OperationName]`
40
+ * **Description**: [E.g., Creating a new record]
41
+ * **Input Schema**:
42
+ - `[ParamName]`: [ParamType]
43
+ * **Handler Execution Steps**:
44
+ 1. Trigger **Input Validator** to verify payload formatting.
45
+ 2. Call `[Repository].exists([uniqueKey])` to check for conflicts (return `Result.conflict` if true).
46
+ 3. Instantiate `[DomainEntity]`.
47
+ 4. Invoke `[Repository].add([EntityInstance])`.
48
+ 5. Return `Result.success([EntityId])`.
49
+
50
+ ### 2.2 Repository Interfaces
51
+
52
+ #### Interface: `I[EntityName]Repository`
53
+ * `findById(id: UniqueIdentifier): Promise<[EntityName] | null>`
54
+ * `add(entity: [EntityName]): Promise<void>`
55
+ * `update(entity: [EntityName]): Promise<void>`
56
+ * `delete(id: UniqueIdentifier): Promise<void>`
57
+
58
+ ---
59
+
60
+ ## 3. Infrastructure Layer
61
+
62
+ Implements Application interfaces and coordinates technology-specific libraries.
63
+
64
+ ### 3.1 Persistence
65
+
66
+ #### Class: `[EntityName]Repository`
67
+ * **Interface**: `I[EntityName]Repository`
68
+ * **Data Mapping**:
69
+ - Map entity `[EntityName]` to table `[table_name]`.
70
+ - Convert Value Object `[ValueObjectName]` to primitive database column type `[column_type]` on save, and deserialize on fetch.
71
+ * **Transaction Management**:
72
+ - Save changes using the persistence tracker in the repository's persist methods.
73
+
74
+ ### 3.2 External Gateways
75
+ * [E.g., File storage clients, mail gateways, third-party REST clients]
76
+
77
+ ---
78
+
79
+ ## 4. Presentation / API Layer
80
+
81
+ Entry point translating network protocols to Use Case payloads.
82
+
83
+ ### 4.1 Endpoints & Routing
84
+
85
+ #### Route: `[HTTP_METHOD] /api/[resource_path]`
86
+ * **Description**: [E.g., Create a resource]
87
+ * **Request Contract**:
88
+ - `[FieldName]`: [FieldType]
89
+ * **Response & Status Codes**:
90
+ - `201 Created` / `200 OK` -> `[ResponseContract]`
91
+ - `400 Bad Request` -> Validation Schema Errors
92
+ - `409 Conflict` -> Business Rule Violations
93
+ - `404 Not Found` -> Resource Missing
@@ -0,0 +1,35 @@
1
+ # Clean Architecture Review Checklist
2
+
3
+ Use this checklist to scan and review code bases for conformity to Clean Architecture boundaries.
4
+
5
+ ---
6
+
7
+ ## 1. Dependency Directions
8
+ * [ ] **Physical Inward Dependency (🔴 Critical)**: Do inner circles (Domain, Application) import, reference, or depend on outer circles (Infrastructure, Presentation, ORM, Web Frameworks)?
9
+ * [ ] **Query Stream Leakage (🔴 Critical)**: Do repository interfaces return ORM-specific query streams (e.g., `IQueryable`, `IPreparedQuery`)? This leaks persistence details to Application.
10
+ * [ ] **ORM Annotation Leakage (🟡 Warning)**: Do domain entities contain database-specific annotations (e.g., `@Table`, `@Column`, `[Key]`, `[Required]`)? (Map ORM metadata in the Infrastructure layer instead).
11
+ * [ ] **External SDK Leakage (🟡 Warning)**: Does the Application layer reference third-party SDK types as handler parameters? (Isolate using DTOs or custom interfaces).
12
+
13
+ ---
14
+
15
+ ## 2. Domain Layer
16
+ * [ ] **Anemic Model (🟡 Warning)**: Are entities plain data bags with public setters, shifting business rules into Application Services?
17
+ * [ ] **Invariant Protection (🟡 Warning)**: Do entity constructors and methods validate rules? Can an entity be instantiated in an invalid state?
18
+ * [ ] **Pointless Value Objects (🟢 Info)**: Are primitives wrapped in value objects without any validation or formatting benefits? (Avoid pointless overhead).
19
+ * [ ] **Coupling by Nested Entities (🟡 Warning)**: Do entities reference other aggregate roots directly as objects (e.g., `class Order { user: User }`)? (Reference aggregate roots via IDs instead to avoid ORM pre-loading performance traps).
20
+
21
+ ---
22
+
23
+ ## 3. Application & Use Case Layer
24
+ * [ ] **Single Responsibility Use Cases (🟢 Info)**: Do use case classes or handlers manage multiple unrelated actions? (Prefer a single handler per business command/query).
25
+ * [ ] **Cross-Cutting Concern Pollution (🟡 Warning)**: Are logging, validation, and transaction commits scattered across use case handlers? (Centralize via pipeline middleware or interceptors).
26
+ * [ ] **Exception Control Flow (🟡 Warning)**: Does application code throw exceptions for expected failures (e.g., password mismatch, username conflict)? (Use Result objects instead).
27
+ * [ ] **Database Transaction Leaks (🔴 Critical)**: Does Application code directly call SQL, NoSQL, or Transaction Commit APIs? (Isolate via `IRepository` and `IUnitOfWork` interfaces).
28
+
29
+ ---
30
+
31
+ ## 4. Presentation & API Layer
32
+ * [ ] **Thin Controllers (🟡 Warning)**: Do controllers or endpoint handlers contain business logic? (Controllers must only parse request payloads and dispatch them).
33
+ * [ ] **Contract Leakage (🟡 Warning)**: Do controllers expose Domain Entities or persistence models directly as API payloads? (Use separate Request/Response DTO contracts).
34
+ * [ ] **Format Validation Isolation (🟢 Info)**: Is basic format validation (e.g., empty string, regex check) caught at the boundary via validators, separate from domain invariants?
35
+ * [ ] **Status Code Mapping (🟢 Info)**: Are Result errors correctly mapped to transport status codes (e.g., HTTP 400, 404, 409, 500)?
@@ -0,0 +1,26 @@
1
+ {
2
+ "should_trigger": [
3
+ "How to design a clean architecture order module?",
4
+ "I want to map out a Clean Architecture project structure, how should I layer it?",
5
+ "Could you check if this domain entity is an anemic model and tell me how to make it a Rich Domain Model?",
6
+ "How do I implement the Repository Pattern in Clean Architecture without leaking database concerns?",
7
+ "Should book loan business logic reside in the Domain or Application layer?",
8
+ "Can you do a Clean Architecture code review on my project structure and code?",
9
+ "How do I use the Result Pattern instead of Exceptions for flow control?",
10
+ "How should I reference associations between aggregate roots in Clean Architecture to avoid ORM performance traps?",
11
+ "Why shouldn't a repository return IQueryable?",
12
+ "Help me design microservice core logic layers using technology-neutral architecture concepts."
13
+ ],
14
+ "should_not_trigger": [
15
+ "How do I write an ASP.NET Core Minimal API Controller in C#?",
16
+ "Help me install EF Core SqlServer package and add a new Migration.",
17
+ "How to write a MediatR Pipeline Behavior?",
18
+ "How do I write a React file upload UI component?",
19
+ "Teach me how to write a PostgreSQL JSONB column query in SQL.",
20
+ "Does this code have a memory leak? Please review for performance issues.",
21
+ "How do I configure Docker to run a MySQL database?",
22
+ "What are the three pillars of object-oriented programming?",
23
+ "How do I implement a binary search tree in Python?",
24
+ "Write a simple script to parse a CSV file and sum a column."
25
+ ]
26
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "skill_name": "neo-clean-architecture",
3
+ "evals": [
4
+ {
5
+ "id": 1,
6
+ "prompt": "Design a Clean Architecture blueprint for an 'Online Library System'. Key requirements: Borrow books (limits: max 5 books per reader, book must be available, loan record automatically saves checkout date and due date). Keep it technology-neutral and concept-focused; do not use specific programming languages.",
7
+ "expected_output": "A structured Clean Architecture plan containing Domain layer (Entities: Book/Reader/Loan, Value Object: LoanDuration), Application layer (BorrowBookCommand & Handler, IBookRepository interface), and generic descriptions of Infrastructure and Presentation layers, without C# or Java annotations.",
8
+ "assertions": [
9
+ "The output lists the four standard layers (Domain, Application, Infrastructure, Presentation)",
10
+ "The domain entity includes invariant validation methods (e.g., limit checks or status validation)",
11
+ "The repository interface is defined in the Application layer, not the Infrastructure layer",
12
+ "Entities reference each other by ID (e.g., Loan references ReaderId/BookId) rather than full object nests",
13
+ "The design does not depend on specific libraries or frameworks (e.g., EF Core, MediatR, Prisma)"
14
+ ]
15
+ },
16
+ {
17
+ "id": 2,
18
+ "prompt": "Review this code snippet for Clean Architecture conformity and suggest remediation:\n```javascript\n// In Controller\napp.post('/api/orders', async (req, res) => {\n const { userId, items } = req.body;\n if (!userId) return res.status(400).send('User ID is required');\n \n // Direct database query\n const activeOrder = await db.query('SELECT * FROM orders WHERE user_id = $1 AND status = \\'ACTIVE\\'', [userId]);\n if (activeOrder.rows.length > 0) {\n return res.status(409).send('Each user can have only one active order');\n }\n \n const order = {\n id: generateUUID(),\n userId,\n items,\n status: 'ACTIVE',\n createdAt: new Date()\n };\n await db.query('INSERT INTO orders (id, user_id, items, status, created_at) VALUES ($1, $2, $3, $4, $5)', [order.id, order.userId, JSON.stringify(order.items), order.status, order.createdAt]);\n \n res.status(201).json(order);\n});\n```",
19
+ "expected_output": "An architecture review pointing out database dependency and business logic (limit of one active order) leakage in the controller. It should offer remediation to split code into an Order entity (protecting invariants), a CreateOrderUseCase/Handler, and an IOrderRepository interface, providing technology-neutral code examples.",
20
+ "assertions": [
21
+ "Identifies business logic leakage in the controller as a violation",
22
+ "Identifies direct database coupling in the controller as a violation",
23
+ "Recommends moving 'one active order check' to the Application/Domain layer",
24
+ "Includes a technology-neutral refactored code example (with Repository interface and Use Case handler)",
25
+ "Conforms to the review report template format (containing score, findings, and remediation categories)"
26
+ ]
27
+ }
28
+ ]
29
+ }
@@ -0,0 +1,130 @@
1
+ # Clean Architecture Design Principles
2
+
3
+ This document defines core concepts of Clean Architecture, focusing on technology-neutral guidelines applicable across different programming languages and frameworks.
4
+
5
+ ---
6
+
7
+ ## 1. Separation of Concerns
8
+
9
+ Components change for different reasons and at different rates:
10
+ * **Business Rules** (e.g., discount logic): Exist in the **Domain** core. Changes reflect business policy shifts.
11
+ * **Application Use Cases** (e.g., notifying users after sign-up): Coordinate flows in the **Application** layer.
12
+ * **Technical Details** (e.g., PostgreSQL migration, REST-to-gRPC switch): Restricted to **Infrastructure** and **Presentation**.
13
+
14
+ Coupling these layers increases regression risks. Boundaries isolate changes to keep updates localized.
15
+
16
+ ---
17
+
18
+ ## 2. Inward Dependency Rule
19
+
20
+ Source code dependencies must point strictly inward. Inner circles have zero knowledge of outer circles.
21
+
22
+ ```
23
+ ┌──────────────────────────────────────────────┐
24
+ │ Presentation / API Layer │
25
+ │ ┌────────────────────────────────────────┐ │
26
+ │ │ Infrastructure Layer │ │
27
+ │ │ ┌──────────────────────────────────┐ │ │
28
+ │ │ │ Application Layer (Use Cases) │ │ │
29
+ │ │ │ ┌────────────────────────────┐ │ │ │
30
+ │ │ │ │ Domain Core (Entities) │ │ │ │
31
+ │ │ │ └────────────────────────────┘ │ │ │
32
+ │ │ └──────────────────────────────────┘ │ │
33
+ │ └────────────────────────────────────────┘ │
34
+ └──────────────────────────────────────────────┘
35
+ ```
36
+
37
+ * **Domain Core**: Inmost circle. Depends on nothing. Free of frameworks, database drivers, or outer-circle constructs.
38
+ * **Application**: Depends only on Domain. Defines use cases and abstractions (e.g., Repository interfaces).
39
+ * **Infrastructure**: Depends on Application and Domain. Implements application interfaces, managing persistence and external networks.
40
+ * **Presentation**: Depends on Application. Entry point handling transport protocols (HTTP/gRPC/CLI) and dispatching inputs.
41
+
42
+ ### Dependency Inversion Principle (DIP)
43
+ To persist data without letting the Application depend on Infrastructure:
44
+ * **Approach**: Define an abstract interface (e.g., `IRepository`) in the Application layer. Implement this interface (e.g., `SqlRepository`) in the Infrastructure.
45
+ * **Result**: At runtime, DI resolves the implementation. At compile time, the source code dependency points inward, protecting the boundary.
46
+
47
+ ---
48
+
49
+ ## 3. Rich Domain Model
50
+
51
+ Entities must protect their **Invariants (business rules and consistency constraints)**. Properties must be read-only, and state changes must go through semantic methods.
52
+
53
+ Anemic Domain Models (data containers with public setters) scatter business rules across services, leading to duplication and maintenance overhead.
54
+
55
+ ```javascript
56
+ // ✅ Correct Design: Read-only properties, state changes managed via semantic methods
57
+ class Prompt {
58
+ #id;
59
+ #title;
60
+ #content;
61
+ #tags = new Set();
62
+
63
+ constructor(title, content) {
64
+ if (!title || title.trim() === "") throw new Error("Title is required");
65
+ this.#id = generateUUID();
66
+ this.#title = title.trim();
67
+ this.#content = content;
68
+ }
69
+
70
+ get title() { return this.#title; }
71
+ get content() { return this.#content; }
72
+ get tags() { return Array.from(this.#tags); }
73
+
74
+ updateContent(newContent) {
75
+ if (!newContent || newContent.trim() === "") throw new Error("Content cannot be empty");
76
+ if (this.#content === newContent) return;
77
+ this.#content = newContent;
78
+ }
79
+
80
+ addTag(tagValue) {
81
+ const normalized = tagValue.trim().toLowerCase();
82
+ if (normalized.length === 0) return;
83
+ this.#tags.add(normalized);
84
+ }
85
+ }
86
+ ```
87
+
88
+ ---
89
+
90
+ ## 4. Value Objects
91
+
92
+ Value Objects have no identity (ID) and are defined entirely by their properties. Two Value Objects are equal if their attributes match.
93
+
94
+ ### Avoid Over-engineering
95
+ Do not wrap primitives unless they validate (e.g., `Email` format) or transform data (e.g., `Tag` slugification). Use Value Objects only when:
96
+ 1. **Validation is needed**: E.g., verifying `Email` format.
97
+ 2. **Behavior is needed**: E.g., converting tag inputs to slugs.
98
+ 3. **Attributes form a conceptual whole**: E.g., `Money(amount, currency)`.
99
+
100
+ ---
101
+
102
+ ## 5. Result Pattern
103
+
104
+ Expected business failures (e.g., resource not found, title conflict) should return a structured `Result` object instead of throwing runtime exceptions.
105
+
106
+ Exceptions must be reserved for unexpected, fatal system issues (e.g., database connection loss, out-of-memory).
107
+
108
+ ### Generic Result Design
109
+ ```javascript
110
+ class Result {
111
+ constructor(isSuccess, value = null, error = null, errorType = "None") {
112
+ this.isSuccess = isSuccess;
113
+ this.value = value;
114
+ this.error = error;
115
+ this.errorType = errorType; // e.g., "NotFound", "Validation", "Conflict", "None"
116
+ }
117
+
118
+ static success(value) {
119
+ return new Result(true, value, null, "None");
120
+ }
121
+
122
+ static failure(error, type = "Failure") {
123
+ return new Result(false, null, error, type);
124
+ }
125
+
126
+ static notFound(error = "Resource not found") {
127
+ return new Result(false, null, error, "NotFound");
128
+ }
129
+ }
130
+ ```
@@ -0,0 +1,73 @@
1
+ # Clean Architecture Layer Specifications & Mappings
2
+
3
+ This document defines the responsibilities of each layer and provides guidance on translating technology-specific code/libraries into clean, technology-neutral concepts.
4
+
5
+ ---
6
+
7
+ ## Layers & Boundary Rules
8
+
9
+ | Layer Name | Core Responsibility | Absolute Prohibitions (Boundary Rules) |
10
+ | :--- | :--- | :--- |
11
+ | **Domain** | 1. Entities<br>2. Value Objects<br>3. Domain logic & invariants<br>4. Domain events | 🚫 No database or ORM dependencies.<br>🚫 No transport protocol references (HTTP/gRPC/CLI).<br>🚫 No references to outer-layer modules (Application/Infrastructure).<br>🚫 No third-party framework annotations (e.g., Spring, Nest, ASP.NET). |
12
+ | **Application** | 1. Use case handlers<br>2. Command & Query inputs<br>3. Repository & Gateway interfaces<br>4. Pipeline / Interceptor interfaces | 🚫 No SQL queries or DB connection details.<br>🚫 No direct HTTP requests, responses, or routing concerns.<br>🚫 No direct access to outer networks, filesystems, or email drivers. |
13
+ | **Infrastructure** | 1. Implement Application interfaces (Repositories)<br>2. Persistence settings & ORM configurations<br>3. External gateway implementations (Mail, Queue, File Storage) | 🚫 No business logic execution outside application-defined interfaces.<br>🚫 No direct database state modification bypassing domain invariants.<br>🚫 No dependencies on Presentation layer structures (e.g., HTTP sessions). |
14
+ | **Presentation / API** | 1. Parse and validate Request Contracts<br>2. Basic format validation (length, null check, regex)<br>3. Dispatch inputs to Application Use Cases<br>4. Map Result to Response Contracts & Status Codes | 🚫 No direct database queries (must go through Application).<br>🚫 No business rules or invariant checks.<br>🚫 No business transaction assembly across aggregates. |
15
+
16
+ ---
17
+
18
+ ## Technology-Specific to Clean Concept Mappings
19
+
20
+ When reviewing codebases, map programming language syntax and library features to these universal concepts:
21
+
22
+ ### 1. Request Orchestration (e.g., MediatR in C#, Spring Service in Java)
23
+ * **Library Feature**:
24
+ * C# `IMediator.Send(command)` or `IRequestHandler`.
25
+ * Java `@Service` annotations mixing use case execution with business logic.
26
+ * **Technology-Neutral Concept**:
27
+ * **Command/Query Dispatcher** or **Use Case Interactor**.
28
+ * Separate each business workflow into a dedicated `UseCase` class or `Handler` function, dividing input schemas from execution logic.
29
+ * **Concept Mapping Code**:
30
+ ```javascript
31
+ // Technology-neutral Use Case concept
32
+ class CreateUserUseCase {
33
+ constructor(userRepository, emailGateway) {
34
+ this.userRepository = userRepository;
35
+ this.emailGateway = emailGateway;
36
+ }
37
+
38
+ async execute(command) {
39
+ // Flow coordination...
40
+ }
41
+ }
42
+ ```
43
+
44
+ ### 2. Cross-Cutting Concerns (e.g., MediatR Pipeline, Spring AOP, Express Middleware)
45
+ * **Library Feature**:
46
+ * C# `IPipelineBehavior<TRequest, TResponse>` or Express `next()` middleware.
47
+ * **Technology-Neutral Concept**:
48
+ * **Pipeline Middleware / Interceptor**.
49
+ * Intercept actions before and after use case execution to run Logging, Validation, Transaction, and Caching. This isolates the core handler from infrastructure concerns.
50
+
51
+ ### 3. Persistence Mapping (e.g., EF Core, Hibernate, Prisma, Mongoose)
52
+ * **Library Feature**:
53
+ * C# `DbContext`, `DbSet`, `IEntityTypeConfiguration`, or ORM navigation properties with Lazy Loading.
54
+ * **Technology-Neutral Concept**:
55
+ * **Persistence Context** and **Data Mapper**.
56
+ * Map entities to database schemas, converting value objects to database-friendly primitives. The Domain layer must remain free of ORM annotations or persistence metadata.
57
+
58
+ ### 4. Repository Leakage
59
+ * **Library Feature**:
60
+ * Returning C# `IQueryable<T>` or Java `Stream<T>` from repositories.
61
+ * **Technology-Neutral Concept**:
62
+ * **Leaky Abstraction Anti-Pattern**.
63
+ * Returning query streams allows Application code to inject query filters (e.g., SQL/LINQ criteria), leaking database capabilities inward and blocking unit test isolation.
64
+ * **Remediation**: Repositories must return **concrete collections** (e.g., `List` or pagination objects) or expose semantic queries (e.g., `findActiveUsersByRole`).
65
+
66
+ ### 5. Input Validation (e.g., FluentValidation, JSR-380 annotations)
67
+ * **Library Feature**:
68
+ * `AbstractValidator` or `@NotNull` property constraints.
69
+ * **Technology-Neutral Concept**:
70
+ * **Input Validator**.
71
+ * Manage basic schema checks at boundaries. Separate validation into:
72
+ 1. **Format Validation**: Intercept malformed payloads at API/Application boundaries.
73
+ 2. **Invariant Validation**: Enforce business policy rules inside the Domain entity constructor/methods.