@polymorphism-tech/morph-spec 4.9.0 → 4.10.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 (124) hide show
  1. package/README.md +2 -2
  2. package/bin/morph-spec.js +30 -0
  3. package/bin/task-manager.js +34 -22
  4. package/claude-plugin.json +1 -1
  5. package/docs/CHEATSHEET.md +1 -1
  6. package/docs/QUICKSTART.md +1 -1
  7. package/framework/CLAUDE.md +99 -98
  8. package/framework/agents.json +37 -7
  9. package/framework/commands/commit.md +166 -0
  10. package/framework/commands/morph-apply.md +13 -2
  11. package/framework/commands/morph-archive.md +8 -2
  12. package/framework/commands/morph-infra.md +6 -0
  13. package/framework/commands/morph-preflight.md +6 -0
  14. package/framework/commands/morph-proposal.md +56 -7
  15. package/framework/commands/morph-status.md +6 -0
  16. package/framework/commands/morph-troubleshoot.md +6 -0
  17. package/framework/hooks/claude-code/notification/approval-reminder.js +3 -2
  18. package/framework/hooks/claude-code/post-tool-use/dispatch.js +154 -31
  19. package/framework/hooks/claude-code/post-tool-use/skill-reminder.js +7 -84
  20. package/framework/hooks/claude-code/post-tool-use/validator-feedback.js +8 -17
  21. package/framework/hooks/claude-code/pre-compact/save-morph-context.js +16 -3
  22. package/framework/hooks/claude-code/pre-tool-use/enforce-phase-writes.js +4 -3
  23. package/framework/hooks/claude-code/pre-tool-use/protect-spec-files.js +3 -2
  24. package/framework/hooks/claude-code/pre-tool-use/task-tracking-guard.js +60 -0
  25. package/framework/hooks/claude-code/session-start/inject-morph-context.js +55 -2
  26. package/framework/hooks/claude-code/session-start/post-compact-restore.js +41 -0
  27. package/framework/hooks/claude-code/stop/validate-completion.js +2 -15
  28. package/framework/hooks/claude-code/user-prompt/enrich-prompt.js +23 -5
  29. package/framework/hooks/shared/compact-restore.js +100 -0
  30. package/framework/hooks/shared/dispatch-helpers.js +116 -0
  31. package/framework/hooks/shared/phase-utils.js +9 -5
  32. package/framework/hooks/shared/state-reader.js +27 -3
  33. package/framework/phases.json +30 -7
  34. package/framework/rules/morph-workflow.md +88 -86
  35. package/framework/skills/level-0-meta/mcp-registry.json +86 -51
  36. package/framework/skills/level-0-meta/{brainstorming → morph-brainstorming}/SKILL.md +13 -16
  37. package/framework/skills/level-0-meta/{code-review → morph-code-review}/SKILL.md +1 -1
  38. package/framework/skills/level-0-meta/{code-review-nextjs → morph-code-review-nextjs}/SKILL.md +2 -2
  39. package/framework/skills/level-0-meta/{frontend-review → morph-frontend-review}/SKILL.md +5 -5
  40. package/framework/skills/level-0-meta/morph-init/SKILL.md +72 -7
  41. package/framework/skills/level-0-meta/{post-implementation → morph-post-implementation}/SKILL.md +9 -9
  42. package/framework/skills/level-0-meta/morph-replicate/SKILL.md +1 -1
  43. package/framework/skills/level-0-meta/{terminal-title → morph-terminal-title}/SKILL.md +1 -1
  44. package/framework/skills/level-0-meta/{tool-usage-guide → morph-tool-usage-guide}/SKILL.md +2 -3
  45. package/framework/skills/level-0-meta/{tool-usage-guide → morph-tool-usage-guide}/references/tools-per-phase.md +1 -2
  46. package/framework/skills/level-0-meta/{verification-before-completion → morph-verification-before-completion}/SKILL.md +1 -1
  47. package/framework/skills/level-0-meta/{verification-before-completion → morph-verification-before-completion}/scripts/check-phase-outputs.mjs +2 -2
  48. package/framework/skills/level-1-workflows/morph-phase-clarify/SKILL.md +238 -0
  49. package/framework/skills/level-1-workflows/{phase-codebase-analysis → morph-phase-codebase-analysis}/SKILL.md +251 -251
  50. package/framework/skills/level-1-workflows/morph-phase-design/SKILL.md +507 -0
  51. package/framework/skills/level-1-workflows/{phase-implement → morph-phase-implement}/SKILL.md +590 -491
  52. package/framework/skills/level-1-workflows/morph-phase-implement/prompts/code-quality-reviewer-prompt.md +50 -0
  53. package/framework/skills/level-1-workflows/morph-phase-implement/prompts/implementer-prompt.md +45 -0
  54. package/framework/skills/level-1-workflows/morph-phase-implement/prompts/spec-reviewer-prompt.md +47 -0
  55. package/framework/skills/level-1-workflows/morph-phase-plan/SKILL.md +254 -0
  56. package/framework/skills/level-1-workflows/{phase-setup → morph-phase-setup}/SKILL.md +237 -194
  57. package/framework/skills/level-1-workflows/{phase-tasks → morph-phase-tasks}/SKILL.md +307 -270
  58. package/framework/skills/level-1-workflows/{phase-tasks → morph-phase-tasks}/scripts/validate-tasks.mjs +3 -3
  59. package/framework/skills/level-1-workflows/{phase-uiux → morph-phase-uiux}/SKILL.md +320 -285
  60. package/framework/skills/level-1-workflows/morph-scope-escalation/SKILL.md +97 -0
  61. package/framework/standards/integration/mcp/mcp-tools.md +25 -7
  62. package/framework/templates/docs/onboarding.md +2 -2
  63. package/package.json +1 -2
  64. package/src/commands/agents/dispatch-agents.js +50 -3
  65. package/src/commands/mcp/mcp-setup.js +39 -2
  66. package/src/commands/phase/phase-reset.js +74 -0
  67. package/src/commands/project/doctor.js +19 -5
  68. package/src/commands/scope/escalate.js +215 -0
  69. package/src/commands/state/advance-phase.js +27 -53
  70. package/src/commands/state/state.js +1 -1
  71. package/src/commands/task/expand.js +100 -0
  72. package/src/core/paths/output-schema.js +4 -3
  73. package/src/core/state/phase-state-machine.js +7 -4
  74. package/src/core/state/state-manager.js +4 -3
  75. package/src/lib/detectors/claude-config-detector.js +93 -347
  76. package/src/lib/detectors/design-system-detector.js +189 -189
  77. package/src/lib/detectors/index.js +155 -57
  78. package/src/lib/generators/context-generator.js +2 -2
  79. package/src/lib/installers/mcp-installer.js +37 -5
  80. package/src/lib/phase-chain/phase-validator.js +22 -16
  81. package/src/lib/scope/impact-analyzer.js +106 -0
  82. package/src/lib/tasks/task-parser.js +1 -1
  83. package/src/lib/validators/shared/emit-validator-dispatch.js +64 -0
  84. package/src/scripts/setup-infra.js +15 -0
  85. package/src/utils/agents-installer.js +32 -12
  86. package/src/utils/file-copier.js +0 -1
  87. package/src/utils/hooks-installer.js +15 -1
  88. package/framework/skills/level-1-workflows/phase-clarify/SKILL.md +0 -216
  89. package/framework/skills/level-1-workflows/phase-design/SKILL.md +0 -383
  90. package/src/commands/project/index.js +0 -8
  91. package/src/core/index.js +0 -10
  92. package/src/core/state/index.js +0 -8
  93. package/src/core/templates/index.js +0 -9
  94. package/src/core/templates/template-data-sources.js +0 -325
  95. package/src/core/workflows/index.js +0 -7
  96. package/src/lib/detectors/config-detector.js +0 -223
  97. package/src/lib/detectors/standards-generator.js +0 -335
  98. package/src/lib/detectors/structure-detector.js +0 -275
  99. package/src/lib/monitor/agent-resolver.js +0 -144
  100. package/src/lib/monitor/renderer.js +0 -230
  101. package/src/lib/orchestration/index.js +0 -7
  102. package/src/lib/orchestration/team-orchestrator.js +0 -404
  103. package/src/sanitizer/context-sanitizer.js +0 -221
  104. package/src/sanitizer/patterns.js +0 -163
  105. package/src/writer/file-writer.js +0 -86
  106. /package/framework/skills/level-0-meta/{brainstorming → morph-brainstorming}/references/proposal-example.md +0 -0
  107. /package/framework/skills/level-0-meta/{code-review → morph-code-review}/references/review-example.md +0 -0
  108. /package/framework/skills/level-0-meta/{code-review → morph-code-review}/references/review-guidelines.md +0 -0
  109. /package/framework/skills/level-0-meta/{code-review → morph-code-review}/scripts/scan-csharp.mjs +0 -0
  110. /package/framework/skills/level-0-meta/{code-review-nextjs → morph-code-review-nextjs}/references/review-example-nextjs.md +0 -0
  111. /package/framework/skills/level-0-meta/{code-review-nextjs → morph-code-review-nextjs}/scripts/scan-nextjs.mjs +0 -0
  112. /package/framework/skills/level-0-meta/{frontend-review → morph-frontend-review}/scripts/scan-accessibility.mjs +0 -0
  113. /package/framework/skills/level-0-meta/{post-implementation → morph-post-implementation}/scripts/detect-dev-server.mjs +0 -0
  114. /package/framework/skills/level-0-meta/{post-implementation → morph-post-implementation}/scripts/detect-stack.mjs +0 -0
  115. /package/framework/skills/level-0-meta/{simulation-checklist → morph-simulation-checklist}/SKILL.md +0 -0
  116. /package/framework/skills/level-0-meta/{terminal-title → morph-terminal-title}/scripts/set_title.sh +0 -0
  117. /package/framework/skills/level-1-workflows/{phase-clarify → morph-phase-clarify}/references/clarifications-example.md +0 -0
  118. /package/framework/skills/level-1-workflows/{phase-design → morph-phase-design}/references/architecture-analysis-guide.md +0 -0
  119. /package/framework/skills/level-1-workflows/{phase-design → morph-phase-design}/references/spec-authoring-guide.md +0 -0
  120. /package/framework/skills/level-1-workflows/{phase-design → morph-phase-design}/references/spec-example.md +0 -0
  121. /package/framework/skills/level-1-workflows/{phase-implement → morph-phase-implement}/references/recap-example.md +0 -0
  122. /package/framework/skills/level-1-workflows/{phase-implement → morph-phase-implement}/references/vsa-implementation-guide.md +0 -0
  123. /package/framework/skills/level-1-workflows/{phase-tasks → morph-phase-tasks}/references/task-planning-patterns.md +0 -0
  124. /package/framework/skills/level-1-workflows/{phase-tasks → morph-phase-tasks}/references/tasks-example.md +0 -0
@@ -0,0 +1,166 @@
1
+ ---
2
+ allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git diff:*), Bash(git log:*)
3
+ argument-hint: [message] | --no-verify | --amend
4
+ description: Create well-formatted commits with conventional commit format and emoji
5
+ ---
6
+
7
+ # Smart Git Commit
8
+
9
+ Create well-formatted commit: $ARGUMENTS
10
+
11
+ ## Current Repository State
12
+
13
+ - Git status: !git status --porcelain
14
+ - Current branch: !git branch --show-current
15
+ - Staged changes: !git diff --cached --stat
16
+ - Unstaged changes: !git diff --stat
17
+ - Recent commits: !git log --oneline -5
18
+
19
+ ## What This Command Does
20
+
21
+ 1. Unless specified with --no-verify, automatically runs pre-commit checks:
22
+ - pnpm lint to ensure code quality
23
+ - pnpm build to verify the build succeeds
24
+ - pnpm generate:docs to update documentation
25
+ 2. Checks which files are staged with git status
26
+ 3. If 0 files are staged, automatically adds all modified and new files with git add
27
+ 4. Performs a git diff to understand what changes are being committed
28
+ 5. Analyzes the diff to determine if multiple distinct logical changes are present
29
+ 6. If multiple distinct changes are detected, suggests breaking the commit into multiple smaller commits
30
+ 7. For each commit (or the single commit if not split), creates a commit message using emoji conventional commit format
31
+
32
+ ## Best Practices for Commits
33
+
34
+ - **Verify before committing**: Ensure code is linted, builds correctly, and documentation is updated
35
+ - **Atomic commits**: Each commit should contain related changes that serve a single purpose
36
+ - **Split large changes**: If changes touch multiple concerns, split them into separate commits
37
+ - **Conventional commit format**: Use the format <type>: <description> where type is one of:
38
+ - feat: A new feature
39
+ - fix: A bug fix
40
+ - docs: Documentation changes
41
+ - style: Code style changes (formatting, etc)
42
+ - refactor: Code changes that neither fix bugs nor add features
43
+ - perf: Performance improvements
44
+ - test: Adding or fixing tests
45
+ - chore: Changes to the build process, tools, etc.
46
+ - **Present tense, imperative mood**: Write commit messages as commands (e.g., "add feature" not "added feature")
47
+ - **Concise first line**: Keep the first line under 72 characters
48
+ - **Emoji**: Each commit type is paired with an appropriate emoji:
49
+ - ✨ feat: New feature
50
+ - 🐛 fix: Bug fix
51
+ - 📝 docs: Documentation
52
+ - 💄 style: Formatting/style
53
+ - ♻️ refactor: Code refactoring
54
+ - ⚡️ perf: Performance improvements
55
+ - ✅ test: Tests
56
+ - 🔧 chore: Tooling, configuration
57
+ - 🚀 ci: CI/CD improvements
58
+ - 🗑️ revert: Reverting changes
59
+ - 🧪 test: Add a failing test
60
+ - 🚨 fix: Fix compiler/linter warnings
61
+ - 🔒️ fix: Fix security issues
62
+ - 👥 chore: Add or update contributors
63
+ - 🚚 refactor: Move or rename resources
64
+ - 🏗️ refactor: Make architectural changes
65
+ - 🔀 chore: Merge branches
66
+ - 📦️ chore: Add or update compiled files or packages
67
+ - ➕ chore: Add a dependency
68
+ - ➖ chore: Remove a dependency
69
+ - 🌱 chore: Add or update seed files
70
+ - 🧑‍💻 chore: Improve developer experience
71
+ - 🧵 feat: Add or update code related to multithreading or concurrency
72
+ - 🔍️ feat: Improve SEO
73
+ - 🏷️ feat: Add or update types
74
+ - 💬 feat: Add or update text and literals
75
+ - 🌐 feat: Internationalization and localization
76
+ - 👔 feat: Add or update business logic
77
+ - 📱 feat: Work on responsive design
78
+ - 🚸 feat: Improve user experience / usability
79
+ - 🩹 fix: Simple fix for a non-critical issue
80
+ - 🥅 fix: Catch errors
81
+ - 👽️ fix: Update code due to external API changes
82
+ - 🔥 fix: Remove code or files
83
+ - 🎨 style: Improve structure/format of the code
84
+ - 🚑️ fix: Critical hotfix
85
+ - 🎉 chore: Begin a project
86
+ - 🔖 chore: Release/Version tags
87
+ - 🚧 wip: Work in progress
88
+ - 💚 fix: Fix CI build
89
+ - 📌 chore: Pin dependencies to specific versions
90
+ - 👷 ci: Add or update CI build system
91
+ - 📈 feat: Add or update analytics or tracking code
92
+ - ✏️ fix: Fix typos
93
+ - ⏪️ revert: Revert changes
94
+ - 📄 chore: Add or update license
95
+ - 💥 feat: Introduce breaking changes
96
+ - 🍱 assets: Add or update assets
97
+ - ♿️ feat: Improve accessibility
98
+ - 💡 docs: Add or update comments in source code
99
+ - 🗃️ db: Perform database related changes
100
+ - 🔊 feat: Add or update logs
101
+ - 🔇 fix: Remove logs
102
+ - 🤡 test: Mock things
103
+ - 🥚 feat: Add or update an easter egg
104
+ - 🙈 chore: Add or update .gitignore file
105
+ - 📸 test: Add or update snapshots
106
+ - ⚗️ experiment: Perform experiments
107
+ - 🚩 feat: Add, update, or remove feature flags
108
+ - 💫 ui: Add or update animations and transitions
109
+ - ⚰️ refactor: Remove dead code
110
+ - 🦺 feat: Add or update code related to validation
111
+ - ✈️ feat: Improve offline support
112
+
113
+ ## Guidelines for Splitting Commits
114
+
115
+ When analyzing the diff, consider splitting commits based on these criteria:
116
+
117
+ 1. **Different concerns**: Changes to unrelated parts of the codebase
118
+ 2. **Different types of changes**: Mixing features, fixes, refactoring, etc.
119
+ 3. **File patterns**: Changes to different types of files (e.g., source code vs documentation)
120
+ 4. **Logical grouping**: Changes that would be easier to understand or review separately
121
+ 5. **Size**: Very large changes that would be clearer if broken down
122
+
123
+ ## Examples
124
+
125
+ Good commit messages:
126
+ - ✨ feat: add user authentication system
127
+ - 🐛 fix: resolve memory leak in rendering process
128
+ - 📝 docs: update API documentation with new endpoints
129
+ - ♻️ refactor: simplify error handling logic in parser
130
+ - 🚨 fix: resolve linter warnings in component files
131
+ - 🧑‍💻 chore: improve developer tooling setup process
132
+ - 👔 feat: implement business logic for transaction validation
133
+ - 🩹 fix: address minor styling inconsistency in header
134
+ - 🚑️ fix: patch critical security vulnerability in auth flow
135
+ - 🎨 style: reorganize component structure for better readability
136
+ - 🔥 fix: remove deprecated legacy code
137
+ - 🦺 feat: add input validation for user registration form
138
+ - 💚 fix: resolve failing CI pipeline tests
139
+ - 📈 feat: implement analytics tracking for user engagement
140
+ - 🔒️ fix: strengthen authentication password requirements
141
+ - ♿️ feat: improve form accessibility for screen readers
142
+
143
+ Example of splitting commits:
144
+ - First commit: ✨ feat: add new solc version type definitions
145
+ - Second commit: 📝 docs: update documentation for new solc versions
146
+ - Third commit: 🔧 chore: update package.json dependencies
147
+ - Fourth commit: 🏷️ feat: add type definitions for new API endpoints
148
+ - Fifth commit: 🧵 feat: improve concurrency handling in worker threads
149
+ - Sixth commit: 🚨 fix: resolve linting issues in new code
150
+ - Seventh commit: ✅ test: add unit tests for new solc version features
151
+ - Eighth commit: 🔒️ fix: update dependencies with security vulnerabilities
152
+
153
+ ## Command Options
154
+
155
+ - --no-verify: Skip running the pre-commit checks (lint, build, generate:docs)
156
+
157
+ ## Important Notes
158
+
159
+ - By default, pre-commit checks (pnpm lint, pnpm build, pnpm generate:docs) will run to ensure code quality
160
+ - If these checks fail, you'll be asked if you want to proceed with the commit anyway or fix the issues first
161
+ - If specific files are already staged, the command will only commit those files
162
+ - If no files are staged, it will automatically stage all modified and new files
163
+ - The commit message will be constructed based on the changes detected
164
+ - Before committing, the command will review the diff to identify if multiple commits would be more appropriate
165
+ - If suggesting multiple commits, it will help you stage and commit the changes separately
166
+ - Always reviews the commit diff to ensure the message matches the changes
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: Implementa a feature especificada seguindo as tasks definidas na FASE 5 do workflow MORPH
3
+ argument-hint: <feature-name>
4
+ allowed-tools: Read, Write, Edit, Bash, Glob, Grep
5
+ ---
6
+
1
7
  # Apply MORPH Feature Implementation - FASE 5
2
8
 
3
9
  Implemente a feature especificada seguindo as tasks definidas.
@@ -42,7 +48,11 @@ npx morph-spec state get {feature-name}
42
48
  - [ ] Phase passou por "clarify"
43
49
  - [ ] Spec atualizado com clarificações
44
50
 
45
- 6. **FASE 4 (Tasks):**
51
+ 6. **FASE 4 (Plan):**
52
+ - [ ] Output `plan` criado
53
+ - [ ] Plano de implementação aprovado
54
+
55
+ 7. **FASE 5 (Tasks):**
46
56
  - [ ] Output `tasks` criado
47
57
  - [ ] `tasks.json` tem array de tasks
48
58
  - [ ] `tasks.total` > 0 no state
@@ -69,7 +79,8 @@ Para completar as fases de planejamento, execute:
69
79
 
70
80
  1. **Carregue o contexto**:
71
81
  - Leia `.morph/features/{feature}/1-design/spec.md`
72
- - Leia `.morph/features/{feature}/3-tasks/tasks.md`
82
+ - Leia `.morph/features/{feature}/3-plan/plan.md`
83
+ - Leia `.morph/features/{feature}/4-tasks/tasks.md`
73
84
  - Leia `.morph/features/{feature}/1-design/contracts.cs`
74
85
  - Leia framework/standards/ e .morph/context/ para padrões
75
86
 
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: Arquiva uma feature concluída movendo de features/ para archive/ e atualizando o state
3
+ argument-hint: <feature-name>
4
+ allowed-tools: Read, Write, Edit, Bash
5
+ ---
6
+
1
7
  # Archive MORPH Feature
2
8
 
3
9
  Arquive uma feature concluída, movendo-a de `features/` para `archive/`.
@@ -13,12 +19,12 @@ Verifique antes de arquivar:
13
19
  ## Workflow
14
20
 
15
21
  1. **Valide a conclusão**:
16
- - Leia `.morph/features/{feature}/3-tasks/tasks.md`
22
+ - Leia `.morph/features/{feature}/4-tasks/tasks.md`
17
23
  - Verifique que todas tasks estão completadas
18
24
  - Confirme com o usuário se pode arquivar
19
25
 
20
26
  2. **Complete o recap**:
21
- - Atualize `.morph/features/{feature}/4-implement/recap.md`
27
+ - Atualize `.morph/features/{feature}/5-implement/recap.md`
22
28
  - Preencha métricas finais
23
29
  - Documente lições aprendidas
24
30
 
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: Gerencia infraestrutura Azure com Bicep templates — provisiona, atualiza e monitora recursos cloud
3
+ argument-hint: [up|down|plan|status]
4
+ allowed-tools: Read, Write, Edit, Bash, Glob
5
+ ---
6
+
1
7
  # /morph-infra - Infrastructure Management
2
8
 
3
9
  Gerencia infraestrutura Azure usando Bicep templates.
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: Valida readiness do projeto antes do deploy Azure — verifica specs, contratos, testes, e infraestrutura
3
+ argument-hint: [feature-name]
4
+ allowed-tools: Read, Bash, Glob, Grep
5
+ ---
6
+
1
7
  # Pre-Flight Check for Azure Deployment
2
8
 
3
9
  Validates project readiness before deploying to Azure.
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: MORPH Spec Pipeline — cria ou retoma o planejamento de uma feature pelas fases 0→4 com pausas obrigatórias de aprovação
3
+ argument-hint: <feature-name>
4
+ allowed-tools: Read, Write, Edit, Bash, Glob, Grep
5
+ ---
6
+
1
7
  # MORPH Spec Pipeline
2
8
 
3
9
  Crie ou retome o planejamento de uma feature, guiando automaticamente pelas fases 0→4 com pausas obrigatórias.
@@ -37,7 +43,8 @@ npx morph-spec state get {feature-name}
37
43
  .morph/features/{feature-name}/
38
44
  ├── 0-proposal/proposal.md
39
45
  ├── 1-design/spec.md (iniciar)
40
- └── 3-tasks/tasks.md (iniciar)
46
+ └── 4-tasks/tasks.md (iniciar)
47
+
41
48
  ```
42
49
 
43
50
  5. **Preencha `proposal.md`** baseado em `framework/templates/proposal.md`
@@ -55,11 +62,17 @@ npx morph-spec state get {feature-name}
55
62
 
56
63
  Apresente: resumo da proposta, agentes ativados, custo estimado, 3 itens de pausa.
57
64
 
65
+ Após o usuário aprovar:
66
+ ```bash
67
+ npx morph-spec approve {feature-name} proposal
68
+ npx morph-spec phase advance {feature-name}
69
+ ```
70
+
58
71
  ---
59
72
 
60
73
  ## 3. Após Aprovação do Proposal → FASE 1: SETUP (auto, sem pausa)
61
74
 
62
- **Ler:** `.claude/skills/level-1-workflows/phase-setup.md` para instruções detalhadas.
75
+ Use o skill `morph-phase-setup` para instruções detalhadas.
63
76
 
64
77
  Resumo: carregar contexto do projeto, confirmar stack, listar agentes ativos, atualizar state.
65
78
 
@@ -70,14 +83,20 @@ Resumo: carregar contexto do projeto, confirmar stack, listar agentes ativos, at
70
83
  ## 4. FASE 1.5: UI/UX (condicional)
71
84
 
72
85
  Verificar se `uiux-designer` está nos `activeAgents`:
73
- - **Se SIM:** Ler `.claude/skills/level-1-workflows/phase-uiux.md` e executar. **PAUSA OBRIGATORIA** após gerar deliverables UI.
86
+ - **Se SIM:** Use o skill `morph-phase-uiux` e executar. **PAUSA OBRIGATORIA** após gerar deliverables UI.
74
87
  - **Se NÃO:** Pular para FASE 2.
75
88
 
89
+ Após o usuário aprovar:
90
+ ```bash
91
+ npx morph-spec approve {feature-name} uiux
92
+ npx morph-spec phase advance {feature-name}
93
+ ```
94
+
76
95
  ---
77
96
 
78
97
  ## 5. FASE 2: DESIGN
79
98
 
80
- **Ler:** `.claude/skills/level-1-workflows/phase-design.md` para instruções detalhadas.
99
+ Use o skill `morph-phase-design` para instruções detalhadas.
81
100
 
82
101
  Resumo: gerar spec.md, contracts.cs, decisions.md com ADRs, estimar custos.
83
102
 
@@ -85,11 +104,17 @@ Resumo: gerar spec.md, contracts.cs, decisions.md com ADRs, estimar custos.
85
104
 
86
105
  Apresente: spec, contracts, decisions, custos. 3 itens de pausa (aprovar, ajustar escopo, modificar contracts).
87
106
 
107
+ Após o usuário aprovar:
108
+ ```bash
109
+ npx morph-spec approve {feature-name} design
110
+ npx morph-spec phase advance {feature-name}
111
+ ```
112
+
88
113
  ---
89
114
 
90
115
  ## 6. Após Aprovação do Design → FASE 3: CLARIFY (interativo)
91
116
 
92
- **Ler:** `.claude/skills/level-1-workflows/phase-clarify.md` para instruções detalhadas.
117
+ Use o skill `morph-phase-clarify` para instruções detalhadas.
93
118
 
94
119
  Resumo: identificar ambiguidades, gerar 3-7 perguntas, aguardar respostas, atualizar spec com clarificações e edge cases.
95
120
 
@@ -97,9 +122,27 @@ Resumo: identificar ambiguidades, gerar 3-7 perguntas, aguardar respostas, atual
97
122
 
98
123
  ---
99
124
 
100
- ## 7. FASE 4: TASKS
125
+ ## 6.5. FASE 4: PLAN
126
+
127
+ Use o skill `morph-phase-plan` para instruções detalhadas.
101
128
 
102
- **Ler:** `.claude/skills/level-1-workflows/phase-tasks.md` para instruções detalhadas.
129
+ Resumo: gerar plano de implementação detalhado com paths exatos, código TDD, e estratégia de execução context-aware.
130
+
131
+ ### PAUSA OBRIGATORIA
132
+
133
+ Apresente: plano de implementação com estratégia recomendada. 3 itens de pausa (aprovar plano, ajustar estratégia, modificar plano).
134
+
135
+ Após o usuário aprovar:
136
+ ```bash
137
+ npx morph-spec approve {feature-name} plan
138
+ npx morph-spec phase advance {feature-name}
139
+ ```
140
+
141
+ ---
142
+
143
+ ## 7. FASE 5: TASKS
144
+
145
+ Use o skill `morph-phase-tasks` para instruções detalhadas.
103
146
 
104
147
  Resumo: quebrar spec em tasks T001-TXXX, definir dependências, checkpoints, estimativas.
105
148
 
@@ -107,6 +150,12 @@ Resumo: quebrar spec em tasks T001-TXXX, definir dependências, checkpoints, est
107
150
 
108
151
  Apresente: breakdown de tasks, ordem de execução, estimativa total. 3 itens de pausa (aprovar, repriorizar, adicionar/remover).
109
152
 
153
+ Após o usuário aprovar:
154
+ ```bash
155
+ npx morph-spec approve {feature-name} tasks
156
+ npx morph-spec phase advance {feature-name}
157
+ ```
158
+
110
159
  ---
111
160
 
112
161
  ## 8. Planejamento Completo
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: Mostra o status atual do projeto MORPH e todas as features em desenvolvimento com suas fases e aprovações
3
+ argument-hint: [feature-name]
4
+ allowed-tools: Read, Bash
5
+ ---
6
+
1
7
  # MORPH Project Status
2
8
 
3
9
  Mostre o status atual do projeto MORPH e features em desenvolvimento.
@@ -1,3 +1,9 @@
1
+ ---
2
+ description: Busca soluções para erros e problemas comuns no desenvolvimento .NET/Blazor/Azure com análise root-cause
3
+ argument-hint: "[error-message]"
4
+ allowed-tools: Read, Bash, Glob, Grep
5
+ ---
6
+
1
7
  # Troubleshoot - Buscar Soluções para Erros
2
8
 
3
9
  Busca soluções para erros e problemas comuns no desenvolvimento .NET/Blazor/Azure.
@@ -10,7 +10,7 @@
10
10
  * Fail-open: exits 0 on any error.
11
11
  */
12
12
 
13
- import { stateExists, getActiveFeature, getPendingGates } from '../../shared/state-reader.js';
13
+ import { stateExists, getActiveFeature, getPendingGates, derivePhaseForFeature } from '../../shared/state-reader.js';
14
14
  import { injectContext, pass } from '../../shared/hook-response.js';
15
15
  import { logHookActivity } from '../../shared/activity-logger.js';
16
16
 
@@ -36,7 +36,8 @@ try {
36
36
  implement: ['design', 'tasks']
37
37
  };
38
38
 
39
- const relevantGates = phaseGateRelevance[feature.phase] || [];
39
+ const currentPhase = feature.phase || derivePhaseForFeature(name);
40
+ const relevantGates = phaseGateRelevance[currentPhase] || [];
40
41
  const pendingRelevant = pending.filter(g => relevantGates.includes(g));
41
42
 
42
43
  if (pendingRelevant.length === 0) pass();
@@ -1,25 +1,33 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * PostToolUse Hook: Improved Dispatch
4
+ * PostToolUse Hook: Dispatch + Validator Injection
5
5
  *
6
6
  * Event: PostToolUse | Matcher: Bash
7
7
  *
8
- * Replaces the old agent-teams/dispatch.js with:
9
- * - Reads state BEFORE dispatching to pass correct from/to phases
10
- * - Handles more CLI commands: approve, state init, checkpoint commands
11
- * - Triggers checkpoint validation on task completion when count % 3 === 0
8
+ * Handles:
9
+ * - morph-spec task done: auto-checkpoint every 3 tasks + validator dispatch injection
10
+ * - morph-spec phase advance: phase chain evaluation + validator dispatch injection
11
+ * - morph-spec approve: pass-through
12
+ *
13
+ * Validator dispatch: extracts VALIDATION DISPATCH JSON from tool output
14
+ * and injects it as additionalContext so Claude reliably dispatches validators
15
+ * as subagents via the Agent tool.
12
16
  *
13
17
  * Fail-open: exits 0 on any error.
14
18
  */
15
19
 
16
20
  import { execSync } from 'child_process';
17
21
  import { readFileSync, existsSync } from 'fs';
18
- import { resolve } from 'path';
22
+ import { resolve, join, dirname } from 'path';
23
+ import { fileURLToPath } from 'url';
24
+
25
+ const __dirname = dirname(fileURLToPath(import.meta.url));
19
26
  import { readStdin } from '../../shared/stdin-reader.js';
20
- import { stateExists, getFeature } from '../../shared/state-reader.js';
27
+ import { stateExists, getFeature, getFeaturePhase } from '../../shared/state-reader.js';
21
28
  import { pass, injectContext } from '../../shared/hook-response.js';
22
29
  import { logHookActivity } from '../../shared/activity-logger.js';
30
+ import { extractValidationDispatch, formatValidatorInstruction, getToolOutput, parseTaskDoneCommand, parsePhaseAdvanceCommand } from '../../shared/dispatch-helpers.js';
23
31
 
24
32
  try {
25
33
  if (!stateExists()) pass();
@@ -30,24 +38,27 @@ try {
30
38
  const command = payload?.tool_input?.command || '';
31
39
  if (!command) pass();
32
40
 
33
- dispatch(command);
41
+ await dispatch(command, payload);
34
42
  } catch {
35
43
  // Fail-open
36
44
  process.exit(0);
37
45
  }
38
46
 
39
- function dispatch(command) {
47
+ async function dispatch(command, payload) {
40
48
  // morph-spec task done <feature> <taskId> [--skip-validation]
41
- const taskDoneMatch = command.match(/morph-spec\s+task\s+done\s+(\S+)\s+(\S+)/);
42
- if (taskDoneMatch) {
43
- const [, featureName, taskId] = taskDoneMatch;
49
+ const taskDoneParsed = parseTaskDoneCommand(command);
50
+ if (taskDoneParsed) {
51
+ const { featureName } = taskDoneParsed;
52
+ const skipValidation = command.includes('--skip-validation');
53
+
54
+ const contextParts = [];
44
55
 
45
56
  // Check if checkpoint should run (every 3 tasks)
46
57
  let dispatchResult = 'task_done';
47
58
  try {
48
59
  const feature = getFeature(featureName);
49
60
  if (feature?.tasks) {
50
- const completed = (feature.tasks.completed || 0) + 1; // +1 because task-done hasn't executed yet
61
+ const completed = (feature.tasks.completed || 0) + 1;
51
62
  if (completed > 0 && completed % 3 === 0) {
52
63
  const checkpointNum = Math.floor(completed / 3);
53
64
  run(`morph-spec checkpoint-save ${featureName} --note "Auto-checkpoint #${checkpointNum} at task ${completed}"`);
@@ -58,16 +69,45 @@ function dispatch(command) {
58
69
  // Non-blocking
59
70
  }
60
71
 
72
+ // Inject validator dispatch for task completion.
73
+ // Skip when --skip-validation: no validators needed, avoids subprocess fallback.
74
+ if (!skipValidation) {
75
+ const validatorText = await buildValidatorDispatchContext(featureName, payload);
76
+ if (validatorText) {
77
+ contextParts.push(validatorText);
78
+ dispatchResult = 'task_done_with_validators';
79
+ }
80
+ }
81
+
61
82
  logHookActivity('phase-dispatch', 'PostToolUse', dispatchResult);
83
+
84
+ if (contextParts.length > 0) {
85
+ injectContext(contextParts.join('\n\n'));
86
+ }
62
87
  pass();
63
88
  }
64
89
 
65
90
  // morph-spec phase advance <feature>
66
- const phaseAdvanceMatch = command.match(/morph-spec\s+phase\s+advance\s+(\S+)/);
67
- if (phaseAdvanceMatch) {
68
- const [, featureName] = phaseAdvanceMatch;
69
- evaluatePhaseChain(featureName);
70
- logHookActivity('phase-dispatch', 'PostToolUse', 'phase_chain');
91
+ const phaseAdvanceParsed = parsePhaseAdvanceCommand(command);
92
+ if (phaseAdvanceParsed) {
93
+ const { featureName } = phaseAdvanceParsed;
94
+
95
+ const contextParts = [];
96
+
97
+ // Phase chain evaluation
98
+ const chainText = buildPhaseChainContext(featureName);
99
+ if (chainText) contextParts.push(chainText);
100
+
101
+ // Validator dispatch injection
102
+ const validatorText = await buildValidatorDispatchContext(featureName, payload);
103
+ if (validatorText) contextParts.push(validatorText);
104
+
105
+ logHookActivity('phase-dispatch', 'PostToolUse',
106
+ validatorText ? 'phase_advance_with_validators' : 'phase_chain');
107
+
108
+ if (contextParts.length > 0) {
109
+ injectContext(contextParts.join('\n\n'));
110
+ }
71
111
  pass();
72
112
  }
73
113
 
@@ -83,45 +123,128 @@ function dispatch(command) {
83
123
  }
84
124
 
85
125
  /**
86
- * Evaluate whether the phase chain should auto-continue after a phase advance.
87
- * Injects a `morph-spec phase run` instruction when the workflow has phaseChain.enabled.
88
- * Silently passes when workflow doesn't support chaining or feature is not found.
126
+ * Build phase chain context text (returns null if not applicable).
127
+ * Replaces the old evaluatePhaseChain that called injectContext directly.
89
128
  *
90
129
  * @param {string} featureName
130
+ * @returns {string|null}
91
131
  */
92
- function evaluatePhaseChain(featureName) {
132
+ function buildPhaseChainContext(featureName) {
93
133
  try {
94
134
  const feature = getFeature(featureName);
95
- if (!feature) return;
135
+ if (!feature) return null;
96
136
 
97
137
  const workflowId = feature.workflow;
98
- if (!workflowId || workflowId === 'auto') return;
138
+ if (!workflowId || workflowId === 'auto') return null;
99
139
 
100
- // Load workflow config to check phaseChain.enabled
101
140
  const configPath = resolve(
102
141
  process.cwd(),
103
142
  `.morph/framework/workflows/configs/${workflowId}.json`
104
143
  );
105
- if (!existsSync(configPath)) return;
144
+ if (!existsSync(configPath)) return null;
106
145
 
107
146
  let workflowConfig;
108
147
  try {
109
148
  workflowConfig = JSON.parse(readFileSync(configPath, 'utf8'));
110
149
  } catch {
111
- return;
150
+ return null;
112
151
  }
113
152
 
114
- if (!workflowConfig?.phaseChain?.enabled) return;
153
+ if (!workflowConfig?.phaseChain?.enabled) return null;
115
154
 
116
- // Inject instruction to continue the phase chain
117
- injectContext(
155
+ return (
118
156
  `Phase advance complete. Continue the phase chain:\n` +
119
157
  ` morph-spec phase run ${featureName}\n\n` +
120
158
  `The phase runner will check eligibility and auto-advance if all gates pass. ` +
121
159
  `It will pause automatically on blocked tasks, low pass rate, or trust gates.`
122
160
  );
123
161
  } catch {
124
- // Non-blocking — fail silently
162
+ return null;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Extract validator dispatch from tool output and build injection context.
168
+ *
169
+ * Strategy:
170
+ * 1. Try to parse VALIDATION DISPATCH JSON from the tool_result (stdout of phase advance)
171
+ * 2. If not found, fallback to running dispatch-agents CLI in validate mode
172
+ *
173
+ * @param {string} featureName
174
+ * @param {object} payload - PostToolUse hook payload
175
+ * @returns {string|null} - Formatted injection text or null
176
+ */
177
+ async function buildValidatorDispatchContext(featureName, payload) {
178
+ try {
179
+ // Strategy 1: Extract from tool output
180
+ const toolOutput = getToolOutput(payload);
181
+ const dispatch = extractValidationDispatch(toolOutput);
182
+ if (dispatch) return formatValidatorInstruction(dispatch);
183
+
184
+ // Strategy 2: Direct import of buildDispatchConfig (no subprocess)
185
+ return await buildDispatchDirect(featureName);
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Fallback: build validator dispatch config via direct import (no subprocess).
193
+ *
194
+ * Attempts to import buildDispatchConfig from the installed package or local
195
+ * framework. Falls back to null on any error (fail-open).
196
+ *
197
+ * @param {string} featureName
198
+ * @returns {Promise<string|null>}
199
+ */
200
+ async function buildDispatchDirect(featureName) {
201
+ try {
202
+ const phase = getFeaturePhase(featureName);
203
+ if (!phase) return null;
204
+
205
+ // Try local project path first, then package path
206
+ let buildDispatchConfig;
207
+ const localPath = resolve(process.cwd(), 'src/commands/agents/dispatch-agents.js');
208
+ const pkgPath = resolve(process.cwd(), 'node_modules/@polymorphism-tech/morph-spec/src/commands/agents/dispatch-agents.js');
209
+
210
+ if (existsSync(localPath)) {
211
+ ({ buildDispatchConfig } = await import(`file://${localPath.replace(/\\/g, '/')}`));
212
+ } else if (existsSync(pkgPath)) {
213
+ ({ buildDispatchConfig } = await import(`file://${pkgPath.replace(/\\/g, '/')}`));
214
+ } else {
215
+ return null;
216
+ }
217
+
218
+ const config = await buildDispatchConfig(process.cwd(), featureName, phase, { mode: 'validate' });
219
+ const validators = config.agents?.filter(a => a.tier === 4);
220
+ if (!validators || validators.length === 0) return null;
221
+
222
+ const agentsJsonPath = resolve(process.cwd(), 'framework/agents.json');
223
+ const pkgAgentsPath = resolve(process.cwd(), 'node_modules/@polymorphism-tech/morph-spec/framework/agents.json');
224
+ const agentsPath = existsSync(agentsJsonPath) ? agentsJsonPath : pkgAgentsPath;
225
+
226
+ let allAgents = {};
227
+ if (existsSync(agentsPath)) {
228
+ allAgents = JSON.parse(readFileSync(agentsPath, 'utf8')).agents || {};
229
+ }
230
+
231
+ const dispatch = {
232
+ validators: validators.map(v => {
233
+ const agentData = allAgents[v.id];
234
+ return {
235
+ id: v.id,
236
+ title: v.title,
237
+ taskPrompt: v.taskPrompt,
238
+ severity: agentData?.hook_behavior?.severity || 'error',
239
+ blocksOnFail: agentData?.hook_behavior?.blocks_on_fail ?? true,
240
+ checks: agentData?.hook_behavior?.validates || [],
241
+ };
242
+ }),
243
+ };
244
+
245
+ return formatValidatorInstruction(dispatch);
246
+ } catch {
247
+ return null;
125
248
  }
126
249
  }
127
250