@polymorphism-tech/morph-spec 2.3.0 → 3.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 (166) hide show
  1. package/CLAUDE.md +446 -1730
  2. package/README.md +515 -516
  3. package/bin/morph-spec.js +366 -294
  4. package/bin/task-manager.js +429 -368
  5. package/bin/validate.js +369 -268
  6. package/content/.claude/commands/morph-apply.md +221 -158
  7. package/content/.claude/commands/morph-deploy.md +529 -0
  8. package/content/.claude/commands/morph-preflight.md +227 -0
  9. package/content/.claude/commands/morph-proposal.md +122 -101
  10. package/content/.claude/commands/morph-status.md +86 -86
  11. package/content/.claude/commands/morph-troubleshoot.md +122 -0
  12. package/content/.claude/skills/infra/azure-deploy-specialist.md +699 -0
  13. package/content/.claude/skills/level-0-meta/README.md +7 -0
  14. package/content/.claude/skills/level-0-meta/code-review.md +226 -0
  15. package/content/.claude/skills/level-0-meta/morph-checklist.md +117 -0
  16. package/content/.claude/skills/level-0-meta/simulation-checklist.md +77 -0
  17. package/content/.claude/skills/level-1-workflows/README.md +7 -0
  18. package/content/.claude/skills/level-1-workflows/morph-replicate.md +213 -0
  19. package/content/.claude/{commands/morph-clarify.md → skills/level-1-workflows/phase-clarify.md} +131 -184
  20. package/content/.claude/{commands/morph-design.md → skills/level-1-workflows/phase-design.md} +213 -275
  21. package/content/.claude/skills/level-1-workflows/phase-setup.md +106 -0
  22. package/content/.claude/skills/level-1-workflows/phase-tasks.md +164 -0
  23. package/content/.claude/{commands/morph-uiux.md → skills/level-1-workflows/phase-uiux.md} +169 -211
  24. package/content/.claude/skills/level-2-domains/README.md +14 -0
  25. package/content/.claude/skills/level-2-domains/ai-agents/ai-system-architect.md +192 -0
  26. package/content/.claude/skills/{specialists → level-2-domains/architecture}/po-pm-advisor.md +197 -197
  27. package/content/.claude/skills/level-2-domains/architecture/standards-architect.md +156 -0
  28. package/content/.claude/skills/level-2-domains/backend/dotnet-senior.md +287 -0
  29. package/content/.claude/skills/level-2-domains/backend/ef-modeler.md +113 -0
  30. package/content/.claude/skills/level-2-domains/backend/hangfire-orchestrator.md +126 -0
  31. package/content/.claude/skills/level-2-domains/backend/ms-agent-expert.md +109 -0
  32. package/content/.claude/skills/level-2-domains/frontend/blazor-builder.md +210 -0
  33. package/content/.claude/skills/level-2-domains/frontend/nextjs-expert.md +154 -0
  34. package/content/.claude/skills/level-2-domains/frontend/ui-ux-designer.md +191 -0
  35. package/content/.claude/skills/{specialists → level-2-domains/infrastructure}/azure-architect.md +142 -142
  36. package/content/.claude/skills/level-2-domains/infrastructure/bicep-architect.md +126 -0
  37. package/content/.claude/skills/level-2-domains/infrastructure/container-specialist.md +131 -0
  38. package/content/.claude/skills/level-2-domains/infrastructure/devops-engineer.md +119 -0
  39. package/content/.claude/skills/level-2-domains/integrations/asaas-financial.md +130 -0
  40. package/content/.claude/skills/level-2-domains/integrations/azure-identity.md +142 -0
  41. package/content/.claude/skills/level-2-domains/integrations/clerk-auth.md +108 -0
  42. package/content/.claude/skills/level-2-domains/integrations/resend-email.md +119 -0
  43. package/content/.claude/skills/level-2-domains/quality/code-analyzer.md +235 -0
  44. package/content/.claude/skills/level-2-domains/quality/testing-specialist.md +126 -0
  45. package/content/.claude/skills/level-3-technologies/README.md +7 -0
  46. package/content/.claude/skills/level-4-patterns/README.md +7 -0
  47. package/content/.claude/skills/specialists/prompt-engineer.md +189 -0
  48. package/content/.claude/skills/specialists/seo-growth-hacker.md +320 -0
  49. package/content/.morph/config/agents.json +762 -242
  50. package/content/.morph/config/config.template.json +122 -108
  51. package/content/.morph/docs/workflows/design-impl.md +37 -0
  52. package/content/.morph/docs/workflows/enforcement-pipeline.md +668 -0
  53. package/content/.morph/docs/workflows/fast-track.md +29 -0
  54. package/content/.morph/docs/workflows/full-morph.md +76 -0
  55. package/content/.morph/docs/workflows/standard.md +44 -0
  56. package/content/.morph/docs/workflows/ui-refresh.md +39 -0
  57. package/content/.morph/examples/scheduled-reports/decisions.md +158 -0
  58. package/content/.morph/examples/scheduled-reports/proposal.md +95 -0
  59. package/content/.morph/examples/scheduled-reports/spec.md +267 -0
  60. package/content/.morph/hooks/README.md +348 -239
  61. package/content/.morph/hooks/pre-commit-agents.sh +24 -24
  62. package/content/.morph/hooks/task-completed.js +73 -0
  63. package/content/.morph/hooks/teammate-idle.js +68 -0
  64. package/content/.morph/schemas/tasks.schema.json +220 -0
  65. package/content/.morph/standards/agent-framework-blazor-ui.md +359 -0
  66. package/content/.morph/standards/agent-framework-production.md +410 -0
  67. package/content/.morph/standards/agent-framework-setup.md +413 -453
  68. package/content/.morph/standards/agent-framework-workflows.md +349 -0
  69. package/content/.morph/standards/agent-teams-workflow.md +474 -0
  70. package/content/.morph/standards/architecture.md +325 -325
  71. package/content/.morph/standards/azure.md +605 -379
  72. package/content/.morph/standards/dotnet10-migration.md +520 -494
  73. package/content/.morph/templates/CONTEXT-FEATURE.md +276 -0
  74. package/content/.morph/templates/CONTEXT.md +170 -0
  75. package/content/.morph/templates/agent.cs +163 -172
  76. package/content/.morph/templates/clarify-questions.md +159 -0
  77. package/content/.morph/templates/contracts/Commands.cs +74 -0
  78. package/content/.morph/templates/contracts/Entities.cs +25 -0
  79. package/content/.morph/templates/contracts/Queries.cs +74 -0
  80. package/content/.morph/templates/contracts/README.md +74 -0
  81. package/content/.morph/templates/decisions.md +123 -106
  82. package/content/.morph/templates/infra/azure-pipelines-deploy.yml +480 -0
  83. package/content/.morph/templates/infra/deploy-checklist.md +426 -0
  84. package/content/.morph/templates/proposal.md +141 -155
  85. package/content/.morph/templates/recap.md +94 -105
  86. package/content/.morph/templates/simulation.md +353 -0
  87. package/content/.morph/templates/spec.md +149 -148
  88. package/content/.morph/templates/state.template.json +222 -222
  89. package/content/.morph/templates/tasks.md +257 -235
  90. package/content/.morph/templates/ui-components.md +362 -276
  91. package/content/CLAUDE.md +150 -442
  92. package/detectors/structure-detector.js +245 -250
  93. package/docs/README.md +144 -149
  94. package/docs/getting-started.md +301 -302
  95. package/docs/installation.md +361 -361
  96. package/docs/validation-checklist.md +265 -266
  97. package/package.json +80 -80
  98. package/src/commands/advance-phase.js +266 -0
  99. package/src/commands/analyze-blazor-concurrency.js +193 -0
  100. package/src/commands/deploy.js +780 -0
  101. package/src/commands/detect-agents.js +167 -0
  102. package/src/commands/doctor.js +356 -280
  103. package/src/commands/generate-context.js +40 -0
  104. package/src/commands/init.js +258 -245
  105. package/src/commands/lint-fluent.js +352 -0
  106. package/src/commands/rollback-phase.js +185 -0
  107. package/src/commands/session-summary.js +291 -0
  108. package/src/commands/task.js +78 -75
  109. package/src/commands/troubleshoot.js +222 -0
  110. package/src/commands/update.js +192 -159
  111. package/src/commands/validate-blazor-state.js +210 -0
  112. package/src/commands/validate-blazor.js +156 -0
  113. package/src/commands/validate-css.js +84 -0
  114. package/src/commands/validate-phase.js +221 -0
  115. package/src/lib/blazor-concurrency-analyzer.js +288 -0
  116. package/src/lib/blazor-state-validator.js +291 -0
  117. package/src/lib/blazor-validator.js +374 -0
  118. package/src/lib/complexity-analyzer.js +441 -292
  119. package/src/lib/context-generator.js +513 -0
  120. package/src/lib/continuous-validator.js +421 -440
  121. package/src/lib/css-validator.js +352 -0
  122. package/src/lib/decision-constraint-loader.js +109 -0
  123. package/src/lib/design-system-detector.js +187 -0
  124. package/src/lib/design-system-scaffolder.js +299 -0
  125. package/src/lib/hook-executor.js +256 -0
  126. package/src/lib/recap-generator.js +205 -0
  127. package/src/lib/spec-validator.js +258 -0
  128. package/src/lib/standards-context-injector.js +287 -0
  129. package/src/lib/state-manager.js +397 -340
  130. package/src/lib/team-orchestrator.js +322 -0
  131. package/src/lib/troubleshoot-grep.js +194 -0
  132. package/src/lib/troubleshoot-index.js +144 -0
  133. package/src/lib/validation-runner.js +283 -0
  134. package/src/lib/validators/contract-compliance-validator.js +273 -0
  135. package/src/lib/validators/design-system-validator.js +231 -0
  136. package/src/utils/file-copier.js +187 -139
  137. package/content/.claude/commands/morph-costs.md +0 -206
  138. package/content/.claude/commands/morph-setup.md +0 -100
  139. package/content/.claude/commands/morph-tasks.md +0 -319
  140. package/content/.claude/skills/infra/bicep-architect.md +0 -419
  141. package/content/.claude/skills/infra/container-specialist.md +0 -437
  142. package/content/.claude/skills/infra/devops-engineer.md +0 -405
  143. package/content/.claude/skills/integrations/asaas-financial.md +0 -333
  144. package/content/.claude/skills/integrations/azure-identity.md +0 -309
  145. package/content/.claude/skills/integrations/clerk-auth.md +0 -290
  146. package/content/.claude/skills/specialists/ai-system-architect.md +0 -604
  147. package/content/.claude/skills/specialists/cost-guardian.md +0 -110
  148. package/content/.claude/skills/specialists/ef-modeler.md +0 -211
  149. package/content/.claude/skills/specialists/hangfire-orchestrator.md +0 -255
  150. package/content/.claude/skills/specialists/ms-agent-expert.md +0 -263
  151. package/content/.claude/skills/specialists/standards-architect.md +0 -78
  152. package/content/.claude/skills/specialists/ui-ux-designer.md +0 -1100
  153. package/content/.claude/skills/stacks/dotnet-blazor.md +0 -606
  154. package/content/.claude/skills/stacks/dotnet-nextjs.md +0 -402
  155. package/content/.claude/skills/stacks/shopify.md +0 -445
  156. package/content/.morph/config/azure-pricing.json +0 -70
  157. package/content/.morph/config/azure-pricing.schema.json +0 -50
  158. package/content/.morph/hooks/pre-commit-costs.sh +0 -91
  159. package/docs/api/cost-calculator.js.html +0 -513
  160. package/docs/api/design-system-generator.js.html +0 -382
  161. package/docs/api/global.html +0 -5263
  162. package/docs/api/index.html +0 -96
  163. package/docs/api/state-manager.js.html +0 -423
  164. package/src/commands/cost.js +0 -181
  165. package/src/commands/update-pricing.js +0 -206
  166. package/src/lib/cost-calculator.js +0 -429
@@ -0,0 +1,299 @@
1
+ /**
2
+ * Design System Scaffolder
3
+ *
4
+ * Automatically scaffolds design system files when needed.
5
+ * Called internally by advance-phase.js gate and phase-uiux skill.
6
+ *
7
+ * NOT a user-facing CLI command - internal automation only.
8
+ *
9
+ * MORPH-SPEC 3.0 - Phase 3.5: Design System Enforcement
10
+ */
11
+
12
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
13
+ import { join, dirname } from 'path';
14
+ import { parseColors, parseTypography, parseSpacing } from './design-system-generator.js';
15
+
16
+ /**
17
+ * Scaffold a design system by scanning existing CSS or using template
18
+ * @param {string} projectPath - Root path of the project
19
+ * @param {string|null} featureName - Feature name (optional, for feature-level)
20
+ * @param {Object} options - Scaffolding options
21
+ * @param {boolean} options.featureLevel - Create feature-level design system
22
+ * @param {boolean} options.scanExisting - Scan existing CSS files
23
+ * @returns {Object} { created: boolean, path: string, source: 'scanned'|'template' }
24
+ */
25
+ export function scaffoldDesignSystem(projectPath, featureName = null, options = {}) {
26
+ const { featureLevel = false, scanExisting = true } = options;
27
+
28
+ // Determine output path
29
+ const outputPath = featureLevel && featureName
30
+ ? join(projectPath, '.morph/project/outputs', featureName, 'ui-design-system.md')
31
+ : join(projectPath, '.morph/project/design-system.md');
32
+
33
+ // Don't overwrite existing design system
34
+ if (existsSync(outputPath)) {
35
+ return {
36
+ created: false,
37
+ path: outputPath,
38
+ source: 'existing',
39
+ message: 'Design system already exists'
40
+ };
41
+ }
42
+
43
+ let designSystemContent;
44
+ let source;
45
+
46
+ // Try to scan existing CSS files for design tokens
47
+ if (scanExisting) {
48
+ const scannedTokens = scanExistingCSSForTokens(projectPath);
49
+
50
+ if (scannedTokens.hasTokens) {
51
+ designSystemContent = generateFromScannedTokens(scannedTokens);
52
+ source = 'scanned';
53
+ } else {
54
+ designSystemContent = generateFromTemplate();
55
+ source = 'template';
56
+ }
57
+ } else {
58
+ designSystemContent = generateFromTemplate();
59
+ source = 'template';
60
+ }
61
+
62
+ // Ensure directory exists
63
+ mkdirSync(dirname(outputPath), { recursive: true });
64
+
65
+ // Write design system
66
+ writeFileSync(outputPath, designSystemContent, 'utf8');
67
+
68
+ return {
69
+ created: true,
70
+ path: outputPath,
71
+ source,
72
+ message: source === 'scanned'
73
+ ? 'Design system created from existing CSS variables'
74
+ : 'Design system created from template with sensible defaults'
75
+ };
76
+ }
77
+
78
+ /**
79
+ * Scan existing CSS files for design tokens
80
+ * @param {string} projectPath - Root path of the project
81
+ * @returns {Object} { hasTokens: boolean, colors: Object, typography: Object, spacing: Object }
82
+ */
83
+ function scanExistingCSSForTokens(projectPath) {
84
+ const result = {
85
+ hasTokens: false,
86
+ colors: { primary: {}, secondary: {}, neutral: {}, semantic: {} },
87
+ typography: { fontFamily: {}, fontSize: {}, fontWeight: {}, lineHeight: {} },
88
+ spacing: {}
89
+ };
90
+
91
+ // Common CSS locations to scan
92
+ const cssLocations = [
93
+ 'wwwroot/css/site.css',
94
+ 'wwwroot/css/app.css',
95
+ 'styles/globals.css',
96
+ 'src/styles/globals.css'
97
+ ];
98
+
99
+ for (const cssPath of cssLocations) {
100
+ const fullPath = join(projectPath, cssPath);
101
+ if (!existsSync(fullPath)) continue;
102
+
103
+ try {
104
+ const content = readFileSync(fullPath, 'utf8');
105
+
106
+ // Check if file has CSS custom properties
107
+ const hasCustomProps = /:root\s*\{[\s\S]*?--/.test(content);
108
+ if (!hasCustomProps) continue;
109
+
110
+ result.hasTokens = true;
111
+
112
+ // Extract CSS variables
113
+ const varRegex = /--([\w-]+)\s*:\s*([^;]+);/g;
114
+ let match;
115
+
116
+ while ((match = varRegex.exec(content)) !== null) {
117
+ const [, varName, varValue] = match;
118
+ const cleanValue = varValue.trim();
119
+
120
+ // Categorize by variable name
121
+ if (varName.includes('color') || varName.includes('primary') || varName.includes('secondary')) {
122
+ if (varName.includes('primary')) {
123
+ result.colors.primary[varName] = cleanValue;
124
+ } else if (varName.includes('secondary')) {
125
+ result.colors.secondary[varName] = cleanValue;
126
+ } else if (varName.includes('neutral') || varName.includes('gray')) {
127
+ result.colors.neutral[varName] = cleanValue;
128
+ } else if (varName.includes('success') || varName.includes('error') || varName.includes('warning') || varName.includes('info')) {
129
+ result.colors.semantic[varName] = cleanValue;
130
+ }
131
+ } else if (varName.includes('font')) {
132
+ if (varName.includes('family')) {
133
+ result.typography.fontFamily[varName] = cleanValue;
134
+ } else if (varName.includes('size')) {
135
+ result.typography.fontSize[varName] = cleanValue;
136
+ }
137
+ } else if (varName.includes('spacing') || varName.includes('gap') || varName.includes('margin') || varName.includes('padding')) {
138
+ result.spacing[varName] = cleanValue;
139
+ }
140
+ }
141
+ } catch (err) {
142
+ // Continue scanning other files
143
+ }
144
+ }
145
+
146
+ return result;
147
+ }
148
+
149
+ /**
150
+ * Generate design system content from scanned tokens
151
+ * @param {Object} tokens - Scanned tokens
152
+ * @returns {string} Markdown content
153
+ */
154
+ function generateFromScannedTokens(tokens) {
155
+ let md = '# Design System\n\n';
156
+ md += '> Auto-generated from existing CSS variables by MORPH-SPEC\n\n';
157
+
158
+ // Colors
159
+ if (Object.keys(tokens.colors.primary).length > 0 ||
160
+ Object.keys(tokens.colors.secondary).length > 0 ||
161
+ Object.keys(tokens.colors.neutral).length > 0 ||
162
+ Object.keys(tokens.colors.semantic).length > 0) {
163
+ md += '## Colors\n\n';
164
+
165
+ if (Object.keys(tokens.colors.primary).length > 0) {
166
+ md += '### Primary Colors\n\n';
167
+ Object.entries(tokens.colors.primary).forEach(([name, value]) => {
168
+ md += `- **${formatVariableName(name)}** (\`${value}\`)\n`;
169
+ });
170
+ md += '\n';
171
+ }
172
+
173
+ if (Object.keys(tokens.colors.secondary).length > 0) {
174
+ md += '### Secondary Colors\n\n';
175
+ Object.entries(tokens.colors.secondary).forEach(([name, value]) => {
176
+ md += `- **${formatVariableName(name)}** (\`${value}\`)\n`;
177
+ });
178
+ md += '\n';
179
+ }
180
+
181
+ if (Object.keys(tokens.colors.neutral).length > 0) {
182
+ md += '### Neutral Colors\n\n';
183
+ Object.entries(tokens.colors.neutral).forEach(([name, value]) => {
184
+ md += `- **${formatVariableName(name)}** (\`${value}\`)\n`;
185
+ });
186
+ md += '\n';
187
+ }
188
+
189
+ if (Object.keys(tokens.colors.semantic).length > 0) {
190
+ md += '### Semantic Colors\n\n';
191
+ Object.entries(tokens.colors.semantic).forEach(([name, value]) => {
192
+ md += `- **${formatVariableName(name)}** (\`${value}\`)\n`;
193
+ });
194
+ md += '\n';
195
+ }
196
+ }
197
+
198
+ // Typography
199
+ if (Object.keys(tokens.typography.fontFamily).length > 0 || Object.keys(tokens.typography.fontSize).length > 0) {
200
+ md += '## Typography\n\n';
201
+
202
+ Object.entries(tokens.typography.fontFamily).forEach(([name, value]) => {
203
+ md += `- **${formatVariableName(name)}**: ${value}\n`;
204
+ });
205
+
206
+ Object.entries(tokens.typography.fontSize).forEach(([name, value]) => {
207
+ md += `- **${formatVariableName(name)}**: ${value}\n`;
208
+ });
209
+
210
+ md += '\n';
211
+ }
212
+
213
+ // Spacing
214
+ if (Object.keys(tokens.spacing).length > 0) {
215
+ md += '## Spacing\n\n';
216
+
217
+ Object.entries(tokens.spacing).forEach(([name, value]) => {
218
+ md += `- **${formatVariableName(name)}**: ${value}\n`;
219
+ });
220
+
221
+ md += '\n';
222
+ }
223
+
224
+ return md;
225
+ }
226
+
227
+ /**
228
+ * Generate design system content from template
229
+ * @returns {string} Markdown content
230
+ */
231
+ function generateFromTemplate() {
232
+ return `# Design System
233
+
234
+ > Created by MORPH-SPEC with sensible defaults
235
+
236
+ ## Colors
237
+
238
+ ### Primary Colors
239
+ - **Primary 500** (\`#007bff\`) - Main brand color
240
+ - **Primary 600** (\`#0056b3\`) - Darker variant
241
+ - **Primary 700** (\`#004085\`) - Darkest variant
242
+
243
+ ### Secondary Colors
244
+ - **Secondary 500** (\`#6c757d\`) - Secondary color
245
+ - **Secondary 600** (\`#545b62\`) - Darker variant
246
+
247
+ ### Neutral Colors
248
+ - **Neutral 100** (\`#f8f9fa\`) - Lightest gray
249
+ - **Neutral 200** (\`#e9ecef\`) - Light gray
250
+ - **Neutral 500** (\`#adb5bd\`) - Medium gray
251
+ - **Neutral 900** (\`#212529\`) - Almost black
252
+
253
+ ### Semantic Colors
254
+ - **Success** (\`#28a745\`) - Success state
255
+ - **Error** (\`#dc3545\`) - Error state
256
+ - **Warning** (\`#ffc107\`) - Warning state
257
+ - **Info** (\`#17a2b8\`) - Info state
258
+
259
+ ## Typography
260
+
261
+ - **Font Family**: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif
262
+ - **Base Size**: 16px
263
+ - **H1**: 2.5rem
264
+ - **H2**: 2rem
265
+ - **H3**: 1.75rem
266
+ - **Body**: 1rem
267
+ - **Small**: 0.875rem
268
+
269
+ ## Spacing
270
+
271
+ - **Spacing XS**: 0.25rem
272
+ - **Spacing SM**: 0.5rem
273
+ - **Spacing MD**: 1rem
274
+ - **Spacing LG**: 1.5rem
275
+ - **Spacing XL**: 2rem
276
+ - **Spacing 2XL**: 3rem
277
+
278
+ ## Usage
279
+
280
+ This design system should be used for all UI components in this project.
281
+
282
+ - Use CSS variables: \`var(--color-primary-500)\`
283
+ - Avoid hardcoded hex colors
284
+ - Use spacing tokens for consistent layout
285
+ - Follow typography scale for text sizes
286
+ `;
287
+ }
288
+
289
+ /**
290
+ * Format CSS variable name to readable title
291
+ * @param {string} varName - CSS variable name (e.g., 'color-primary-500')
292
+ * @returns {string} Formatted name (e.g., 'Color Primary 500')
293
+ */
294
+ function formatVariableName(varName) {
295
+ return varName
296
+ .split('-')
297
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))
298
+ .join(' ');
299
+ }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * @fileoverview Hook Executor for Claude Code Agent Teams
3
+ *
4
+ * Executes validators in response to Claude Code hook events:
5
+ * - TeammateIdle: When a teammate is waiting (validate their work before proceeding)
6
+ * - TaskCompleted: When a task is marked complete (validate deliverables)
7
+ *
8
+ * Validators can be configured to block on failure (severity: "error") or
9
+ * warn without blocking (severity: "warning").
10
+ *
11
+ * @module hook-executor
12
+ */
13
+
14
+ import fs from 'fs/promises';
15
+ import path from 'path';
16
+ import { runValidation } from './validation-runner.js';
17
+
18
+ /**
19
+ * Load agents.json to get hook configuration
20
+ * @param {string} projectPath - Root path of the project
21
+ * @returns {Promise<Object>} Parsed agents configuration
22
+ */
23
+ async function loadAgentsConfig(projectPath) {
24
+ const agentsPath = path.join(projectPath, 'content/.morph/config/agents.json');
25
+ const content = await fs.readFile(agentsPath, 'utf8');
26
+ return JSON.parse(content);
27
+ }
28
+
29
+ /**
30
+ * Load feature state to get active agents
31
+ * @param {string} projectPath - Root path of the project
32
+ * @param {string} featureName - Feature name
33
+ * @returns {Promise<Object|null>} Feature state or null if not found
34
+ */
35
+ async function loadFeatureState(projectPath, featureName) {
36
+ const statePath = path.join(projectPath, '.morph/state.json');
37
+ try {
38
+ const content = await fs.readFile(statePath, 'utf8');
39
+ const state = JSON.parse(content);
40
+
41
+ // Handle both array and object format
42
+ if (Array.isArray(state.features)) {
43
+ return state.features.find(f => f.name === featureName);
44
+ } else if (state.features && typeof state.features === 'object') {
45
+ const feature = state.features[featureName];
46
+ return feature ? { name: featureName, ...feature } : null;
47
+ }
48
+ } catch (err) {
49
+ return null;
50
+ }
51
+
52
+ return null;
53
+ }
54
+
55
+ /**
56
+ * Get validators that should run for a given hook event
57
+ * @param {Object} agentsConfig - Loaded agents.json
58
+ * @param {string[]} activeAgentIds - Active agent IDs for the feature
59
+ * @param {string} hookEvent - Hook event name (e.g., "TeammateIdle", "TaskCompleted")
60
+ * @returns {Array} Validators to run: [{ agentId, hookBehavior, validators }]
61
+ */
62
+ function getHookValidators(agentsConfig, activeAgentIds, hookEvent) {
63
+ const hookValidators = [];
64
+
65
+ for (const agentId of activeAgentIds) {
66
+ const agent = agentsConfig.agents[agentId];
67
+ if (!agent) continue;
68
+
69
+ // Check if this is a Tier 4 validator agent with hook configuration
70
+ if (agent.tier === 4 && agent.role === 'validator' && agent.relationships?.runs_in === 'hooks') {
71
+ const hookTriggers = agent.relationships.hook_triggers || [];
72
+
73
+ // Check if this hook event triggers this validator
74
+ if (hookTriggers.includes(hookEvent)) {
75
+ hookValidators.push({
76
+ agentId,
77
+ hookBehavior: agent.hook_behavior || {},
78
+ validators: agent.validators || []
79
+ });
80
+ }
81
+ }
82
+ }
83
+
84
+ return hookValidators;
85
+ }
86
+
87
+ /**
88
+ * Execute hook validators
89
+ * @param {string} projectPath - Root path of the project
90
+ * @param {string} featureName - Feature name
91
+ * @param {string} hookEvent - Hook event name
92
+ * @param {Object} options - Execution options
93
+ * @param {boolean} options.dryRun - If true, only show what would run without executing
94
+ * @param {boolean} options.verbose - Show detailed output
95
+ * @returns {Promise<Object>} Execution result: { passed, blocked, warnings, errors }
96
+ */
97
+ export async function executeHook(projectPath, featureName, hookEvent, options = {}) {
98
+ const { dryRun = false, verbose = false } = options;
99
+
100
+ // Load configuration
101
+ const agentsConfig = await loadAgentsConfig(projectPath);
102
+ const feature = await loadFeatureState(projectPath, featureName);
103
+
104
+ if (!feature) {
105
+ return {
106
+ passed: false,
107
+ blocked: true,
108
+ errors: [`Feature "${featureName}" not found in state.json`],
109
+ warnings: []
110
+ };
111
+ }
112
+
113
+ // Get validators for this hook event
114
+ const activeAgentIds = feature.activeAgents || [];
115
+ const hookValidators = getHookValidators(agentsConfig, activeAgentIds, hookEvent);
116
+
117
+ if (hookValidators.length === 0) {
118
+ if (verbose) {
119
+ console.log(`ℹ️ No validators configured for hook event: ${hookEvent}`);
120
+ }
121
+ return {
122
+ passed: true,
123
+ blocked: false,
124
+ errors: [],
125
+ warnings: []
126
+ };
127
+ }
128
+
129
+ if (verbose) {
130
+ console.log(`\n🎯 Executing ${hookEvent} hook for feature: ${featureName}`);
131
+ console.log(` Validators: ${hookValidators.map(v => v.agentId).join(', ')}\n`);
132
+ }
133
+
134
+ if (dryRun) {
135
+ console.log('🔍 DRY RUN - Would execute:');
136
+ hookValidators.forEach(v => {
137
+ console.log(` - ${v.agentId} (severity: ${v.hookBehavior.severity || 'warning'})`);
138
+ if (v.hookBehavior.validates) {
139
+ v.hookBehavior.validates.forEach(check => {
140
+ console.log(` • ${check}`);
141
+ });
142
+ }
143
+ });
144
+ return {
145
+ passed: true,
146
+ blocked: false,
147
+ errors: [],
148
+ warnings: []
149
+ };
150
+ }
151
+
152
+ // Execute validators
153
+ const results = {
154
+ passed: true,
155
+ blocked: false,
156
+ errors: [],
157
+ warnings: []
158
+ };
159
+
160
+ for (const hookValidator of hookValidators) {
161
+ const { agentId, hookBehavior, validators } = hookValidator;
162
+
163
+ if (verbose) {
164
+ console.log(`\n🔍 Running ${agentId} validators...`);
165
+ }
166
+
167
+ // Run all validators for this agent
168
+ for (const validatorId of validators) {
169
+ try {
170
+ const validationResult = await runValidation(
171
+ projectPath,
172
+ featureName,
173
+ [validatorId],
174
+ { quiet: !verbose }
175
+ );
176
+
177
+ if (!validationResult.passed) {
178
+ const severity = hookBehavior.severity || 'warning';
179
+ const blocksOnFail = hookBehavior.blocks_on_fail !== false; // Default true
180
+
181
+ if (severity === 'error' && blocksOnFail) {
182
+ results.passed = false;
183
+ results.blocked = true;
184
+ results.errors.push({
185
+ agentId,
186
+ validatorId,
187
+ issues: validationResult.results[validatorId]?.issues || []
188
+ });
189
+ } else {
190
+ results.warnings.push({
191
+ agentId,
192
+ validatorId,
193
+ issues: validationResult.results[validatorId]?.issues || []
194
+ });
195
+ }
196
+ }
197
+ } catch (err) {
198
+ results.errors.push({
199
+ agentId,
200
+ validatorId,
201
+ error: err.message
202
+ });
203
+ }
204
+ }
205
+ }
206
+
207
+ return results;
208
+ }
209
+
210
+ /**
211
+ * Format hook execution results for display
212
+ * @param {Object} results - Results from executeHook
213
+ * @param {string} hookEvent - Hook event name
214
+ * @returns {string} Formatted output
215
+ */
216
+ export function formatHookResults(results, hookEvent) {
217
+ const lines = [];
218
+
219
+ if (results.passed) {
220
+ lines.push(`✅ ${hookEvent} hook: All validators passed`);
221
+ } else {
222
+ lines.push(`❌ ${hookEvent} hook: Validation FAILED`);
223
+ }
224
+
225
+ if (results.errors.length > 0) {
226
+ lines.push('\n🚫 ERRORS (blocking):');
227
+ results.errors.forEach(error => {
228
+ lines.push(` ${error.agentId} → ${error.validatorId}`);
229
+ if (error.error) {
230
+ lines.push(` Error: ${error.error}`);
231
+ } else if (error.issues) {
232
+ error.issues.forEach(issue => {
233
+ lines.push(` • ${issue.message} (${issue.file}:${issue.line})`);
234
+ });
235
+ }
236
+ });
237
+ }
238
+
239
+ if (results.warnings.length > 0) {
240
+ lines.push('\n⚠️ WARNINGS (non-blocking):');
241
+ results.warnings.forEach(warning => {
242
+ lines.push(` ${warning.agentId} → ${warning.validatorId}`);
243
+ if (warning.issues) {
244
+ warning.issues.forEach(issue => {
245
+ lines.push(` • ${issue.message} (${issue.file}:${issue.line})`);
246
+ });
247
+ }
248
+ });
249
+ }
250
+
251
+ if (results.blocked) {
252
+ lines.push('\n⛔ Hook execution BLOCKED - fix errors before proceeding');
253
+ }
254
+
255
+ return lines.join('\n');
256
+ }