@polymorphism-tech/morph-spec 11.1.1 → 11.2.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 (106) hide show
  1. package/README.md +1 -1
  2. package/bin/morph-spec.js +9 -19
  3. package/docs/CHEATSHEET.md +3 -3
  4. package/docs/QUICKSTART.md +1 -1
  5. package/framework/CLAUDE.md +2 -0
  6. package/framework/MORPH.md +7 -2
  7. package/framework/agents.json +3 -3
  8. package/framework/docs/CLI.md +14 -12
  9. package/framework/evals/review-checklist.md +9 -16
  10. package/framework/hooks/README.md +15 -9
  11. package/framework/hooks/claude-code/core/README.md +2 -2
  12. package/framework/hooks/claude-code/core/chain.js +9 -25
  13. package/framework/hooks/claude-code/core/comment-guard.js +3 -9
  14. package/framework/hooks/claude-code/core/conventional-commit.js +3 -3
  15. package/framework/hooks/claude-code/core/graph-refresh-kick.js +4 -4
  16. package/framework/hooks/claude-code/core/masked-exit.js +4 -3
  17. package/framework/hooks/claude-code/core/pre-bash-denylist.js +2 -2
  18. package/framework/hooks/claude-code/core/protect-spec-files.js +2 -4
  19. package/framework/hooks/claude-code/core/stack-changed.js +5 -4
  20. package/framework/hooks/claude-code/core/validate-completion.js +15 -12
  21. package/framework/hooks/shared/contract.js +22 -1
  22. package/framework/hooks/shared/git-paths.js +6 -0
  23. package/framework/hooks/shared/graph-freshness.js +3 -3
  24. package/framework/hooks/shared/graph-refresh.js +5 -10
  25. package/framework/hooks/shared/hook-response.js +1 -18
  26. package/framework/hooks/shared/payload-utils.js +12 -1
  27. package/framework/hooks/shared/phase-utils.js +4 -52
  28. package/framework/hooks/shared/report-progress.js +1 -1
  29. package/framework/mcp/registry.json +1 -17
  30. package/framework/rules/dotnet-templates.md +32 -33
  31. package/framework/rules/infrastructure-standards.md +9 -9
  32. package/framework/rules/neon-standards.md +4 -4
  33. package/framework/rules/nextjs-templates.md +10 -11
  34. package/framework/rules/ui-design.md +2 -2
  35. package/framework/schemas/config.schema.json +4 -0
  36. package/framework/skills/core/create-umbraco-lp/SKILL.md +1 -1
  37. package/framework/skills/core/migrate-lp-to-umbraco/SKILL.md +1 -1
  38. package/framework/skills/core/morph-apply/SKILL.md +5 -4
  39. package/framework/skills/core/morph-plan/SKILL.md +1 -1
  40. package/framework/skills/core/morph-uiux/SKILL.md +5 -5
  41. package/framework/standards/integration/mcp/mcp-tools.md +2 -2
  42. package/framework/templates/REGISTRY.json +1 -75
  43. package/framework/templates/docs/plan.md +1 -1
  44. package/framework/templates/dotnet/ai-kit/tests/Morph.AiKit.Tests/Morph.AiKit.Tests.csproj +1 -1
  45. package/framework/templates/infrastructure/docker/docker-compose.template.yml +15 -16
  46. package/package.json +6 -15
  47. package/src/commands/graph/build.js +2 -2
  48. package/src/commands/mcp/mcp-setup.js +6 -4
  49. package/src/commands/project/doctor.js +42 -126
  50. package/src/commands/project/env.js +2 -1
  51. package/src/commands/project/init.js +28 -170
  52. package/src/commands/project/stack-set.js +3 -1
  53. package/src/commands/project/update.js +49 -153
  54. package/src/commands/scaffold/scaffold.js +21 -4
  55. package/src/commands/validation/check.js +12 -10
  56. package/src/commands/validation/prove-red.js +61 -22
  57. package/src/core/paths/output-schema.js +8 -27
  58. package/src/core/templates/template-registry.js +8 -43
  59. package/src/core/templates/template-renderer.js +3 -200
  60. package/src/lib/ai/ai-checks.js +1 -1
  61. package/src/lib/ai/ai-project-scan.js +1 -1
  62. package/src/lib/ai/code-audit.js +2 -2
  63. package/src/lib/check/signals.js +25 -7
  64. package/src/lib/contract/defaults.js +2 -2
  65. package/src/lib/detectors/claude-config-detector.js +0 -52
  66. package/src/lib/detectors/index.js +5 -30
  67. package/src/lib/diff/diff-lines.js +3 -3
  68. package/src/lib/generators/scaffold-generator.js +5 -17
  69. package/src/lib/git/default-branch.js +5 -13
  70. package/src/lib/graph/graph-health.js +1 -1
  71. package/src/lib/graph/graphifyignore.js +3 -4
  72. package/src/lib/graph/sanitize.js +2 -2
  73. package/src/lib/installers/effects.js +0 -13
  74. package/src/lib/installers/mcp-installer.js +5 -17
  75. package/src/lib/installers/memory-installer.js +5 -8
  76. package/src/lib/installers/stack-assets.js +33 -7
  77. package/src/lib/installers/stack-sync.js +4 -4
  78. package/src/lib/plan/checks.js +1 -1
  79. package/src/lib/plan/media.js +3 -3
  80. package/src/lib/plan/plan-parser.js +1 -1
  81. package/src/lib/review-reports.js +8 -14
  82. package/src/lib/scan/worktree-dirs.js +1 -3
  83. package/src/lib/specs/adr-index.js +4 -4
  84. package/src/lib/specs/revocations.js +3 -3
  85. package/src/lib/stack/stack-scan.js +3 -3
  86. package/src/lib/standards/registry.js +1 -1
  87. package/src/lib/standards/verified-against.js +2 -2
  88. package/src/lib/tests-audit/audit.js +2 -2
  89. package/src/scripts/global-install.js +41 -19
  90. package/src/scripts/setup-infra.js +57 -165
  91. package/src/utils/agents-installer.js +8 -30
  92. package/src/utils/claude-settings-manager.js +29 -27
  93. package/src/utils/hooks-installer.js +30 -44
  94. package/src/utils/version-checker.js +2 -31
  95. package/CLAUDE.md +0 -118
  96. package/framework/commands/create-umbraco-lp.md +0 -37
  97. package/framework/commands/migrate-lp-to-umbraco.md +0 -35
  98. package/framework/commands/morph-apply.md +0 -14
  99. package/framework/hooks/shared/spawn-command.js +0 -23
  100. package/framework/templates/CLAUDE.md.core.guide.md +0 -29
  101. package/framework/templates/CLAUDE.md.core.template +0 -22
  102. package/framework/templates/context/ARCHITECTURE.md +0 -106
  103. package/src/commands/context/context-refresh.js +0 -63
  104. package/src/lib/generators/architecture-scanner.js +0 -543
  105. package/src/lib/generators/settings-generator.js +0 -97
  106. package/src/lib/graph/god-nodes.js +0 -65
@@ -1,63 +0,0 @@
1
- import { scanArchitecture, renderArchitectureContext } from '../../lib/generators/architecture-scanner.js';
2
- import { logger } from '../../utils/logger.js';
3
-
4
- export async function contextRefreshCommand(options = {}) {
5
- const projectPath = options.path || process.cwd();
6
-
7
- if (!options.quiet) {
8
- logger.header('Architecture Context Refresh');
9
- logger.dim(`Scanning: ${projectPath}`);
10
- logger.blank();
11
- }
12
-
13
- try {
14
- const scanResult = await scanArchitecture(projectPath);
15
-
16
- if (options.json) {
17
- console.log(JSON.stringify(scanResult, null, 2));
18
- return;
19
- }
20
-
21
- const outputPath = await renderArchitectureContext(projectPath, scanResult);
22
-
23
- if (!options.quiet) {
24
- const counts = [];
25
- if (scanResult.entities.length > 0) counts.push(`${scanResult.entities.length} entities`);
26
- if (scanResult.endpoints.length > 0) counts.push(`${scanResult.endpoints.length} endpoints`);
27
- if (scanResult.nextjs.pages.length > 0) counts.push(`${scanResult.nextjs.pages.length} pages`);
28
- if (scanResult.nextjs.components.length > 0) counts.push(`${scanResult.nextjs.components.length} components`);
29
- if (scanResult.integrations.length > 0) counts.push(`${scanResult.integrations.length} integrations`);
30
- if (scanResult.database.length > 0) counts.push(`${scanResult.database.length} tables`);
31
- if (scanResult.stack.dotnet.length > 0) counts.push(`${scanResult.stack.dotnet.length} .NET packages`);
32
- if (scanResult.stack.npm.length > 0) counts.push(`${scanResult.stack.npm.length} npm packages`);
33
-
34
- if (counts.length > 0) {
35
- logger.success(`Found: ${counts.join(', ')}`);
36
- } else {
37
- logger.warn('No architectural patterns detected (empty project?)');
38
- }
39
-
40
- logger.success(`Written to: ${outputPath}`);
41
-
42
- if (options.verbose) {
43
- logger.blank();
44
- if (scanResult.entities.length > 0) {
45
- logger.info('Entities:');
46
- for (const e of scanResult.entities) logger.dim(` ${e.name} (${e.type}) — ${e.path}`);
47
- }
48
- if (scanResult.endpoints.length > 0) {
49
- logger.info('Endpoints:');
50
- for (const ep of scanResult.endpoints) logger.dim(` ${ep.method || '???'} ${ep.route} — ${ep.name}`);
51
- }
52
- if (scanResult.nextjs.pages.length > 0) {
53
- logger.info('Pages:');
54
- for (const p of scanResult.nextjs.pages) logger.dim(` ${p.route} — ${p.path}`);
55
- }
56
- }
57
- }
58
- } catch (err) {
59
- if (options.quiet) throw err;
60
- logger.error(`Scan failed: ${err.message}`);
61
- process.exitCode = 1;
62
- }
63
- }
@@ -1,543 +0,0 @@
1
- import fs from 'fs/promises';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
4
- import { existsSync, readFileSync } from 'fs';
5
- import { scanGraph } from '../graph/god-nodes.js';
6
- import { renderTemplate } from '../../core/templates/template-renderer.js';
7
- import { WORKTREE_DIR_NAMES } from '../scan/worktree-dirs.js';
8
-
9
- export const SKIP_DIRS = new Set(['node_modules', 'bin', 'obj', '.git', '.morph', '.next', 'dist', 'out', ...WORKTREE_DIR_NAMES]);
10
- const MAX_FILES_PER_SCANNER = 200;
11
-
12
- async function walkDir(dir, filter, base = dir, limit = MAX_FILES_PER_SCANNER) {
13
- const results = [];
14
-
15
- async function recurse(currentDir) {
16
- if (results.length >= limit) return;
17
-
18
- let entries;
19
- try {
20
- entries = await fs.readdir(currentDir, { withFileTypes: true });
21
- } catch {
22
- return;
23
- }
24
-
25
- for (const entry of entries) {
26
- if (results.length >= limit) break;
27
-
28
- if (entry.isDirectory()) {
29
- if (SKIP_DIRS.has(entry.name)) continue;
30
- await recurse(path.join(currentDir, entry.name));
31
- } else if (entry.isFile()) {
32
- const abs = path.join(currentDir, entry.name);
33
- const rel = path.relative(base, abs).replace(/\\/g, '/');
34
- if (filter(rel, entry.name)) {
35
- results.push({ abs, rel });
36
- }
37
- }
38
- }
39
- }
40
-
41
- await recurse(dir);
42
- return results;
43
- }
44
-
45
- export async function scanEntities(projectPath) {
46
- try {
47
- const files = await walkDir(
48
- projectPath,
49
- (rel, name) => name.endsWith('.cs') && (rel.includes('Entities/') || rel.includes('Features/') || rel.includes('Models/'))
50
- );
51
-
52
- const entities = [];
53
- const entityRegex = /(?:public\s+)?(?:sealed\s+)?(class|record)\s+(\w+)/g;
54
-
55
- for (const file of files) {
56
- try {
57
- const content = await fs.readFile(file.abs, 'utf8');
58
- let match;
59
- entityRegex.lastIndex = 0;
60
- while ((match = entityRegex.exec(content)) !== null) {
61
- const line = content.slice(Math.max(0, match.index - 80), match.index + match[0].length);
62
- if (/sealed|record/.test(line) || file.rel.includes('Entities/')) {
63
- entities.push({
64
- name: match[2],
65
- type: match[1],
66
- path: file.rel
67
- });
68
- }
69
- }
70
- } catch {}
71
- }
72
-
73
- return entities;
74
- } catch {
75
- return [];
76
- }
77
- }
78
-
79
- export async function scanEndpoints(projectPath) {
80
- try {
81
- const files = await walkDir(
82
- projectPath,
83
- (rel, name) => name.endsWith('.cs') && (rel.includes('Endpoints/') || rel.includes('Features/'))
84
- );
85
-
86
- const endpoints = [];
87
- const classRegex = /class\s+(\w+)[^{]*(?:IApiEndpoint|IEndpoint|Endpoint)/;
88
- const routeRegex = /Route\s*(?:=>|=)\s*"([^"]+)"/;
89
- const methodRegex = /(?:Http(Get|Post|Put|Delete|Patch))|(?:\.Map(Get|Post|Put|Delete|Patch))/i;
90
-
91
- for (const file of files) {
92
- try {
93
- const content = await fs.readFile(file.abs, 'utf8');
94
- const classMatch = classRegex.exec(content);
95
- if (!classMatch) continue;
96
-
97
- const routeMatch = routeRegex.exec(content);
98
- const methodMatch = methodRegex.exec(content);
99
-
100
- endpoints.push({
101
- name: classMatch[1],
102
- route: routeMatch ? routeMatch[1] : '(unknown)',
103
- method: methodMatch ? (methodMatch[1] || methodMatch[2] || '').toUpperCase() : '',
104
- path: file.rel
105
- });
106
- } catch {}
107
- }
108
-
109
- return endpoints;
110
- } catch {
111
- return [];
112
- }
113
- }
114
-
115
- export async function scanNextjsComponents(projectPath) {
116
- try {
117
- const result = { pages: [], layouts: [], components: [] };
118
-
119
- const appFiles = await walkDir(
120
- projectPath,
121
- (rel, name) =>
122
- (name === 'page.tsx' || name === 'page.jsx' || name === 'layout.tsx' || name === 'layout.jsx') &&
123
- (rel.startsWith('app/') || rel.startsWith('src/app/'))
124
- );
125
-
126
- for (const file of appFiles) {
127
- const isLayout = file.rel.includes('layout.');
128
- const routeDir = path.dirname(file.rel).replace(/^(?:src\/)?app/, '').replace(/\\/g, '/');
129
- const route = routeDir || '/';
130
-
131
- if (isLayout) {
132
- result.layouts.push({ path: file.rel });
133
- } else {
134
- result.pages.push({ route: route === '' ? '/' : route, path: file.rel });
135
- }
136
- }
137
-
138
- const componentFiles = await walkDir(
139
- projectPath,
140
- (rel, name) =>
141
- (name.endsWith('.tsx') || name.endsWith('.jsx')) &&
142
- (rel.startsWith('src/components/') || rel.startsWith('components/') || rel.includes('/components/'))
143
- );
144
-
145
- for (const file of componentFiles) {
146
- const name = path.basename(file.rel, path.extname(file.rel));
147
- if (name === 'index' || name.includes('.test') || name.includes('.spec')) continue;
148
- result.components.push({ name, path: file.rel });
149
- }
150
-
151
- return result;
152
- } catch {
153
- return { pages: [], layouts: [], components: [] };
154
- }
155
- }
156
-
157
- export async function scanIntegrations(projectPath) {
158
- try {
159
- const files = await walkDir(
160
- projectPath,
161
- (rel, name) => /^appsettings(?:\.\w+)?\.json$/.test(name),
162
- projectPath,
163
- 20
164
- );
165
-
166
- const envFiles = await walkDir(
167
- projectPath,
168
- (rel, name) => name === '.env' || name === '.env.local' || name === '.env.production',
169
- projectPath,
170
- 5
171
- );
172
-
173
- const knownServices = {
174
- 'NeonAuth': 'auth',
175
- 'AsaaS': 'payment',
176
- 'Resend': 'email',
177
- 'Hangfire': 'background-jobs',
178
- 'Neon': 'database',
179
- 'ConnectionStrings': 'database',
180
- 'Redis': 'cache',
181
- 'SendGrid': 'email',
182
- 'Stripe': 'payment',
183
- 'AzureAd': 'auth',
184
- 'OpenAI': 'ai',
185
- 'AzureOpenAI': 'ai'
186
- };
187
-
188
- const detected = new Map();
189
-
190
- for (const file of files) {
191
- try {
192
- const content = JSON.parse(await fs.readFile(file.abs, 'utf8'));
193
- for (const [service, type] of Object.entries(knownServices)) {
194
- if (content[service] || content[service.toLowerCase()]) {
195
- const hasValues = content[service] && typeof content[service] === 'object'
196
- ? Object.values(content[service]).some(v => v && v !== '' && !String(v).startsWith('{{'))
197
- : true;
198
- if (!detected.has(service) || hasValues) {
199
- detected.set(service, { name: service, type, configured: hasValues });
200
- }
201
- }
202
- }
203
- if (content.ConnectionStrings) {
204
- for (const [key, val] of Object.entries(content.ConnectionStrings)) {
205
- if (val && !String(val).startsWith('{{')) {
206
- detected.set(`DB:${key}`, { name: `ConnectionString:${key}`, type: 'database', configured: true });
207
- }
208
- }
209
- }
210
- } catch {}
211
- }
212
-
213
- const envPrefixes = {
214
- 'NEON_AUTH_': 'NeonAuth',
215
- 'DATABASE_URL': 'Neon',
216
- 'NEON_': 'Neon',
217
- 'RESEND_': 'Resend',
218
- 'STRIPE_': 'Stripe',
219
- 'OPENAI_': 'OpenAI',
220
- 'ASAAS_': 'AsaaS'
221
- };
222
-
223
- for (const file of envFiles) {
224
- try {
225
- const content = await fs.readFile(file.abs, 'utf8');
226
- for (const [prefix, service] of Object.entries(envPrefixes)) {
227
- if (content.includes(prefix)) {
228
- const type = knownServices[service] || 'integration';
229
- if (!detected.has(service)) {
230
- detected.set(service, { name: service, type, configured: true });
231
- }
232
- }
233
- }
234
- } catch {}
235
- }
236
-
237
- return Array.from(detected.values());
238
- } catch {
239
- return [];
240
- }
241
- }
242
-
243
- export async function scanDatabaseSchema(projectPath) {
244
- try {
245
- const files = await walkDir(
246
- projectPath,
247
- (rel, name) => name.endsWith('.cs') && rel.includes('Migrations/') && !name.endsWith('.Designer.cs'),
248
- projectPath,
249
- 100
250
- );
251
-
252
- const tables = new Map();
253
- const toTableRegex = /\.ToTable\("(\w+)"/g;
254
- const createTableRegex = /migrationBuilder\.CreateTable\(\s*name:\s*"(\w+)"/g;
255
-
256
- for (const file of files) {
257
- try {
258
- const content = await fs.readFile(file.abs, 'utf8');
259
- const migrationName = path.basename(file.rel, '.cs');
260
-
261
- for (const regex of [toTableRegex, createTableRegex]) {
262
- regex.lastIndex = 0;
263
- let match;
264
- while ((match = regex.exec(content)) !== null) {
265
- if (!tables.has(match[1])) {
266
- tables.set(match[1], { table: match[1], migration: migrationName });
267
- }
268
- }
269
- }
270
- } catch {}
271
- }
272
-
273
- const sqlFiles = await walkDir(
274
- projectPath,
275
- (rel, name) => name.endsWith('.sql') && rel.includes('migrations/'),
276
- projectPath,
277
- 100
278
- );
279
-
280
- const createSqlRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?["']?(\w+)["']?/gi;
281
-
282
- for (const file of sqlFiles) {
283
- try {
284
- const content = await fs.readFile(file.abs, 'utf8');
285
- const migrationName = path.basename(file.rel, '.sql');
286
- createSqlRegex.lastIndex = 0;
287
- let match;
288
- while ((match = createSqlRegex.exec(content)) !== null) {
289
- if (!tables.has(match[1])) {
290
- tables.set(match[1], { table: match[1], migration: migrationName });
291
- }
292
- }
293
- } catch {}
294
- }
295
-
296
- return Array.from(tables.values());
297
- } catch {
298
- return [];
299
- }
300
- }
301
-
302
- export async function scanStackDependencies(projectPath) {
303
- try {
304
- const result = { dotnet: [], npm: [] };
305
-
306
- const csprojFiles = await walkDir(
307
- projectPath,
308
- (rel, name) => name.endsWith('.csproj'),
309
- projectPath,
310
- 10
311
- );
312
-
313
- const packageRefRegex = /<PackageReference\s+Include="([^"]+)"\s+Version="([^"]+)"/g;
314
-
315
- for (const file of csprojFiles) {
316
- try {
317
- const content = await fs.readFile(file.abs, 'utf8');
318
- packageRefRegex.lastIndex = 0;
319
- let match;
320
- while ((match = packageRefRegex.exec(content)) !== null) {
321
- result.dotnet.push({ name: match[1], version: match[2] });
322
- }
323
- } catch {}
324
- }
325
-
326
- const pkgPath = path.join(projectPath, 'package.json');
327
- if (existsSync(pkgPath)) {
328
- try {
329
- const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
330
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
331
- for (const [name, version] of Object.entries(allDeps)) {
332
- result.npm.push({ name, version: String(version) });
333
- }
334
- } catch {}
335
- }
336
-
337
- for (const subdir of ['web', 'frontend', 'client', 'src']) {
338
- const subPkgPath = path.join(projectPath, subdir, 'package.json');
339
- if (existsSync(subPkgPath)) {
340
- try {
341
- const pkg = JSON.parse(await fs.readFile(subPkgPath, 'utf8'));
342
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
343
- for (const [name, version] of Object.entries(allDeps)) {
344
- if (!result.npm.some(d => d.name === name)) {
345
- result.npm.push({ name, version: String(version) });
346
- }
347
- }
348
- } catch {}
349
- }
350
- }
351
-
352
- return result;
353
- } catch {
354
- return { dotnet: [], npm: [] };
355
- }
356
- }
357
-
358
- export async function scanArchitecture(projectPath) {
359
- const [entities, endpoints, nextjs, integrations, database, stack, graph] = await Promise.all([
360
- scanEntities(projectPath),
361
- scanEndpoints(projectPath),
362
- scanNextjsComponents(projectPath),
363
- scanIntegrations(projectPath),
364
- scanDatabaseSchema(projectPath),
365
- scanStackDependencies(projectPath),
366
- // Aditivo: sem grafo devolve listas vazias; o inventário acima tem a exaustividade que o grafo não tem.
367
- scanGraph(projectPath)
368
- ]);
369
-
370
- return {
371
- timestamp: new Date().toISOString(),
372
- entities,
373
- endpoints,
374
- nextjs,
375
- integrations,
376
- database,
377
- stack,
378
- graph
379
- };
380
- }
381
-
382
- // Project-local `.morph/framework/templates/` override first, then the CLI package's own.
383
- function resolveTemplatePath(projectPath, templateRelPath) {
384
- const projectLocal = path.join(projectPath, '.morph/framework/templates', templateRelPath);
385
- if (existsSync(projectLocal)) return projectLocal;
386
-
387
- const cliFramework = path.join(
388
- cliRootDir(), 'framework', 'templates', templateRelPath
389
- );
390
- if (existsSync(cliFramework)) return cliFramework;
391
-
392
- return null;
393
- }
394
-
395
- // fileURLToPath, not `new URL(...).pathname`: the latter stays percent-encoded, so a path with a space
396
- // (the default global npm install on Windows) never resolves and the template is silently dropped.
397
- function cliRootDir() {
398
- return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..');
399
- }
400
-
401
- // Read by `morph-plan` for the concept-level inventory the graph doesn't give. If that reader goes away,
402
- // remove this generator too.
403
- export async function renderArchitectureContext(projectPath, scanResult, options = {}) {
404
- const templatePath = resolveTemplatePath(projectPath, 'context/ARCHITECTURE.md');
405
-
406
- let projectName = options.projectName;
407
- if (!projectName) {
408
- const configPath = path.join(projectPath, '.morph/config/config.json');
409
- if (existsSync(configPath)) {
410
- try {
411
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
412
- projectName = config.project?.name;
413
- } catch {}
414
- }
415
- if (!projectName) {
416
- projectName = path.basename(projectPath);
417
- }
418
- }
419
-
420
- const variables = {
421
- projectName,
422
- hasDotnet: scanResult.entities.length > 0 || scanResult.endpoints.length > 0,
423
- entities: scanResult.entities,
424
- entityCount: scanResult.entities.length,
425
- endpoints: scanResult.endpoints,
426
- endpointCount: scanResult.endpoints.length,
427
- hasNextjs: scanResult.nextjs.pages.length > 0 || scanResult.nextjs.components.length > 0,
428
- pages: scanResult.nextjs.pages,
429
- pageCount: scanResult.nextjs.pages.length,
430
- layouts: scanResult.nextjs.layouts,
431
- components: scanResult.nextjs.components,
432
- componentCount: scanResult.nextjs.components.length,
433
- hasIntegrations: scanResult.integrations.length > 0,
434
- integrations: scanResult.integrations,
435
- hasTables: scanResult.database.length > 0,
436
- tables: scanResult.database,
437
- tableCount: scanResult.database.length,
438
- hasDotnetPackages: scanResult.stack.dotnet.length > 0,
439
- dotnetPackages: scanResult.stack.dotnet,
440
- hasNpmPackages: scanResult.stack.npm.length > 0,
441
- npmPackages: scanResult.stack.npm,
442
- // Comunidade ainda rotulada Community_N fica de fora: sem `graphify label` é ruído puro.
443
- hasGraph: scanResult.graph?.available === true && (scanResult.graph.godNodes?.length ?? 0) > 0,
444
- godNodes: scanResult.graph?.godNodes ?? [],
445
- communities: (scanResult.graph?.communities ?? []).filter((c) => c.labeled),
446
- hasLabeledCommunities: (scanResult.graph?.communities ?? []).some((c) => c.labeled)
447
- };
448
-
449
- let content;
450
- if (templatePath) {
451
- content = renderTemplate(templatePath, variables);
452
- } else {
453
- content = generateFallbackMarkdown(variables);
454
- }
455
-
456
- const contextDir = path.join(projectPath, '.morph/context');
457
- await fs.mkdir(contextDir, { recursive: true });
458
- const outputPath = path.join(contextDir, 'README.md');
459
- await fs.writeFile(outputPath, content, 'utf8');
460
-
461
- return outputPath;
462
- }
463
-
464
- function generateFallbackMarkdown(vars) {
465
- const lines = [`# ${vars.projectName} — Architecture Context\n`];
466
- lines.push('> Auto-generated by morph-spec context refresh\n');
467
-
468
- if (vars.hasDotnet) {
469
- lines.push('## .NET Entities\n');
470
- for (const e of vars.entities) {
471
- lines.push(`- \`${e.name}\` (${e.type}) — ${e.path}`);
472
- }
473
- lines.push('\n## API Endpoints\n');
474
- for (const ep of vars.endpoints) {
475
- lines.push(`- ${ep.method ? ep.method + ' ' : ''}\`${ep.route}\` — ${ep.name} (${ep.path})`);
476
- }
477
- lines.push('');
478
- }
479
-
480
- if (vars.hasNextjs) {
481
- lines.push('## Next.js Pages\n');
482
- for (const p of vars.pages) {
483
- lines.push(`- \`${p.route}\` — ${p.path}`);
484
- }
485
- if (vars.components.length > 0) {
486
- lines.push('\n## Components\n');
487
- for (const c of vars.components) {
488
- lines.push(`- \`${c.name}\` — ${c.path}`);
489
- }
490
- }
491
- lines.push('');
492
- }
493
-
494
- if (vars.hasIntegrations) {
495
- lines.push('## Integrations\n');
496
- for (const i of vars.integrations) {
497
- lines.push(`- **${i.name}** (${i.type}) — ${i.configured ? 'configured' : 'not configured'}`);
498
- }
499
- lines.push('');
500
- }
501
-
502
- if (vars.hasTables) {
503
- lines.push('## Database Tables\n');
504
- for (const t of vars.tables) {
505
- lines.push(`- \`${t.table}\` (from ${t.migration})`);
506
- }
507
- lines.push('');
508
- }
509
-
510
- if (vars.hasDotnetPackages) {
511
- lines.push('## .NET Packages\n');
512
- for (const p of vars.dotnetPackages) {
513
- lines.push(`- \`${p.name}\` ${p.version}`);
514
- }
515
- lines.push('');
516
- }
517
-
518
- if (vars.hasNpmPackages) {
519
- lines.push('## NPM Packages\n');
520
- for (const p of vars.npmPackages) {
521
- lines.push(`- \`${p.name}\` ${p.version}`);
522
- }
523
- lines.push('');
524
- }
525
-
526
- if (vars.hasGraph) {
527
- lines.push('## Centralidade (grafo de codebase)\n');
528
- lines.push('| Símbolo | Arquivo | Grau |');
529
- lines.push('|---------|---------|------|');
530
- for (const n of vars.godNodes) {
531
- lines.push(`| \`${n.label}\` | \`${n.source_file}\` | ${n.degree} |`);
532
- }
533
- lines.push('');
534
- if (vars.hasLabeledCommunities) {
535
- lines.push('### Comunidades\n');
536
- for (const c of vars.communities) {
537
- lines.push(`- **${c.label}** (${c.size} nós)`);
538
- }
539
- lines.push('');
540
- }
541
- }
542
- return lines.join('\n');
543
- }
@@ -1,97 +0,0 @@
1
- // `_morph_managed` marks the managed entries, so a reset never touches the user's.
2
-
3
- import { join } from 'path';
4
- import { existsSync } from 'fs';
5
- import { readFile, writeFile, mkdir } from 'fs/promises';
6
-
7
- const MORPH_MANAGED_KEY = '_morph_managed';
8
-
9
- export async function generateSettings(targetPath, detectedConfig, morphConfig = {}) {
10
- const claudeDir = join(targetPath, '.claude');
11
- const settingsPath = join(claudeDir, 'settings.local.json');
12
-
13
- const existing = withoutLegacyPermissions(await readSettingsSafe(settingsPath));
14
- const generated = {};
15
-
16
- const managed = {
17
- mcps_detected: detectedConfig.mcpServers.map(s => s.name),
18
- plugins_detected: detectedConfig.plugins.map(p => (typeof p === 'string' ? p : p?.name)),
19
- generated_at: new Date().toISOString()
20
- };
21
-
22
- const merged = mergeSettings(existing, generated);
23
- merged[MORPH_MANAGED_KEY] = managed;
24
-
25
- if (!existsSync(claudeDir)) {
26
- await mkdir(claudeDir, { recursive: true });
27
- }
28
-
29
- await writeFile(settingsPath, JSON.stringify(merged, null, 2) + '\n', 'utf-8');
30
-
31
- return {
32
- settingsPath,
33
- managed
34
- };
35
- }
36
-
37
- /** Never overwrites user entries: arrays are unioned, objects merged, only new keys added. */
38
- export function mergeSettings(existing, generated) {
39
- const result = { ...existing };
40
-
41
- for (const [key, value] of Object.entries(generated)) {
42
- if (key === MORPH_MANAGED_KEY) continue;
43
-
44
- if (Array.isArray(value) && Array.isArray(result[key])) {
45
- const set = new Set(result[key]);
46
- for (const item of value) {
47
- set.add(item);
48
- }
49
- result[key] = [...set];
50
- } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
51
- result[key] = mergeSettings(result[key] || {}, value);
52
- } else if (!(key in result)) {
53
- result[key] = value;
54
- }
55
- }
56
-
57
- return result;
58
- }
59
-
60
- export async function saveIntegrations(targetPath, detectedConfig) {
61
- const integrationsPath = join(targetPath, '.morph', 'config', 'integrations.json');
62
- const integrationsDir = join(targetPath, '.morph', 'config');
63
-
64
- if (!existsSync(integrationsDir)) {
65
- await mkdir(integrationsDir, { recursive: true });
66
- }
67
-
68
- const integrations = {
69
- version: '1.0.0',
70
- detectedAt: new Date().toISOString(),
71
- plugins: detectedConfig.plugins,
72
- mcpServers: detectedConfig.mcpServers,
73
- customSkills: detectedConfig.customSkills.length,
74
- customCommands: detectedConfig.customCommands.length,
75
- hooks: detectedConfig.hooks.length
76
- };
77
-
78
- await writeFile(integrationsPath, JSON.stringify(integrations, null, 2) + '\n', 'utf-8');
79
- return integrationsPath;
80
- }
81
-
82
- // Claude Code reads only `permissions: { allow, deny }`. Old generators wrote wildcard rules as a bare
83
- // array that never applied; converting it to { allow } would silently enable them.
84
- function withoutLegacyPermissions(settings) {
85
- if (!Array.isArray(settings.permissions)) return settings;
86
- const { permissions, ...rest } = settings;
87
- return rest;
88
- }
89
-
90
- async function readSettingsSafe(settingsPath) {
91
- try {
92
- if (!existsSync(settingsPath)) return {};
93
- return JSON.parse(await readFile(settingsPath, 'utf-8'));
94
- } catch {
95
- return {};
96
- }
97
- }