@polymorphism-tech/morph-spec 4.10.6 → 4.10.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.
Files changed (149) hide show
  1. package/CLAUDE.md +3 -0
  2. package/LICENSE +71 -71
  3. package/README.md +379 -379
  4. package/bin/morph-spec.js +89 -0
  5. package/bin/task-manager.js +59 -6
  6. package/claude-plugin.json +14 -14
  7. package/docs/CHEATSHEET.md +1 -1
  8. package/docs/QUICKSTART.md +206 -206
  9. package/framework/agents/README.md +14 -14
  10. package/framework/agents/architecture/standards-architect.md +159 -159
  11. package/framework/agents/frontend/blazor-builder.md +13 -0
  12. package/framework/agents/frontend/css-specialist.md +87 -0
  13. package/framework/agents/frontend/nextjs-expert.md +13 -0
  14. package/framework/agents/frontend/nextjs-ui-specialist.md +218 -0
  15. package/framework/agents/frontend/ui-ux-designer.md +80 -10
  16. package/framework/agents/infrastructure/azure-architect.md +149 -149
  17. package/framework/agents/infrastructure/infra-architect.md +48 -48
  18. package/framework/agents.json +2268 -2567
  19. package/framework/hooks/README.md +204 -204
  20. package/framework/hooks/claude-code/post-tool-use/dispatch.js +10 -5
  21. package/framework/hooks/claude-code/session-start/inject-morph-context.js +10 -24
  22. package/framework/hooks/shared/phase-utils.js +139 -139
  23. package/framework/hooks/shared/worktree-helpers.js +30 -8
  24. package/framework/rules/csharp-standards.md +13 -13
  25. package/framework/rules/frontend-standards.md +13 -13
  26. package/framework/rules/infrastructure-standards.md +16 -16
  27. package/framework/rules/testing-standards.md +14 -14
  28. package/framework/skills/README.md +0 -1
  29. package/framework/skills/level-0-meta/morph-brainstorming/SKILL.md +12 -0
  30. package/framework/skills/level-0-meta/morph-code-review-nextjs/references/review-example-nextjs.md +254 -254
  31. package/framework/skills/level-0-meta/morph-init/SKILL.md +88 -3
  32. package/framework/skills/level-1-workflows/morph-phase-clarify/SKILL.md +247 -247
  33. package/framework/skills/level-1-workflows/morph-phase-codebase-analysis/SKILL.md +270 -270
  34. package/framework/skills/level-1-workflows/morph-phase-design/SKILL.md +515 -499
  35. package/framework/skills/level-1-workflows/morph-phase-implement/SKILL.md +508 -471
  36. package/framework/skills/level-1-workflows/morph-phase-plan/SKILL.md +12 -1
  37. package/framework/skills/level-1-workflows/morph-phase-setup/SKILL.md +272 -258
  38. package/framework/skills/level-1-workflows/morph-phase-tasks/SKILL.md +317 -311
  39. package/framework/skills/level-1-workflows/morph-phase-uiux/SKILL.md +424 -323
  40. package/framework/skills/level-1-workflows/morph-scope-escalation/SKILL.md +1 -1
  41. package/framework/standards/STANDARDS.json +2040 -2040
  42. package/framework/standards/frontend/nextjs/motion-patterns.md +321 -0
  43. package/framework/standards/frontend/nextjs/nextjs-patterns.md +17 -17
  44. package/framework/templates/README.md +814 -814
  45. package/framework/templates/code/dotnet/contracts/Commands.cs +74 -74
  46. package/framework/templates/code/dotnet/contracts/Entities.cs +25 -25
  47. package/framework/templates/code/dotnet/contracts/Queries.cs +74 -74
  48. package/framework/templates/code/dotnet/contracts/README.md +74 -74
  49. package/framework/templates/code/dotnet/contracts/api-contracts.cs +173 -173
  50. package/framework/templates/code/dotnet/frontend/component.razor +239 -239
  51. package/framework/templates/code/dotnet/jobs/agent.cs +163 -163
  52. package/framework/templates/code/dotnet/jobs/job.cs +171 -171
  53. package/framework/templates/code/dotnet/test.cs +239 -239
  54. package/framework/templates/code/sql/rls-policy.sql +57 -57
  55. package/framework/templates/code/sql/supabase-migration.sql +100 -100
  56. package/framework/templates/code/sql/supabase-migration.template.sql +113 -113
  57. package/framework/templates/code/typescript/contracts.ts +168 -168
  58. package/framework/templates/context/CONTEXT.md +181 -181
  59. package/framework/templates/context/design-system.md +211 -0
  60. package/framework/templates/docs/proposal.md +182 -182
  61. package/framework/templates/docs/user-stories.md +34 -34
  62. package/framework/templates/examples/design-system-examples.md +357 -357
  63. package/framework/templates/examples/spec-examples.md +90 -90
  64. package/framework/templates/feature/decisions.md +187 -187
  65. package/framework/templates/feature/recap.md +146 -146
  66. package/framework/templates/feature/tasks.md +199 -199
  67. package/framework/templates/infrastructure/azure/README.md +286 -286
  68. package/framework/templates/infrastructure/azure/deploy-checklist.md +426 -426
  69. package/framework/templates/infrastructure/azure/parameters.dev.json +29 -29
  70. package/framework/templates/infrastructure/azure/parameters.prod.json +29 -29
  71. package/framework/templates/infrastructure/azure/parameters.staging.json +29 -29
  72. package/framework/templates/infrastructure/docker/docker-compose.template.yml +67 -67
  73. package/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +38 -38
  74. package/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +48 -48
  75. package/framework/templates/infrastructure/docker/easypanel.template.json +54 -54
  76. package/package.json +82 -82
  77. package/src/commands/agents/agent-metrics.js +174 -0
  78. package/src/commands/agents/audit-dispatch.js +82 -0
  79. package/src/commands/agents/detect-agents.js +275 -0
  80. package/src/commands/agents/dispatch-agents.js +41 -135
  81. package/src/commands/agents/index.js +13 -4
  82. package/src/commands/agents/manage-agents.js +352 -0
  83. package/src/commands/project/doctor.js +59 -0
  84. package/src/commands/project/install-plugin-cmd.js +28 -28
  85. package/src/commands/project/setup-infra-cmd.js +12 -12
  86. package/src/commands/project/update.js +1 -17
  87. package/src/commands/project/worktree.js +58 -2
  88. package/src/commands/state/advance-phase.js +11 -3
  89. package/src/commands/tasks/index.js +4 -4
  90. package/src/commands/templates/index.js +5 -5
  91. package/src/commands/utils/index.js +3 -3
  92. package/src/commands/validation/index.js +4 -4
  93. package/src/core/state/phase-state-machine.js +217 -217
  94. package/src/core/state/state-manager.js +81 -0
  95. package/src/lib/agents/agents-manager.js +349 -0
  96. package/src/lib/agents/metrics-calculator.js +125 -0
  97. package/src/lib/agents/output-collector.js +75 -0
  98. package/src/lib/generators/context-generator.js +8 -7
  99. package/src/lib/generators/design-system-generator.js +298 -298
  100. package/src/lib/generators/index.js +10 -10
  101. package/src/lib/generators/metadata-extractor.js +387 -387
  102. package/src/lib/stack-filter.js +65 -65
  103. package/src/lib/standards/index.js +7 -7
  104. package/src/lib/standards/standards-context-injector.js +302 -302
  105. package/src/lib/tasks/task-parser.js +94 -3
  106. package/src/lib/validators/architecture/architecture-validator.js +387 -387
  107. package/src/lib/validators/architecture/index.js +7 -7
  108. package/src/lib/validators/blazor/blazor-concurrency-analyzer.js +316 -316
  109. package/src/lib/validators/blazor/blazor-state-validator.js +279 -279
  110. package/src/lib/validators/blazor/blazor-validator.js +369 -369
  111. package/src/lib/validators/blazor/index.js +9 -9
  112. package/src/lib/validators/checkpoint-persistence.js +39 -0
  113. package/src/lib/validators/content/content-validator.js +287 -279
  114. package/src/lib/validators/content/index.js +7 -7
  115. package/src/lib/validators/contracts/index.js +7 -7
  116. package/src/lib/validators/css/css-validator.js +352 -352
  117. package/src/lib/validators/css/index.js +7 -7
  118. package/src/lib/validators/design-system/design-system-validator.js +231 -231
  119. package/src/lib/validators/design-system/index.js +7 -7
  120. package/src/lib/validators/nextjs/index.js +6 -6
  121. package/src/lib/validators/nextjs/next-component-validator.js +183 -183
  122. package/src/lib/validators/packages/index.js +7 -7
  123. package/src/lib/validators/packages/package-validator.js +360 -360
  124. package/src/lib/validators/shared/index.js +12 -12
  125. package/src/lib/validators/shared/issue-counter.js +18 -18
  126. package/src/lib/validators/shared/result-formatter.js +124 -124
  127. package/src/lib/validators/spec-validator.js +2 -2
  128. package/src/lib/validators/ui/index.js +7 -7
  129. package/src/lib/validators/ui/ui-contrast-validator.js +422 -422
  130. package/src/lib/validators/validation-runner.js +20 -0
  131. package/src/scripts/global-install.js +58 -58
  132. package/src/scripts/install-plugin.js +126 -126
  133. package/src/scripts/setup-infra.js +1 -17
  134. package/src/utils/agent-id-mapper.js +11 -0
  135. package/src/utils/agents-installer.js +40 -8
  136. package/src/utils/claude-md-injector.js +90 -90
  137. package/src/utils/claude-settings-manager.js +1 -1
  138. package/src/utils/file-copier.js +200 -196
  139. package/src/utils/hooks-installer.js +556 -739
  140. package/src/utils/logger.js +32 -32
  141. package/src/utils/skills-installer.js +178 -178
  142. package/src/utils/tier-helpers.js +24 -0
  143. package/src/utils/version-checker.js +175 -175
  144. package/framework/agents/architecture/po-pm-advisor.md +0 -203
  145. package/framework/hooks/claude-code/user-prompt/set-terminal-title.js +0 -68
  146. package/framework/skills/level-1-workflows/morph-phase-implement/.morph/logs/activity.json +0 -38
  147. package/framework/skills/level-1-workflows/morph-phase-tasks/.morph/logs/activity.json +0 -14
  148. package/framework/templates/.idea/morph-templates.xml +0 -92
  149. package/framework/templates/.vscode/morph-templates.code-snippets +0 -186
@@ -1,499 +1,515 @@
1
- ---
2
- name: morph-phase-design
3
- description: MORPH-SPEC Phase 2 (Design). Schema-first interactive design: reads EF models/Supabase/DB, validates findings with user, then routes to VSA Blueprint or DDD Architecture Blueprint based on config.architecture.style, producing spec.md, contracts.cs, schema-analysis.md, and decisions.md through a quality loop (score 0-100). Use after setup phase to create technical specifications grounded in the real database schema.
4
- argument-hint: "[feature-name]"
5
- user-invocable: false
6
- allowed-tools: Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion, Agent
7
- cliVersion: "4.10.6"
8
- ---
9
-
10
- # MORPH Design — Phase 2
11
-
12
- > INTERNAL: Workflow skill used by /morph-proposal during automated phase orchestration. Not a user command.
13
-
14
- Schema-first interactive design: read the real schema, validate with user, generate blueprint, produce artifacts through a quality loop.
15
-
16
- ## Prerequisites
17
-
18
- - [ ] Phase 1 (Setup) completed
19
- - [ ] Phase 1.5 (UI/UX) completed OR skipped
20
- - [ ] Proposal approved by the user
21
-
22
- ## Recommended Tools
23
-
24
- > **Ref:** `framework/skills/level-0-meta/morph-tool-usage-guide/SKILL.md` for full guide.
25
- > **Ref:** `references/spec-example.md` — filled-in spec.md showing expected output quality.
26
- > **Ref:** `references/spec-authoring-guide.md` — section structure for spec.md.
27
-
28
- | Action | Tool | Alternative |
29
- |--------|------|-------------|
30
- | Read proposal + UI specs | **Read** output files | — |
31
- | **Detect architecture** | **Read** `.morph/config/config.json` → check `architecture.style` | **Bash** `grep` |
32
- | **Schema: Supabase** | **Supabase MCP** `list_tables()`, `get_table_schema()`, `get_relationships()` | — |
33
- | **Schema: EF Core** | **Glob** `**/Entities/**/*.cs` + **Glob** `**/*Context.cs` → **Read** | **Grep** `DbSet<` |
34
- | **Schema: Next.js/TS** | **Glob** `src/**/types/**/*.ts` + **Grep** `interface\|type.*=` | — |
35
- | Schema: RLS policies | **Supabase MCP** `query()` with `pg_policies` | **Read** policy files |
36
- | Dispatch vsa-architect | **Agent** `subagent_type=vsa-architect` + `prompt=agent.taskPrompt` | — |
37
- | Dispatch domain-architect | **Agent** `subagent_type=domain-architect` + `prompt=agent.taskPrompt` | — |
38
- | Dispatch tech leads | **Agent** for each active agent from dispatch config | — |
39
- | Research library | **Context7 MCP** `query_docs()` | **WebSearch** + **WebFetch** |
40
- | Render contracts VSA | **Bash** `npx morph-spec template render dotnet-contracts-vsa ...` | — |
41
- | Render contracts DDD | **Bash** `npx morph-spec template render dotnet-contracts-level{N} ...` | — |
42
- | Render spec.md | **Bash** `npx morph-spec template render docs/spec ...` | — |
43
- | Render decisions.md | **Bash** `npx morph-spec template render docs/decisions ...` | — |
44
- | Update state | **Bash** `npx morph-spec state mark-output $ARGUMENTS <type>` | — |
45
-
46
- **Anti-patterns:**
47
- - Do not generate contracts before reading the real schema — guessed field names corrupt the entire design
48
- - Do not present a Blueprint without validating with the user first
49
- - Do not ask questions as plain text — always use `AskUserQuestion`
50
- - Do not ignore `config.architecture.style` — always detect it before CHECKPOINT 2
51
-
52
- ---
53
-
54
- ## PRE-FLIGHT
55
-
56
- **STEP 0 (BEFORE any reads or writes) — Ensure phase is design:**
57
-
58
- ```bash
59
- npx morph-spec state get $ARGUMENTS
60
- ```
61
-
62
- Check the `"phase"` field in the output:
63
-
64
- **If `"phase": "design"`** → phase is correct, proceed.
65
-
66
- **If `"phase": "proposal"`** → execute in sequence:
67
- 1. `npx morph-spec state mark-output $ARGUMENTS proposal`
68
- 2. `npx morph-spec phase advance $ARGUMENTS` (→ setup)
69
- 3. `npx morph-spec phase advance $ARGUMENTS` (→ design)
70
-
71
- **If `"phase": "setup"`** → execute:
72
- 1. `npx morph-spec phase advance $ARGUMENTS` (→ design)
73
-
74
- **Any other value** → do not proceed — inconsistent state, report to user.
75
-
76
- > **Rule:** Never write to `1-design/` while the phase is not `design`. The hook will block and the sequence will be corrupted.
77
-
78
- ---
79
-
80
- Read in parallel:
81
- ```
82
- Read: .morph/features/$ARGUMENTS/0-proposal/proposal.md
83
- + Read: .morph/config/config.json ← detect architecture.style
84
- + Read: .morph/context/README.md
85
- ```
86
-
87
- **Detect architecture style:**
88
-
89
- | Value of `config.architecture.style` | Path |
90
- |--------------------------------------|------|
91
- | `"vertical-slice"` | → **VSA** (CHECKPOINT 2-VSA + VSA contracts) |
92
- | any other value or absent | → **DDD** (CHECKPOINT 2-DDD + DDD contracts) |
93
-
94
- If scope ≥ 20 tasks or refactor touches ≥ 5 domain files → **EnterPlanMode** before continuing.
95
-
96
- ---
97
-
98
- ## CHECKPOINT 1 — Real Schema (MANDATORY before any generation)
99
-
100
- > **Rule:** Never assume field names. Every generated DTO must have a traceable origin in the schema.
101
-
102
- ### 1.1 Read real schema
103
-
104
- Execute in parallel according to the stack detected in `config.json`:
105
-
106
- **Supabase (preferred if available):**
107
- ```
108
- Supabase MCP: list_tables() → get_table_schema(table) for each relevant table
109
- + get_relationships() → RLS policies if applicable
110
- ```
111
-
112
- **EF Core (.NET):**
113
- ```
114
- Glob: **/Entities/**/*.cs → Read each entity file
115
- Glob: **/*DbContext.cs → Read to see DbSet<> and relations
116
- Grep: "DbSet<" → confirm mapped entities
117
- ```
118
-
119
- **TypeScript/Next.js:**
120
- ```
121
- Glob: src/**/types/**/*.ts, src/**/models/**/*.ts
122
- Grep: "export interface|export type" → Read found files
123
- ```
124
-
125
- ### 1.2 Generate schema-analysis.md
126
-
127
- Write `.morph/features/$ARGUMENTS/1-design/schema-analysis.md` with:
128
-
129
- ```markdown
130
- # Schema Analysis — {Feature}
131
-
132
- ## Relevant Entities
133
-
134
- ### {EntityName}
135
- | Field | DB Type | C#/TS Type | Nullable | Notes |
136
- |-------|---------|-----------|----------|-------|
137
- | id | uuid | Guid | No | PK |
138
- | ... | ... | ... | ... | ... |
139
-
140
- ## Relationships
141
- - {Entity A} 1—N {Entity B} via {FK field}
142
-
143
- ## JSONB / Complex Fields
144
- - {field}: internal structure {known keys}
145
-
146
- ## Fields Not Referenced in Proposal
147
- - {field}: present in schema but no reference in the proposal
148
- ```
149
-
150
- ### 1.3 Validate with user
151
-
152
- Use `AskUserQuestion`:
153
-
154
- ```json
155
- {
156
- "questions": [{
157
- "header": "Schema OK?",
158
- "question": "Found these entities and fields in the schema. Are they correct before generating contracts?",
159
- "multiSelect": false,
160
- "options": [
161
- { "label": "Confirm and continue", "description": "Schema mapped correctly" },
162
- { "label": "I have corrections", "description": "Use Other to describe what's wrong" }
163
- ]
164
- }]
165
- }
166
- ```
167
-
168
- - **"Confirm"** → proceed to Checkpoint 2
169
- - **"I have corrections" / Other** → apply corrections to schema-analysis.md and repeat 1.3
170
-
171
- ---
172
-
173
- ## CHECKPOINT 2 — Architecture Blueprint (MANDATORY before generating contracts)
174
-
175
- > Use the path corresponding to the style detected in PRE-FLIGHT.
176
-
177
- ---
178
-
179
- ### CHECKPOINT 2-VSA — Vertical Slice Architecture
180
-
181
- #### 2-VSA.1 Dispatch vsa-architect
182
-
183
- ```bash
184
- npx morph-spec dispatch-agents $ARGUMENTS design
185
- ```
186
-
187
- Use the `taskPrompt` from the `vsa-architect` agent in the result. Call:
188
-
189
- ```
190
- Agent(subagent_type=vsa-architect, prompt=<taskPrompt + contents of proposal.md + schema-analysis.md>)
191
- ```
192
-
193
- The agent produces a VSA Blueprint with:
194
- - Entity fields (based on the schema validated in Checkpoint 1)
195
- - Operations (GetAll, GetById, Create, Update, Delete + custom)
196
- - Routes (`GET /api/{feature}s`, `POST /api/{feature}s`, etc.)
197
- - Error types (`{Entity}Errors.NotFound`, `{Entity}Errors.AlreadyExists`, etc.)
198
- - Validation rules per field
199
-
200
- **Parallelize** with other active agents from the dispatch config.
201
-
202
- #### 2-VSA.2 Validate Blueprint with user
203
-
204
- Present the generated blueprint in a readable format and use `AskUserQuestion`:
205
-
206
- ```json
207
- {
208
- "questions": [{
209
- "header": "Blueprint OK?",
210
- "question": "Planned these slices and operations for the feature. Confirm before generating spec and contracts?",
211
- "multiSelect": false,
212
- "options": [
213
- { "label": "Confirm blueprint", "description": "Generate spec.md and contracts with this blueprint" },
214
- { "label": "Need adjustments", "description": "Use Other to describe what to change" }
215
- ]
216
- }]
217
- }
218
- ```
219
-
220
- - **"Confirm"** → proceed to VSA generation
221
- - **"Need adjustments" / Other** → update blueprint and repeat 2-VSA.2
222
-
223
- ---
224
-
225
- ### CHECKPOINT 2-DDD — Domain-Driven Design
226
-
227
- #### 2-DDD.1 Determine Complexity Level
228
-
229
- Read the proposal and evaluate using the 5 detection questions in `framework/standards/architecture/ddd/complexity-levels.md`:
230
-
231
- | Level | When to use |
232
- |-------|-------------|
233
- | **Level 1 (CRUD)** | Simple entities, no complex business rules, basic CRUD |
234
- | **Level 2 (Business Logic)** | Domain invariants, business workflows, multiple related entities |
235
- | **Level 3 (Bounded Context)** | Context isolation, integration events, distributed systems |
236
-
237
- > If uncertain, assume Level 1 and use `AskUserQuestion` to confirm.
238
-
239
- #### 2-DDD.2 Dispatch domain-architect
240
-
241
- ```bash
242
- npx morph-spec dispatch-agents $ARGUMENTS design
243
- ```
244
-
245
- Use the `taskPrompt` from the `domain-architect` agent in the result. Call:
246
-
247
- ```
248
- Agent(subagent_type=domain-architect, prompt=<taskPrompt + contents of proposal.md + schema-analysis.md + detected level>)
249
- ```
250
-
251
- The agent produces an Architecture Blueprint with:
252
- - **Level 1:** Entities, repositories, services, DTOs
253
- - **Level 2:** AggregateRoot, Value Objects, Domain Events, CQRS handlers
254
- - **Level 3:** BC setup, Integration Events, Anti-corruption layer
255
-
256
- **Parallelize** with other active agents from the dispatch config.
257
-
258
- #### 2-DDD.3 Validate Blueprint with user
259
-
260
- Present the generated blueprint in a readable format and use `AskUserQuestion`:
261
-
262
- ```json
263
- {
264
- "questions": [{
265
- "header": "Blueprint OK?",
266
- "question": "Planned this domain architecture for the feature. Confirm before generating spec and contracts?",
267
- "multiSelect": false,
268
- "options": [
269
- { "label": "Confirm blueprint", "description": "Generate spec.md and contracts with this blueprint" },
270
- { "label": "Need adjustments", "description": "Use Other to describe what to change" }
271
- ]
272
- }]
273
- }
274
- ```
275
-
276
- - **"Confirm"** → proceed to DDD generation
277
- - **"Need adjustments" / Other** → update blueprint and repeat 2-DDD.3
278
-
279
- ---
280
-
281
- ## Artifact Generation
282
-
283
- With schema validated (Checkpoint 1) and blueprint confirmed (Checkpoint 2):
284
-
285
- ### Generate spec.md
286
-
287
- > Detailed structure: `references/spec-authoring-guide.md`
288
-
289
- Read the spec-authoring-guide first, then create `.morph/features/$ARGUMENTS/1-design/spec.md` with:
290
- - Overview, Functional Requirements (FR001...) with measurable acceptance criteria
291
- - Non-Functional Requirements, Data Model
292
- - **VSA:** section `## Architecture Style: Vertical Slice` with slices and operations
293
- - **DDD:** section `## Domain Complexity` with level (1/2/3) and justification
294
- - Infrastructure Requirements (if applicable)
295
-
296
- ### Generate contracts — VSA
297
-
298
- **Mandatory source:** fields from `schema-analysis.md` + operations from the VSA Blueprint.
299
-
300
- ```bash
301
- npx morph-spec template render \
302
- dotnet-contracts-vsa \
303
- .morph/features/$ARGUMENTS/1-design/contracts.cs \
304
- '{
305
- "FEATURE_NAME": "$ARGUMENTS",
306
- "NAMESPACE": "{ProjectNamespace}",
307
- "ROUTE": "/api/{kebabCase FEATURE_NAME}s",
308
- "DATE": "{{TODAY}}"
309
- }'
310
- ```
311
-
312
- After rendering, fill in the `// placeholder:` sections with real fields from schema-analysis.md.
313
-
314
- **Mandatory VSA patterns:**
315
- - `sealed` on handlers, endpoints, validators, records
316
- - `Guid.CreateVersion7()` for IDs
317
- - `result.Match()` in endpoints
318
- - `{Entity}Errors` static shared across all slices
319
- - CancellationToken in all async methods
320
-
321
- ### Generate contracts — DDD
322
-
323
- **Mandatory source:** fields from `schema-analysis.md` + components from the DDD Blueprint.
324
-
325
- ```bash
326
- # Replace {N} with the detected level (1, 2, or 3):
327
- npx morph-spec template render \
328
- dotnet-contracts-level{N} \
329
- .morph/features/$ARGUMENTS/1-design/contracts.cs \
330
- '{
331
- "FEATURE_NAME": "$ARGUMENTS",
332
- "NAMESPACE": "{ProjectNamespace}",
333
- "DATE": "{{TODAY}}"
334
- }'
335
- ```
336
-
337
- After rendering, fill in the `// placeholder:` sections with real fields from schema-analysis.md.
338
-
339
- **Mandatory DDD patterns:**
340
- - Level 1: repository interfaces + service with mapped methods
341
- - Level 2: AggregateRoot with invariants + immutable Value Objects + Domain Events
342
- - Level 3: adds Integration Events + Bounded Context boundary
343
-
344
- ### Stack adaptation for contracts
345
-
346
- For TypeScript/Next.js projects, generate `contracts.ts` instead of `contracts.cs`. Use TypeScript interfaces with the same DDD/VSA patterns adapted to the language (e.g., `readonly` fields for Value Objects, union types for status enums, typed event interfaces for Domain Events).
347
-
348
- ### Generate decisions.md
349
-
350
- ```bash
351
- npx morph-spec template render docs/decisions \
352
- .morph/features/$ARGUMENTS/1-design/decisions.md \
353
- '{"FEATURE_NAME": "$ARGUMENTS", "DATE": "{{TODAY}}", "decisions": []}'
354
- ```
355
-
356
- Mandatory ADRs: architecture choice (VSA vs DDD + justification), UI library (if UI/UX phase ran), external integrations, Azure resources with cost estimates.
357
-
358
- ---
359
-
360
- ## Quality Scoring System
361
-
362
- After generating artifacts, evaluate the design with the **Quality Score (0–100)**:
363
-
364
- | Dimension | Pts | Maximum score criteria |
365
- |-----------|-----|----------------------|
366
- | **Schema fidelity** | 25 | All fields in contracts have traceable origin in schema-analysis.md — zero guessed |
367
- | **Functional coverage** | 20 | All FRs from the proposal are in spec with measurable acceptance criteria |
368
- | **Blueprint complete** | 20 | **VSA:** all slices have handler, validator (except GetAll), endpoint and errors \| **DDD:** all entities/aggregates/services have components for the detected level |
369
- | **External integrations** | 20 | APIs/services with payload, error format and retry policy documented |
370
- | **Infra / costs** | 15 | Azure resources estimated with cost, or "N/A" explicitly documented |
371
-
372
- **Thresholds:**
373
-
374
- | Score | Action |
375
- |-------|--------|
376
- | ≥ 85 | Design satisfactory. Offer to close or optionally refine |
377
- | 70–84 | Continue. Focus on the weakest dimensions |
378
- | < 70 | Continue. Open technical questions block implementation |
379
-
380
- ---
381
-
382
- ## Quality Loop
383
-
384
- **Repeat until: score ≥ 85 OR user approves.**
385
-
386
- ### A. Calculate score
387
-
388
- Score each dimension based on the generated artifacts. Identify the most impactful gaps.
389
-
390
- ### B. Identify open questions
391
-
392
- Typical questions by dimension:
393
-
394
- | Weak dimension | Example questions |
395
- |----------------|-------------------|
396
- | Schema fidelity | "The `metadata` field (JSONB) — what is its structure? Which keys?" |
397
- | Functional coverage | "FR003 says 'notify user' — by email, push, or both?" |
398
- | Blueprint VSA | "Should the CreateOrder slice trigger an email job or is it synchronous?" |
399
- | Blueprint DDD | "Should `Place()` on OrderAggregate emit `OrderPlacedEvent`?" |
400
- | Integrations | "Does the payment API use webhook or polling to confirm?" |
401
- | Infra/costs | "Does this feature need Azure storage? Which tier?" |
402
-
403
- ### C. Ask via AskUserQuestion
404
-
405
- Maximum 3 technical questions per call. In the last call of each round, always include:
406
-
407
- ```json
408
- {
409
- "header": "Continue?",
410
- "question": "Continue refining or finalize the design?",
411
- "multiSelect": false,
412
- "options": [
413
- { "label": "Continue refining", "description": "More open questions identified" },
414
- { "label": "Finalize design", "description": "Proceed to Clarify with current design" }
415
- ]
416
- }
417
- ```
418
-
419
- > If score ≥ 85, adjust: `"Continue (optional)"` with description `"Score {N}/100 — design is satisfactory"`
420
-
421
- ### D. Incorporate answers
422
-
423
- Update spec.md, contracts, and decisions.md with the answers received. Recalculate the score.
424
-
425
- ### E. Exit condition
426
-
427
- - User chose **"Finalize design"** → exit loop
428
- - Score ≥ 85 AND no new questions → exit loop
429
-
430
- ---
431
-
432
- ## Post-Loop: Update State
433
-
434
- ```bash
435
- npx morph-spec state mark-output $ARGUMENTS schema-analysis
436
- npx morph-spec state mark-output $ARGUMENTS spec
437
- npx morph-spec state mark-output $ARGUMENTS contracts
438
- npx morph-spec state mark-output $ARGUMENTS decisions
439
- ```
440
-
441
- If Azure costs were estimated:
442
- ```bash
443
- npx morph-spec state set $ARGUMENTS costs.estimated {X.XX}
444
- ```
445
-
446
- ## MANDATORY PAUSE
447
-
448
- ```json
449
- {
450
- "questions": [{
451
- "header": "Approval",
452
- "question": "Design generated. Approve to continue to Clarify?",
453
- "multiSelect": false,
454
- "options": [
455
- { "label": "Approve and continue", "description": "Advance to Clarify phase" },
456
- { "label": "I have feedback", "description": "Describe what to change (Other)" }
457
- ]
458
- }]
459
- }
460
- ```
461
-
462
- - **"Approve and continue"** →
463
- ```bash
464
- npx morph-spec approve $ARGUMENTS design
465
- npx morph-spec phase advance $ARGUMENTS
466
- ```
467
- - **"I have feedback" / Other** → apply feedback and repeat PAUSE
468
-
469
- ## Generated Outputs
470
-
471
- - `.morph/features/$ARGUMENTS/1-design/schema-analysis.md` — Real schema mapped and validated
472
- - `.morph/features/$ARGUMENTS/1-design/spec.md` — Complete technical specification
473
- - `.morph/features/$ARGUMENTS/1-design/contracts.cs` (or `.ts` for TypeScript projects) — Contracts based on real schema (VSA or DDD)
474
- - `.morph/features/$ARGUMENTS/1-design/decisions.md` — Documented ADRs
475
-
476
- ## Advancement Criteria
477
-
478
- - [x] Architecture style detected from `config.architecture.style`
479
- - [x] Schema validated by user (Checkpoint 1)
480
- - [x] Blueprint confirmed by user (Checkpoint 2-VSA or 2-DDD)
481
- - [x] Quality score ≥ 85 OR user finalized
482
- - [x] All field names in contracts traceable to schema-analysis.md
483
- - [x] State updated
484
- - [x] User approved at MANDATORY PAUSE
485
-
486
- ---
487
-
488
- <!-- morph-outputs:design -->
489
- | Output | Path |
490
- |--------|------|
491
- | `schemaAnalysis` | `.morph/features/{feature}/1-design/schema-analysis.md` |
492
- | `spec` | `.morph/features/{feature}/1-design/spec.md` |
493
- | `contracts` | `.morph/features/{feature}/1-design/contracts.cs` |
494
- | `contractsTs` | `.morph/features/{feature}/1-design/contracts.ts` |
495
- | `contractsVsa` | `.morph/features/{feature}/1-design/contracts-vsa.cs` |
496
- | `decisions` | `.morph/features/{feature}/1-design/decisions.md` |
497
- <!-- /morph-outputs -->
498
-
499
- Continue automatically to Phase 3 (Clarify) after approval.
1
+ ---
2
+ name: morph-phase-design
3
+ description: MORPH-SPEC Phase 2 (Design). Schema-first interactive design: reads EF models/Supabase/DB, validates findings with user, then routes to VSA Blueprint or DDD Architecture Blueprint based on config.architecture.style, producing spec.md, contracts.cs, schema-analysis.md, and decisions.md through a quality loop (score 0-100). Use after setup phase to create technical specifications grounded in the real database schema.
4
+ argument-hint: "[feature-name]"
5
+ user-invocable: false
6
+ allowed-tools: Read, Write, Edit, Bash, Glob, Grep, AskUserQuestion, Agent
7
+ cliVersion: "4.10.8"
8
+ ---
9
+
10
+ # MORPH Design — Phase 2
11
+
12
+ > INTERNAL: Workflow skill used by /morph-proposal during automated phase orchestration. Not a user command.
13
+
14
+ Schema-first interactive design: read the real schema, validate with user, generate blueprint, produce artifacts through a quality loop.
15
+
16
+ ## Prerequisites
17
+
18
+ - [ ] Phase 1 (Setup) completed
19
+ - [ ] Phase 1.5 (UI/UX) completed OR skipped
20
+ - [ ] Proposal approved by the user
21
+
22
+ ## Recommended Tools
23
+
24
+ > **Ref:** `framework/skills/level-0-meta/morph-tool-usage-guide/SKILL.md` for full guide.
25
+ > **Ref:** `references/spec-example.md` — filled-in spec.md showing expected output quality.
26
+ > **Ref:** `references/spec-authoring-guide.md` — section structure for spec.md.
27
+
28
+ | Action | Tool | Alternative |
29
+ |--------|------|-------------|
30
+ | Read proposal + UI specs | **Read** output files | — |
31
+ | **Detect architecture** | **Read** `.morph/config/config.json` → check `architecture.style` | **Bash** `grep` |
32
+ | **Schema: Supabase** | **Supabase MCP** `list_tables()`, `get_table_schema()`, `get_relationships()` | — |
33
+ | **Schema: EF Core** | **Glob** `**/Entities/**/*.cs` + **Glob** `**/*Context.cs` → **Read** | **Grep** `DbSet<` |
34
+ | **Schema: Next.js/TS** | **Glob** `src/**/types/**/*.ts` + **Grep** `interface\|type.*=` | — |
35
+ | Schema: RLS policies | **Supabase MCP** `query()` with `pg_policies` | **Read** policy files |
36
+ | Dispatch vsa-architect | **Agent** `subagent_type=vsa-architect` + `prompt=agent.taskPrompt` | — |
37
+ | Dispatch domain-architect | **Agent** `subagent_type=domain-architect` + `prompt=agent.taskPrompt` | — |
38
+ | Dispatch tech leads | **Agent** for each active agent from dispatch config | — |
39
+ | Research library | **Context7 MCP** `query_docs()` | **WebSearch** + **WebFetch** |
40
+ | Render contracts VSA | **Bash** `npx morph-spec template render dotnet-contracts-vsa ...` | — |
41
+ | Render contracts DDD | **Bash** `npx morph-spec template render dotnet-contracts-level{N} ...` | — |
42
+ | Render spec.md | **Bash** `npx morph-spec template render docs/spec ...` | — |
43
+ | Render decisions.md | **Bash** `npx morph-spec template render docs/decisions ...` | — |
44
+ | Update state | **Bash** `npx morph-spec state mark-output $ARGUMENTS <type>` | — |
45
+
46
+ **Anti-patterns:**
47
+ - Do not generate contracts before reading the real schema — guessed field names corrupt the entire design
48
+ - Do not present a Blueprint without validating with the user first
49
+ - Do not ask questions as plain text — always use `AskUserQuestion`
50
+ - Do not ignore `config.architecture.style` — always detect it before CHECKPOINT 2
51
+
52
+ ---
53
+
54
+ ## PRE-FLIGHT
55
+
56
+ ### Create session tasks for visibility
57
+
58
+ ```
59
+ TaskCreate: "Pre-flight validation" → activeForm: "Validating pre-flight"
60
+ TaskCreate: "Schema analysis" → activeForm: "Analyzing schema"
61
+ TaskCreate: "Architecture blueprint" → activeForm: "Designing architecture"
62
+ TaskCreate: "Generate spec.md" → activeForm: "Writing spec"
63
+ TaskCreate: "Generate contracts" → activeForm: "Writing contracts"
64
+ TaskCreate: "Generate decisions.md" → activeForm: "Documenting decisions"
65
+ TaskCreate: "Design approval" → activeForm: "Awaiting design approval"
66
+ ```
67
+
68
+ Update each to `in_progress` before starting and `completed` after finishing.
69
+
70
+ ---
71
+
72
+ **STEP 0 (BEFORE any reads or writes) — Ensure phase is design:**
73
+
74
+ ```bash
75
+ npx morph-spec state get $ARGUMENTS
76
+ ```
77
+
78
+ Check the `"phase"` field in the output:
79
+
80
+ **If `"phase": "design"`** → phase is correct, proceed.
81
+
82
+ **If `"phase": "proposal"`** → execute in sequence:
83
+ 1. `npx morph-spec state mark-output $ARGUMENTS proposal`
84
+ 2. `npx morph-spec phase advance $ARGUMENTS` (→ setup)
85
+ 3. `npx morph-spec phase advance $ARGUMENTS` (→ design)
86
+
87
+ **If `"phase": "setup"`** → execute:
88
+ 1. `npx morph-spec phase advance $ARGUMENTS` (→ design)
89
+
90
+ **Any other value** → do not proceed — inconsistent state, report to user.
91
+
92
+ > **Rule:** Never write to `1-design/` while the phase is not `design`. The hook will block and the sequence will be corrupted.
93
+
94
+ ---
95
+
96
+ Read in parallel:
97
+ ```
98
+ Read: .morph/features/$ARGUMENTS/0-proposal/proposal.md
99
+ + Read: .morph/config/config.json ← detect architecture.style
100
+ + Read: .morph/context/README.md
101
+ ```
102
+
103
+ **Detect architecture style:**
104
+
105
+ | Value of `config.architecture.style` | Path |
106
+ |--------------------------------------|------|
107
+ | `"vertical-slice"` | → **VSA** (CHECKPOINT 2-VSA + VSA contracts) |
108
+ | any other value or absent | → **DDD** (CHECKPOINT 2-DDD + DDD contracts) |
109
+
110
+ If scope ≥ 20 tasks or refactor touches ≥ 5 domain files → **EnterPlanMode** before continuing.
111
+
112
+ ---
113
+
114
+ ## CHECKPOINT 1 — Real Schema (MANDATORY before any generation)
115
+
116
+ > **Rule:** Never assume field names. Every generated DTO must have a traceable origin in the schema.
117
+
118
+ ### 1.1 Read real schema
119
+
120
+ Execute in parallel according to the stack detected in `config.json`:
121
+
122
+ **Supabase (preferred if available):**
123
+ ```
124
+ Supabase MCP: list_tables() → get_table_schema(table) for each relevant table
125
+ + get_relationships() → RLS policies if applicable
126
+ ```
127
+
128
+ **EF Core (.NET):**
129
+ ```
130
+ Glob: **/Entities/**/*.cs → Read each entity file
131
+ Glob: **/*DbContext.cs → Read to see DbSet<> and relations
132
+ Grep: "DbSet<" → confirm mapped entities
133
+ ```
134
+
135
+ **TypeScript/Next.js:**
136
+ ```
137
+ Glob: src/**/types/**/*.ts, src/**/models/**/*.ts
138
+ Grep: "export interface|export type" → Read found files
139
+ ```
140
+
141
+ ### 1.2 Generate schema-analysis.md
142
+
143
+ Write `.morph/features/$ARGUMENTS/1-design/schema-analysis.md` with:
144
+
145
+ ```markdown
146
+ # Schema Analysis — {Feature}
147
+
148
+ ## Relevant Entities
149
+
150
+ ### {EntityName}
151
+ | Field | DB Type | C#/TS Type | Nullable | Notes |
152
+ |-------|---------|-----------|----------|-------|
153
+ | id | uuid | Guid | No | PK |
154
+ | ... | ... | ... | ... | ... |
155
+
156
+ ## Relationships
157
+ - {Entity A} 1—N {Entity B} via {FK field}
158
+
159
+ ## JSONB / Complex Fields
160
+ - {field}: internal structure {known keys}
161
+
162
+ ## Fields Not Referenced in Proposal
163
+ - {field}: present in schema but no reference in the proposal
164
+ ```
165
+
166
+ ### 1.3 Validate with user
167
+
168
+ Use `AskUserQuestion`:
169
+
170
+ ```json
171
+ {
172
+ "questions": [{
173
+ "header": "Schema OK?",
174
+ "question": "Found these entities and fields in the schema. Are they correct before generating contracts?",
175
+ "multiSelect": false,
176
+ "options": [
177
+ { "label": "Confirm and continue", "description": "Schema mapped correctly" },
178
+ { "label": "I have corrections", "description": "Use Other to describe what's wrong" }
179
+ ]
180
+ }]
181
+ }
182
+ ```
183
+
184
+ - **"Confirm"** → proceed to Checkpoint 2
185
+ - **"I have corrections" / Other** → apply corrections to schema-analysis.md and repeat 1.3
186
+
187
+ ---
188
+
189
+ ## CHECKPOINT 2 — Architecture Blueprint (MANDATORY before generating contracts)
190
+
191
+ > Use the path corresponding to the style detected in PRE-FLIGHT.
192
+
193
+ ---
194
+
195
+ ### CHECKPOINT 2-VSA — Vertical Slice Architecture
196
+
197
+ #### 2-VSA.1 Dispatch vsa-architect
198
+
199
+ ```bash
200
+ npx morph-spec dispatch-agents $ARGUMENTS design
201
+ ```
202
+
203
+ Use the `taskPrompt` from the `vsa-architect` agent in the result. Call:
204
+
205
+ ```
206
+ Agent(subagent_type=vsa-architect, prompt=<taskPrompt + contents of proposal.md + schema-analysis.md>)
207
+ ```
208
+
209
+ The agent produces a VSA Blueprint with:
210
+ - Entity fields (based on the schema validated in Checkpoint 1)
211
+ - Operations (GetAll, GetById, Create, Update, Delete + custom)
212
+ - Routes (`GET /api/{feature}s`, `POST /api/{feature}s`, etc.)
213
+ - Error types (`{Entity}Errors.NotFound`, `{Entity}Errors.AlreadyExists`, etc.)
214
+ - Validation rules per field
215
+
216
+ **Parallelize** with other active agents from the dispatch config.
217
+
218
+ #### 2-VSA.2 Validate Blueprint with user
219
+
220
+ Present the generated blueprint in a readable format and use `AskUserQuestion`:
221
+
222
+ ```json
223
+ {
224
+ "questions": [{
225
+ "header": "Blueprint OK?",
226
+ "question": "Planned these slices and operations for the feature. Confirm before generating spec and contracts?",
227
+ "multiSelect": false,
228
+ "options": [
229
+ { "label": "Confirm blueprint", "description": "Generate spec.md and contracts with this blueprint" },
230
+ { "label": "Need adjustments", "description": "Use Other to describe what to change" }
231
+ ]
232
+ }]
233
+ }
234
+ ```
235
+
236
+ - **"Confirm"** → proceed to VSA generation
237
+ - **"Need adjustments" / Other** → update blueprint and repeat 2-VSA.2
238
+
239
+ ---
240
+
241
+ ### CHECKPOINT 2-DDD — Domain-Driven Design
242
+
243
+ #### 2-DDD.1 Determine Complexity Level
244
+
245
+ Read the proposal and evaluate using the 5 detection questions in `framework/standards/architecture/ddd/complexity-levels.md`:
246
+
247
+ | Level | When to use |
248
+ |-------|-------------|
249
+ | **Level 1 (CRUD)** | Simple entities, no complex business rules, basic CRUD |
250
+ | **Level 2 (Business Logic)** | Domain invariants, business workflows, multiple related entities |
251
+ | **Level 3 (Bounded Context)** | Context isolation, integration events, distributed systems |
252
+
253
+ > If uncertain, assume Level 1 and use `AskUserQuestion` to confirm.
254
+
255
+ #### 2-DDD.2 Dispatch domain-architect
256
+
257
+ ```bash
258
+ npx morph-spec dispatch-agents $ARGUMENTS design
259
+ ```
260
+
261
+ Use the `taskPrompt` from the `domain-architect` agent in the result. Call:
262
+
263
+ ```
264
+ Agent(subagent_type=domain-architect, prompt=<taskPrompt + contents of proposal.md + schema-analysis.md + detected level>)
265
+ ```
266
+
267
+ The agent produces an Architecture Blueprint with:
268
+ - **Level 1:** Entities, repositories, services, DTOs
269
+ - **Level 2:** AggregateRoot, Value Objects, Domain Events, CQRS handlers
270
+ - **Level 3:** BC setup, Integration Events, Anti-corruption layer
271
+
272
+ **Parallelize** with other active agents from the dispatch config.
273
+
274
+ #### 2-DDD.3 Validate Blueprint with user
275
+
276
+ Present the generated blueprint in a readable format and use `AskUserQuestion`:
277
+
278
+ ```json
279
+ {
280
+ "questions": [{
281
+ "header": "Blueprint OK?",
282
+ "question": "Planned this domain architecture for the feature. Confirm before generating spec and contracts?",
283
+ "multiSelect": false,
284
+ "options": [
285
+ { "label": "Confirm blueprint", "description": "Generate spec.md and contracts with this blueprint" },
286
+ { "label": "Need adjustments", "description": "Use Other to describe what to change" }
287
+ ]
288
+ }]
289
+ }
290
+ ```
291
+
292
+ - **"Confirm"** → proceed to DDD generation
293
+ - **"Need adjustments" / Other** → update blueprint and repeat 2-DDD.3
294
+
295
+ ---
296
+
297
+ ## Artifact Generation
298
+
299
+ With schema validated (Checkpoint 1) and blueprint confirmed (Checkpoint 2):
300
+
301
+ ### Generate spec.md
302
+
303
+ > Detailed structure: `references/spec-authoring-guide.md`
304
+
305
+ Read the spec-authoring-guide first, then create `.morph/features/$ARGUMENTS/1-design/spec.md` with:
306
+ - Overview, Functional Requirements (FR001...) with measurable acceptance criteria
307
+ - Non-Functional Requirements, Data Model
308
+ - **VSA:** section `## Architecture Style: Vertical Slice` with slices and operations
309
+ - **DDD:** section `## Domain Complexity` with level (1/2/3) and justification
310
+ - Infrastructure Requirements (if applicable)
311
+
312
+ ### Generate contracts — VSA
313
+
314
+ **Mandatory source:** fields from `schema-analysis.md` + operations from the VSA Blueprint.
315
+
316
+ ```bash
317
+ npx morph-spec template render \
318
+ dotnet-contracts-vsa \
319
+ .morph/features/$ARGUMENTS/1-design/contracts.cs \
320
+ '{
321
+ "FEATURE_NAME": "$ARGUMENTS",
322
+ "NAMESPACE": "{ProjectNamespace}",
323
+ "ROUTE": "/api/{kebabCase FEATURE_NAME}s",
324
+ "DATE": "{{TODAY}}"
325
+ }'
326
+ ```
327
+
328
+ After rendering, fill in the `// placeholder:` sections with real fields from schema-analysis.md.
329
+
330
+ **Mandatory VSA patterns:**
331
+ - `sealed` on handlers, endpoints, validators, records
332
+ - `Guid.CreateVersion7()` for IDs
333
+ - `result.Match()` in endpoints
334
+ - `{Entity}Errors` static shared across all slices
335
+ - CancellationToken in all async methods
336
+
337
+ ### Generate contracts — DDD
338
+
339
+ **Mandatory source:** fields from `schema-analysis.md` + components from the DDD Blueprint.
340
+
341
+ ```bash
342
+ # Replace {N} with the detected level (1, 2, or 3):
343
+ npx morph-spec template render \
344
+ dotnet-contracts-level{N} \
345
+ .morph/features/$ARGUMENTS/1-design/contracts.cs \
346
+ '{
347
+ "FEATURE_NAME": "$ARGUMENTS",
348
+ "NAMESPACE": "{ProjectNamespace}",
349
+ "DATE": "{{TODAY}}"
350
+ }'
351
+ ```
352
+
353
+ After rendering, fill in the `// placeholder:` sections with real fields from schema-analysis.md.
354
+
355
+ **Mandatory DDD patterns:**
356
+ - Level 1: repository interfaces + service with mapped methods
357
+ - Level 2: AggregateRoot with invariants + immutable Value Objects + Domain Events
358
+ - Level 3: adds Integration Events + Bounded Context boundary
359
+
360
+ ### Stack adaptation for contracts
361
+
362
+ For TypeScript/Next.js projects, generate `contracts.ts` instead of `contracts.cs`. Use TypeScript interfaces with the same DDD/VSA patterns adapted to the language (e.g., `readonly` fields for Value Objects, union types for status enums, typed event interfaces for Domain Events).
363
+
364
+ ### Generate decisions.md
365
+
366
+ ```bash
367
+ npx morph-spec template render docs/decisions \
368
+ .morph/features/$ARGUMENTS/1-design/decisions.md \
369
+ '{"FEATURE_NAME": "$ARGUMENTS", "DATE": "{{TODAY}}", "decisions": []}'
370
+ ```
371
+
372
+ Mandatory ADRs: architecture choice (VSA vs DDD + justification), UI library (if UI/UX phase ran), external integrations, Azure resources with cost estimates.
373
+
374
+ ---
375
+
376
+ ## Quality Scoring System
377
+
378
+ After generating artifacts, evaluate the design with the **Quality Score (0–100)**:
379
+
380
+ | Dimension | Pts | Maximum score criteria |
381
+ |-----------|-----|----------------------|
382
+ | **Schema fidelity** | 25 | All fields in contracts have traceable origin in schema-analysis.md — zero guessed |
383
+ | **Functional coverage** | 20 | All FRs from the proposal are in spec with measurable acceptance criteria |
384
+ | **Blueprint complete** | 20 | **VSA:** all slices have handler, validator (except GetAll), endpoint and errors \| **DDD:** all entities/aggregates/services have components for the detected level |
385
+ | **External integrations** | 20 | APIs/services with payload, error format and retry policy documented |
386
+ | **Infra / costs** | 15 | Azure resources estimated with cost, or "N/A" explicitly documented |
387
+
388
+ **Thresholds:**
389
+
390
+ | Score | Action |
391
+ |-------|--------|
392
+ | ≥ 85 | Design satisfactory. Offer to close or optionally refine |
393
+ | 70–84 | Continue. Focus on the weakest dimensions |
394
+ | < 70 | Continue. Open technical questions block implementation |
395
+
396
+ ---
397
+
398
+ ## Quality Loop
399
+
400
+ **Repeat until: score ≥ 85 OR user approves.**
401
+
402
+ ### A. Calculate score
403
+
404
+ Score each dimension based on the generated artifacts. Identify the most impactful gaps.
405
+
406
+ ### B. Identify open questions
407
+
408
+ Typical questions by dimension:
409
+
410
+ | Weak dimension | Example questions |
411
+ |----------------|-------------------|
412
+ | Schema fidelity | "The `metadata` field (JSONB) — what is its structure? Which keys?" |
413
+ | Functional coverage | "FR003 says 'notify user' — by email, push, or both?" |
414
+ | Blueprint VSA | "Should the CreateOrder slice trigger an email job or is it synchronous?" |
415
+ | Blueprint DDD | "Should `Place()` on OrderAggregate emit `OrderPlacedEvent`?" |
416
+ | Integrations | "Does the payment API use webhook or polling to confirm?" |
417
+ | Infra/costs | "Does this feature need Azure storage? Which tier?" |
418
+
419
+ ### C. Ask via AskUserQuestion
420
+
421
+ Maximum 3 technical questions per call. In the last call of each round, always include:
422
+
423
+ ```json
424
+ {
425
+ "header": "Continue?",
426
+ "question": "Continue refining or finalize the design?",
427
+ "multiSelect": false,
428
+ "options": [
429
+ { "label": "Continue refining", "description": "More open questions identified" },
430
+ { "label": "Finalize design", "description": "Proceed to Clarify with current design" }
431
+ ]
432
+ }
433
+ ```
434
+
435
+ > If score ≥ 85, adjust: `"Continue (optional)"` with description `"Score {N}/100 — design is satisfactory"`
436
+
437
+ ### D. Incorporate answers
438
+
439
+ Update spec.md, contracts, and decisions.md with the answers received. Recalculate the score.
440
+
441
+ ### E. Exit condition
442
+
443
+ - User chose **"Finalize design"** → exit loop
444
+ - Score ≥ 85 AND no new questions → exit loop
445
+
446
+ ---
447
+
448
+ ## Post-Loop: Update State
449
+
450
+ ```bash
451
+ npx morph-spec state mark-output $ARGUMENTS schema-analysis
452
+ npx morph-spec state mark-output $ARGUMENTS spec
453
+ npx morph-spec state mark-output $ARGUMENTS contracts
454
+ npx morph-spec state mark-output $ARGUMENTS decisions
455
+ ```
456
+
457
+ If Azure costs were estimated:
458
+ ```bash
459
+ npx morph-spec state set $ARGUMENTS costs.estimated {X.XX}
460
+ ```
461
+
462
+ ## MANDATORY PAUSE
463
+
464
+ ```json
465
+ {
466
+ "questions": [{
467
+ "header": "Approval",
468
+ "question": "Design generated. Approve to continue to Clarify?",
469
+ "multiSelect": false,
470
+ "options": [
471
+ { "label": "Approve and continue", "description": "Advance to Clarify phase" },
472
+ { "label": "I have feedback", "description": "Describe what to change (Other)" }
473
+ ]
474
+ }]
475
+ }
476
+ ```
477
+
478
+ - **"Approve and continue"** →
479
+ ```bash
480
+ npx morph-spec approve $ARGUMENTS design
481
+ npx morph-spec phase advance $ARGUMENTS
482
+ ```
483
+ - **"I have feedback" / Other** → apply feedback and repeat PAUSE
484
+
485
+ ## Generated Outputs
486
+
487
+ - `.morph/features/$ARGUMENTS/1-design/schema-analysis.md` — Real schema mapped and validated
488
+ - `.morph/features/$ARGUMENTS/1-design/spec.md` — Complete technical specification
489
+ - `.morph/features/$ARGUMENTS/1-design/contracts.cs` (or `.ts` for TypeScript projects) — Contracts based on real schema (VSA or DDD)
490
+ - `.morph/features/$ARGUMENTS/1-design/decisions.md` — Documented ADRs
491
+
492
+ ## Advancement Criteria
493
+
494
+ - [x] Architecture style detected from `config.architecture.style`
495
+ - [x] Schema validated by user (Checkpoint 1)
496
+ - [x] Blueprint confirmed by user (Checkpoint 2-VSA or 2-DDD)
497
+ - [x] Quality score ≥ 85 OR user finalized
498
+ - [x] All field names in contracts traceable to schema-analysis.md
499
+ - [x] State updated
500
+ - [x] User approved at MANDATORY PAUSE
501
+
502
+ ---
503
+
504
+ <!-- morph-outputs:design -->
505
+ | Output | Caminho |
506
+ |--------|---------|
507
+ | `schemaAnalysis` | `.morph/features/{feature}/1-design/schema-analysis.md` |
508
+ | `spec` | `.morph/features/{feature}/1-design/spec.md` |
509
+ | `contracts` | `.morph/features/{feature}/1-design/contracts.cs` |
510
+ | `contractsTs` | `.morph/features/{feature}/1-design/contracts.ts` |
511
+ | `contractsVsa` | `.morph/features/{feature}/1-design/contracts-vsa.cs` |
512
+ | `decisions` | `.morph/features/{feature}/1-design/decisions.md` |
513
+ <!-- /morph-outputs -->
514
+
515
+ Continue automatically to Phase 3 (Clarify) after approval.