@polymorphism-tech/morph-spec 7.8.0 → 7.8.1

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 (166) hide show
  1. package/README.md +2 -2
  2. package/bin/validate.js +379 -379
  3. package/claude-plugin.json +1 -1
  4. package/docs/CHEATSHEET.md +1 -1
  5. package/docs/QUICKSTART.md +1 -1
  6. package/framework/commands/commit.md +166 -166
  7. package/framework/commands/morph-infra.md +215 -215
  8. package/framework/commands/morph-preflight.md +205 -205
  9. package/framework/commands/morph-troubleshoot.md +124 -124
  10. package/framework/hooks/claude-code/statusline.py +679 -679
  11. package/framework/hooks/claude-code/statusline.sh +11 -11
  12. package/framework/hooks/git/commit-msg/conventional-commits.sh +33 -33
  13. package/framework/hooks/git/pre-commit/agents.sh +25 -25
  14. package/framework/hooks/git/pre-commit/orchestrator.sh +64 -64
  15. package/framework/hooks/git/pre-commit/specs.sh +50 -50
  16. package/framework/hooks/git/pre-push/run-tests.sh +44 -44
  17. package/framework/hooks/shared/activity-logger.js +160 -160
  18. package/framework/hooks/shared/hook-response.js +45 -45
  19. package/framework/hooks/shared/payload-utils.js +78 -78
  20. package/framework/hooks/shared/stdin-reader.js +26 -26
  21. package/framework/rubrics/backend.json +41 -41
  22. package/framework/rules/ai-agents-standards.md +45 -45
  23. package/framework/rules/dotnet-templates.md +86 -86
  24. package/framework/rules/frontend-standards.md +13 -13
  25. package/framework/rules/infrastructure-standards.md +27 -27
  26. package/framework/rules/neon-standards.md +25 -25
  27. package/framework/rules/nextjs-standards.md +20 -20
  28. package/framework/rules/nextjs-templates.md +40 -40
  29. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  30. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  31. package/framework/skills/core/morph-brainstorming/SKILL.md +8 -4
  32. package/framework/skills/core/morph-eval/SKILL.md +1 -1
  33. package/framework/skills/core/morph-plan/SKILL.md +8 -4
  34. package/framework/skills/core/morph-proposal/SKILL.md +1 -1
  35. package/framework/skills/core/morph-review/SKILL.md +13 -7
  36. package/framework/skills/core/morph-stack-scan/SKILL.md +1 -1
  37. package/framework/skills/core/morph-standards/SKILL.md +1 -1
  38. package/framework/standards/ai-agents/agent-session.md +160 -160
  39. package/framework/standards/ai-agents/batching.md +193 -193
  40. package/framework/standards/ai-agents/context-providers.md +188 -188
  41. package/framework/standards/ai-agents/mcp-server.md +250 -250
  42. package/framework/standards/ai-agents/mcp-tools.md +197 -197
  43. package/framework/standards/ai-agents/middleware-patterns.md +207 -207
  44. package/framework/standards/ai-agents/modalities-image-gen.md +173 -173
  45. package/framework/standards/ai-agents/modalities-speech-to-text.md +171 -171
  46. package/framework/standards/ai-agents/modalities-text-to-speech.md +181 -181
  47. package/framework/standards/ai-agents/modalities-vision.md +201 -201
  48. package/framework/standards/ai-agents/multi-agent-patterns.md +155 -155
  49. package/framework/standards/ai-agents/production.md +275 -275
  50. package/framework/standards/ai-agents/prompts-in-db.md +214 -214
  51. package/framework/standards/ai-agents/providers/model-registry.md +158 -158
  52. package/framework/standards/ai-agents/service-tier-flex.md +135 -135
  53. package/framework/standards/ai-agents/structured-output.md +249 -249
  54. package/framework/standards/ai-agents/sweet-spot.md +109 -109
  55. package/framework/templates/IDE-SNIPPETS.md +262 -262
  56. package/framework/templates/code/dotnet/abstractions/api-endpoint.cs +7 -7
  57. package/framework/templates/code/dotnet/ai-agents/AgentBootstrap.cs.template +39 -39
  58. package/framework/templates/code/dotnet/ai-agents/EmbeddingService.cs.template +68 -68
  59. package/framework/templates/code/dotnet/ai-agents/ModelRegistry.cs.template +117 -117
  60. package/framework/templates/code/dotnet/ai-agents/PromptRepository.cs.template +95 -95
  61. package/framework/templates/code/dotnet/ai-agents/ResilientToolMiddleware.cs.template +61 -61
  62. package/framework/templates/code/dotnet/ai-agents/VectorSearchTool.cs.template +107 -107
  63. package/framework/templates/code/dotnet/ai-agents/model-registry.json.template +58 -58
  64. package/framework/templates/code/dotnet/contracts/contracts-vsa.cs +281 -281
  65. package/framework/templates/code/dotnet/database/migration.cs +83 -83
  66. package/framework/templates/code/dotnet/feature/endpoint.cs.hbs +21 -21
  67. package/framework/templates/code/dotnet/feature/request.cs.hbs +4 -4
  68. package/framework/templates/code/dotnet/feature/response.cs.hbs +4 -4
  69. package/framework/templates/code/dotnet/feature/validator.cs.hbs +15 -15
  70. package/framework/templates/code/sql/ai-agents/agent-prompts-migration.sql.template +58 -58
  71. package/framework/templates/code/sql/ai-agents/pgvector-embeddings-migration.sql.template +91 -91
  72. package/framework/templates/code/typescript/contracts.ts +167 -167
  73. package/framework/templates/docs/clarifications.md +253 -253
  74. package/framework/templates/docs/schema-analysis.md +119 -119
  75. package/framework/templates/docs/ui-components.md +52 -52
  76. package/framework/templates/docs/ui-design-system.md +76 -76
  77. package/framework/templates/docs/ui-flows.md +167 -167
  78. package/framework/templates/docs/ui-mockups.md +98 -98
  79. package/framework/templates/feature/decisions.md +122 -122
  80. package/framework/templates/frontend/nextjs/Dockerfile.nextjs.hbs +43 -43
  81. package/framework/templates/frontend/nextjs/client-component.tsx.hbs +26 -26
  82. package/framework/templates/frontend/nextjs/env.mjs.hbs +32 -32
  83. package/framework/templates/frontend/nextjs/feature-form.tsx.hbs +56 -56
  84. package/framework/templates/frontend/nextjs/page.tsx.hbs +22 -22
  85. package/framework/templates/frontend/nextjs/tsconfig.json.hbs +26 -26
  86. package/framework/templates/frontend/nextjs/use-feature.ts.hbs +54 -54
  87. package/framework/templates/infrastructure/docker/Dockerfile.template +58 -58
  88. package/framework/templates/infrastructure/docker/docker-compose.template.yml +50 -50
  89. package/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +38 -38
  90. package/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +48 -48
  91. package/framework/templates/infrastructure/github/README.md +56 -56
  92. package/framework/templates/infrastructure/github/actions/docker-build-push/action.yml.hbs +45 -45
  93. package/framework/templates/infrastructure/github/actions/health-check/action.yml.hbs +27 -27
  94. package/framework/templates/infrastructure/github/workflows/docker-build-push.yml.hbs +59 -59
  95. package/framework/templates/infrastructure/github/workflows/dotnet-build.yml.hbs +39 -39
  96. package/framework/templates/integrations/asaas-client.cs +387 -387
  97. package/framework/templates/integrations/asaas-webhook.cs +351 -351
  98. package/framework/templates/meta-prompts/fusion/fusion-agent.md +76 -76
  99. package/framework/templates/meta-prompts/fusion/fusion-aggregator.md +100 -100
  100. package/framework/templates/meta-prompts/parallel-workers/parallel-coordinator.md +113 -113
  101. package/framework/templates/meta-prompts/validators/pre-commit-validator.md +95 -95
  102. package/framework/templates/project/validate.js +120 -120
  103. package/framework/templates/state.template.json +17 -17
  104. package/framework/templates/ui/design-system.css +226 -226
  105. package/package.json +1 -1
  106. package/src/commands/dashboard/dashboard.js +53 -53
  107. package/src/commands/index.js +13 -13
  108. package/src/commands/mcp/mcp-setup.js +519 -519
  109. package/src/commands/project/checkpoint.js +209 -209
  110. package/src/commands/project/update.js +7 -4
  111. package/src/core/state/phase-state-machine.js +197 -197
  112. package/src/core/templates/template-renderer.js +477 -477
  113. package/src/dashboard/app/components/DetailPanel.jsx +11 -11
  114. package/src/dashboard/app/components/FlowGraph.jsx +17 -17
  115. package/src/dashboard/app/components/SearchFilter.jsx +22 -22
  116. package/src/dashboard/app/hooks/useDetailPanel.js +15 -15
  117. package/src/dashboard/app/main.jsx +13 -13
  118. package/src/dashboard/app/pages/AgentMap.jsx +370 -370
  119. package/src/dashboard/app/pages/HookInspector.jsx +418 -418
  120. package/src/dashboard/app/pages/LiveState.jsx +239 -239
  121. package/src/dashboard/app/pages/PhasePipeline.jsx +408 -408
  122. package/src/dashboard/app/pages/RulesMap.jsx +273 -273
  123. package/src/dashboard/app/pages/SkillsLibrary.jsx +366 -366
  124. package/src/dashboard/app/pages/Standards.jsx +332 -332
  125. package/src/dashboard/app/styles/index.css +47 -47
  126. package/src/dashboard/index.html +12 -12
  127. package/src/dashboard/package.json +24 -24
  128. package/src/dashboard/scanner/hooks-scanner.js +41 -41
  129. package/src/dashboard/scanner/phases-scanner.js +15 -15
  130. package/src/dashboard/scanner/rubrics-scanner.js +12 -12
  131. package/src/dashboard/scanner/rules-scanner.js +37 -37
  132. package/src/dashboard/scanner/skills-scanner.js +43 -43
  133. package/src/dashboard/scanner/squads-scanner.js +13 -13
  134. package/src/dashboard/scanner/standards-scanner.js +26 -26
  135. package/src/dashboard/vite-plugin-morph-data.js +17 -17
  136. package/src/dashboard/vite.config.js +24 -24
  137. package/src/lib/agents/metrics-aggregator.js +56 -56
  138. package/src/lib/agents/metrics-calculator.js +125 -125
  139. package/src/lib/agents/output-collector.js +73 -73
  140. package/src/lib/detectors/claude-config-detector.js +152 -152
  141. package/src/lib/detectors/design-system-detector.js +231 -231
  142. package/src/lib/detectors/index.js +217 -217
  143. package/src/lib/generators/architecture-scanner.js +639 -639
  144. package/src/lib/generators/design-system-generator.js +508 -508
  145. package/src/lib/generators/index.js +13 -13
  146. package/src/lib/generators/settings-generator.js +209 -209
  147. package/src/lib/hooks/hook-executor.js +167 -167
  148. package/src/lib/installers/mcp-installer.js +719 -719
  149. package/src/lib/tasks/task-classifier.js +30 -30
  150. package/src/lib/tasks/task-parser.js +209 -209
  151. package/src/lib/tasks/test-runner.js +81 -81
  152. package/src/lib/validators/architecture/architecture-validator.js +259 -259
  153. package/src/lib/validators/checkpoint-persistence.js +39 -39
  154. package/src/lib/validators/contracts/contract-compliance-validator.js +274 -274
  155. package/src/lib/validators/css/css-validator.js +340 -340
  156. package/src/lib/validators/packages/package-validator.js +347 -347
  157. package/src/lib/validators/shared/emit-validator-dispatch.js +14 -14
  158. package/src/lib/validators/shared/issue-counter.js +14 -14
  159. package/src/lib/validators/validation-runner.js +349 -349
  160. package/src/scripts/setup-infra.js +383 -383
  161. package/src/utils/agent-id-mapper.js +11 -11
  162. package/src/utils/banner.js +1 -2
  163. package/src/utils/claude-settings-manager.js +300 -300
  164. package/src/utils/skills-installer.js +172 -172
  165. package/framework/templates/.idea/morph-templates.xml +0 -92
  166. package/framework/templates/.vscode/morph-templates.code-snippets +0 -186
@@ -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
+ }