@polymorphism-tech/morph-spec 4.8.19 → 4.9.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 (137) hide show
  1. package/CLAUDE.md +21 -0
  2. package/README.md +2 -2
  3. package/bin/morph-spec.js +15 -56
  4. package/bin/task-manager.js +115 -14
  5. package/bin/validate.js +67 -33
  6. package/claude-plugin.json +1 -1
  7. package/docs/CHEATSHEET.md +201 -203
  8. package/docs/QUICKSTART.md +2 -2
  9. package/framework/CLAUDE.md +21 -0
  10. package/framework/agents.json +698 -176
  11. package/framework/hooks/claude-code/post-tool-use/context-refresh.js +1 -1
  12. package/framework/hooks/claude-code/post-tool-use/dispatch.js +2 -2
  13. package/framework/hooks/claude-code/post-tool-use/skill-reminder.js +155 -0
  14. package/framework/hooks/claude-code/pre-tool-use/protect-spec-files.js +1 -1
  15. package/framework/hooks/claude-code/session-start/inject-morph-context.js +71 -2
  16. package/framework/hooks/claude-code/statusline.py +76 -30
  17. package/framework/hooks/claude-code/user-prompt/set-terminal-title.js +14 -6
  18. package/framework/hooks/shared/activity-logger.js +0 -24
  19. package/framework/hooks/shared/phase-utils.js +3 -0
  20. package/framework/hooks/shared/skill-reminder-helpers.js +79 -0
  21. package/framework/hooks/shared/stale-task-reset.js +57 -0
  22. package/framework/hooks/shared/state-reader.js +2 -2
  23. package/framework/hooks/shared/worktree-helpers.js +53 -0
  24. package/framework/phases.json +40 -8
  25. package/framework/skills/level-0-meta/brainstorming/SKILL.md +1 -1
  26. package/framework/skills/level-0-meta/code-review/SKILL.md +1 -1
  27. package/framework/skills/level-0-meta/code-review-nextjs/SKILL.md +163 -163
  28. package/framework/skills/level-0-meta/frontend-review/SKILL.md +5 -5
  29. package/framework/skills/level-0-meta/morph-checklist/SKILL.md +2 -2
  30. package/framework/skills/level-0-meta/morph-init/SKILL.md +5 -5
  31. package/framework/skills/level-0-meta/morph-replicate/SKILL.md +4 -4
  32. package/framework/skills/level-0-meta/morph-replicate/references/blazor-html-mapping.md +1 -1
  33. package/framework/skills/level-0-meta/post-implementation/SKILL.md +59 -12
  34. package/framework/skills/level-0-meta/simulation-checklist/SKILL.md +1 -1
  35. package/framework/skills/level-0-meta/terminal-title/SKILL.md +1 -1
  36. package/framework/skills/level-0-meta/tool-usage-guide/SKILL.md +1 -1
  37. package/framework/skills/level-0-meta/tool-usage-guide/references/tools-per-phase.md +6 -5
  38. package/framework/skills/level-0-meta/verification-before-completion/SKILL.md +1 -1
  39. package/framework/skills/level-1-workflows/phase-clarify/SKILL.md +215 -189
  40. package/framework/skills/level-1-workflows/phase-codebase-analysis/SKILL.md +251 -251
  41. package/framework/skills/level-1-workflows/phase-design/SKILL.md +382 -365
  42. package/framework/skills/level-1-workflows/phase-implement/SKILL.md +492 -450
  43. package/framework/skills/level-1-workflows/phase-setup/SKILL.md +194 -190
  44. package/framework/skills/level-1-workflows/phase-tasks/SKILL.md +270 -270
  45. package/framework/skills/level-1-workflows/phase-uiux/SKILL.md +285 -285
  46. package/framework/standards/STANDARDS.json +640 -88
  47. package/framework/standards/infrastructure/vercel/vercel-database.md +106 -0
  48. package/framework/templates/REGISTRY.json +1825 -1909
  49. package/framework/templates/context/CONTEXT-FEATURE.md +276 -276
  50. package/framework/templates/docs/onboarding.md +1 -5
  51. package/package.json +2 -6
  52. package/src/commands/agents/dispatch-agents.js +55 -4
  53. package/src/commands/project/doctor.js +16 -47
  54. package/src/commands/project/init.js +1 -1
  55. package/src/commands/project/status.js +2 -2
  56. package/src/commands/project/update.js +381 -365
  57. package/src/commands/project/worktree.js +154 -0
  58. package/src/commands/state/advance-phase.js +120 -30
  59. package/src/commands/state/approve.js +2 -2
  60. package/src/commands/state/index.js +7 -8
  61. package/src/commands/state/phase-runner.js +1 -1
  62. package/src/commands/state/state.js +61 -6
  63. package/src/commands/tasks/task.js +78 -99
  64. package/src/commands/templates/template-render.js +93 -173
  65. package/src/commands/trust/trust.js +26 -21
  66. package/src/core/paths/output-schema.js +15 -0
  67. package/src/core/state/state-manager.js +28 -54
  68. package/src/core/workflows/workflow-detector.js +9 -87
  69. package/src/lib/phase-chain/phase-validator.js +330 -0
  70. package/src/lib/stack/stack-profile.js +88 -0
  71. package/src/lib/tasks/task-classifier.js +16 -0
  72. package/src/lib/tasks/test-runner.js +77 -0
  73. package/src/lib/trust/trust-manager.js +32 -144
  74. package/src/lib/validators/spec-validator.js +58 -4
  75. package/src/lib/validators/validation-runner.js +23 -11
  76. package/src/scripts/setup-infra.js +240 -224
  77. package/src/utils/agents-installer.js +2 -2
  78. package/src/utils/banner.js +1 -1
  79. package/src/utils/claude-settings-manager.js +1 -1
  80. package/src/utils/file-copier.js +1 -0
  81. package/src/utils/hooks-installer.js +258 -8
  82. package/framework/hooks/dev/check-sync-health.js +0 -117
  83. package/framework/hooks/dev/guard-version-numbers.js +0 -57
  84. package/framework/hooks/dev/sync-standards-registry.js +0 -60
  85. package/framework/hooks/dev/sync-template-registry.js +0 -60
  86. package/framework/hooks/dev/validate-skill-format.js +0 -70
  87. package/framework/hooks/dev/validate-standard-format.js +0 -73
  88. package/framework/templates/meta-prompts/hops/hop-retry.md +0 -78
  89. package/framework/templates/meta-prompts/hops/hop-validation.md +0 -97
  90. package/framework/templates/meta-prompts/hops/hop-wrapper.md +0 -36
  91. package/framework/workflows/configs/design-impl.json +0 -49
  92. package/framework/workflows/configs/express.json +0 -45
  93. package/framework/workflows/configs/fast-track.json +0 -42
  94. package/framework/workflows/configs/full-morph.json +0 -79
  95. package/framework/workflows/configs/fusion.json +0 -39
  96. package/framework/workflows/configs/long-running.json +0 -33
  97. package/framework/workflows/configs/spec-only.json +0 -43
  98. package/framework/workflows/configs/ui-refresh.json +0 -49
  99. package/framework/workflows/configs/zero-touch.json +0 -82
  100. package/src/commands/project/monitor.js +0 -295
  101. package/src/commands/project/tutorial.js +0 -115
  102. package/src/commands/state/validate-phase.js +0 -238
  103. package/src/commands/templates/generate-contracts.js +0 -445
  104. package/src/core/orchestrator.js +0 -171
  105. package/src/core/registry/command-registry.js +0 -28
  106. package/src/core/registry/index.js +0 -8
  107. package/src/core/registry/validator-registry.js +0 -204
  108. package/src/core/templates/template-validator.js +0 -296
  109. package/src/generator/config-generator.js +0 -206
  110. package/src/generator/templates/config.json.template +0 -40
  111. package/src/generator/templates/project.md.template +0 -67
  112. package/src/lib/agents/micro-agent-factory.js +0 -161
  113. package/src/lib/analysis/complexity-analyzer.js +0 -441
  114. package/src/lib/analysis/index.js +0 -7
  115. package/src/lib/analytics/analytics-engine.js +0 -345
  116. package/src/lib/checkpoints/checkpoint-hooks.js +0 -298
  117. package/src/lib/checkpoints/index.js +0 -7
  118. package/src/lib/context/context-bundler.js +0 -241
  119. package/src/lib/context/context-optimizer.js +0 -212
  120. package/src/lib/context/context-tracker.js +0 -273
  121. package/src/lib/context/core-four-tracker.js +0 -201
  122. package/src/lib/context/mcp-optimizer.js +0 -200
  123. package/src/lib/execution/fusion-executor.js +0 -304
  124. package/src/lib/execution/parallel-executor.js +0 -270
  125. package/src/lib/hooks/stop-hook-executor.js +0 -286
  126. package/src/lib/hops/hop-composer.js +0 -221
  127. package/src/lib/phase-chain/eligibility-checker.js +0 -243
  128. package/src/lib/threads/thread-coordinator.js +0 -238
  129. package/src/lib/threads/thread-manager.js +0 -317
  130. package/src/lib/tracking/artifact-trail.js +0 -202
  131. package/src/scanner/project-scanner.js +0 -242
  132. package/src/ui/diff-display.js +0 -91
  133. package/src/ui/interactive-wizard.js +0 -96
  134. package/src/ui/user-review.js +0 -211
  135. package/src/ui/wizard-questions.js +0 -188
  136. package/src/utils/color-utils.js +0 -70
  137. package/src/utils/process-handler.js +0 -97
@@ -1,238 +0,0 @@
1
- /**
2
- * MORPH-SPEC Phase Validator Command
3
- *
4
- * Validates that required previous phases have been completed before advancing.
5
- * Prevents skipping phases accidentally.
6
- *
7
- * Usage:
8
- * morph-spec validate-phase <feature-name> <target-phase>
9
- *
10
- * Example:
11
- * morph-spec validate-phase scheduled-reports implement
12
- */
13
-
14
- import fs from 'fs';
15
- import path from 'path';
16
- import chalk from 'chalk';
17
- import { loadState, getFeature } from '../../core/state/state-manager.js';
18
-
19
- // Phase definitions with requirements
20
- const PHASES = {
21
- 'proposal': {
22
- order: 0,
23
- name: 'FASE 0: PROPOSAL',
24
- requiredOutputs: [],
25
- description: 'Initial proposal and agent detection'
26
- },
27
- 'setup': {
28
- order: 1,
29
- name: 'FASE 1: SETUP',
30
- requiredOutputs: ['proposal.md'],
31
- description: 'Load context and standards'
32
- },
33
- 'uiux': {
34
- order: 2,
35
- name: 'FASE 1.5: UI/UX DESIGN',
36
- requiredOutputs: ['proposal.md'],
37
- optionalOutputs: ['ui-design-system.md', 'ui-mockups.md', 'ui-components.md', 'ui-flows.md'],
38
- description: 'UI/UX design (conditional - only if frontend)',
39
- optional: true
40
- },
41
- 'design': {
42
- order: 3,
43
- name: 'FASE 2: DESIGN',
44
- requiredOutputs: ['proposal.md'],
45
- description: 'Technical specification and contracts'
46
- },
47
- 'clarify': {
48
- order: 4,
49
- name: 'FASE 3: CLARIFY',
50
- requiredOutputs: ['proposal.md', 'spec.md'],
51
- description: 'Clarify ambiguities and edge cases'
52
- },
53
- 'tasks': {
54
- order: 5,
55
- name: 'FASE 4: TASKS',
56
- requiredOutputs: ['proposal.md', 'spec.md'],
57
- description: 'Break down into executable tasks'
58
- },
59
- 'implement': {
60
- order: 6,
61
- name: 'FASE 5: IMPLEMENT',
62
- requiredOutputs: ['proposal.md', 'spec.md'],
63
- description: 'Execute tasks and implement code'
64
- },
65
- 'sync': {
66
- order: 7,
67
- name: 'FASE 6: SYNC',
68
- requiredOutputs: ['proposal.md', 'spec.md', 'decisions.md'],
69
- description: 'Sync decisions to project standards',
70
- optional: true
71
- }
72
- };
73
-
74
- // Map output filenames to their phase subfolders
75
- const OUTPUT_PHASE_MAP = {
76
- 'proposal.md': '0-proposal',
77
- 'schema-analysis.md': '1-design',
78
- 'spec.md': '1-design',
79
- 'clarifications.md': '1-design',
80
- 'contracts.cs': '1-design',
81
- 'decisions.md': '1-design',
82
- 'ui-design-system.md': '2-ui',
83
- 'ui-mockups.md': '2-ui',
84
- 'ui-components.md': '2-ui',
85
- 'ui-flows.md': '2-ui',
86
- 'tasks.md': '3-tasks',
87
- 'recap.md': '4-implement'
88
- };
89
-
90
- /**
91
- * Check if output file exists
92
- */
93
- function checkOutput(featurePath, outputFile) {
94
- const phaseDir = OUTPUT_PHASE_MAP[outputFile] || '';
95
- const filePath = path.join(featurePath, phaseDir, outputFile);
96
- return fs.existsSync(filePath);
97
- }
98
-
99
- /**
100
- * Validate phase requirements
101
- */
102
- function validatePhase(featureName, targetPhase) {
103
- const featurePath = path.join(process.cwd(), '.morph/features', featureName);
104
-
105
- // Check if feature directory exists
106
- if (!fs.existsSync(featurePath)) {
107
- return {
108
- valid: false,
109
- error: `Feature directory not found: ${featurePath}`,
110
- suggestion: `Run 'morph-spec state set ${featureName} phase proposal' to start`,
111
- missingOutputs: [],
112
- phase: null
113
- };
114
- }
115
-
116
- // Get target phase definition
117
- const phaseDefinition = PHASES[targetPhase];
118
- if (!phaseDefinition) {
119
- return {
120
- valid: false,
121
- error: `Unknown phase: ${targetPhase}`,
122
- validPhases: Object.keys(PHASES),
123
- missingOutputs: [],
124
- phase: null
125
- };
126
- }
127
-
128
- // Check required outputs
129
- const missingOutputs = [];
130
- for (const output of phaseDefinition.requiredOutputs) {
131
- if (!checkOutput(featurePath, output)) {
132
- missingOutputs.push(output);
133
- }
134
- }
135
-
136
- // Check state.json for current phase
137
- let stateWarning = null;
138
- try {
139
- const feature = getFeature(featureName);
140
- if (feature) {
141
- const currentPhaseOrder = PHASES[feature.phase]?.order ?? -1;
142
- const targetPhaseOrder = phaseDefinition.order;
143
-
144
- if (targetPhaseOrder > currentPhaseOrder + 1) {
145
- stateWarning = `Skipping phases: current is '${feature.phase}' (order ${currentPhaseOrder}), target is '${targetPhase}' (order ${targetPhaseOrder})`;
146
- }
147
- }
148
- } catch {
149
- // State file may not exist, that's OK
150
- }
151
-
152
- // Special validation: if target is 'implement', check tasks exist in state
153
- if (targetPhase === 'implement') {
154
- try {
155
- const feature = getFeature(featureName);
156
- if (feature && (!feature.tasks || feature.tasks.total === 0)) {
157
- missingOutputs.push('tasks in state.json (run morph-spec task to add tasks)');
158
- }
159
- } catch {
160
- // State file may not exist
161
- }
162
- }
163
-
164
- return {
165
- valid: missingOutputs.length === 0,
166
- error: null,
167
- missingOutputs,
168
- phase: phaseDefinition,
169
- featurePath,
170
- stateWarning
171
- };
172
- }
173
-
174
- /**
175
- * Main command handler
176
- */
177
- export async function validatePhaseCommand(feature, phase, options = {}) {
178
- console.log(chalk.cyan('\n╔════════════════════════════════════════════════╗'));
179
- console.log(chalk.cyan('║ MORPH-SPEC PHASE VALIDATOR ║'));
180
- console.log(chalk.cyan('╚════════════════════════════════════════════════╝\n'));
181
-
182
- const result = validatePhase(feature, phase);
183
-
184
- console.log(chalk.gray('Feature:'), feature);
185
- console.log(chalk.gray('Target Phase:'), result.phase ? result.phase.name : phase);
186
-
187
- if (result.phase) {
188
- console.log(chalk.gray('Description:'), result.phase.description);
189
- }
190
-
191
- if (result.stateWarning) {
192
- console.log(chalk.yellow(`\n⚠️ Warning: ${result.stateWarning}`));
193
- }
194
-
195
- if (result.valid) {
196
- console.log(chalk.green('\n✓ VALIDATION PASSED'));
197
- console.log(chalk.green(' All required outputs are present.'));
198
- console.log(chalk.green(` Safe to proceed to ${result.phase.name}\n`));
199
-
200
- if (options.verbose) {
201
- console.log(chalk.gray('Required outputs found:'));
202
- result.phase.requiredOutputs.forEach(output => {
203
- console.log(chalk.gray(` ✓ ${output}`));
204
- });
205
- console.log('');
206
- }
207
- } else {
208
- console.log(chalk.red('\n✗ VALIDATION FAILED'));
209
-
210
- if (result.error) {
211
- console.log(chalk.red(` Error: ${result.error}\n`));
212
-
213
- if (result.suggestion) {
214
- console.log(chalk.yellow(` Suggestion: ${result.suggestion}\n`));
215
- }
216
-
217
- if (result.validPhases) {
218
- console.log(chalk.yellow('Valid phases:'));
219
- result.validPhases.forEach(p => {
220
- const def = PHASES[p];
221
- console.log(chalk.gray(` - ${p}: ${def.name}${def.optional ? ' (optional)' : ''}`));
222
- });
223
- }
224
- } else {
225
- console.log(chalk.red(' Missing required outputs:'));
226
- result.missingOutputs.forEach(output => {
227
- console.log(chalk.gray(` - ${output}`));
228
- });
229
-
230
- console.log(chalk.yellow(`\n Action required:`));
231
- console.log(chalk.yellow(` Complete the missing outputs before advancing to ${result.phase.name}`));
232
- }
233
- console.log('');
234
- process.exit(1);
235
- }
236
- }
237
-
238
- export { PHASES, validatePhase };
@@ -1,445 +0,0 @@
1
- /**
2
- * MORPH-SPEC Generate Contracts Command
3
- *
4
- * Reads schema-analysis.md and generates contracts.cs with REAL field names and types.
5
- * Bridges the gap between schema analysis and contract template rendering (Problem 5 fix).
6
- *
7
- * Usage:
8
- * morph-spec generate contracts <feature>
9
- * morph-spec generate contracts <feature> --dry-run
10
- * morph-spec generate contracts <feature> --output <path>
11
- */
12
-
13
- import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'fs';
14
- import { join, dirname } from 'path';
15
- import chalk from 'chalk';
16
- import { logger } from '../../utils/logger.js';
17
- import { markOutput } from '../../core/state/state-manager.js';
18
-
19
- // ============================================================================
20
- // Type Mapping — SQL/TypeScript → C#
21
- // ============================================================================
22
-
23
- const TYPE_MAP = {
24
- // String
25
- 'varchar': 'string', 'text': 'string', 'character varying': 'string',
26
- 'char': 'string', 'nvarchar': 'string', 'ntext': 'string', 'string': 'string',
27
- 'character': 'string', 'name': 'string', 'citext': 'string',
28
- // UUID
29
- 'uuid': 'Guid', 'uniqueidentifier': 'Guid',
30
- // Integer
31
- 'int': 'int', 'integer': 'int', 'int4': 'int', 'number': 'int',
32
- 'bigint': 'long', 'int8': 'long', 'smallint': 'short', 'int2': 'short',
33
- 'serial': 'int', 'bigserial': 'long', 'oid': 'int',
34
- // Decimal
35
- 'decimal': 'decimal', 'numeric': 'decimal', 'money': 'decimal',
36
- 'float': 'double', 'double precision': 'double', 'real': 'float',
37
- 'float4': 'float', 'float8': 'double',
38
- // Boolean
39
- 'boolean': 'bool', 'bool': 'bool', 'bit': 'bool',
40
- // DateTime
41
- 'timestamp': 'DateTime', 'timestamp with time zone': 'DateTimeOffset',
42
- 'timestamp without time zone': 'DateTime', 'timestamptz': 'DateTimeOffset',
43
- 'datetime': 'DateTime', 'datetime2': 'DateTime', 'datetimeoffset': 'DateTimeOffset',
44
- 'date': 'DateOnly', 'time': 'TimeOnly', 'timetz': 'TimeOnly',
45
- // JSON
46
- 'jsonb': 'JsonElement', 'json': 'JsonElement',
47
- // Binary
48
- 'bytea': 'byte[]', 'binary': 'byte[]', 'varbinary': 'byte[]',
49
- };
50
-
51
- /**
52
- * Map a raw SQL/TS type string to a C# type.
53
- * Non-nullable value types get ? suffix when nullable is true.
54
- */
55
- function toCSharpType(rawType, nullable) {
56
- const lower = rawType.toLowerCase().trim();
57
- const csType = TYPE_MAP[lower] ?? 'string';
58
- const isReferenceType = csType === 'string' || csType === 'byte[]' || csType === 'JsonElement';
59
- const suffix = nullable && !isReferenceType ? '?' : '';
60
- return csType + suffix;
61
- }
62
-
63
- /**
64
- * Convert snake_case / kebab-case / space-separated to PascalCase.
65
- */
66
- function toPascalCase(str) {
67
- return str
68
- .split(/[_\s-]+/)
69
- .map(w => (w ? w[0].toUpperCase() + w.slice(1).toLowerCase() : ''))
70
- .join('');
71
- }
72
-
73
- /**
74
- * Derive a C# entity class name from a table name.
75
- * Strips a trailing plural 's' where safe (leads → Lead, users → User).
76
- */
77
- function toEntityName(tableName) {
78
- const pascal = toPascalCase(tableName);
79
- // Simple singularization: strip trailing s unless double-s, -us, -ss pattern
80
- if (pascal.endsWith('s') && !pascal.endsWith('ss') && !pascal.endsWith('us') && pascal.length > 3) {
81
- return pascal.slice(0, -1);
82
- }
83
- return pascal;
84
- }
85
-
86
- // ============================================================================
87
- // Schema-Analysis Parser
88
- // ============================================================================
89
-
90
- /**
91
- * Parse schema-analysis.md to extract table definitions with column metadata.
92
- *
93
- * Handles the standard MORPH-SPEC template output:
94
- * ### Table: <name>
95
- * **Columns:**
96
- * | Column Name | Type | Nullable | Default | Notes |
97
- * |------------|------|----------|---------|-------|
98
- * | id | uuid | NO | gen..() | PK |
99
- *
100
- * @param {string} content - Raw file content of schema-analysis.md
101
- * @returns {Array<{name: string, columns: Array<{name, type, nullable, notes}>}>}
102
- */
103
- export function parseSchemaAnalysisMd(content) {
104
- const tables = [];
105
-
106
- // Locate all "### Table:" headings and slice between them
107
- const headingRe = /^### Table:/gm;
108
- const positions = [];
109
- let m;
110
- while ((m = headingRe.exec(content)) !== null) {
111
- positions.push(m.index);
112
- }
113
- if (positions.length === 0) return tables;
114
-
115
- const sections = positions.map((pos, i) => {
116
- const end = positions[i + 1] ?? content.length;
117
- return content.slice(pos, end);
118
- });
119
-
120
- for (const section of sections) {
121
- const nameMatch = section.match(/^### Table:\s*(\S+)/);
122
- if (!nameMatch) continue;
123
- const tableName = nameMatch[1].replace(/[*`]/g, ''); // strip markdown decoration (preserve underscores)
124
-
125
- // Find **Columns:** subsection
126
- const colIdx = section.indexOf('**Columns:**');
127
- if (colIdx === -1) continue;
128
-
129
- const afterColumns = section.slice(colIdx + '**Columns:**'.length);
130
- const columns = [];
131
- let headerSeen = false;
132
-
133
- for (const line of afterColumns.split('\n')) {
134
- const trimmed = line.trim();
135
-
136
- // Stop at next sub-section (**Relationships:**, **Indexes:**, etc.)
137
- if (trimmed.startsWith('**') && trimmed.endsWith('**')) break;
138
- if (!trimmed.startsWith('|')) continue;
139
-
140
- // Split markdown table row into cells
141
- const cells = trimmed.split('|').slice(1, -1).map(c => c.trim());
142
- if (cells.length < 2) continue;
143
-
144
- // Skip header row
145
- if (!headerSeen && cells[0] === 'Column Name') {
146
- headerSeen = true;
147
- continue;
148
- }
149
-
150
- // Skip separator rows (---|---| etc.)
151
- if (cells[0].match(/^-+:?$/) || cells[0].match(/^:?-+$/)) continue;
152
-
153
- if (cells[0]) {
154
- columns.push({
155
- name: cells[0],
156
- type: cells[1] || 'string',
157
- nullable: (cells[2] || 'NO').toUpperCase() === 'YES',
158
- default: cells[3] && cells[3] !== '-' ? cells[3] : null,
159
- notes: cells[4] || '',
160
- });
161
- }
162
- }
163
-
164
- if (columns.length > 0) {
165
- tables.push({ name: tableName, columns });
166
- }
167
- }
168
-
169
- return tables;
170
- }
171
-
172
- // ============================================================================
173
- // Contract Generator
174
- // ============================================================================
175
-
176
- /**
177
- * Determine whether a column is a primary key or auto-managed field
178
- * (should be excluded from Create/Update requests).
179
- */
180
- function isAutoManagedField(col) {
181
- const name = col.name.toLowerCase();
182
- const notes = col.notes.toLowerCase();
183
- return (
184
- notes.includes('pk') ||
185
- name === 'id' ||
186
- name === 'created_at' || name === 'createdat' ||
187
- name === 'updated_at' || name === 'updatedat' ||
188
- notes.includes('auto') || notes.includes('generated') || notes.includes('computed')
189
- );
190
- }
191
-
192
- /**
193
- * Generate C# contracts.cs content from parsed table definitions.
194
- *
195
- * Produces:
196
- * - One Dto record per table (all columns)
197
- * - One CreateRequest record per table (non-auto fields, required)
198
- * - One UpdateRequest record per table (non-auto fields, nullable/patch)
199
- * - Service interface for the primary table
200
- * - NotFoundException for the primary entity
201
- *
202
- * @param {Array} tables - Parsed table definitions
203
- * @param {string} featureName - Feature name (used for namespace/class names)
204
- * @param {string} namespace - C# namespace
205
- * @returns {string} Generated C# source
206
- */
207
- function generateContracts(tables, featureName, namespace) {
208
- const entityName = toPascalCase(featureName);
209
- const today = new Date().toISOString().split('T')[0];
210
-
211
- const lines = [
212
- `// ============================================================`,
213
- `// CONTRACTS: ${entityName} — Generated from real schema-analysis.md`,
214
- `// Generated by MORPH-SPEC generate contracts | Date: ${today}`,
215
- `// Source: .morph/features/${featureName}/1-design/schema-analysis.md`,
216
- `// Review: rename types, add validation attributes, adjust access modifiers.`,
217
- `// ============================================================`,
218
- ``,
219
- `using System;`,
220
- `using System.Text.Json;`,
221
- `using System.Collections.Generic;`,
222
- `using System.Threading;`,
223
- `using System.Threading.Tasks;`,
224
- ``,
225
- `namespace ${namespace}.Application.Features.${entityName};`,
226
- ``,
227
- ];
228
-
229
- for (const table of tables) {
230
- const dtoPascal = toEntityName(table.name);
231
- const userFields = table.columns.filter(c => !isAutoManagedField(c));
232
-
233
- lines.push(`#region ${dtoPascal}`, ``);
234
-
235
- // ── DTO ──────────────────────────────────────────────────────────────────
236
- lines.push(`/// <summary>Read DTO — maps to the "${table.name}" table.</summary>`);
237
- lines.push(`public record ${dtoPascal}Dto(`);
238
- table.columns.forEach((col, i) => {
239
- const csType = toCSharpType(col.type, col.nullable);
240
- const propName = toPascalCase(col.name);
241
- const comment = col.notes && col.notes !== '-' ? ` // ${table.name}.${col.name} (${col.type})` : '';
242
- const comma = i < table.columns.length - 1 ? ',' : '';
243
- lines.push(` ${csType} ${propName}${comma}${comment}`);
244
- });
245
- lines.push(`);`, ``);
246
-
247
- // ── Create Request ────────────────────────────────────────────────────────
248
- lines.push(`/// <summary>Command to create a new ${dtoPascal}.</summary>`);
249
- lines.push(`public record Create${dtoPascal}Request(`);
250
- if (userFields.length > 0) {
251
- userFields.forEach((col, i) => {
252
- const csType = toCSharpType(col.type, false); // Required for create
253
- const propName = toPascalCase(col.name);
254
- const comma = i < userFields.length - 1 ? ',' : '';
255
- lines.push(` ${csType} ${propName}${comma}`);
256
- });
257
- } else {
258
- lines.push(` // TODO: Add required fields — all columns are auto-managed`);
259
- }
260
- lines.push(`);`, ``);
261
-
262
- // ── Update Request ────────────────────────────────────────────────────────
263
- lines.push(`/// <summary>Command to update an existing ${dtoPascal} (patch semantics).</summary>`);
264
- lines.push(`public record Update${dtoPascal}Request(`);
265
- if (userFields.length > 0) {
266
- userFields.forEach((col, i) => {
267
- const csType = toCSharpType(col.type, true); // All nullable for patch
268
- const propName = toPascalCase(col.name);
269
- const comma = i < userFields.length - 1 ? ',' : '';
270
- lines.push(` ${csType} ${propName}${comma}`);
271
- });
272
- } else {
273
- lines.push(` // TODO: Add updatable fields`);
274
- }
275
- lines.push(`);`, ``);
276
- lines.push(`#endregion`, ``);
277
- }
278
-
279
- // ── Service Interface for primary entity ──────────────────────────────────
280
- const primaryTable = tables[0];
281
- const primaryEntity = primaryTable ? toEntityName(primaryTable.name) : entityName;
282
-
283
- lines.push(
284
- `#region Service Interface`,
285
- ``,
286
- `public interface I${entityName}Service`,
287
- `{`,
288
- ` Task<${primaryEntity}Dto?> GetByIdAsync(Guid id, CancellationToken ct = default);`,
289
- ` Task<List<${primaryEntity}Dto>> GetAllAsync(CancellationToken ct = default);`,
290
- ` Task<${primaryEntity}Dto> CreateAsync(Create${primaryEntity}Request request, CancellationToken ct = default);`,
291
- ` Task UpdateAsync(Guid id, Update${primaryEntity}Request request, CancellationToken ct = default);`,
292
- ` Task DeleteAsync(Guid id, CancellationToken ct = default);`,
293
- `}`,
294
- ``,
295
- `#endregion`,
296
- ``,
297
- );
298
-
299
- // ── Exception ─────────────────────────────────────────────────────────────
300
- lines.push(
301
- `#region Exceptions`,
302
- ``,
303
- `public class ${primaryEntity}NotFoundException(Guid id)`,
304
- ` : Exception($"${primaryEntity} '{{id}}' not found.");`,
305
- ``,
306
- `#endregion`,
307
- );
308
-
309
- return lines.join('\n') + '\n';
310
- }
311
-
312
- // ============================================================================
313
- // Namespace Detection
314
- // ============================================================================
315
-
316
- /**
317
- * Attempt to derive the C# namespace from project config or .csproj file.
318
- */
319
- async function detectNamespace(projectPath) {
320
- const configPath = join(projectPath, '.morph/config/config.json');
321
- try {
322
- const config = JSON.parse(readFileSync(configPath, 'utf-8'));
323
- if (config.project?.namespace) return config.project.namespace;
324
- if (config.project?.name) {
325
- return config.project.name
326
- .split(/[\s\-_]+/)
327
- .map(w => (w ? w[0].toUpperCase() + w.slice(1) : ''))
328
- .join('');
329
- }
330
- } catch { /* ignore */ }
331
-
332
- // Try to find a .csproj via git ls-files
333
- try {
334
- const { execSync } = await import('child_process');
335
- const csprojList = execSync('git ls-files "*.csproj"', {
336
- cwd: projectPath,
337
- stdio: ['pipe', 'pipe', 'pipe'],
338
- encoding: 'utf-8',
339
- }).trim().split('\n').filter(Boolean);
340
- if (csprojList.length > 0) {
341
- const name = csprojList[0].split('/').pop().replace('.csproj', '');
342
- return name.replace(/\.|-/g, '');
343
- }
344
- } catch { /* not a git repo or no .csproj */ }
345
-
346
- return 'YourProject';
347
- }
348
-
349
- // ============================================================================
350
- // CLI Entry Point
351
- // ============================================================================
352
-
353
- /**
354
- * Main handler for: morph-spec generate contracts <feature>
355
- *
356
- * @param {string} featureName - Feature slug (e.g. "email-marketing")
357
- * @param {Object} options
358
- * @param {boolean} options.dryRun - Print to stdout instead of writing
359
- * @param {string} options.output - Override output path
360
- */
361
- export async function generateContractsCommand(featureName, options = {}) {
362
- logger.header(`Generate Contracts: ${featureName}`);
363
- logger.blank();
364
-
365
- const projectPath = options.projectPath || process.cwd();
366
-
367
- // Locate schema-analysis.md
368
- const schemaPath = join(projectPath, `.morph/features/${featureName}/1-design/schema-analysis.md`);
369
- if (!existsSync(schemaPath)) {
370
- logger.error(`schema-analysis.md not found at: ${schemaPath}`);
371
- logger.dim(' Run the Design phase schema analysis first:');
372
- logger.dim(' npx morph-spec phase advance ' + featureName);
373
- logger.dim(' then execute /phase-codebase-analysis in Claude Code');
374
- process.exit(1);
375
- }
376
-
377
- logger.dim(`Reading: ${schemaPath}`);
378
- const content = readFileSync(schemaPath, 'utf-8');
379
-
380
- // Parse tables
381
- const tables = parseSchemaAnalysisMd(content);
382
-
383
- if (tables.length === 0) {
384
- logger.error('No tables found in schema-analysis.md');
385
- logger.blank();
386
- logger.dim(' Ensure the file uses the standard MORPH-SPEC format:');
387
- logger.dim(' ### Table: your_table_name');
388
- logger.dim(' **Columns:**');
389
- logger.dim(' | Column Name | Type | Nullable | Default | Notes |');
390
- logger.dim(' |------------|------|----------|---------|-------|');
391
- logger.dim(' | id | uuid | NO | - | PK |');
392
- process.exit(1);
393
- }
394
-
395
- logger.info(`Tables found: ${chalk.cyan(tables.map(t => t.name).join(', '))}`);
396
- tables.forEach(t => {
397
- const colSummary = t.columns
398
- .slice(0, 4)
399
- .map(c => `${c.name}:${c.type}`)
400
- .join(', ');
401
- const more = t.columns.length > 4 ? ` +${t.columns.length - 4} more` : '';
402
- logger.dim(` ${t.name}: ${colSummary}${more}`);
403
- });
404
- logger.blank();
405
-
406
- // Detect namespace
407
- const namespace = await detectNamespace(projectPath);
408
- logger.dim(`Namespace: ${namespace}`);
409
- logger.blank();
410
-
411
- // Generate content
412
- const contractsContent = generateContracts(tables, featureName, namespace);
413
-
414
- // Output path
415
- const outputPath = options.output
416
- || join(projectPath, `.morph/features/${featureName}/1-design/contracts.cs`);
417
-
418
- if (options.dryRun) {
419
- logger.info(chalk.cyan('📋 DRY RUN — Preview (nothing written):'));
420
- logger.blank();
421
- console.log(contractsContent);
422
- logger.dim(`Would be written to: ${outputPath}`);
423
- return;
424
- }
425
-
426
- mkdirSync(dirname(outputPath), { recursive: true });
427
- writeFileSync(outputPath, contractsContent, 'utf-8');
428
-
429
- logger.success('✅ contracts.cs generated from real schema');
430
- logger.dim(` Output: ${chalk.cyan(outputPath)}`);
431
- const totalCols = tables.reduce((n, t) => n + t.columns.length, 0);
432
- logger.dim(` ${tables.length} table(s) → ${totalCols} columns mapped`);
433
- logger.blank();
434
-
435
- // Mark output in state (non-blocking)
436
- try {
437
- markOutput(featureName, 'contracts');
438
- logger.dim(' State: contracts output marked ✓');
439
- } catch {
440
- // Feature might not be in state yet — non-blocking
441
- }
442
-
443
- logger.blank();
444
- logger.dim('Next step: review contracts.cs for type accuracy, then proceed with /phase-design');
445
- }