@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,231 @@
1
+ /**
2
+ * Design System Validator
3
+ *
4
+ * Validates that CSS and Razor files only use design system tokens
5
+ * instead of hardcoded colors, fonts, or spacing values.
6
+ *
7
+ * MORPH-SPEC 3.0 - Phase 3: Design System Enforcement
8
+ */
9
+
10
+ import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
11
+ import { join, extname } from 'path';
12
+ import { parseColors, parseTypography, parseSpacing } from '../design-system-generator.js';
13
+ import { detectDesignSystem } from '../design-system-detector.js';
14
+
15
+ /**
16
+ * Validate design system compliance
17
+ * @param {string} projectPath - Root path of the project
18
+ * @param {string} featureName - Feature name (optional)
19
+ * @param {Object} options - Validation options
20
+ * @returns {Object} { errors, warnings, issues }
21
+ */
22
+ export async function validateDesignSystem(projectPath, featureName = null, options = {}) {
23
+ const result = {
24
+ errors: 0,
25
+ warnings: 0,
26
+ issues: []
27
+ };
28
+
29
+ // Detect design system
30
+ const dsDetection = detectDesignSystem(projectPath, featureName);
31
+
32
+ if (!dsDetection.hasDesignSystem) {
33
+ result.errors++;
34
+ result.issues.push({
35
+ level: 'error',
36
+ message: 'No design system found',
37
+ solution: 'Create a design system at .morph/project/design-system.md or run design system generator'
38
+ });
39
+ return result;
40
+ }
41
+
42
+ // Parse design system
43
+ let designSystem;
44
+ try {
45
+ const markdown = readFileSync(dsDetection.path, 'utf8');
46
+ designSystem = {
47
+ colors: parseColors(markdown),
48
+ typography: parseTypography(markdown),
49
+ spacing: parseSpacing(markdown)
50
+ };
51
+ } catch (err) {
52
+ result.errors++;
53
+ result.issues.push({
54
+ level: 'error',
55
+ message: `Failed to parse design system: ${err.message}`,
56
+ file: dsDetection.path
57
+ });
58
+ return result;
59
+ }
60
+
61
+ // Build allowed color set
62
+ const allowedColors = new Set();
63
+ Object.values(designSystem.colors.primary).forEach(hex => allowedColors.add(hex.toLowerCase()));
64
+ Object.values(designSystem.colors.secondary).forEach(hex => allowedColors.add(hex.toLowerCase()));
65
+ Object.values(designSystem.colors.neutral).forEach(hex => allowedColors.add(hex.toLowerCase()));
66
+ Object.values(designSystem.colors.semantic).forEach(hex => allowedColors.add(hex.toLowerCase()));
67
+
68
+ // Common system colors (allowed)
69
+ const systemColors = new Set([
70
+ '#ffffff', '#fff', '#000000', '#000', 'transparent', 'inherit', 'currentcolor'
71
+ ]);
72
+
73
+ // Scan CSS files
74
+ const cssFiles = findFiles(projectPath, ['.css'], options.scanPaths || ['wwwroot/css', 'styles']);
75
+ for (const cssFile of cssFiles) {
76
+ const cssResult = validateCSSFile(cssFile, allowedColors, systemColors);
77
+ result.warnings += cssResult.warnings;
78
+ result.issues.push(...cssResult.issues);
79
+ }
80
+
81
+ // Scan Razor files
82
+ const razorFiles = findFiles(projectPath, ['.razor'], options.scanPaths || ['Components', 'Pages']);
83
+ for (const razorFile of razorFiles) {
84
+ const razorResult = validateRazorFile(razorFile, allowedColors, systemColors);
85
+ result.warnings += razorResult.warnings;
86
+ result.issues.push(...razorResult.issues);
87
+ }
88
+
89
+ return result;
90
+ }
91
+
92
+ /**
93
+ * Find files with specific extensions in directories
94
+ */
95
+ function findFiles(projectPath, extensions, scanPaths) {
96
+ const files = [];
97
+
98
+ for (const scanPath of scanPaths) {
99
+ const fullPath = join(projectPath, scanPath);
100
+ if (!existsSync(fullPath)) continue;
101
+
102
+ try {
103
+ walkDirectory(fullPath, extensions, files);
104
+ } catch (err) {
105
+ // Ignore permission errors
106
+ }
107
+ }
108
+
109
+ return files;
110
+ }
111
+
112
+ /**
113
+ * Recursively walk directory
114
+ */
115
+ function walkDirectory(dir, extensions, files) {
116
+ const items = readdirSync(dir);
117
+
118
+ for (const item of items) {
119
+ const fullPath = join(dir, item);
120
+ const stat = statSync(fullPath);
121
+
122
+ if (stat.isDirectory()) {
123
+ walkDirectory(fullPath, extensions, files);
124
+ } else if (stat.isFile()) {
125
+ const ext = extname(fullPath);
126
+ if (extensions.includes(ext)) {
127
+ files.push(fullPath);
128
+ }
129
+ }
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Validate CSS file for hardcoded colors
135
+ */
136
+ function validateCSSFile(filePath, allowedColors, systemColors) {
137
+ const result = {
138
+ warnings: 0,
139
+ issues: []
140
+ };
141
+
142
+ try {
143
+ const content = readFileSync(filePath, 'utf8');
144
+
145
+ // Match hex colors: #RGB or #RRGGBB
146
+ const hexRegex = /#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})\b/g;
147
+
148
+ let match;
149
+ let lineNumber = 1;
150
+ let lastIndex = 0;
151
+
152
+ while ((match = hexRegex.exec(content)) !== null) {
153
+ const hex = match[0].toLowerCase();
154
+
155
+ // Count line number
156
+ const upToMatch = content.substring(lastIndex, match.index);
157
+ lineNumber += (upToMatch.match(/\n/g) || []).length;
158
+ lastIndex = match.index;
159
+
160
+ // Skip if in allowed or system colors
161
+ if (allowedColors.has(hex) || systemColors.has(hex)) {
162
+ continue;
163
+ }
164
+
165
+ result.warnings++;
166
+ result.issues.push({
167
+ level: 'warning',
168
+ message: `Hardcoded color ${hex} not in design system palette`,
169
+ file: filePath,
170
+ line: lineNumber,
171
+ solution: 'Use CSS variable like var(--color-primary-500) instead'
172
+ });
173
+ }
174
+ } catch (err) {
175
+ // Ignore read errors
176
+ }
177
+
178
+ return result;
179
+ }
180
+
181
+ /**
182
+ * Validate Razor file for inline styles with hardcoded colors
183
+ */
184
+ function validateRazorFile(filePath, allowedColors, systemColors) {
185
+ const result = {
186
+ warnings: 0,
187
+ issues: []
188
+ };
189
+
190
+ try {
191
+ const content = readFileSync(filePath, 'utf8');
192
+
193
+ // Match style="" attributes with hex colors
194
+ const styleRegex = /style\s*=\s*"([^"]*)"/gi;
195
+
196
+ let match;
197
+ while ((match = styleRegex.exec(content)) !== null) {
198
+ const styleContent = match[1];
199
+
200
+ // Find hex colors in style attribute
201
+ const hexRegex = /#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})\b/g;
202
+ let hexMatch;
203
+
204
+ while ((hexMatch = hexRegex.exec(styleContent)) !== null) {
205
+ const hex = hexMatch[0].toLowerCase();
206
+
207
+ // Skip if in allowed or system colors
208
+ if (allowedColors.has(hex) || systemColors.has(hex)) {
209
+ continue;
210
+ }
211
+
212
+ // Count line number
213
+ const upToMatch = content.substring(0, match.index);
214
+ const lineNumber = (upToMatch.match(/\n/g) || []).length + 1;
215
+
216
+ result.warnings++;
217
+ result.issues.push({
218
+ level: 'warning',
219
+ message: `Inline style with hardcoded color ${hex} not in design system`,
220
+ file: filePath,
221
+ line: lineNumber,
222
+ solution: 'Use CSS class with design system variables or component props instead of inline styles'
223
+ });
224
+ }
225
+ }
226
+ } catch (err) {
227
+ // Ignore read errors
228
+ }
229
+
230
+ return result;
231
+ }
@@ -1,139 +1,187 @@
1
- import fs from 'fs-extra';
2
- import { join, dirname } from 'path';
3
- import { fileURLToPath } from 'url';
4
-
5
- const __dirname = dirname(fileURLToPath(import.meta.url));
6
-
7
- export function getContentDir() {
8
- return join(__dirname, '..', '..', 'content');
9
- }
10
-
11
- export async function copyDirectory(src, dest, options = {}) {
12
- const { filter, overwrite = true } = options;
13
-
14
- await fs.copy(src, dest, {
15
- overwrite,
16
- filter: filter || (() => true),
17
- errorOnExist: false
18
- });
19
- }
20
-
21
- export async function copyFile(src, dest) {
22
- await fs.ensureDir(dirname(dest));
23
- await fs.copy(src, dest, { overwrite: true });
24
- }
25
-
26
- export async function pathExists(path) {
27
- return fs.pathExists(path);
28
- }
29
-
30
- export async function readJson(path) {
31
- return fs.readJson(path);
32
- }
33
-
34
- export async function writeJson(path, data) {
35
- await fs.ensureDir(dirname(path));
36
- await fs.writeJson(path, data, { spaces: 2 });
37
- }
38
-
39
- export async function ensureDir(path) {
40
- await fs.ensureDir(path);
41
- }
42
-
43
- export async function writeFile(path, content) {
44
- await fs.ensureDir(dirname(path));
45
- await fs.writeFile(path, content, 'utf8');
46
- }
47
-
48
- export async function removeDir(path) {
49
- await fs.remove(path);
50
- }
51
-
52
- export async function readFile(path) {
53
- return fs.readFile(path, 'utf8');
54
- }
55
-
56
- /**
57
- * Create symlink with fallback to copy if symlink fails
58
- * @param {string} target - Path to the original file/folder
59
- * @param {string} link - Path where symlink should be created
60
- * @param {string} type - 'file' or 'dir'
61
- * @returns {Promise<'symlink' | 'copy'>} - Returns how the link was created
62
- */
63
- export async function createSymlink(target, link, type = 'file') {
64
- await fs.ensureDir(dirname(link));
65
-
66
- try {
67
- // Try to create symlink
68
- await fs.ensureSymlink(target, link, type);
69
- return 'symlink';
70
- } catch (error) {
71
- // Fallback: copy the file/directory if symlink fails
72
- // (Windows may require admin permissions for symlinks)
73
- if (type === 'file') {
74
- await copyFile(target, link);
75
- } else {
76
- await copyDirectory(target, link);
77
- }
78
- return 'copy';
79
- }
80
- }
81
-
82
- export async function updateGitignore(projectPath) {
83
- const gitignorePath = join(projectPath, '.gitignore');
84
-
85
- const morphRules = [
86
- '',
87
- '# MORPH-SPEC',
88
- '.morph/examples/',
89
- '.morph/templates/',
90
- '.claude/settings.local.json',
91
- ''
92
- ];
93
-
94
- let content = '';
95
- let hasMorphSection = false;
96
-
97
- // Read existing .gitignore if it exists
98
- if (await pathExists(gitignorePath)) {
99
- content = await readFile(gitignorePath);
100
- hasMorphSection = content.includes('# MORPH-SPEC');
101
- }
102
-
103
- // If MORPH section already exists, check if rules are up to date
104
- if (hasMorphSection) {
105
- const lines = content.split('\n');
106
- const morphStartIndex = lines.findIndex(line => line.trim() === '# MORPH-SPEC');
107
-
108
- // Find the end of MORPH section (next empty line or section header)
109
- let morphEndIndex = morphStartIndex + 1;
110
- while (morphEndIndex < lines.length &&
111
- lines[morphEndIndex].trim() !== '' &&
112
- !lines[morphEndIndex].startsWith('#')) {
113
- morphEndIndex++;
114
- }
115
-
116
- // Extract current MORPH rules
117
- const currentMorphRules = lines.slice(morphStartIndex, morphEndIndex + 1);
118
- const expectedMorphRules = morphRules.slice(1, -1); // Remove empty lines from comparison
119
-
120
- // Check if all expected rules are present
121
- const missingRules = expectedMorphRules.filter(rule =>
122
- rule.startsWith('#') || !currentMorphRules.some(line => line.trim() === rule)
123
- );
124
-
125
- if (missingRules.length > 0) {
126
- // Update the section with all rules
127
- lines.splice(morphStartIndex, morphEndIndex - morphStartIndex, ...morphRules.slice(1, -1));
128
- content = lines.join('\n');
129
- }
130
- } else {
131
- // Add MORPH section
132
- if (content && !content.endsWith('\n')) {
133
- content += '\n';
134
- }
135
- content += morphRules.join('\n');
136
- }
137
-
138
- await writeFile(gitignorePath, content);
139
- }
1
+ import fs from 'fs-extra';
2
+ import { join, dirname, resolve } from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const __dirname = dirname(fileURLToPath(import.meta.url));
6
+
7
+ function isSamePath(a, b) {
8
+ return resolve(a) === resolve(b);
9
+ }
10
+
11
+ export function getContentDir() {
12
+ return join(__dirname, '..', '..', 'content');
13
+ }
14
+
15
+ export async function copyDirectory(src, dest, options = {}) {
16
+ if (isSamePath(src, dest)) return;
17
+
18
+ const { filter, overwrite = true } = options;
19
+
20
+ await fs.copy(src, dest, {
21
+ overwrite,
22
+ filter: filter || (() => true),
23
+ errorOnExist: false
24
+ });
25
+ }
26
+
27
+ export async function copyFile(src, dest) {
28
+ if (isSamePath(src, dest)) return;
29
+
30
+ await fs.ensureDir(dirname(dest));
31
+ await fs.copy(src, dest, { overwrite: true });
32
+ }
33
+
34
+ export async function pathExists(path) {
35
+ return fs.pathExists(path);
36
+ }
37
+
38
+ export async function readJson(path) {
39
+ return fs.readJson(path);
40
+ }
41
+
42
+ export async function writeJson(path, data) {
43
+ await fs.ensureDir(dirname(path));
44
+ await fs.writeJson(path, data, { spaces: 2 });
45
+ }
46
+
47
+ export async function ensureDir(path) {
48
+ await fs.ensureDir(path);
49
+ }
50
+
51
+ export async function writeFile(path, content) {
52
+ await fs.ensureDir(dirname(path));
53
+ await fs.writeFile(path, content, 'utf8');
54
+ }
55
+
56
+ export async function removeDir(path) {
57
+ await fs.remove(path);
58
+ }
59
+
60
+ export async function readFile(path) {
61
+ return fs.readFile(path, 'utf8');
62
+ }
63
+
64
+ /**
65
+ * Create symlink with fallback to copy if symlink fails
66
+ * @param {string} target - Path to the original file/folder
67
+ * @param {string} link - Path where symlink should be created
68
+ * @param {string} type - 'file' or 'dir'
69
+ * @returns {Promise<'symlink' | 'copy'>} - Returns how the link was created
70
+ */
71
+ export async function createSymlink(target, link, type = 'file') {
72
+ await fs.ensureDir(dirname(link));
73
+
74
+ try {
75
+ // Try to create symlink
76
+ await fs.ensureSymlink(target, link, type);
77
+ return 'symlink';
78
+ } catch (error) {
79
+ // Fallback: copy the file/directory if symlink fails
80
+ // (Windows may require admin permissions for symlinks)
81
+ if (type === 'file') {
82
+ await copyFile(target, link);
83
+ } else {
84
+ await copyDirectory(target, link);
85
+ }
86
+ return 'copy';
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Create a directory link (junction on Windows, symlink on other platforms)
92
+ * with fallback to directory copy if linking fails.
93
+ * @param {string} target - Path to the original directory
94
+ * @param {string} link - Path where the link should be created
95
+ * @returns {Promise<'junction' | 'symlink' | 'copy'>} - How the link was created
96
+ */
97
+ export async function createDirectoryLink(target, link) {
98
+ await fs.ensureDir(dirname(link));
99
+
100
+ // Remove existing link/directory before recreating
101
+ if (await pathExists(link)) {
102
+ await fs.remove(link);
103
+ }
104
+
105
+ if (process.platform === 'win32') {
106
+ try {
107
+ // Junction on Windows - does NOT require admin privileges
108
+ await fs.symlink(target, link, 'junction');
109
+ return 'junction';
110
+ } catch {
111
+ try {
112
+ await fs.ensureSymlink(target, link, 'dir');
113
+ return 'symlink';
114
+ } catch {
115
+ await copyDirectory(target, link);
116
+ return 'copy';
117
+ }
118
+ }
119
+ } else {
120
+ try {
121
+ await fs.ensureSymlink(target, link, 'dir');
122
+ return 'symlink';
123
+ } catch {
124
+ await copyDirectory(target, link);
125
+ return 'copy';
126
+ }
127
+ }
128
+ }
129
+
130
+ export async function updateGitignore(projectPath) {
131
+ const gitignorePath = join(projectPath, '.gitignore');
132
+
133
+ const morphRules = [
134
+ '',
135
+ '# MORPH-SPEC',
136
+ '.morph/examples/',
137
+ '.morph/templates/',
138
+ '.claude/settings.local.json',
139
+ ''
140
+ ];
141
+
142
+ let content = '';
143
+ let hasMorphSection = false;
144
+
145
+ // Read existing .gitignore if it exists
146
+ if (await pathExists(gitignorePath)) {
147
+ content = await readFile(gitignorePath);
148
+ hasMorphSection = content.includes('# MORPH-SPEC');
149
+ }
150
+
151
+ // If MORPH section already exists, check if rules are up to date
152
+ if (hasMorphSection) {
153
+ const lines = content.split('\n');
154
+ const morphStartIndex = lines.findIndex(line => line.trim() === '# MORPH-SPEC');
155
+
156
+ // Find the end of MORPH section (next empty line or section header)
157
+ let morphEndIndex = morphStartIndex + 1;
158
+ while (morphEndIndex < lines.length &&
159
+ lines[morphEndIndex].trim() !== '' &&
160
+ !lines[morphEndIndex].startsWith('#')) {
161
+ morphEndIndex++;
162
+ }
163
+
164
+ // Extract current MORPH rules
165
+ const currentMorphRules = lines.slice(morphStartIndex, morphEndIndex + 1);
166
+ const expectedMorphRules = morphRules.slice(1, -1); // Remove empty lines from comparison
167
+
168
+ // Check if all expected rules are present
169
+ const missingRules = expectedMorphRules.filter(rule =>
170
+ rule.startsWith('#') || !currentMorphRules.some(line => line.trim() === rule)
171
+ );
172
+
173
+ if (missingRules.length > 0) {
174
+ // Update the section with all rules
175
+ lines.splice(morphStartIndex, morphEndIndex - morphStartIndex, ...morphRules.slice(1, -1));
176
+ content = lines.join('\n');
177
+ }
178
+ } else {
179
+ // Add MORPH section
180
+ if (content && !content.endsWith('\n')) {
181
+ content += '\n';
182
+ }
183
+ content += morphRules.join('\n');
184
+ }
185
+
186
+ await writeFile(gitignorePath, content);
187
+ }