@polymorphism-tech/morph-spec 4.5.0 → 4.7.0

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 (292) hide show
  1. package/CLAUDE.md +77 -56
  2. package/README.md +394 -700
  3. package/docs/ARCHITECTURE.md +331 -0
  4. package/docs/CHEATSHEET.md +221 -0
  5. package/docs/COMMAND-FLOWS.md +368 -0
  6. package/docs/QUICKSTART.md +212 -0
  7. package/docs/examples/order-management/contracts.cs +84 -0
  8. package/docs/examples/order-management/proposal.md +24 -0
  9. package/docs/examples/order-management/spec.md +162 -0
  10. package/docs/plans/2026-02-23-ddd-architecture-refactor.md +1153 -0
  11. package/docs/plans/2026-02-23-ddd-nextsteps.md +682 -0
  12. package/docs/plans/2026-02-23-infra-architect-refactor.md +437 -0
  13. package/docs/plans/2026-02-23-nextjs-code-review-design.md +156 -0
  14. package/docs/plans/2026-02-23-nextjs-code-review-impl.md +1254 -0
  15. package/docs/plans/2026-02-23-nextjs-standards-design.md +149 -0
  16. package/docs/plans/2026-02-23-nextjs-standards-impl.md +1846 -0
  17. package/framework/{skills/level-2-domains → agents}/README.md +14 -14
  18. package/framework/{skills/level-2-domains → agents}/ai-agents/ai-system-architect.md +1 -4
  19. package/framework/{skills/level-2-domains → agents}/architecture/po-pm-advisor.md +1 -2
  20. package/framework/{skills/level-2-domains → agents}/architecture/prompt-engineer.md +1 -2
  21. package/framework/{skills/level-2-domains → agents}/architecture/seo-growth-hacker.md +1 -2
  22. package/framework/{skills/level-2-domains → agents}/architecture/standards-architect.md +159 -162
  23. package/framework/agents/backend/api-designer.md +103 -0
  24. package/framework/{skills/level-2-domains → agents}/backend/dotnet-senior.md +1 -2
  25. package/framework/agents/backend/ef-modeler.md +119 -0
  26. package/framework/{skills/level-2-domains → agents}/backend/hangfire-orchestrator.md +1 -4
  27. package/framework/{skills/level-2-domains → agents}/backend/ms-agent-expert.md +1 -4
  28. package/framework/{skills/level-2-domains → agents}/frontend/blazor-builder.md +1 -4
  29. package/framework/agents/frontend/nextjs-expert.md +118 -0
  30. package/framework/{skills/level-2-domains → agents}/frontend/ui-ux-designer.md +1 -2
  31. package/framework/{skills/level-2-domains → agents}/infrastructure/azure-architect.md +147 -148
  32. package/framework/{skills/level-2-domains → agents}/infrastructure/azure-deploy-specialist.md +1 -2
  33. package/framework/{skills/level-2-domains → agents}/infrastructure/bicep-architect.md +1 -4
  34. package/framework/{skills/level-2-domains → agents}/infrastructure/container-specialist.md +1 -4
  35. package/framework/{skills/level-2-domains → agents}/infrastructure/devops-engineer.md +1 -4
  36. package/framework/agents/infrastructure/infra-architect.md +45 -0
  37. package/framework/{skills/level-2-domains → agents}/integrations/asaas-financial.md +1 -4
  38. package/framework/{skills/level-2-domains → agents}/integrations/azure-identity.md +1 -4
  39. package/framework/{skills/level-2-domains → agents}/integrations/clerk-auth.md +1 -4
  40. package/framework/{skills/level-2-domains → agents}/integrations/hangfire-integration.md +1 -2
  41. package/framework/{skills/level-2-domains → agents}/integrations/resend-email.md +1 -4
  42. package/framework/{skills/level-2-domains → agents}/quality/code-analyzer.md +1 -4
  43. package/framework/{skills/level-2-domains → agents}/quality/testing-specialist.md +1 -4
  44. package/framework/agents.json +1145 -278
  45. package/framework/hooks/claude-code/statusline.py +384 -85
  46. package/framework/hooks/shared/phase-utils.js +129 -129
  47. package/framework/rules/frontend-standards.md +0 -3
  48. package/framework/rules/nextjs-standards.md +17 -0
  49. package/framework/skills/README.md +66 -0
  50. package/framework/skills/level-0-meta/{brainstorming.md → brainstorming/SKILL.md} +3 -1
  51. package/framework/skills/level-0-meta/brainstorming/references/proposal-example.md +138 -0
  52. package/framework/skills/level-0-meta/{code-review.md → code-review/SKILL.md} +3 -2
  53. package/framework/skills/level-0-meta/code-review/references/review-example.md +164 -0
  54. package/framework/skills/level-0-meta/code-review/scripts/scan-csharp.mjs +121 -0
  55. package/framework/skills/level-0-meta/code-review-nextjs/SKILL.md +147 -0
  56. package/framework/skills/level-0-meta/code-review-nextjs/references/review-example-nextjs.md +254 -0
  57. package/framework/skills/level-0-meta/{morph-checklist.md → morph-checklist/SKILL.md} +2 -5
  58. package/framework/skills/{level-1-workflows/morph-replicate.md → level-0-meta/morph-replicate/SKILL.md} +6 -7
  59. package/framework/skills/level-0-meta/{simulation-checklist.md → simulation-checklist/SKILL.md} +3 -6
  60. package/framework/skills/level-0-meta/{tool-usage-guide.md → tool-usage-guide/SKILL.md} +4 -5
  61. package/framework/skills/level-0-meta/{verification-before-completion.md → verification-before-completion/SKILL.md} +3 -1
  62. package/framework/skills/level-0-meta/verification-before-completion/scripts/check-phase-outputs.mjs +110 -0
  63. package/framework/skills/level-1-workflows/{phase-clarify.md → phase-clarify/SKILL.md} +3 -3
  64. package/framework/skills/level-1-workflows/phase-clarify/references/clarifications-example.md +117 -0
  65. package/framework/skills/level-1-workflows/{phase-codebase-analysis.md → phase-codebase-analysis/SKILL.md} +2 -3
  66. package/framework/skills/level-1-workflows/{phase-design.md → phase-design/SKILL.md} +46 -182
  67. package/framework/skills/level-1-workflows/phase-design/references/spec-example.md +253 -0
  68. package/framework/skills/level-1-workflows/{phase-implement.md → phase-implement/SKILL.md} +3 -3
  69. package/framework/skills/level-1-workflows/phase-implement/references/recap-example.md +132 -0
  70. package/framework/skills/level-1-workflows/{phase-setup.md → phase-setup/SKILL.md} +2 -3
  71. package/framework/skills/level-1-workflows/{phase-tasks.md → phase-tasks/SKILL.md} +42 -3
  72. package/framework/skills/level-1-workflows/phase-tasks/references/tasks-example.md +231 -0
  73. package/framework/skills/level-1-workflows/phase-tasks/scripts/validate-tasks.mjs +112 -0
  74. package/framework/skills/level-1-workflows/{phase-uiux.md → phase-uiux/SKILL.md} +2 -3
  75. package/framework/standards/STANDARDS.json +121 -0
  76. package/framework/standards/architecture/ddd/bounded-contexts.md +105 -0
  77. package/framework/standards/architecture/ddd/complexity-levels.md +108 -0
  78. package/framework/standards/architecture/ddd/ubiquitous-language.md +58 -0
  79. package/framework/standards/frontend/nextjs/app-router.md +123 -0
  80. package/framework/standards/frontend/nextjs/components.md +132 -0
  81. package/framework/standards/frontend/nextjs/data-fetching.md +126 -0
  82. package/framework/standards/frontend/nextjs/forms.md +128 -0
  83. package/framework/standards/frontend/nextjs/naming-conventions.md +67 -0
  84. package/framework/standards/frontend/nextjs/project-structure.md +102 -0
  85. package/framework/standards/frontend/nextjs/state-management.md +72 -0
  86. package/framework/standards/frontend/nextjs/testing.md +111 -0
  87. package/framework/templates/REGISTRY.json +538 -142
  88. package/framework/templates/code/dotnet/contracts/contracts-level1.cs +69 -0
  89. package/framework/templates/code/dotnet/contracts/contracts-level2.cs +86 -0
  90. package/framework/templates/code/dotnet/contracts/contracts-level3.cs +41 -0
  91. package/framework/templates/docs/spec.md +49 -0
  92. package/framework/templates/frontend/nextjs/Dockerfile.nextjs.hbs +43 -0
  93. package/framework/templates/frontend/nextjs/client-component.tsx.hbs +26 -0
  94. package/framework/templates/frontend/nextjs/env.mjs.hbs +32 -0
  95. package/framework/templates/frontend/nextjs/feature-form.tsx.hbs +56 -0
  96. package/framework/templates/frontend/nextjs/page.tsx.hbs +22 -0
  97. package/framework/templates/frontend/nextjs/tsconfig.json.hbs +26 -0
  98. package/framework/templates/frontend/nextjs/use-feature.ts.hbs +54 -0
  99. package/framework/templates/project-structure/dotnet-ddd.md +70 -0
  100. package/framework/workflows/docs/enforcement-pipeline.md +2 -1
  101. package/package.json +1 -1
  102. package/scripts/scan-nextjs.mjs +169 -0
  103. package/src/commands/project/doctor.js +52 -1
  104. package/src/commands/project/init.js +19 -65
  105. package/src/commands/project/update.js +7 -63
  106. package/src/lib/detectors/claude-config-detector.js +1 -3
  107. package/src/lib/standards/standards-context-injector.js +5 -0
  108. package/src/lib/validators/nextjs/index.js +6 -0
  109. package/src/lib/validators/nextjs/next-component-validator.js +181 -0
  110. package/src/lib/validators/validation-runner.js +5 -0
  111. package/src/utils/agents-installer.js +16 -4
  112. package/src/utils/skills-installer.js +59 -15
  113. package/.morph/.morphversion +0 -5
  114. package/.morph/analytics/threads-log.jsonl +0 -44
  115. package/.morph/config/config.json +0 -8
  116. package/.morph/context/README.md +0 -17
  117. package/.morph/framework/agents.json +0 -948
  118. package/.morph/framework/standards/STANDARDS.json +0 -812
  119. package/.morph/framework/standards/ai-agents/blazor-ui.md +0 -364
  120. package/.morph/framework/standards/ai-agents/production.md +0 -415
  121. package/.morph/framework/standards/ai-agents/setup.md +0 -418
  122. package/.morph/framework/standards/ai-agents/team-orchestration.md +0 -479
  123. package/.morph/framework/standards/ai-agents/workflows.md +0 -354
  124. package/.morph/framework/standards/architecture/ddd/aggregates.md +0 -120
  125. package/.morph/framework/standards/architecture/ddd/entities.md +0 -99
  126. package/.morph/framework/standards/architecture/ddd/value-objects.md +0 -124
  127. package/.morph/framework/standards/backend/api/minimal-api.md +0 -494
  128. package/.morph/framework/standards/backend/api/rest.md +0 -492
  129. package/.morph/framework/standards/backend/api/validation.md +0 -88
  130. package/.morph/framework/standards/backend/authentication/passkeys.md +0 -428
  131. package/.morph/framework/standards/backend/database/ef-core.md +0 -199
  132. package/.morph/framework/standards/backend/database/migrations.md +0 -393
  133. package/.morph/framework/standards/backend/database/postgresql/database.md +0 -352
  134. package/.morph/framework/standards/backend/database/repository-patterns.md +0 -528
  135. package/.morph/framework/standards/backend/database/vector-search-rag.md +0 -541
  136. package/.morph/framework/standards/backend/dotnet/async.md +0 -366
  137. package/.morph/framework/standards/backend/dotnet/core.md +0 -117
  138. package/.morph/framework/standards/backend/dotnet/di.md +0 -439
  139. package/.morph/framework/standards/backend/dotnet/program-cs-checklist.md +0 -92
  140. package/.morph/framework/standards/backend/integrations/asaas/asaas-api.md +0 -216
  141. package/.morph/framework/standards/backend/integrations/clerk/clerk-auth.md +0 -290
  142. package/.morph/framework/standards/backend/integrations/hangfire/hangfire-jobs.md +0 -350
  143. package/.morph/framework/standards/backend/integrations/resend/resend-email.md +0 -385
  144. package/.morph/framework/standards/context/analytics.md +0 -96
  145. package/.morph/framework/standards/context/bundles.md +0 -110
  146. package/.morph/framework/standards/context/priming.md +0 -78
  147. package/.morph/framework/standards/core/architecture.md +0 -185
  148. package/.morph/framework/standards/core/coding.md +0 -214
  149. package/.morph/framework/standards/core/git-branching-strategy.md +0 -403
  150. package/.morph/framework/standards/core/git.md +0 -185
  151. package/.morph/framework/standards/core/testing.md +0 -295
  152. package/.morph/framework/standards/data/nosql/blob-storage.md +0 -102
  153. package/.morph/framework/standards/data/nosql/cache/redis.md +0 -97
  154. package/.morph/framework/standards/data/nosql/cosmos-db.md +0 -118
  155. package/.morph/framework/standards/data/vector-search/azure-ai-search.md +0 -121
  156. package/.morph/framework/standards/data/vector-search/rag-chunking.md +0 -104
  157. package/.morph/framework/standards/frontend/blazor/design-checklist.md +0 -222
  158. package/.morph/framework/standards/frontend/blazor/fluent-ui-setup.md +0 -595
  159. package/.morph/framework/standards/frontend/blazor/fluent-ui.md +0 -137
  160. package/.morph/framework/standards/frontend/blazor/html-conversion.md +0 -184
  161. package/.morph/framework/standards/frontend/blazor/lifecycle.md +0 -195
  162. package/.morph/framework/standards/frontend/blazor/pitfalls.md +0 -198
  163. package/.morph/framework/standards/frontend/blazor/state.md +0 -191
  164. package/.morph/framework/standards/frontend/design-system/animations.md +0 -151
  165. package/.morph/framework/standards/frontend/design-system/naming.md +0 -64
  166. package/.morph/framework/standards/frontend/nextjs/nextjs-patterns.md +0 -198
  167. package/.morph/framework/standards/infrastructure/azure/azure.md +0 -624
  168. package/.morph/framework/standards/infrastructure/azure/bicep/bicep-patterns.md +0 -422
  169. package/.morph/framework/standards/infrastructure/azure/devops/azure-devops-setup.md +0 -516
  170. package/.morph/framework/standards/infrastructure/azure/devops/local-development.md +0 -520
  171. package/.morph/framework/standards/infrastructure/azure/services/functions.md +0 -486
  172. package/.morph/framework/standards/infrastructure/azure/services/service-bus.md +0 -459
  173. package/.morph/framework/standards/infrastructure/azure/services/storage.md +0 -407
  174. package/.morph/framework/standards/infrastructure/docker/easypanel-deploy.md +0 -196
  175. package/.morph/framework/standards/infrastructure/supabase/mcp-setup.md +0 -252
  176. package/.morph/framework/standards/infrastructure/supabase/supabase-auth.md +0 -176
  177. package/.morph/framework/standards/infrastructure/supabase/supabase-pgvector.md +0 -169
  178. package/.morph/framework/standards/infrastructure/supabase/supabase-rls.md +0 -184
  179. package/.morph/framework/standards/infrastructure/supabase/supabase-storage.md +0 -153
  180. package/.morph/framework/standards/integration/api/graphql.md +0 -91
  181. package/.morph/framework/standards/integration/api/grpc.md +0 -114
  182. package/.morph/framework/standards/integration/api/rest-design.md +0 -95
  183. package/.morph/framework/standards/integration/event-driven/cqrs.md +0 -101
  184. package/.morph/framework/standards/integration/event-driven/event-sourcing.md +0 -124
  185. package/.morph/framework/standards/integration/event-driven/service-bus.md +0 -95
  186. package/.morph/framework/standards/integration/mcp/mcp-tools.md +0 -384
  187. package/.morph/framework/standards/observability/logging.md +0 -131
  188. package/.morph/framework/standards/observability/metrics.md +0 -121
  189. package/.morph/framework/standards/observability/monitoring.md +0 -114
  190. package/.morph/framework/standards/observability/tracing.md +0 -132
  191. package/.morph/framework/standards/workflows/parallel-execution.md +0 -112
  192. package/.morph/framework/standards/workflows/thread-management.md +0 -113
  193. package/.morph/framework/templates/.idea/morph-templates.xml +0 -92
  194. package/.morph/framework/templates/.vscode/morph-templates.code-snippets +0 -186
  195. package/.morph/framework/templates/IDE-SNIPPETS.md +0 -266
  196. package/.morph/framework/templates/README.md +0 -814
  197. package/.morph/framework/templates/REGISTRY.json +0 -1492
  198. package/.morph/framework/templates/code/dotnet/backend/repository.cs +0 -141
  199. package/.morph/framework/templates/code/dotnet/backend/service.cs +0 -139
  200. package/.morph/framework/templates/code/dotnet/contracts/Commands.cs +0 -74
  201. package/.morph/framework/templates/code/dotnet/contracts/Entities.cs +0 -25
  202. package/.morph/framework/templates/code/dotnet/contracts/Queries.cs +0 -74
  203. package/.morph/framework/templates/code/dotnet/contracts/README.md +0 -74
  204. package/.morph/framework/templates/code/dotnet/contracts/api-contracts.cs +0 -173
  205. package/.morph/framework/templates/code/dotnet/contracts/contracts.cs +0 -217
  206. package/.morph/framework/templates/code/dotnet/contracts/contracts.cs.hbs +0 -172
  207. package/.morph/framework/templates/code/dotnet/database/migration.cs +0 -83
  208. package/.morph/framework/templates/code/dotnet/frontend/component.razor +0 -239
  209. package/.morph/framework/templates/code/dotnet/jobs/agent.cs +0 -163
  210. package/.morph/framework/templates/code/dotnet/jobs/job.cs +0 -171
  211. package/.morph/framework/templates/code/dotnet/test.cs +0 -239
  212. package/.morph/framework/templates/code/sql/rls-policy.sql +0 -57
  213. package/.morph/framework/templates/code/sql/supabase-migration.sql +0 -100
  214. package/.morph/framework/templates/code/sql/supabase-migration.template.sql +0 -113
  215. package/.morph/framework/templates/code/typescript/contracts.ts +0 -168
  216. package/.morph/framework/templates/context/CONTEXT-FEATURE.md +0 -276
  217. package/.morph/framework/templates/context/CONTEXT.md +0 -181
  218. package/.morph/framework/templates/docs/clarifications.md +0 -253
  219. package/.morph/framework/templates/docs/onboarding.md +0 -123
  220. package/.morph/framework/templates/docs/proposal.md +0 -182
  221. package/.morph/framework/templates/docs/schema-analysis.md +0 -119
  222. package/.morph/framework/templates/docs/spec.md +0 -149
  223. package/.morph/framework/templates/docs/ui-components.md +0 -124
  224. package/.morph/framework/templates/docs/ui-design-system.md +0 -76
  225. package/.morph/framework/templates/docs/ui-flows.md +0 -167
  226. package/.morph/framework/templates/docs/ui-mockups.md +0 -98
  227. package/.morph/framework/templates/examples/design-system-examples.md +0 -357
  228. package/.morph/framework/templates/examples/spec-examples.md +0 -90
  229. package/.morph/framework/templates/feature/decisions.md +0 -187
  230. package/.morph/framework/templates/feature/recap.md +0 -146
  231. package/.morph/framework/templates/feature/tasks.md +0 -199
  232. package/.morph/framework/templates/infrastructure/azure/Dockerfile.example +0 -82
  233. package/.morph/framework/templates/infrastructure/azure/README.md +0 -286
  234. package/.morph/framework/templates/infrastructure/azure/app-insights.bicep +0 -63
  235. package/.morph/framework/templates/infrastructure/azure/app-service.bicep +0 -164
  236. package/.morph/framework/templates/infrastructure/azure/container-app-env.bicep +0 -49
  237. package/.morph/framework/templates/infrastructure/azure/container-app.bicep +0 -156
  238. package/.morph/framework/templates/infrastructure/azure/deploy-checklist.md +0 -426
  239. package/.morph/framework/templates/infrastructure/azure/deploy.ps1 +0 -229
  240. package/.morph/framework/templates/infrastructure/azure/deploy.sh +0 -208
  241. package/.morph/framework/templates/infrastructure/azure/key-vault.bicep +0 -91
  242. package/.morph/framework/templates/infrastructure/azure/main.bicep +0 -189
  243. package/.morph/framework/templates/infrastructure/azure/parameters.dev.json +0 -29
  244. package/.morph/framework/templates/infrastructure/azure/parameters.prod.json +0 -29
  245. package/.morph/framework/templates/infrastructure/azure/parameters.staging.json +0 -29
  246. package/.morph/framework/templates/infrastructure/azure/sql-database.bicep +0 -103
  247. package/.morph/framework/templates/infrastructure/azure/storage.bicep +0 -106
  248. package/.morph/framework/templates/infrastructure/docker/Dockerfile.template +0 -58
  249. package/.morph/framework/templates/infrastructure/docker/docker-compose.template.yml +0 -67
  250. package/.morph/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +0 -38
  251. package/.morph/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +0 -48
  252. package/.morph/framework/templates/infrastructure/docker/easypanel.template.json +0 -54
  253. package/.morph/framework/templates/infrastructure/github/README.md +0 -593
  254. package/.morph/framework/templates/infrastructure/github/actions/azure-auth/action.yml.hbs +0 -22
  255. package/.morph/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +0 -45
  256. package/.morph/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +0 -27
  257. package/.morph/framework/templates/infrastructure/github/workflows/deploy-azure-app-service.yml.hbs +0 -61
  258. package/.morph/framework/templates/infrastructure/github/workflows/deploy-easypanel.yml.hbs +0 -31
  259. package/.morph/framework/templates/infrastructure/github/workflows/docker-build-push.yml.hbs +0 -59
  260. package/.morph/framework/templates/infrastructure/github/workflows/dotnet-build.yml.hbs +0 -39
  261. package/.morph/framework/templates/integrations/asaas-client.cs +0 -387
  262. package/.morph/framework/templates/integrations/asaas-webhook.cs +0 -351
  263. package/.morph/framework/templates/integrations/azure-identity-config.cs +0 -288
  264. package/.morph/framework/templates/integrations/clerk-config.cs +0 -258
  265. package/.morph/framework/templates/meta-prompts/fusion/fusion-agent.md +0 -76
  266. package/.morph/framework/templates/meta-prompts/fusion/fusion-aggregator.md +0 -100
  267. package/.morph/framework/templates/meta-prompts/hops/hop-retry.md +0 -78
  268. package/.morph/framework/templates/meta-prompts/hops/hop-validation.md +0 -97
  269. package/.morph/framework/templates/meta-prompts/hops/hop-wrapper.md +0 -36
  270. package/.morph/framework/templates/meta-prompts/parallel-workers/parallel-coordinator.md +0 -113
  271. package/.morph/framework/templates/meta-prompts/parallel-workers/parallel-worker.md +0 -80
  272. package/.morph/framework/templates/meta-prompts/squad-leaders/backend-squad.md +0 -90
  273. package/.morph/framework/templates/meta-prompts/squad-leaders/frontend-squad.md +0 -126
  274. package/.morph/framework/templates/meta-prompts/squad-leaders/squad-leader.md +0 -43
  275. package/.morph/framework/templates/meta-prompts/validators/checkpoint-validator.md +0 -107
  276. package/.morph/framework/templates/meta-prompts/validators/pre-commit-validator.md +0 -95
  277. package/.morph/framework/templates/saas/subscription.cs +0 -347
  278. package/.morph/framework/templates/saas/tenant.cs +0 -338
  279. package/.morph/framework/templates/state.template.json +0 -17
  280. package/.morph/framework/templates/ui/FluentDesignTheme.cs +0 -149
  281. package/.morph/framework/templates/ui/MudTheme.cs +0 -281
  282. package/.morph/framework/templates/ui/design-system.css +0 -226
  283. package/.morph/logs/tool-failures.log +0 -51
  284. package/.morph/memory/pre-compact-2026-02-22T17-01-01-658Z.json +0 -16
  285. package/.morph/state.json +0 -48
  286. package/framework/skills/level-2-domains/backend/api-designer.md +0 -66
  287. package/framework/skills/level-2-domains/backend/ef-modeler.md +0 -65
  288. package/framework/skills/level-2-domains/frontend/nextjs-expert.md +0 -161
  289. package/framework/skills/level-3-technologies/README.md +0 -7
  290. package/framework/skills/level-4-patterns/README.md +0 -7
  291. package/framework/templates/code/dotnet/contracts/contracts.cs +0 -217
  292. package/framework/templates/code/dotnet/contracts/contracts.cs.hbs +0 -172
@@ -0,0 +1,682 @@
1
+ # DDD Next Steps Implementation Plan
2
+
3
+ > **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.
4
+
5
+ **Goal:** Fechar os 5 gaps pós-refactor DDD: instalação nativa do domain-architect, remoção do template legado contracts.cs, phase-tasks DDD-aware, system prompt enriquecido do domain-architect, e exemplo end-to-end de feature Level 2.
6
+
7
+ **Architecture:** Cada task é independente e toca uma camada diferente: agents-installer (JS), templates (remoção + registry), skills (markdown), agents.json (JSON), e docs/examples (markdown). Nenhuma task depende de outra para executar.
8
+
9
+ **Tech Stack:** Node.js ESM, `node:test`, Handlebars v2.0, JSON, Markdown.
10
+
11
+ ---
12
+
13
+ ## Contexto Crítico
14
+
15
+ - Worktree: criar em `.worktrees/feat-ddd-nextsteps` a partir de `main`
16
+ - Test suite baseline: 659 pass, 0 fail, 1 skip
17
+ - `src/utils/agents-installer.js` — filtra tier 1+2, instala `morph-{id}.md` em `.claude/agents/`
18
+ - `framework/agents.json` v3.2.0-hierarchical — `domain-architect` é tier 2, `always_active: true`
19
+ - Arquivos com referência ao template legado `contracts.cs`:
20
+ - `framework/skills/level-1-workflows/phase-design/SKILL.md` (linha 38)
21
+ - `framework/skills/level-0-meta/tool-usage-guide/SKILL.md` (linha ~144)
22
+ - `framework/templates/REGISTRY.json` (entrada `code/dotnet/contracts/contracts.cs`)
23
+ - `framework/templates/code/dotnet/contracts/contracts.cs` (o próprio arquivo — DELETAR)
24
+ - `framework/templates/code/dotnet/contracts/contracts.cs.hbs` (se existir — DELETAR)
25
+
26
+ ---
27
+
28
+ ## Task 1: domain-architect como native subagent — verificar + testar
29
+
30
+ **Files:**
31
+ - Modify: `test/utils/agents-installer.test.js`
32
+
33
+ **Step 1: Verificar que domain-architect está sendo instalado**
34
+
35
+ ```bash
36
+ node -e "
37
+ import { installAgents } from './src/utils/agents-installer.js';
38
+ import { mkdtempSync } from 'fs';
39
+ import { tmpdir } from 'os';
40
+ import { join } from 'path';
41
+
42
+ const out = mkdtempSync(join(tmpdir(), 'morph-test-'));
43
+ await installAgents(process.cwd(), out);
44
+ const files = require('fs').readdirSync(join(out, '.claude', 'agents'));
45
+ console.log(files.filter(f => f.includes('domain-architect')));
46
+ " --input-type=module
47
+ ```
48
+
49
+ **Forma mais simples — usar o executável:**
50
+ ```bash
51
+ node --test test/utils/agents-installer.test.js 2>&1 | grep -i "domain"
52
+ ```
53
+
54
+ **Step 2: Ler `test/utils/agents-installer.test.js` para entender a estrutura atual**
55
+
56
+ ```bash
57
+ # Procurar onde estão os testes de agent names específicos
58
+ grep -n "domain\|tier.*2\|morph-" test/utils/agents-installer.test.js | head -20
59
+ ```
60
+
61
+ **Step 3: Escrever o failing test** — adicionar dentro da suite `installAgents` existente:
62
+
63
+ ```javascript
64
+ test('installs domain-architect as morph-domain-architect.md', async () => {
65
+ const { agentFiles, agentsDir } = await setupInstall();
66
+ const file = agentFiles.find(f => f === 'morph-domain-architect.md');
67
+ assert.ok(file, 'morph-domain-architect.md must be installed');
68
+
69
+ const content = readFileSync(join(agentsDir, file), 'utf8');
70
+ assert.ok(content.includes('domain-architect') || content.includes('Domain Modeling'),
71
+ 'File must reference domain-architect');
72
+ assert.ok(content.includes('ddd') || content.includes('aggregate') || content.includes('complexity'),
73
+ 'File must mention DDD concepts');
74
+ });
75
+
76
+ test('domain-architect is installed with tier-2 defaults (no Task tool)', async () => {
77
+ const { agentFiles, agentsDir } = await setupInstall();
78
+ const content = readFileSync(join(agentsDir, 'morph-domain-architect.md'), 'utf8');
79
+ assert.ok(!content.includes('Task'), 'Tier-2 agent must NOT have Task tool');
80
+ assert.match(content, /maxTurns.*20/, 'Tier-2 agent must have maxTurns: 20');
81
+ });
82
+ ```
83
+
84
+ > **Nota:** `setupInstall` é o helper já existente no test file — leia o arquivo para entender o padrão exato antes de escrever os testes.
85
+
86
+ **Step 4: Rodar para ver falhar**
87
+
88
+ ```bash
89
+ node --test test/utils/agents-installer.test.js 2>&1 | grep -E "pass|fail"
90
+ ```
91
+
92
+ Esperado: novos testes falham (domain-architect não encontrado) OU já passam (se já instalado).
93
+
94
+ Se já passam: os testes são válidos como regressão. Commit assim mesmo.
95
+ Se falham: investigar o agente no agents.json — verificar se `tier: 2` está correto.
96
+
97
+ **Step 5: Rodar suite para confirmar nenhuma regressão**
98
+
99
+ ```bash
100
+ node --test test/utils/agents-installer.test.js 2>&1 | grep -E "# (pass|fail)"
101
+ ```
102
+
103
+ **Step 6: Commit**
104
+
105
+ ```bash
106
+ git add test/utils/agents-installer.test.js
107
+ git commit -m "test(agents): add domain-architect native subagent installation tests"
108
+ ```
109
+
110
+ ---
111
+
112
+ ## Task 2: Remover template legado contracts.cs + atualizar referências
113
+
114
+ **Files:**
115
+ - Delete: `framework/templates/code/dotnet/contracts/contracts.cs`
116
+ - Delete: `framework/templates/code/dotnet/contracts/contracts.cs.hbs` (se existir)
117
+ - Modify: `framework/skills/level-1-workflows/phase-design/SKILL.md`
118
+ - Modify: `framework/skills/level-0-meta/tool-usage-guide/SKILL.md`
119
+ - Modify: `framework/templates/REGISTRY.json`
120
+ - Modify: `test/templates/contracts-levels.test.js` (adicionar teste de ausência)
121
+
122
+ **Step 1: Confirmar quais arquivos existem e todas as referências**
123
+
124
+ ```bash
125
+ ls framework/templates/code/dotnet/contracts/
126
+ grep -rn "contracts\.cs" framework/skills/ framework/templates/ .claude/skills/ --include="*.md" --include="*.json" | grep -v "level1\|level2\|level3\|contracts-level"
127
+ ```
128
+
129
+ **Step 2: Deletar o template legado**
130
+
131
+ ```bash
132
+ rm framework/templates/code/dotnet/contracts/contracts.cs
133
+ # Se existir:
134
+ rm -f "framework/templates/code/dotnet/contracts/contracts.cs.hbs"
135
+ ```
136
+
137
+ **Step 3: Atualizar `framework/templates/REGISTRY.json`**
138
+
139
+ Remover a entrada com `"path": "code/dotnet/contracts/contracts.cs"`.
140
+
141
+ Verificar: `node -e "const r=JSON.parse(require('fs').readFileSync('framework/templates/REGISTRY.json')); console.log(r.templates?.filter(t=>t.path?.includes('contracts.cs')&&!t.path?.includes('level')))"`
142
+
143
+ Esperado: array vazio.
144
+
145
+ **Step 4: Atualizar `framework/skills/level-1-workflows/phase-design/SKILL.md`**
146
+
147
+ Localizar a linha na tabela "Ferramentas Recomendadas" que diz:
148
+ ```
149
+ | Renderizar template contracts.cs | **Bash** `npx morph-spec template render code/dotnet/contracts/contracts.cs ...` | — |
150
+ ```
151
+
152
+ Substituir por:
153
+ ```
154
+ | Renderizar template contracts (nível detectado) | **Bash** `npx morph-spec template render code/dotnet/contracts/contracts-level{N}.cs ...` onde N = nível detectado no Passo 1.5 | — |
155
+ ```
156
+
157
+ **Step 5: Atualizar `framework/skills/level-0-meta/tool-usage-guide/SKILL.md`**
158
+
159
+ Localizar a linha que referencia `contracts.cs` genérico (~linha 144) e substituir pela versão com level{N}.
160
+
161
+ **Step 6: Adicionar teste de ausência em `test/templates/contracts-levels.test.js`**
162
+
163
+ ```javascript
164
+ test('legacy contracts.cs template no longer exists', () => {
165
+ const legacyPath = join(FRAMEWORK_DIR, 'templates', 'code', 'dotnet', 'contracts', 'contracts.cs');
166
+ assert.throws(
167
+ () => readFileSync(legacyPath),
168
+ { code: 'ENOENT' },
169
+ 'Legacy contracts.cs must not exist — use contracts-level1/2/3.cs instead'
170
+ );
171
+ });
172
+ ```
173
+
174
+ **Step 7: Rodar testes**
175
+
176
+ ```bash
177
+ node --test test/templates/contracts-levels.test.js 2>&1 | grep -E "# (pass|fail)"
178
+ ```
179
+ Esperado: 8 pass (7 anteriores + 1 novo), 0 fail.
180
+
181
+ **Step 8: Rodar suite completa**
182
+
183
+ ```bash
184
+ node --test 2>&1 | grep -E "# (pass|fail)"
185
+ ```
186
+ Esperado: 0 fail.
187
+
188
+ **Step 9: Commit**
189
+
190
+ ```bash
191
+ git add -A framework/templates/code/dotnet/contracts/ \
192
+ framework/templates/REGISTRY.json \
193
+ framework/skills/level-1-workflows/phase-design/SKILL.md \
194
+ framework/skills/level-0-meta/tool-usage-guide/SKILL.md \
195
+ test/templates/contracts-levels.test.js
196
+ git commit -m "feat(templates): remove legacy contracts.cs — level1/2/3 are the only contracts templates"
197
+ ```
198
+
199
+ ---
200
+
201
+ ## Task 3: phase-tasks DDD-aware
202
+
203
+ **Files:**
204
+ - Modify: `framework/skills/level-1-workflows/phase-tasks/SKILL.md`
205
+
206
+ **Step 1: Ler o arquivo atual** para entender onde inserir
207
+
208
+ ```bash
209
+ grep -n "Passo\|Step\|### " framework/skills/level-1-workflows/phase-tasks/SKILL.md | head -20
210
+ ```
211
+
212
+ **Step 2: Inserir "Passo 0" ANTES do Passo 1 atual**
213
+
214
+ O Passo 0 lê o nível de domínio do spec.md e ajusta a geração de tasks:
215
+
216
+ ```markdown
217
+ ### Passo 0: Ler Nível de Domínio
218
+
219
+ **Ref:** `framework/standards/architecture/ddd/complexity-levels.md`
220
+
221
+ Antes de quebrar tasks, leia a seção `## Domain Complexity` do spec.md:
222
+
223
+ ```bash
224
+ # Extrair nível do spec.md
225
+ grep -A2 "## Domain Complexity" .morph/features/$ARGUMENTS/1-design/spec.md
226
+ ```
227
+
228
+ Use o nível para ajustar as categorias de tasks:
229
+
230
+ | Nível | Categorias de Tasks |
231
+ |-------|---------------------|
232
+ | **1 — CRUD** | `domain` (Entity simples) → `infrastructure` (Repository, EF Config) → `application` (Service CRUD) → `presentation` (API/Page) → `tests` |
233
+ | **2 — Business Logic** | `domain` (AggregateRoot, ValueObjects, DomainEvents) → `infrastructure` (Repository, EF Config) → `application` (Commands, Queries, Handlers) → `presentation` (API/Page) → `tests` |
234
+ | **3 — Bounded Context** | `domain-bc` (BC setup, Aggregates, Events) → `infrastructure` (BC repositories, EF) → `application` (Commands, Queries, Integration handlers) → `presentation` → `tests` |
235
+
236
+ **Tasks adicionais obrigatórias por nível:**
237
+
238
+ **Nível 2 only:**
239
+ - `T{N}: Implementar AggregateRoot {EntityName} com factory method e invariants` (domain)
240
+ - `T{N}: Implementar ValueObjects: {lista}` (domain)
241
+ - `T{N}: Implementar DomainEvents: {lista}` (domain)
242
+ - `T{N}: Implementar Command Handlers com MediatR` (application)
243
+ - `T{N}: Implementar Query Handlers com read models` (application)
244
+
245
+ **Nível 3 only (além do Nível 2):**
246
+ - `T{N}: Configurar namespace/pasta do Bounded Context {BC}` (infrastructure)
247
+ - `T{N}: Implementar Integration Events para comunicação cross-BC` (domain-bc)
248
+ - `T{N}: Implementar handlers de Integration Events` (application)
249
+
250
+ ---
251
+ ```
252
+
253
+ **Step 3: Verificar que a inserção está antes do Passo 1**
254
+
255
+ ```bash
256
+ grep -n "Passo 0\|Passo 1\|complexity" framework/skills/level-1-workflows/phase-tasks/SKILL.md | head -10
257
+ ```
258
+ Esperado: Passo 0 antes do Passo 1, referência a complexity-levels.md presente.
259
+
260
+ **Step 4: Commit**
261
+
262
+ ```bash
263
+ git add framework/skills/level-1-workflows/phase-tasks/SKILL.md
264
+ git commit -m "feat(skills): add Passo 0 DDD-aware task generation to phase-tasks — 3 level task templates"
265
+ ```
266
+
267
+ ---
268
+
269
+ ## Task 4: Enriquecer system prompt do domain-architect
270
+
271
+ **Files:**
272
+ - Modify: `framework/agents.json`
273
+
274
+ **Step 1: Ler o `spawn_prompt` atual do domain-architect**
275
+
276
+ ```bash
277
+ node -e "
278
+ const a = JSON.parse(require('fs').readFileSync('framework/agents.json', 'utf8'));
279
+ const da = a.agents.find(x => x.id === 'domain-architect');
280
+ console.log(JSON.stringify(da.teammate, null, 2));
281
+ "
282
+ ```
283
+
284
+ **Step 2: Atualizar os campos do domain-architect**
285
+
286
+ Mudanças necessárias no objeto `domain-architect`:
287
+
288
+ 1. `standards` — adicionar os 3 novos standards DDD:
289
+ ```json
290
+ "standards": [
291
+ "core/coding.md",
292
+ "core/architecture.md",
293
+ "architecture/ddd/complexity-levels.md",
294
+ "architecture/ddd/aggregates.md",
295
+ "architecture/ddd/entities.md",
296
+ "architecture/ddd/value-objects.md",
297
+ "architecture/ddd/bounded-contexts.md",
298
+ "architecture/ddd/ubiquitous-language.md"
299
+ ]
300
+ ```
301
+
302
+ 2. `teammate.spawn_prompt` — substituir pelo prompt enriquecido:
303
+ ```
304
+ You are the Domain Modeling Leader for MORPH-SPEC. Your primary responsibility is detecting the correct domain complexity level and producing the Aggregate Blueprint before any contracts are generated.
305
+
306
+ ALWAYS start with the 5-question complexity detection:
307
+ 1. Does the main entity have state transitions? (Draft → Confirmed → Shipped) → Yes = Level 2+
308
+ 2. Are there business invariants? ("can only cancel if Active") → Yes = Level 2+
309
+ 3. Are there derived calculations? (Total, Balance, Discount) → Yes = Level 2+
310
+ 4. Do other modules need to react to changes? (Domain Events with consumers) → Yes = Level 2+
311
+ 5. Did the user explicitly declare a Bounded Context? Or are there 3+ domains with conflicting models? → Yes = Level 3
312
+ If none of the above: Level 1 (CRUD)
313
+
314
+ For Level 1: Use contracts-level1.cs template. No AggregateRoot, no Domain Events.
315
+ For Level 2: Use contracts-level2.cs template. Design AggregateRoot with factory methods, invariants, Value Objects, Domain Events.
316
+ For Level 3: Use contracts-level3.cs template. Add BOUNDED_CONTEXT namespace, Integration Events, cross-BC ID references only.
317
+
318
+ Document in spec.md under ## Domain Complexity and ## Aggregate Blueprint (Level 2+).
319
+ Coordinate ef-modeler for persistence design and event-architect for Domain Event patterns.
320
+ Ref: framework/standards/architecture/ddd/complexity-levels.md
321
+ ```
322
+
323
+ **Step 3: Aplicar as mudanças com Edit tool** (não reescrever o JSON todo)
324
+
325
+ Usar Edit para substituir `"standards": [` block e `"spawn_prompt":` value no domain-architect.
326
+
327
+ **Step 4: Validar JSON**
328
+
329
+ ```bash
330
+ node -e "
331
+ const a = JSON.parse(require('fs').readFileSync('framework/agents.json', 'utf8'));
332
+ const da = a.agents.find(x => x.id === 'domain-architect');
333
+ console.log('standards count:', da.standards.length);
334
+ console.log('spawn_prompt length:', da.teammate.spawn_prompt.length);
335
+ console.log('mentions complexity-levels:', da.teammate.spawn_prompt.includes('complexity-levels'));
336
+ "
337
+ ```
338
+ Esperado: standards count >= 8, spawn_prompt length > 500, mentions complexity-levels: true.
339
+
340
+ **Step 5: Rodar testes do agents-installer para garantir nenhuma regressão**
341
+
342
+ ```bash
343
+ node --test test/utils/agents-installer.test.js 2>&1 | grep -E "# (pass|fail)"
344
+ ```
345
+ Esperado: 0 fail.
346
+
347
+ **Step 6: Commit**
348
+
349
+ ```bash
350
+ git add framework/agents.json
351
+ git commit -m "feat(agents): enrich domain-architect spawn_prompt with 5-question detection + standards list"
352
+ ```
353
+
354
+ ---
355
+
356
+ ## Task 5: Exemplo end-to-end Level 2 (Order Management)
357
+
358
+ **Files:**
359
+ - Create: `docs/examples/order-management/proposal.md`
360
+ - Create: `docs/examples/order-management/spec.md`
361
+ - Create: `docs/examples/order-management/contracts.cs`
362
+
363
+ Este exemplo serve como referência viva de como um feature Level 2 deve se parecer após passar pelo pipeline completo. É documentação — sem testes unitários.
364
+
365
+ **Step 1: Criar `docs/examples/order-management/proposal.md`**
366
+
367
+ ```markdown
368
+ # Proposal: Order Management
369
+
370
+ **Feature:** order-management
371
+ **Type:** Business Logic (Level 2 candidate)
372
+ **Stack:** .NET 10 / C# 14, Blazor Server, EF Core, Azure SQL
373
+
374
+ ## User Story
375
+ Como usuário autenticado, quero criar e gerenciar pedidos de compra para que eu possa
376
+ acompanhar o status dos meus pedidos e receber notificações de mudanças.
377
+
378
+ ## Acceptance Criteria
379
+ - [ ] Usuário pode criar um pedido com 1+ itens
380
+ - [ ] Pedido começa no status Draft
381
+ - [ ] Pedido só pode ser Confirmado se tiver pelo menos 1 item
382
+ - [ ] Pedido Confirmado não pode receber mais itens
383
+ - [ ] Total do pedido é calculado automaticamente
384
+ - [ ] Sistema notifica quando pedido é Confirmado
385
+
386
+ ## Out of Scope
387
+ - Pagamento (feature separada)
388
+ - Envio/logística
389
+ ```
390
+
391
+ **Step 2: Criar `docs/examples/order-management/spec.md`**
392
+
393
+ Preencher o template de spec.md para este feature, incluindo as seções DDD obrigatórias:
394
+
395
+ ```markdown
396
+ # Feature Specification: Order Management
397
+
398
+ | Field | Value |
399
+ |-------|-------|
400
+ | **ID** | order-management |
401
+ | **Status** | Approved |
402
+ | **Created** | 2026-02-23 |
403
+ | **Stack** | .NET 10 / Blazor Server / EF Core |
404
+ | **Complexity** | Medium |
405
+ | **Agents** | Core: All / Specialists: domain-architect, ef-modeler, event-architect |
406
+
407
+ ---
408
+
409
+ ## Overview
410
+
411
+ **Problem:** Usuários precisam criar e gerenciar pedidos com rastreamento de status.
412
+
413
+ **Solution:** Aggregate Order com factory method, invariants de estado, e Domain Events para notificações.
414
+
415
+ **Success Criteria:**
416
+ - [ ] Order CRUD com validações de negócio
417
+ - [ ] Status tracking com transições controladas
418
+ - [ ] Notificação ao confirmar pedido
419
+
420
+ ---
421
+
422
+ ## Requirements
423
+
424
+ **Functional:**
425
+ FR001: Criar pedido com mínimo 1 item | FR002: Confirmar pedido (Draft → Confirmed) | FR003: Cancelar pedido (Draft/Confirmed → Cancelled) | FR004: Calcular total automaticamente
426
+
427
+ **Non-Functional:**
428
+ NFR001: Performance - operações < 200ms | NFR002: Consistência - invariants garantidas em toda operação
429
+
430
+ ---
431
+
432
+ ## User Stories
433
+
434
+ ### US001: Criar Pedido
435
+ **As** usuário autenticado **I want** criar um pedido com itens **so that** posso comprar produtos
436
+
437
+ **Acceptance Criteria:**
438
+ 1. Pedido criado com status Draft
439
+ 2. Total calculado na criação
440
+
441
+ **Edge Cases:** Lista de itens vazia → erro 400
442
+
443
+ ---
444
+
445
+ ## Technical Design
446
+
447
+ ### Stack
448
+ | Component | Technology |
449
+ |-----------|------------|
450
+ | Frontend | Blazor Server |
451
+ | Backend | .NET 10 / C# 14 |
452
+ | Database | Azure SQL / EF Core |
453
+
454
+ ### Data Model
455
+
456
+ #### Order
457
+ | Column | Type | Constraints |
458
+ |--------|------|-------------|
459
+ | Id | Guid | PK |
460
+ | UserId | Guid | FK (reference by ID — cross-aggregate) |
461
+ | Status | OrderStatus | Enum |
462
+ | CreatedAt | datetime2 | Default: GETUTCDATE() |
463
+ | UpdatedAt | datetime2 | Nullable |
464
+
465
+ #### OrderItem (owned entity)
466
+ | Column | Type | Constraints |
467
+ |--------|------|-------------|
468
+ | Id | Guid | PK |
469
+ | OrderId | Guid | FK |
470
+ | ProductId | Guid | Reference by ID |
471
+ | Quantity | int | > 0 |
472
+ | UnitPrice | decimal(18,2) | > 0 |
473
+
474
+ ### Contracts
475
+ > **Ref:** `framework/templates/code/dotnet/contracts/contracts-level2.cs`
476
+
477
+ ---
478
+
479
+ ## Domain Complexity
480
+
481
+ **Nível:** 2 — Business Logic
482
+
483
+ **Justificativa:** Order tem estados com transições controladas (Draft → Confirmed → Cancelled),
484
+ invariants de negócio (não confirmar sem itens, não adicionar itens a pedido confirmado),
485
+ cálculo derivado (Total), e outros módulos precisam reagir (NotificationService ao OrderConfirmed).
486
+
487
+ **Padrões Aplicados:**
488
+ - AggregateRoot com factory method estático
489
+ - Value Objects: Money (UnitPrice, Total)
490
+ - Domain Events: OrderCreatedEvent, OrderConfirmedEvent, OrderCancelledEvent
491
+ - CQRS com MediatR
492
+
493
+ **Padrões Omitidos:**
494
+ - Bounded Contexts — sistema single-domain, desnecessário
495
+
496
+ ---
497
+
498
+ ## Aggregate Blueprint (Nível 2+ apenas)
499
+
500
+ ### Aggregate Root: Order
501
+
502
+ **Invariants:**
503
+ - Order só pode ser Confirmado se Status == Draft E tiver pelo menos 1 item
504
+ - Order Confirmado não pode receber mais itens (AddItem lança DomainException)
505
+ - Order Cancelado não pode ser reativado (estado terminal)
506
+
507
+ **Estados e Transições:**
508
+ ```
509
+ {Draft} → Confirm() → {Confirmed}
510
+ {Draft} → Cancel() → {Cancelled}
511
+ {Confirmed} → Cancel() → {Cancelled}
512
+ ```
513
+
514
+ **Domain Events:**
515
+ - `OrderCreatedEvent` — publicado ao criar (Create factory method)
516
+ - `OrderConfirmedEvent` — publicado ao confirmar (Confirm method)
517
+ - `OrderCancelledEvent` — publicado ao cancelar (Cancel method)
518
+
519
+ **Value Objects:**
520
+ - `Money` — UnitPrice e Total não são decimals simples: têm validação (> 0) e operações (Add, Multiply)
521
+
522
+ **Referências Cross-Aggregate (por ID):**
523
+ - `UserId: Guid` — nunca `User User { get; }`
524
+ - `ProductId: Guid` em OrderItem — nunca `Product Product { get; }`
525
+
526
+ ### Linguagem Ubíqua
527
+
528
+ | Termo | Definição | Código |
529
+ |-------|-----------|--------|
530
+ | Order | Pedido de compra de um usuário | `Order` (AggregateRoot) |
531
+ | Draft | Pedido criado, ainda editável | `OrderStatus.Draft` |
532
+ | Confirm | Ato de finalizar e submeter um pedido | `Order.Confirm()` |
533
+ | OrderItem | Linha de produto dentro de um pedido | `OrderItem` (Entity owned) |
534
+ | Total | Soma calculada de todos os itens | `Order.Total` (property calculada) |
535
+
536
+ ---
537
+
538
+ ## Flows
539
+
540
+ ### Confirmar Pedido
541
+ **Trigger:** Usuário clica "Confirmar Pedido"
542
+ 1. Frontend → `POST /api/orders/{id}/confirm`
543
+ 2. API → `ConfirmOrderCommand(OrderId)`
544
+ 3. Handler → `repository.GetAsync(id)` → `order.Confirm()` → `repository.UpdateAsync(order)`
545
+ 4. `OrderConfirmedEvent` publicado → NotificationService envia email
546
+ **End State:** Order.Status = Confirmed
547
+
548
+ ---
549
+
550
+ ## Definition of Done
551
+ - [ ] Aggregate implementado com todos os invariants
552
+ - [ ] Domain Events publicados e consumidos
553
+ - [ ] Testes unitários do Aggregate (sem EF)
554
+ - [ ] Testes de integração do Handler
555
+ - [ ] API endpoint documentado
556
+ ```
557
+
558
+ **Step 3: Criar `docs/examples/order-management/contracts.cs`**
559
+
560
+ Exemplo real de contracts-level2.cs preenchido para Order:
561
+
562
+ ```csharp
563
+ // ============================================================
564
+ // CONTRACTS: Order Management — Level 2 (Business Logic)
565
+ // Example of correctly filled contracts-level2.cs template
566
+ // Feature: order-management | Date: 2026-02-23
567
+ // ============================================================
568
+
569
+ // ===== AGGREGATE ROOT =====
570
+ // Implementado em: Domain/Orders/Aggregates/Order.cs
571
+ //
572
+ // Invariants (do spec.md > Aggregate Blueprint):
573
+ // - Confirm() só é válido se Status == Draft E Items.Any()
574
+ // - AddItem() lança DomainException se Status != Draft
575
+ // - Cancel() é válido de Draft ou Confirmed → Cancelled (terminal)
576
+
577
+ // Domain/Orders/Events:
578
+ public record OrderCreatedEvent(Guid OrderId, Guid UserId) : DomainEvent;
579
+ public record OrderConfirmedEvent(Guid OrderId, Guid UserId, decimal Total) : DomainEvent;
580
+ public record OrderCancelledEvent(Guid OrderId, string Reason) : DomainEvent;
581
+
582
+ // Application/Orders/Commands:
583
+ public record CreateOrderCommand(Guid UserId, List<CreateOrderItemRequest> Items)
584
+ : IRequest<CreateOrderResult>;
585
+ public record CreateOrderResult(Guid OrderId);
586
+
587
+ public record ConfirmOrderCommand(Guid OrderId) : IRequest;
588
+ public record CancelOrderCommand(Guid OrderId, string Reason) : IRequest;
589
+
590
+ // Application/Orders/Queries:
591
+ public record GetOrderQuery(Guid OrderId) : IRequest<OrderDto?>;
592
+ public record ListOrdersByUserQuery(Guid UserId, int Page = 1, int PageSize = 20)
593
+ : IRequest<PagedResult<OrderDto>>;
594
+
595
+ // Application/Orders — DTOs (read models):
596
+ public record OrderDto(
597
+ Guid Id,
598
+ Guid UserId,
599
+ string Status,
600
+ decimal Total,
601
+ List<OrderItemDto> Items,
602
+ DateTime CreatedAt,
603
+ DateTime? UpdatedAt
604
+ );
605
+
606
+ public record OrderItemDto(Guid ProductId, int Quantity, decimal UnitPrice, decimal Subtotal);
607
+
608
+ public record CreateOrderItemRequest(Guid ProductId, int Quantity, decimal UnitPrice);
609
+
610
+ // Domain/Orders — Repository:
611
+ public interface IOrderRepository
612
+ {
613
+ Task<Order?> GetAsync(Guid id, CancellationToken ct = default);
614
+ Task<List<Order>> GetByUserAsync(Guid userId, CancellationToken ct = default);
615
+ Task AddAsync(Order order, CancellationToken ct = default);
616
+ Task UpdateAsync(Order order, CancellationToken ct = default);
617
+ Task<bool> ExistsAsync(Guid id, CancellationToken ct = default);
618
+ }
619
+
620
+ // Exceptions:
621
+ public class OrderNotFoundException(Guid id) : DomainException($"Order '{id}' not found.");
622
+ public class OrderInvalidStateException(string message) : DomainException(message);
623
+ ```
624
+
625
+ **Step 4: Verificar que os 3 arquivos foram criados**
626
+
627
+ ```bash
628
+ ls docs/examples/order-management/
629
+ ```
630
+ Esperado: `contracts.cs`, `proposal.md`, `spec.md`
631
+
632
+ **Step 5: Commit**
633
+
634
+ ```bash
635
+ git add docs/examples/order-management/
636
+ git commit -m "docs(examples): add order-management Level 2 reference example — proposal + spec + contracts"
637
+ ```
638
+
639
+ ---
640
+
641
+ ## Verificação Final
642
+
643
+ ```bash
644
+ # Testes
645
+ node --test 2>&1 | grep -E "# (pass|fail|skip)"
646
+
647
+ # Sem referências ao template legado
648
+ grep -rn "contracts\.cs" framework/skills/ framework/templates/ \
649
+ --include="*.md" --include="*.json" | grep -v "level1\|level2\|level3\|contracts-level\|contracts\.cs\.hbs"
650
+
651
+ # domain-architect é tier 2 e tem standards DDD
652
+ node -e "
653
+ const a = JSON.parse(require('fs').readFileSync('framework/agents.json', 'utf8'));
654
+ const da = a.agents.find(x => x.id === 'domain-architect');
655
+ console.log('tier:', da.tier);
656
+ console.log('standards:', da.standards.filter(s => s.includes('ddd')));
657
+ "
658
+
659
+ # Exemplo existe
660
+ ls docs/examples/order-management/
661
+ ```
662
+
663
+ ---
664
+
665
+ ## Resumo das Mudanças
666
+
667
+ | Categoria | Arquivos | Tipo |
668
+ |-----------|---------|------|
669
+ | Tests | `test/utils/agents-installer.test.js` | +2 testes domain-architect |
670
+ | Templates | `contracts.cs`, `contracts.cs.hbs` | DELETE |
671
+ | Templates | `REGISTRY.json` | Remove entrada legada |
672
+ | Skills | `phase-design/SKILL.md`, `tool-usage-guide/SKILL.md` | Atualizar referências |
673
+ | Tests | `test/templates/contracts-levels.test.js` | +1 teste ausência legado |
674
+ | Skills | `phase-tasks/SKILL.md` | +Passo 0 DDD-aware |
675
+ | Agents | `agents.json` | domain-architect standards + spawn_prompt |
676
+ | Docs | `docs/examples/order-management/` | 3 novos arquivos |
677
+
678
+ **5 tasks — ~1h30 de execução.**
679
+
680
+ ---
681
+
682
+ *MORPH-SPEC by Polymorphism Tech*