@polymorphism-tech/morph-spec 7.9.3 → 8.0.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 (213) hide show
  1. package/CLAUDE.md +2 -2
  2. package/README.md +31 -2
  3. package/bin/morph-spec.js +50 -2
  4. package/bin/validate.js +379 -379
  5. package/claude-plugin.json +1 -1
  6. package/docs/CHEATSHEET.md +38 -1
  7. package/docs/QUICKSTART.md +60 -1
  8. package/framework/CLAUDE.md +13 -2
  9. package/framework/MORPH.md +38 -2
  10. package/framework/agents.json +22 -3
  11. package/framework/commands/commit.md +166 -166
  12. package/framework/commands/morph-hotfix.md +39 -0
  13. package/framework/commands/morph-infra.md +215 -215
  14. package/framework/commands/morph-preflight.md +205 -205
  15. package/framework/commands/morph-troubleshoot.md +124 -124
  16. package/framework/hooks/README.md +25 -10
  17. package/framework/hooks/claude-code/core/gate-guard.js +4 -2
  18. package/framework/hooks/claude-code/core/loop-detect.js +2 -1
  19. package/framework/hooks/claude-code/core/post-edit-typecheck.js +14 -5
  20. package/framework/hooks/claude-code/core/tasks-json-guard.js +4 -2
  21. package/framework/hooks/claude-code/core/validate-completion.js +1 -1
  22. package/framework/hooks/claude-code/core/worktree-context.js +160 -0
  23. package/framework/hooks/claude-code/statusline.py +679 -679
  24. package/framework/hooks/claude-code/statusline.sh +11 -11
  25. package/framework/hooks/git/commit-msg/conventional-commits.sh +33 -33
  26. package/framework/hooks/git/pre-commit/agents.sh +25 -25
  27. package/framework/hooks/git/pre-commit/orchestrator.sh +64 -64
  28. package/framework/hooks/git/pre-commit/specs.sh +50 -50
  29. package/framework/hooks/git/pre-push/run-tests.sh +44 -44
  30. package/framework/hooks/shared/activity-logger.js +160 -160
  31. package/framework/hooks/shared/build-check.js +2 -2
  32. package/framework/hooks/shared/hook-response.js +17 -5
  33. package/framework/hooks/shared/payload-utils.js +42 -0
  34. package/framework/hooks/shared/state-reader.js +22 -2
  35. package/framework/hooks/shared/stdin-reader.js +26 -26
  36. package/framework/rubrics/backend.json +41 -41
  37. package/framework/rules/ai-agents-standards.md +45 -45
  38. package/framework/rules/dotnet-templates.md +86 -86
  39. package/framework/rules/frontend-standards.md +13 -13
  40. package/framework/rules/infrastructure-standards.md +27 -27
  41. package/framework/rules/neon-standards.md +25 -25
  42. package/framework/rules/nextjs-standards.md +20 -20
  43. package/framework/rules/nextjs-templates.md +40 -40
  44. package/framework/schemas/feature.schema.json +95 -1
  45. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  46. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  47. package/framework/skills/core/morph-apply/SKILL.md +39 -8
  48. package/framework/skills/core/morph-brainstorming/SKILL.md +9 -1
  49. package/framework/skills/core/morph-eval/SKILL.md +6 -1
  50. package/framework/skills/core/morph-hotfix/SKILL.md +136 -0
  51. package/framework/skills/core/morph-implement/SKILL.md +8 -4
  52. package/framework/skills/core/morph-plan/SKILL.md +5 -1
  53. package/framework/skills/core/morph-proposal/SKILL.md +24 -1
  54. package/framework/skills/core/morph-review/SKILL.md +3 -2
  55. package/framework/skills/core/morph-stack-scan/SKILL.md +1 -1
  56. package/framework/skills/core/morph-standards/SKILL.md +1 -1
  57. package/framework/standards/STANDARDS.json +7 -2
  58. package/framework/standards/ai-agents/agent-session.md +160 -160
  59. package/framework/standards/ai-agents/batching.md +193 -193
  60. package/framework/standards/ai-agents/context-providers.md +188 -188
  61. package/framework/standards/ai-agents/mcp-server.md +250 -250
  62. package/framework/standards/ai-agents/mcp-tools.md +197 -197
  63. package/framework/standards/ai-agents/middleware-patterns.md +207 -207
  64. package/framework/standards/ai-agents/modalities-image-gen.md +173 -173
  65. package/framework/standards/ai-agents/modalities-speech-to-text.md +171 -171
  66. package/framework/standards/ai-agents/modalities-text-to-speech.md +181 -181
  67. package/framework/standards/ai-agents/modalities-vision.md +201 -201
  68. package/framework/standards/ai-agents/multi-agent-patterns.md +155 -155
  69. package/framework/standards/ai-agents/production.md +275 -275
  70. package/framework/standards/ai-agents/prompts-in-db.md +214 -214
  71. package/framework/standards/ai-agents/providers/model-registry.md +158 -158
  72. package/framework/standards/ai-agents/service-tier-flex.md +135 -135
  73. package/framework/standards/ai-agents/structured-output.md +249 -249
  74. package/framework/standards/ai-agents/sweet-spot.md +109 -109
  75. package/framework/standards/backend/integrations/neon-auth/neon-auth.md +45 -3
  76. package/framework/templates/.idea/morph-templates.xml +92 -0
  77. package/framework/templates/.vscode/morph-templates.code-snippets +186 -0
  78. package/framework/templates/IDE-SNIPPETS.md +262 -262
  79. package/framework/templates/REGISTRY.json +0 -62
  80. package/framework/templates/code/dotnet/abstractions/api-endpoint.cs +7 -7
  81. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +39 -39
  82. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +68 -68
  83. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +117 -117
  84. package/framework/templates/code/dotnet/ai-agents/PromptRepository.cs.template +95 -95
  85. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +61 -61
  86. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +107 -107
  87. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +58 -58
  88. package/framework/templates/code/dotnet/contracts/contracts-vsa.cs +281 -281
  89. package/framework/templates/code/dotnet/database/migration.cs +83 -83
  90. package/framework/templates/code/dotnet/feature/endpoint.cs.hbs +21 -21
  91. package/framework/templates/code/dotnet/feature/request.cs.hbs +4 -4
  92. package/framework/templates/code/dotnet/feature/response.cs.hbs +4 -4
  93. package/framework/templates/code/dotnet/feature/validator.cs.hbs +15 -15
  94. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +58 -58
  95. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +91 -91
  96. package/framework/templates/code/typescript/contracts.ts +167 -167
  97. package/framework/templates/docs/clarifications.md +253 -253
  98. package/framework/templates/docs/schema-analysis.md +119 -119
  99. package/framework/templates/docs/ui-components.md +52 -52
  100. package/framework/templates/docs/ui-design-system.md +76 -76
  101. package/framework/templates/docs/ui-flows.md +167 -167
  102. package/framework/templates/docs/ui-mockups.md +98 -98
  103. package/framework/templates/feature/decisions.md +122 -122
  104. package/framework/templates/frontend/nextjs/Dockerfile.nextjs.hbs +43 -43
  105. package/framework/templates/frontend/nextjs/client-component.tsx.hbs +26 -26
  106. package/framework/templates/frontend/nextjs/env.mjs.hbs +32 -32
  107. package/framework/templates/frontend/nextjs/feature-form.tsx.hbs +56 -56
  108. package/framework/templates/frontend/nextjs/page.tsx.hbs +22 -22
  109. package/framework/templates/frontend/nextjs/tsconfig.json.hbs +26 -26
  110. package/framework/templates/frontend/nextjs/use-feature.ts.hbs +54 -54
  111. package/framework/templates/infrastructure/docker/Dockerfile.template +58 -58
  112. package/framework/templates/infrastructure/docker/docker-compose.template.yml +50 -50
  113. package/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +38 -38
  114. package/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +48 -48
  115. package/framework/templates/infrastructure/github/README.md +56 -56
  116. package/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +45 -45
  117. package/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +27 -27
  118. package/framework/templates/infrastructure/github/workflows/docker-build-push.yml.hbs +59 -59
  119. package/framework/templates/infrastructure/github/workflows/dotnet-build.yml.hbs +39 -39
  120. package/framework/templates/integrations/asaas-client.cs +387 -387
  121. package/framework/templates/integrations/asaas-webhook.cs +351 -351
  122. package/framework/templates/meta-prompts/fusion/fusion-agent.md +76 -76
  123. package/framework/templates/meta-prompts/fusion/fusion-aggregator.md +100 -100
  124. package/framework/templates/meta-prompts/validators/pre-commit-validator.md +95 -95
  125. package/framework/templates/project/validate.js +120 -120
  126. package/framework/templates/state.template.json +17 -17
  127. package/framework/templates/ui/design-system.css +226 -226
  128. package/package.json +1 -1
  129. package/src/commands/dashboard/dashboard.js +53 -53
  130. package/src/commands/index.js +13 -13
  131. package/src/commands/mcp/mcp-setup.js +519 -519
  132. package/src/commands/project/checkpoint.js +209 -209
  133. package/src/commands/project/doctor.js +4 -2
  134. package/src/commands/project/init.js +46 -2
  135. package/src/commands/project/update.js +5 -3
  136. package/src/commands/project/worktree.js +1005 -46
  137. package/src/commands/state/advance.js +17 -2
  138. package/src/commands/state/approve.js +18 -1
  139. package/src/commands/state/create.js +158 -14
  140. package/src/commands/state/retype.js +126 -0
  141. package/src/commands/state/score.js +4 -0
  142. package/src/commands/tasks/dag.js +32 -0
  143. package/src/commands/validation/index.js +1 -0
  144. package/src/commands/validation/validate-feature.js +33 -5
  145. package/src/commands/validation/verify.js +190 -0
  146. package/src/core/state/phase-state-machine.js +197 -197
  147. package/src/core/state/state-manager.js +35 -10
  148. package/src/core/templates/template-renderer.js +477 -477
  149. package/src/core/work-types.js +79 -0
  150. package/src/dashboard/app/components/DetailPanel.jsx +11 -11
  151. package/src/dashboard/app/components/FlowGraph.jsx +17 -17
  152. package/src/dashboard/app/components/SearchFilter.jsx +22 -22
  153. package/src/dashboard/app/hooks/useDetailPanel.js +15 -15
  154. package/src/dashboard/app/main.jsx +13 -13
  155. package/src/dashboard/app/pages/AgentMap.jsx +370 -370
  156. package/src/dashboard/app/pages/HookInspector.jsx +418 -418
  157. package/src/dashboard/app/pages/LiveState.jsx +11 -1
  158. package/src/dashboard/app/pages/PhasePipeline.jsx +408 -408
  159. package/src/dashboard/app/pages/RulesMap.jsx +273 -273
  160. package/src/dashboard/app/pages/SkillsLibrary.jsx +366 -366
  161. package/src/dashboard/app/pages/Standards.jsx +332 -332
  162. package/src/dashboard/app/styles/index.css +47 -47
  163. package/src/dashboard/index.html +12 -12
  164. package/src/dashboard/package.json +24 -24
  165. package/src/dashboard/scanner/hooks-scanner.js +41 -41
  166. package/src/dashboard/scanner/phases-scanner.js +15 -15
  167. package/src/dashboard/scanner/rubrics-scanner.js +12 -12
  168. package/src/dashboard/scanner/rules-scanner.js +37 -37
  169. package/src/dashboard/scanner/skills-scanner.js +43 -43
  170. package/src/dashboard/scanner/squads-scanner.js +13 -13
  171. package/src/dashboard/scanner/standards-scanner.js +26 -26
  172. package/src/dashboard/scanner/state-scanner.js +42 -0
  173. package/src/dashboard/vite-plugin-morph-data.js +17 -17
  174. package/src/dashboard/vite.config.js +24 -24
  175. package/src/lib/agents/metrics-aggregator.js +56 -56
  176. package/src/lib/agents/metrics-calculator.js +125 -125
  177. package/src/lib/agents/output-collector.js +73 -73
  178. package/src/lib/detectors/claude-config-detector.js +152 -152
  179. package/src/lib/detectors/design-system-detector.js +231 -231
  180. package/src/lib/detectors/index.js +217 -217
  181. package/src/lib/generators/architecture-scanner.js +639 -639
  182. package/src/lib/generators/design-system-generator.js +508 -508
  183. package/src/lib/generators/index.js +13 -13
  184. package/src/lib/generators/settings-generator.js +209 -209
  185. package/src/lib/hooks/hook-executor.js +167 -167
  186. package/src/lib/installers/mcp-installer.js +719 -719
  187. package/src/lib/installers/memory-installer.js +1 -1
  188. package/src/lib/risk-detector.js +16 -0
  189. package/src/lib/tasks/dispatch-planner.js +122 -4
  190. package/src/lib/tasks/mermaid-renderer.js +132 -0
  191. package/src/lib/tasks/task-classifier.js +30 -30
  192. package/src/lib/tasks/task-parser.js +209 -209
  193. package/src/lib/tasks/test-runner.js +27 -6
  194. package/src/lib/validators/architecture/architecture-validator.js +259 -259
  195. package/src/lib/validators/checkpoint-persistence.js +39 -39
  196. package/src/lib/validators/contracts/contract-compliance-validator.js +274 -274
  197. package/src/lib/validators/css/css-validator.js +340 -340
  198. package/src/lib/validators/packages/package-validator.js +347 -347
  199. package/src/lib/validators/shared/emit-validator-dispatch.js +14 -14
  200. package/src/lib/validators/shared/issue-counter.js +14 -14
  201. package/src/lib/validators/validation-runner.js +349 -349
  202. package/src/lib/validators/verify-runner.js +322 -0
  203. package/src/lib/work-type-detector.js +143 -0
  204. package/src/scripts/setup-infra.js +32 -5
  205. package/src/utils/agent-id-mapper.js +11 -11
  206. package/src/utils/agents-installer.js +10 -6
  207. package/src/utils/claude-settings-manager.js +300 -300
  208. package/src/utils/file-copier.js +43 -0
  209. package/src/utils/hooks-installer.js +41 -11
  210. package/src/utils/skills-installer.js +174 -174
  211. package/framework/templates/meta-prompts/parallel-workers/parallel-coordinator.md +0 -113
  212. package/framework/templates/meta-prompts/parallel-workers/parallel-worker.md +0 -80
  213. package/src/lib/tasks/wave-resolver.js +0 -353
@@ -1,349 +1,349 @@
1
- /**
2
- * MORPH-SPEC Validation Runner
3
- *
4
- * Unified orchestrator that runs the right validators based on the feature's
5
- * active agents and decisions. Called by task-done before marking tasks complete.
6
- *
7
- * MORPH-SPEC 3.0 - Phase A: Active Validation Pipeline
8
- */
9
-
10
- import { existsSync, readFileSync } from 'fs';
11
- import { join } from 'path';
12
- import chalk from 'chalk';
13
- import { loadState } from '../../core/state/state-manager.js';
14
- import { getAbsoluteOutputPath, resolveContractsOutputType } from '../../core/paths/output-schema.js';
15
- import { getStackProfile } from '../stack/stack-profile.js';
16
- import { aggregateScores, loadRubric } from './score-aggregator.js';
17
-
18
- /** Validators that only make sense for .NET projects. */
19
- const DOTNET_ONLY_VALIDATORS = new Set([
20
- 'architecture', 'packages', 'contract-compliance'
21
- ]);
22
-
23
- /**
24
- * Heavy validators skipped in 'light' mode (checkpoint-only).
25
- * Light mode runs only spec, content, and stack-specific lightweight validators.
26
- */
27
- const HEAVY_VALIDATORS = new Set([
28
- 'architecture', 'packages', 'contract-compliance',
29
- 'css', 'design-system'
30
- ]);
31
-
32
- /**
33
- * Load agent → validators map from agents.json (data-driven)
34
- * @param {string} projectPath - Root path of the project
35
- * @returns {Object} Map of agent IDs to validator arrays
36
- */
37
- function loadAgentValidatorMap(projectPath) {
38
- try {
39
- const agentsPath = join(projectPath, '.morph/framework/agents.json');
40
- const agentsConfig = JSON.parse(readFileSync(agentsPath, 'utf8'));
41
-
42
- const map = {};
43
- Object.entries(agentsConfig.agents || {}).forEach(([agentId, agent]) => {
44
- if (!agentId.startsWith('_comment') && agent.validators && agent.validators.length > 0) {
45
- map[agentId] = agent.validators;
46
- }
47
- });
48
-
49
- return map;
50
- } catch (err) {
51
- console.warn(chalk.yellow('⚠️ Failed to load agents.json - no validators will run'));
52
- console.warn(chalk.gray(` Run 'morph-spec init' to set up MORPH-SPEC configuration`));
53
- return {}; // Empty map = honest failure
54
- }
55
- }
56
-
57
- /**
58
- * Run all relevant validators for a feature
59
- *
60
- * @param {string} projectPath - Project root path
61
- * @param {string} featureName - Feature name from state.json
62
- * @param {Object} options - Options
63
- * @param {boolean} options.verbose - Show detailed output
64
- * @param {string[]} options.validators - Specific validators to run (overrides agent-based detection)
65
- * @returns {Object} { passed, errors, warnings, issues, summary }
66
- */
67
- export async function runValidation(projectPath, featureName, options = {}) {
68
- const result = {
69
- passed: true,
70
- errors: 0,
71
- warnings: 0,
72
- issues: [],
73
- summary: '',
74
- results: {} // Per-validator results for hooks integration
75
- };
76
-
77
- // Decision constraints support (stub - decision-constraint-loader removed as orphaned code)
78
- const constraints = {
79
- enabledValidators: [], // No constraint-based validators
80
- validators: {} // No validator-specific constraints
81
- };
82
-
83
- // Determine which validators to run
84
- const validatorIds = options.validators || detectValidators(featureName, projectPath);
85
-
86
- // Filter by mode: 'light' skips heavy validators, 'full' (default) runs all
87
- const mode = options.mode || 'full';
88
- if (mode === 'light') {
89
- const beforeCount = validatorIds.length;
90
- for (let i = validatorIds.length - 1; i >= 0; i--) {
91
- if (HEAVY_VALIDATORS.has(validatorIds[i])) {
92
- validatorIds.splice(i, 1);
93
- }
94
- }
95
- }
96
-
97
- // Merge constraint-enabled validators
98
- validatorIds.push(...constraints.enabledValidators);
99
-
100
- if (validatorIds.length === 0) {
101
- // Distinguish: no agents vs. no validators mapped
102
- const state = loadState(false);
103
- const activeAgents = state?.features?.[featureName]?.activeAgents || [];
104
- if (activeAgents.length === 0) {
105
- result.summary = 'No validators ran — feature has no active agents';
106
- console.log(chalk.gray('\n ℹ️ No validators configured (no active agents in state.json)'));
107
- console.log(chalk.gray(' Add agents: morph-spec state add-agent ' + featureName + ' <agent-id>'));
108
- } else {
109
- result.summary = `No validators mapped for active agents: ${activeAgents.join(', ')}`;
110
- console.log(chalk.gray(`\n ℹ️ Agents [${activeAgents.join(', ')}] have no validators in agents.json`));
111
- }
112
- result._skipReason = result.summary;
113
- return result;
114
- }
115
-
116
- // Always show what's running (even non-verbose) — helps confirm validators are active
117
- console.log(chalk.gray(`\n Running ${validatorIds.length} validator(s): ${validatorIds.join(', ')}`));
118
- if (constraints.enabledValidators.length > 0) {
119
- console.log(chalk.gray(` (+ ${constraints.enabledValidators.length} from decisions)`));
120
- }
121
-
122
- // Always run contract compliance if the contracts file exists (stack-aware)
123
- if (!options.skipContracts) {
124
- const _profileForContracts = getStackProfile(projectPath);
125
- const contractsType = resolveContractsOutputType(_profileForContracts.stack);
126
- const contractsPath = getAbsoluteOutputPath(projectPath, featureName, contractsType);
127
- if (existsSync(contractsPath) && !_profileForContracts.isNextjs) {
128
- validatorIds.push('contract-compliance');
129
- }
130
- }
131
-
132
- // Deduplicate
133
- const uniqueValidators = [...new Set(validatorIds)];
134
-
135
- // Run each validator
136
- for (const validatorId of uniqueValidators) {
137
- try {
138
- // Pass validator-specific constraints from decisions.md
139
- const validatorOptions = {
140
- ...options,
141
- constraints: constraints.validators[validatorId] || {}
142
- };
143
-
144
- const validatorResult = await runSingleValidator(validatorId, projectPath, featureName, validatorOptions);
145
-
146
- if (validatorResult) {
147
- result.errors += validatorResult.errors || 0;
148
- result.warnings += validatorResult.warnings || 0;
149
-
150
- if (validatorResult.issues) {
151
- result.issues.push(...validatorResult.issues);
152
- }
153
-
154
- // Store per-validator results for hooks
155
- result.results[validatorId] = {
156
- passed: (validatorResult.errors || 0) === 0,
157
- issues: validatorResult.issues || []
158
- };
159
- }
160
- } catch (err) {
161
- if (options.verbose) {
162
- console.log(chalk.yellow(` ⚠ Validator '${validatorId}' failed: ${err.message}`));
163
- }
164
- result.results[validatorId] = {
165
- passed: false,
166
- error: err.message
167
- };
168
- }
169
- }
170
-
171
- result.passed = result.errors === 0;
172
- result.summary = result.passed
173
- ? `✅ All validations passed (${result.warnings} warnings)`
174
- : `❌ ${result.errors} error(s), ${result.warnings} warning(s)`;
175
-
176
- // Score aggregation — layered on top of pass/fail
177
- try {
178
- const rubricId = readRubricConfig(projectPath);
179
- const rubric = loadRubric(projectPath, rubricId);
180
- const thresholdOverrides = readThresholdConfig(projectPath);
181
- result.scores = aggregateScores(result, rubric, thresholdOverrides);
182
- } catch {
183
- // Score aggregation is non-blocking — if it fails, pass/fail still works
184
- result.scores = null;
185
- }
186
-
187
- return result;
188
- }
189
-
190
- /**
191
- * Detect which validators to run based on feature's active agents
192
- * @param {string} featureName - Feature name
193
- * @param {string} projectPath - Project root path (default: current directory)
194
- * @returns {string[]} Array of validator IDs to run
195
- */
196
- function detectValidators(featureName, projectPath = '.') {
197
- const profile = getStackProfile(projectPath);
198
- const state = loadState(false);
199
-
200
- if (!state || !state.features[featureName]) {
201
- return [...profile.defaultValidators]; // stack-aware defaults
202
- }
203
-
204
- const feature = state.features[featureName];
205
- const agents = feature.activeAgents || [];
206
- const validatorSet = new Set(profile.defaultValidators); // stack defaults first
207
-
208
- const agentValidatorMap = loadAgentValidatorMap(projectPath);
209
- for (const agentId of agents) {
210
- const validators = agentValidatorMap[agentId] || [];
211
- validators.forEach(v => validatorSet.add(v));
212
- }
213
-
214
- // Filter out .NET-only validators for non-.NET projects
215
- if (!profile.isDotnet) {
216
- for (const v of DOTNET_ONLY_VALIDATORS) {
217
- validatorSet.delete(v);
218
- }
219
- }
220
-
221
- return Array.from(validatorSet);
222
- }
223
-
224
- /**
225
- * Run a single validator by ID
226
- */
227
- async function runSingleValidator(validatorId, projectPath, featureName, options) {
228
- switch (validatorId) {
229
- case 'architecture': {
230
- const { validateArchitecture } = await import('./architecture/architecture-validator.js');
231
- return await validateArchitecture(projectPath, options);
232
- }
233
-
234
- case 'packages': {
235
- const { validatePackages } = await import('./packages/package-validator.js');
236
- return await validatePackages(projectPath, options);
237
- }
238
-
239
- case 'contrast': {
240
- const { validateContrast } = await import('./ui/ui-contrast-validator.js');
241
- return await validateContrast(projectPath, options);
242
- }
243
-
244
- case 'css': {
245
- const { validateCss } = await import('./css/css-validator.js');
246
- return await validateCss(projectPath, options);
247
- }
248
-
249
- case 'contract-compliance': {
250
- const { validateContracts } = await import('./contracts/contract-compliance-validator.js');
251
- return await validateContracts(projectPath, featureName, options);
252
- }
253
-
254
- case 'design-system': {
255
- const { validateDesignSystem } = await import('./design-system/design-system-validator.js');
256
- return await validateDesignSystem(projectPath, featureName, options);
257
- }
258
-
259
- case 'nextjs-component': {
260
- const { validateNextComponentFiles } = await import('./nextjs/next-component-validator.js');
261
- return await validateNextComponentFiles(projectPath, options);
262
- }
263
-
264
- default:
265
- if (options.verbose) {
266
- console.log(chalk.gray(` Unknown validator: ${validatorId}`));
267
- }
268
- return null;
269
- }
270
- }
271
-
272
- /**
273
- * Format validation results for console output
274
- */
275
- export function formatValidationResults(result) {
276
- if (result.passed && result.warnings === 0) {
277
- const ranCount = Object.keys(result.results || {}).length;
278
- const countLabel = ranCount > 0 ? ` (${ranCount} validator${ranCount !== 1 ? 's' : ''})` : '';
279
- console.log(chalk.green(`\n ✅ All validations passed${countLabel}!\n`));
280
- return;
281
- }
282
-
283
- if (result.passed && result.warnings > 0) {
284
- console.log(chalk.yellow(`\n ⚠️ Passed with ${result.warnings} warning(s)\n`));
285
- } else {
286
- console.log(chalk.red(`\n ❌ Validation FAILED: ${result.errors} error(s), ${result.warnings} warning(s)\n`));
287
- }
288
-
289
- // Group issues by level
290
- const errors = result.issues.filter(i => i.level === 'error');
291
- const warnings = result.issues.filter(i => i.level === 'warning');
292
-
293
- if (errors.length > 0) {
294
- console.log(chalk.red.bold(' Errors:'));
295
- for (const issue of errors.slice(0, 10)) {
296
- console.log(chalk.red(` ✗ ${issue.message}`));
297
- if (issue.file) console.log(chalk.gray(` ${issue.file}${issue.line ? ':' + issue.line : ''}`));
298
- if (issue.solution) console.log(chalk.cyan(` Fix: ${issue.solution}`));
299
- }
300
- if (errors.length > 10) {
301
- console.log(chalk.gray(` ... and ${errors.length - 10} more errors`));
302
- }
303
- }
304
-
305
- if (warnings.length > 0) {
306
- console.log(chalk.yellow('\n Warnings:'));
307
- for (const issue of warnings.slice(0, 5)) {
308
- console.log(chalk.yellow(` ⚠ ${issue.message}`));
309
- if (issue.file) console.log(chalk.gray(` ${issue.file}`));
310
- }
311
- if (warnings.length > 5) {
312
- console.log(chalk.gray(` ... and ${warnings.length - 5} more warnings`));
313
- }
314
- }
315
-
316
- console.log('');
317
- }
318
-
319
- /**
320
- * Read rubric ID from project config.
321
- * @param {string} projectPath
322
- * @returns {string}
323
- */
324
- function readRubricConfig(projectPath) {
325
- try {
326
- const configPath = join(projectPath, '.morph', 'config', 'config.json');
327
- if (!existsSync(configPath)) return 'default';
328
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
329
- return config.validation?.rubric ?? 'default';
330
- } catch {
331
- return 'default';
332
- }
333
- }
334
-
335
- /**
336
- * Read threshold overrides from project config.
337
- * @param {string} projectPath
338
- * @returns {Object} { approve?: number, retry?: number }
339
- */
340
- function readThresholdConfig(projectPath) {
341
- try {
342
- const configPath = join(projectPath, '.morph', 'config', 'config.json');
343
- if (!existsSync(configPath)) return {};
344
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
345
- return config.validation?.thresholds ?? {};
346
- } catch {
347
- return {};
348
- }
349
- }
1
+ /**
2
+ * MORPH-SPEC Validation Runner
3
+ *
4
+ * Unified orchestrator that runs the right validators based on the feature's
5
+ * active agents and decisions. Called by task-done before marking tasks complete.
6
+ *
7
+ * MORPH-SPEC 3.0 - Phase A: Active Validation Pipeline
8
+ */
9
+
10
+ import { existsSync, readFileSync } from 'fs';
11
+ import { join } from 'path';
12
+ import chalk from 'chalk';
13
+ import { loadState } from '../../core/state/state-manager.js';
14
+ import { getAbsoluteOutputPath, resolveContractsOutputType } from '../../core/paths/output-schema.js';
15
+ import { getStackProfile } from '../stack/stack-profile.js';
16
+ import { aggregateScores, loadRubric } from './score-aggregator.js';
17
+
18
+ /** Validators that only make sense for .NET projects. */
19
+ const DOTNET_ONLY_VALIDATORS = new Set([
20
+ 'architecture', 'packages', 'contract-compliance'
21
+ ]);
22
+
23
+ /**
24
+ * Heavy validators skipped in 'light' mode (checkpoint-only).
25
+ * Light mode runs only spec, content, and stack-specific lightweight validators.
26
+ */
27
+ const HEAVY_VALIDATORS = new Set([
28
+ 'architecture', 'packages', 'contract-compliance',
29
+ 'css', 'design-system'
30
+ ]);
31
+
32
+ /**
33
+ * Load agent → validators map from agents.json (data-driven)
34
+ * @param {string} projectPath - Root path of the project
35
+ * @returns {Object} Map of agent IDs to validator arrays
36
+ */
37
+ function loadAgentValidatorMap(projectPath) {
38
+ try {
39
+ const agentsPath = join(projectPath, '.morph/framework/agents.json');
40
+ const agentsConfig = JSON.parse(readFileSync(agentsPath, 'utf8'));
41
+
42
+ const map = {};
43
+ Object.entries(agentsConfig.agents || {}).forEach(([agentId, agent]) => {
44
+ if (!agentId.startsWith('_comment') && agent.validators && agent.validators.length > 0) {
45
+ map[agentId] = agent.validators;
46
+ }
47
+ });
48
+
49
+ return map;
50
+ } catch (err) {
51
+ console.warn(chalk.yellow('⚠️ Failed to load agents.json - no validators will run'));
52
+ console.warn(chalk.gray(` Run 'morph-spec init' to set up MORPH-SPEC configuration`));
53
+ return {}; // Empty map = honest failure
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Run all relevant validators for a feature
59
+ *
60
+ * @param {string} projectPath - Project root path
61
+ * @param {string} featureName - Feature name from state.json
62
+ * @param {Object} options - Options
63
+ * @param {boolean} options.verbose - Show detailed output
64
+ * @param {string[]} options.validators - Specific validators to run (overrides agent-based detection)
65
+ * @returns {Object} { passed, errors, warnings, issues, summary }
66
+ */
67
+ export async function runValidation(projectPath, featureName, options = {}) {
68
+ const result = {
69
+ passed: true,
70
+ errors: 0,
71
+ warnings: 0,
72
+ issues: [],
73
+ summary: '',
74
+ results: {} // Per-validator results for hooks integration
75
+ };
76
+
77
+ // Decision constraints support (stub - decision-constraint-loader removed as orphaned code)
78
+ const constraints = {
79
+ enabledValidators: [], // No constraint-based validators
80
+ validators: {} // No validator-specific constraints
81
+ };
82
+
83
+ // Determine which validators to run
84
+ const validatorIds = options.validators || detectValidators(featureName, projectPath);
85
+
86
+ // Filter by mode: 'light' skips heavy validators, 'full' (default) runs all
87
+ const mode = options.mode || 'full';
88
+ if (mode === 'light') {
89
+ const beforeCount = validatorIds.length;
90
+ for (let i = validatorIds.length - 1; i >= 0; i--) {
91
+ if (HEAVY_VALIDATORS.has(validatorIds[i])) {
92
+ validatorIds.splice(i, 1);
93
+ }
94
+ }
95
+ }
96
+
97
+ // Merge constraint-enabled validators
98
+ validatorIds.push(...constraints.enabledValidators);
99
+
100
+ if (validatorIds.length === 0) {
101
+ // Distinguish: no agents vs. no validators mapped
102
+ const state = loadState(false);
103
+ const activeAgents = state?.features?.[featureName]?.activeAgents || [];
104
+ if (activeAgents.length === 0) {
105
+ result.summary = 'No validators ran — feature has no active agents';
106
+ console.log(chalk.gray('\n ℹ️ No validators configured (no active agents in state.json)'));
107
+ console.log(chalk.gray(' Add agents: morph-spec state add-agent ' + featureName + ' <agent-id>'));
108
+ } else {
109
+ result.summary = `No validators mapped for active agents: ${activeAgents.join(', ')}`;
110
+ console.log(chalk.gray(`\n ℹ️ Agents [${activeAgents.join(', ')}] have no validators in agents.json`));
111
+ }
112
+ result._skipReason = result.summary;
113
+ return result;
114
+ }
115
+
116
+ // Always show what's running (even non-verbose) — helps confirm validators are active
117
+ console.log(chalk.gray(`\n Running ${validatorIds.length} validator(s): ${validatorIds.join(', ')}`));
118
+ if (constraints.enabledValidators.length > 0) {
119
+ console.log(chalk.gray(` (+ ${constraints.enabledValidators.length} from decisions)`));
120
+ }
121
+
122
+ // Always run contract compliance if the contracts file exists (stack-aware)
123
+ if (!options.skipContracts) {
124
+ const _profileForContracts = getStackProfile(projectPath);
125
+ const contractsType = resolveContractsOutputType(_profileForContracts.stack);
126
+ const contractsPath = getAbsoluteOutputPath(projectPath, featureName, contractsType);
127
+ if (existsSync(contractsPath) && !_profileForContracts.isNextjs) {
128
+ validatorIds.push('contract-compliance');
129
+ }
130
+ }
131
+
132
+ // Deduplicate
133
+ const uniqueValidators = [...new Set(validatorIds)];
134
+
135
+ // Run each validator
136
+ for (const validatorId of uniqueValidators) {
137
+ try {
138
+ // Pass validator-specific constraints from decisions.md
139
+ const validatorOptions = {
140
+ ...options,
141
+ constraints: constraints.validators[validatorId] || {}
142
+ };
143
+
144
+ const validatorResult = await runSingleValidator(validatorId, projectPath, featureName, validatorOptions);
145
+
146
+ if (validatorResult) {
147
+ result.errors += validatorResult.errors || 0;
148
+ result.warnings += validatorResult.warnings || 0;
149
+
150
+ if (validatorResult.issues) {
151
+ result.issues.push(...validatorResult.issues);
152
+ }
153
+
154
+ // Store per-validator results for hooks
155
+ result.results[validatorId] = {
156
+ passed: (validatorResult.errors || 0) === 0,
157
+ issues: validatorResult.issues || []
158
+ };
159
+ }
160
+ } catch (err) {
161
+ if (options.verbose) {
162
+ console.log(chalk.yellow(` ⚠ Validator '${validatorId}' failed: ${err.message}`));
163
+ }
164
+ result.results[validatorId] = {
165
+ passed: false,
166
+ error: err.message
167
+ };
168
+ }
169
+ }
170
+
171
+ result.passed = result.errors === 0;
172
+ result.summary = result.passed
173
+ ? `✅ All validations passed (${result.warnings} warnings)`
174
+ : `❌ ${result.errors} error(s), ${result.warnings} warning(s)`;
175
+
176
+ // Score aggregation — layered on top of pass/fail
177
+ try {
178
+ const rubricId = readRubricConfig(projectPath);
179
+ const rubric = loadRubric(projectPath, rubricId);
180
+ const thresholdOverrides = readThresholdConfig(projectPath);
181
+ result.scores = aggregateScores(result, rubric, thresholdOverrides);
182
+ } catch {
183
+ // Score aggregation is non-blocking — if it fails, pass/fail still works
184
+ result.scores = null;
185
+ }
186
+
187
+ return result;
188
+ }
189
+
190
+ /**
191
+ * Detect which validators to run based on feature's active agents
192
+ * @param {string} featureName - Feature name
193
+ * @param {string} projectPath - Project root path (default: current directory)
194
+ * @returns {string[]} Array of validator IDs to run
195
+ */
196
+ function detectValidators(featureName, projectPath = '.') {
197
+ const profile = getStackProfile(projectPath);
198
+ const state = loadState(false);
199
+
200
+ if (!state || !state.features[featureName]) {
201
+ return [...profile.defaultValidators]; // stack-aware defaults
202
+ }
203
+
204
+ const feature = state.features[featureName];
205
+ const agents = feature.activeAgents || [];
206
+ const validatorSet = new Set(profile.defaultValidators); // stack defaults first
207
+
208
+ const agentValidatorMap = loadAgentValidatorMap(projectPath);
209
+ for (const agentId of agents) {
210
+ const validators = agentValidatorMap[agentId] || [];
211
+ validators.forEach(v => validatorSet.add(v));
212
+ }
213
+
214
+ // Filter out .NET-only validators for non-.NET projects
215
+ if (!profile.isDotnet) {
216
+ for (const v of DOTNET_ONLY_VALIDATORS) {
217
+ validatorSet.delete(v);
218
+ }
219
+ }
220
+
221
+ return Array.from(validatorSet);
222
+ }
223
+
224
+ /**
225
+ * Run a single validator by ID
226
+ */
227
+ async function runSingleValidator(validatorId, projectPath, featureName, options) {
228
+ switch (validatorId) {
229
+ case 'architecture': {
230
+ const { validateArchitecture } = await import('./architecture/architecture-validator.js');
231
+ return await validateArchitecture(projectPath, options);
232
+ }
233
+
234
+ case 'packages': {
235
+ const { validatePackages } = await import('./packages/package-validator.js');
236
+ return await validatePackages(projectPath, options);
237
+ }
238
+
239
+ case 'contrast': {
240
+ const { validateContrast } = await import('./ui/ui-contrast-validator.js');
241
+ return await validateContrast(projectPath, options);
242
+ }
243
+
244
+ case 'css': {
245
+ const { validateCss } = await import('./css/css-validator.js');
246
+ return await validateCss(projectPath, options);
247
+ }
248
+
249
+ case 'contract-compliance': {
250
+ const { validateContracts } = await import('./contracts/contract-compliance-validator.js');
251
+ return await validateContracts(projectPath, featureName, options);
252
+ }
253
+
254
+ case 'design-system': {
255
+ const { validateDesignSystem } = await import('./design-system/design-system-validator.js');
256
+ return await validateDesignSystem(projectPath, featureName, options);
257
+ }
258
+
259
+ case 'nextjs-component': {
260
+ const { validateNextComponentFiles } = await import('./nextjs/next-component-validator.js');
261
+ return await validateNextComponentFiles(projectPath, options);
262
+ }
263
+
264
+ default:
265
+ if (options.verbose) {
266
+ console.log(chalk.gray(` Unknown validator: ${validatorId}`));
267
+ }
268
+ return null;
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Format validation results for console output
274
+ */
275
+ export function formatValidationResults(result) {
276
+ if (result.passed && result.warnings === 0) {
277
+ const ranCount = Object.keys(result.results || {}).length;
278
+ const countLabel = ranCount > 0 ? ` (${ranCount} validator${ranCount !== 1 ? 's' : ''})` : '';
279
+ console.log(chalk.green(`\n ✅ All validations passed${countLabel}!\n`));
280
+ return;
281
+ }
282
+
283
+ if (result.passed && result.warnings > 0) {
284
+ console.log(chalk.yellow(`\n ⚠️ Passed with ${result.warnings} warning(s)\n`));
285
+ } else {
286
+ console.log(chalk.red(`\n ❌ Validation FAILED: ${result.errors} error(s), ${result.warnings} warning(s)\n`));
287
+ }
288
+
289
+ // Group issues by level
290
+ const errors = result.issues.filter(i => i.level === 'error');
291
+ const warnings = result.issues.filter(i => i.level === 'warning');
292
+
293
+ if (errors.length > 0) {
294
+ console.log(chalk.red.bold(' Errors:'));
295
+ for (const issue of errors.slice(0, 10)) {
296
+ console.log(chalk.red(` ✗ ${issue.message}`));
297
+ if (issue.file) console.log(chalk.gray(` ${issue.file}${issue.line ? ':' + issue.line : ''}`));
298
+ if (issue.solution) console.log(chalk.cyan(` Fix: ${issue.solution}`));
299
+ }
300
+ if (errors.length > 10) {
301
+ console.log(chalk.gray(` ... and ${errors.length - 10} more errors`));
302
+ }
303
+ }
304
+
305
+ if (warnings.length > 0) {
306
+ console.log(chalk.yellow('\n Warnings:'));
307
+ for (const issue of warnings.slice(0, 5)) {
308
+ console.log(chalk.yellow(` ⚠ ${issue.message}`));
309
+ if (issue.file) console.log(chalk.gray(` ${issue.file}`));
310
+ }
311
+ if (warnings.length > 5) {
312
+ console.log(chalk.gray(` ... and ${warnings.length - 5} more warnings`));
313
+ }
314
+ }
315
+
316
+ console.log('');
317
+ }
318
+
319
+ /**
320
+ * Read rubric ID from project config.
321
+ * @param {string} projectPath
322
+ * @returns {string}
323
+ */
324
+ function readRubricConfig(projectPath) {
325
+ try {
326
+ const configPath = join(projectPath, '.morph', 'config', 'config.json');
327
+ if (!existsSync(configPath)) return 'default';
328
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
329
+ return config.validation?.rubric ?? 'default';
330
+ } catch {
331
+ return 'default';
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Read threshold overrides from project config.
337
+ * @param {string} projectPath
338
+ * @returns {Object} { approve?: number, retry?: number }
339
+ */
340
+ function readThresholdConfig(projectPath) {
341
+ try {
342
+ const configPath = join(projectPath, '.morph', 'config', 'config.json');
343
+ if (!existsSync(configPath)) return {};
344
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
345
+ return config.validation?.thresholds ?? {};
346
+ } catch {
347
+ return {};
348
+ }
349
+ }