@moon791017/neo-skills 1.1.7 → 1.1.9
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 +3 -1
- package/package.json +1 -1
- package/skills/neo-agent-harness/SKILL.md +41 -4
- package/skills/neo-agent-harness/reference/harness-patterns.md +14 -0
- package/skills/neo-agent-harness/reference/loop-engineering.md +150 -0
- package/skills/neo-clean-architecture/SKILL.md +116 -0
- package/skills/neo-clean-architecture/assets/architecture_template.md +93 -0
- package/skills/neo-clean-architecture/assets/review_checklist.md +35 -0
- package/skills/neo-clean-architecture/evals/eval_queries.json +26 -0
- package/skills/neo-clean-architecture/evals/evals.json +29 -0
- package/skills/neo-clean-architecture/references/design_principles.md +130 -0
- package/skills/neo-clean-architecture/references/layer_specifications.md +73 -0
package/README.md
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
|
|
12
12
|
目前專案提供:
|
|
13
13
|
|
|
14
|
-
- `skills
|
|
14
|
+
- `skills/`:內建多個專家技能。
|
|
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
|
@@ -2,9 +2,11 @@
|
|
|
2
2
|
name: neo-agent-harness
|
|
3
3
|
description: >
|
|
4
4
|
Use this skill when the user asks to improve AI-assisted development reliability,
|
|
5
|
-
AGENTS.md, skills, tests, CI, hooks, review loops,
|
|
6
|
-
|
|
7
|
-
|
|
5
|
+
AGENTS.md, skills, tests, CI, hooks, review loops, agent workflow governance,
|
|
6
|
+
loop engineering, agent automations, worktree isolation, maker/checker separation,
|
|
7
|
+
or external state design for long-running agents.
|
|
8
|
+
It designs feedforward guides, feedback sensors, verification gates, human
|
|
9
|
+
decision points, and loop architectures from repository evidence.
|
|
8
10
|
---
|
|
9
11
|
|
|
10
12
|
# Agent Harness Architect Skill
|
|
@@ -14,10 +16,17 @@ description: >
|
|
|
14
16
|
- The user wants coding agents to be more reliable, safer, or easier to supervise.
|
|
15
17
|
- The user asks for AGENTS.md, skills, tests, CI, hooks, review loops, or project rules to be planned together.
|
|
16
18
|
- The task is about harness engineering, agent harnessability, feedback loops, or "humans on the loop".
|
|
19
|
+
- The user wants to design scheduled automations, cron-driven agent loops, or recurring agent tasks.
|
|
20
|
+
- The user wants multiple agents to work in parallel and needs an isolation strategy (worktree isolation).
|
|
21
|
+
- The user wants to design maker/checker separation (generation and verification by different agents).
|
|
22
|
+
- The user wants to design external memory or cross-conversation state persistence for agents.
|
|
23
|
+
- The user asks how to evolve from a harness to loop-driven development.
|
|
17
24
|
|
|
18
25
|
## Core Principle
|
|
19
26
|
Treat agent-assisted development as a controlled engineering system. Do not only improve prompts; design the guides, sensors, verification steps, and human decision points that let agents work with higher confidence.
|
|
20
27
|
|
|
28
|
+
When the task involves automations, parallel agents, or continuous loops, extend the design to cover loop architecture: the scheduling, isolation, separation, integration, and state layers that let the harness run itself.
|
|
29
|
+
|
|
21
30
|
Use this skill for planning first. Do not modify files unless the user explicitly asks for implementation after the harness plan is clear.
|
|
22
31
|
|
|
23
32
|
## Perceive
|
|
@@ -27,6 +36,9 @@ Use this skill for planning first. Do not modify files unless the user explicitl
|
|
|
27
36
|
- Validation commands: `package.json`, `pyproject.toml`, `Makefile`, CI workflow files, build scripts.
|
|
28
37
|
- Safety and governance: hooks, linters, formatters, secret scanners, dependency scanners.
|
|
29
38
|
- Existing documentation: README, architecture docs, ADRs, testing docs, contribution docs.
|
|
39
|
+
- Agent definitions: `.codex/agents/`, `.claude/agents/`, subagent configs, agent team definitions.
|
|
40
|
+
- Automation and scheduling: cron configs, GitHub Actions workflows, hooks, `/loop` or `/goal` usage.
|
|
41
|
+
- State files: progress markdown, task boards, Linear integrations, cross-conversation state.
|
|
30
42
|
2. Identify the project type, primary languages, current test surface, CI status, and release/deploy path.
|
|
31
43
|
3. Separate discoverable repository facts from product or team preferences that require user confirmation.
|
|
32
44
|
|
|
@@ -48,8 +60,15 @@ Analyze the project through these dimensions:
|
|
|
48
60
|
- Behaviour: requirements, acceptance criteria, user journeys, fixtures, manual test points.
|
|
49
61
|
5. **Human role**
|
|
50
62
|
- Move human effort from repeated low-level correction to high-value decisions: scope, product fit, risk acceptance, architectural tradeoffs, and harness evolution.
|
|
63
|
+
6. **Loop design** (conditional: activate only when the task involves scheduled automations, parallel agents, or continuous loops)
|
|
64
|
+
- **Automations**: which tasks suit scheduled triggers? Frequency, trigger conditions, result routing (triage inbox vs auto-process).
|
|
65
|
+
- **Worktrees**: how to isolate parallel agents? Independent branches and working directories needed?
|
|
66
|
+
- **Maker/checker separation**: which steps need generation and verification by different agents? (For sub-agent definition and implementation, use the neo-sub-agent skill.)
|
|
67
|
+
- **Connectors**: which external tools does the loop need to reach? (issue tracker, CI, Slack, staging API, database)
|
|
68
|
+
- **State**: how to persist cross-conversation progress? Format (markdown / board / Linear)? Who updates it?
|
|
69
|
+
- **Loop risks**: assess comprehension debt, cognitive surrender, and unattended verification risk levels.
|
|
51
70
|
|
|
52
|
-
For detailed patterns and examples, read [reference/harness-patterns.md](reference/harness-patterns.md) when the task needs a full harness design, maturity model, or improvement roadmap. For the complete source article synthesis behind this skill, read [reference/agent-harness-engineering.md](reference/agent-harness-engineering.md) only when deeper conceptual background is needed.
|
|
71
|
+
For detailed patterns and examples, read [reference/harness-patterns.md](reference/harness-patterns.md) when the task needs a full harness design, maturity model, or improvement roadmap. For the complete source article synthesis behind this skill, read [reference/agent-harness-engineering.md](reference/agent-harness-engineering.md) only when deeper conceptual background is needed. For loop engineering patterns, the five loop primitives, risk model, and maturity guidance, read [reference/loop-engineering.md](reference/loop-engineering.md) when the task involves automations, parallel agents, maker/checker separation, or loop-driven development.
|
|
53
72
|
|
|
54
73
|
## Act
|
|
55
74
|
Output in Traditional Chinese (Taiwan). Use this structure:
|
|
@@ -57,6 +76,7 @@ Output in Traditional Chinese (Taiwan). Use this structure:
|
|
|
57
76
|
### 1. 現況盤點
|
|
58
77
|
- Summarize the repository facts discovered.
|
|
59
78
|
- Mention the current guides, sensors, and missing signals.
|
|
79
|
+
- If loop-relevant infrastructure exists (automations, agent definitions, state files), include it here.
|
|
60
80
|
|
|
61
81
|
### 2. Harnessability 評估
|
|
62
82
|
- Rate the current harnessability as `低`, `中`, or `高`.
|
|
@@ -74,9 +94,22 @@ Output in Traditional Chinese (Taiwan). Use this structure:
|
|
|
74
94
|
- Prioritize improvements as P0, P1, and P2.
|
|
75
95
|
- P0 must focus on changes that reduce repeated agent mistakes or prevent high-risk failures.
|
|
76
96
|
|
|
97
|
+
### 5.5 Loop 設計(條件式:僅當任務涉及 loop 時輸出)
|
|
98
|
+
- List tasks suited for scheduled automation, with suggested frequency.
|
|
99
|
+
- Describe the isolation strategy for parallel agents (worktree / branch / container).
|
|
100
|
+
- Identify which steps need maker/checker separation and their verification criteria.
|
|
101
|
+
- List required connectors and external integrations.
|
|
102
|
+
- Design the state persistence scheme and update responsibilities.
|
|
103
|
+
- Assess loop risks: comprehension debt, cognitive surrender, unattended verification, and propose safeguards.
|
|
104
|
+
|
|
77
105
|
### 6. 人類決策點
|
|
78
106
|
- State where humans should stay on the loop.
|
|
79
107
|
- Identify decisions that should not be delegated fully to agents.
|
|
108
|
+
- When loop design is involved, assess these three specific risks:
|
|
109
|
+
- **Verification responsibility**: error accumulation when the loop runs unattended.
|
|
110
|
+
- **Comprehension debt**: the faster the loop produces code, the wider the understanding gap.
|
|
111
|
+
- **Cognitive surrender**: tendency to stop having opinions when the loop runs itself.
|
|
112
|
+
- Clearly mark which loop stages still require human intervention (scope decisions, risk acceptance, architectural tradeoffs).
|
|
80
113
|
|
|
81
114
|
### 7. 驗證方式
|
|
82
115
|
- Provide exact commands or review steps when discoverable.
|
|
@@ -88,3 +121,7 @@ Output in Traditional Chinese (Taiwan). Use this structure:
|
|
|
88
121
|
- Do not recommend broad automation before the project has reliable local validation commands.
|
|
89
122
|
- Do not propose fully autonomous changes for security, compliance, production deploys, or product-scope decisions.
|
|
90
123
|
- Keep the output actionable and tied to repository evidence.
|
|
124
|
+
- Do not recommend loop-driven automations for projects that lack reliable local validation commands and stable CI.
|
|
125
|
+
- When designing loops, explicitly assess comprehension debt, cognitive surrender, and unattended verification risks.
|
|
126
|
+
- For sub-agent design and implementation details, defer to the neo-sub-agent skill to avoid responsibility overlap.
|
|
127
|
+
- Mark loop engineering concepts as emerging practice, not established best practice.
|
|
@@ -178,3 +178,17 @@ Common improvement sequence:
|
|
|
178
178
|
- Humans prioritize and approve harness changes.
|
|
179
179
|
- Low-risk improvements can be automated after repeated success.
|
|
180
180
|
- Harness quality itself is reviewed regularly.
|
|
181
|
+
|
|
182
|
+
### Level 5: Loop-Driven Development
|
|
183
|
+
|
|
184
|
+
- Harness is driven by scheduled automations, no longer relying on manual triggers.
|
|
185
|
+
- Multiple agents work in parallel across isolated worktrees.
|
|
186
|
+
- Generation and verification are handled by separate agents (maker/checker separation).
|
|
187
|
+
- Connectors let the loop directly operate issue trackers, PRs, CI, and notification channels.
|
|
188
|
+
- A state file persists progress across conversations; each run resumes from where the last one stopped.
|
|
189
|
+
- The human role shifts from in-the-loop line-by-line review to on-the-loop supervision: designing loops, sampling outputs, and evolving the harness.
|
|
190
|
+
- Comprehension debt, cognitive surrender, and unattended verification risks are explicitly assessed and managed.
|
|
191
|
+
- High-risk changes are forced out of the loop to await human decisions.
|
|
192
|
+
|
|
193
|
+
Prerequisites: Level 4 harness improvement loop is running stably, CI is reliable, and review processes are mature.
|
|
194
|
+
Note: Loop engineering is still an emerging practice. Start with low-risk, repetitive tasks.
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# Loop Engineering
|
|
2
|
+
|
|
3
|
+
Use this reference when designing loop architectures that automate agent-driven workflows beyond a single session.
|
|
4
|
+
|
|
5
|
+
## Loop 與 Harness 的關係
|
|
6
|
+
|
|
7
|
+
- Harness = 單一 agent 的工作環境(guides + sensors + gates)
|
|
8
|
+
- Loop = harness 之上的排程驅動層,讓 harness 自己跑
|
|
9
|
+
- 設計 loop 不是取代 prompt,而是把反覆的 prompt 動作系統化
|
|
10
|
+
|
|
11
|
+
```text
|
|
12
|
+
Loop = Automations + Worktrees + Skills + Connectors + Sub-agents + State
|
|
13
|
+
─────────────────────────────────────────────────────────────────
|
|
14
|
+
running on top of the Harness
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## 五個基本原件 + State
|
|
18
|
+
|
|
19
|
+
### 1. Automations(心跳)
|
|
20
|
+
|
|
21
|
+
Automations 是讓 loop 成為「真的迴圈」而非「跑過一次」的關鍵。
|
|
22
|
+
|
|
23
|
+
- 排程式觸發,定時執行探索與分類。
|
|
24
|
+
- 找到問題的送 triage inbox,沒發現的自動歸檔。
|
|
25
|
+
- 可搭配 skills 維護排程任務的可維護性——呼叫 `$skill-name` 而非貼一大段指令。
|
|
26
|
+
- `/loop` 按頻率重複執行;`/goal` 持續執行直到停止條件成立,且由獨立模型判斷是否完成。
|
|
27
|
+
|
|
28
|
+
工具對應:
|
|
29
|
+
|
|
30
|
+
- Codex:Automations tab(選專案、prompt、頻率、環境),結果進 Triage inbox;`/goal` run-until-done。
|
|
31
|
+
- Claude Code:`/loop`、`/goal`、hooks、cron、GitHub Actions。
|
|
32
|
+
|
|
33
|
+
### 2. Worktrees(隔離)
|
|
34
|
+
|
|
35
|
+
多 agent 並行時避免檔案衝突。
|
|
36
|
+
|
|
37
|
+
- 每個 agent 在獨立的 git worktree 工作,共享 repo history。
|
|
38
|
+
- 一個 agent 的編輯不會碰到另一個的 checkout。
|
|
39
|
+
- 人的 review bandwidth 仍是瓶頸——worktree 解決機械衝突,但你能同時審幾條線決定了你能跑幾個 agent(orchestration tax)。
|
|
40
|
+
|
|
41
|
+
工具對應:
|
|
42
|
+
|
|
43
|
+
- Codex:內建 worktree per thread。
|
|
44
|
+
- Claude Code:`git worktree`、`--worktree` flag、subagent 的 `isolation: worktree` 設定。
|
|
45
|
+
|
|
46
|
+
### 3. Skills(知識固化)
|
|
47
|
+
|
|
48
|
+
把反覆解釋的專案上下文寫成 SKILL.md。
|
|
49
|
+
|
|
50
|
+
- 消除 intent debt:每次冷啟動,agent 會用自信的猜測填補意圖缺口。Skill 把意圖寫在外面,agent 每次讀取,不需重建。
|
|
51
|
+
- 沒有 skills 的 loop 每個 cycle 從零推導你的整個專案;有 skills 的 loop 會累積複利。
|
|
52
|
+
- Skill 是創作格式,Plugin 是發布格式——跨 repo 分享時打包成 plugin。
|
|
53
|
+
|
|
54
|
+
工具對應:
|
|
55
|
+
|
|
56
|
+
- Codex:Agent Skills (`SKILL.md`),用 `$name` 或 `/skills` 呼叫,或由 description 自動觸發。
|
|
57
|
+
- Claude Code:Agent Skills (`SKILL.md`)。
|
|
58
|
+
|
|
59
|
+
### 4. Plugins / Connectors(外部整合)
|
|
60
|
+
|
|
61
|
+
透過 MCP 連接外部工具,讓 loop 能在真實環境中行動。
|
|
62
|
+
|
|
63
|
+
- 可連接 issue tracker、database、staging API、Slack。
|
|
64
|
+
- Codex 和 Claude Code 都用 MCP,connector 通常跨工具可用。
|
|
65
|
+
- Plugins 把 connectors 和 skills 打包在一起,方便團隊成員一次安裝。
|
|
66
|
+
|
|
67
|
+
差異:只能看 filesystem 的 loop 是小 loop;能開 PR、連 ticket、ping channel 的 loop 才是完整的。
|
|
68
|
+
|
|
69
|
+
### 5. Sub-agents(生成與驗證分離)
|
|
70
|
+
|
|
71
|
+
Loop 裡最關鍵的結構性設計是把 maker 和 checker 分開。
|
|
72
|
+
|
|
73
|
+
- 寫程式碼的 model 對自己的作業打分數太寬容。第二個 agent 用不同指令(有時不同 model)才能抓到第一個說服自己接受的問題。
|
|
74
|
+
- `/goal` 底層也是 maker/checker 分離——用獨立的小模型判斷 loop 是否完成,而不是讓做事的 agent 自己說完成了。
|
|
75
|
+
- 常見分工:一個 explore、一個 implement、一個 verify against spec。
|
|
76
|
+
- Sub-agents 會燒更多 token,花在值得第二意見的地方。
|
|
77
|
+
|
|
78
|
+
> **職責邊界**:本段只講「為什麼 loop 需要 maker/checker 分離」這個設計決策。具體 sub-agent 的定義格式、指令撰寫、model 選擇等實作細節,請使用 `neo-sub-agent` 技能。
|
|
79
|
+
|
|
80
|
+
工具對應:
|
|
81
|
+
|
|
82
|
+
- Codex:`.codex/agents/` 下的 TOML 定義檔,每個有 name、description、instructions、optional model 和 reasoning effort。
|
|
83
|
+
- Claude Code:`.claude/agents/` 下的 subagent 定義 + agent teams。
|
|
84
|
+
|
|
85
|
+
### 6. State(外部記憶)
|
|
86
|
+
|
|
87
|
+
模型在對話之間會遺忘,進度必須寫在 repo 裡。
|
|
88
|
+
|
|
89
|
+
- 格式:markdown 檔、Linear board、或任何對話外的持久化儲存。
|
|
90
|
+
- State 是 loop 的脊椎——記住做過什麼、通過什麼、還剩什麼。
|
|
91
|
+
- 看起來太簡單不重要,但每個 long-running agent 都依賴它:agent 會忘,repo 不會。
|
|
92
|
+
|
|
93
|
+
## 原件對照表
|
|
94
|
+
|
|
95
|
+
| 原件 | Loop 中的職責 | Codex | Claude Code |
|
|
96
|
+
|:--|:--|:--|:--|
|
|
97
|
+
| Automations | 排程探索與分類 | Automations tab, `/goal` | `/loop`, `/goal`, hooks, cron, GitHub Actions |
|
|
98
|
+
| Worktrees | 隔離並行 | 內建 worktree per thread | `git worktree`, `--worktree`, `isolation: worktree` |
|
|
99
|
+
| Skills | 固化專案知識 | Agent Skills (`SKILL.md`), `$name` | Agent Skills (`SKILL.md`) |
|
|
100
|
+
| Plugins / Connectors | 外部工具整合 | Connectors (MCP) + Plugins | MCP servers + Plugins |
|
|
101
|
+
| Sub-agents | 生成與驗證分離 | `.codex/agents/` TOML | `.claude/agents/` + agent teams |
|
|
102
|
+
| State | 跨對話進度 | Markdown / Linear connector | Markdown (`AGENTS.md`, progress files) / Linear MCP |
|
|
103
|
+
|
|
104
|
+
## 範例:一個完整 loop 的流程
|
|
105
|
+
|
|
106
|
+
1. **Automation** 每天早上在 repo 上執行,prompt 呼叫 triage skill。
|
|
107
|
+
2. Triage skill 讀取昨天的 CI failures、open issues、recent commits。
|
|
108
|
+
3. 發現值得處理的 findings,寫入 **state file** 或 Linear board。
|
|
109
|
+
4. 對每個 finding,開一個隔離的 **worktree**。
|
|
110
|
+
5. 送一個 **sub-agent**(maker)進 worktree 草擬修復。
|
|
111
|
+
6. 送第二個 **sub-agent**(checker)用專案 **skills** 和現有 tests 審查草稿。
|
|
112
|
+
7. **Connectors** 開 PR、更新 ticket、CI 通過後 ping channel。
|
|
113
|
+
8. 無法處理的 finding 送到 triage inbox 給人。
|
|
114
|
+
9. **State file** 記錄什麼被嘗試了、什麼通過了、什麼還開著。
|
|
115
|
+
10. 明天早上的 run 從 state 接續。
|
|
116
|
+
|
|
117
|
+
你設計了一次,之後不再手動 prompt 任何步驟。
|
|
118
|
+
|
|
119
|
+
## Loop 三大風險
|
|
120
|
+
|
|
121
|
+
### 1. 驗證仍在你身上
|
|
122
|
+
|
|
123
|
+
Loop 無人值守時也會無人值守地犯錯。Maker/checker 分離是必要但不充分的——「done」是一個 claim,不是 proof。你的工作是 ship 你確認有效的程式碼。
|
|
124
|
+
|
|
125
|
+
### 2. 理解債(Comprehension Debt)
|
|
126
|
+
|
|
127
|
+
Loop 越快產出你沒寫的程式碼,你對系統的理解缺口越大。除非你讀 loop 產出的東西,否則理解債只會加速累積。
|
|
128
|
+
|
|
129
|
+
### 3. 認知投降(Cognitive Surrender)
|
|
130
|
+
|
|
131
|
+
當 loop 自己跑,人很容易停止有主見、照單全收。同一個 loop 設計,有判斷力的人用來加速理解深入的工作,沒有判斷力的人用來迴避理解工作本身——同一動作,相反結果。
|
|
132
|
+
|
|
133
|
+
### 風險防護策略
|
|
134
|
+
|
|
135
|
+
- 定期抽查 loop 產出,不要只看 CI 綠燈。
|
|
136
|
+
- 設定 loop 的產出量上限,避免 review backlog 失控。
|
|
137
|
+
- 在 state file 記錄人類最後審查的時間點。
|
|
138
|
+
- 高風險變更(安全、合規、產品 scope)強制跳出 loop 等人。
|
|
139
|
+
- 定期用 loop 的錯誤模式回饋改善 harness(agentic flywheel)。
|
|
140
|
+
|
|
141
|
+
## 何時適合引入 Loop vs 留在 Harness
|
|
142
|
+
|
|
143
|
+
| 條件 | 建議 |
|
|
144
|
+
|:--|:--|
|
|
145
|
+
| 專案沒有可靠的本地驗證指令 | 先建 harness |
|
|
146
|
+
| CI 不穩定或經常紅燈 | 先修 CI |
|
|
147
|
+
| 團隊對 agent 產出沒有 review 流程 | 先建 review 流程 |
|
|
148
|
+
| Maturity Level < 3 | 先升級 harness |
|
|
149
|
+
| 重複性高、風險低的任務(triage、格式修復、依賴更新) | 適合 loop |
|
|
150
|
+
| 變更涉及產品 scope、安全、架構取捨 | 不適合全自動 loop |
|
|
@@ -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.
|