@polymorphism-tech/morph-spec 4.15.0 → 4.17.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 (100) hide show
  1. package/README.md +2 -2
  2. package/bin/morph-spec.js +4 -0
  3. package/bin/task-manager.js +999 -962
  4. package/claude-plugin.json +1 -1
  5. package/docs/CHEATSHEET.md +1 -1
  6. package/docs/QUICKSTART.md +1 -1
  7. package/framework/agents/ai-agents/vector-search-expert.md +247 -233
  8. package/framework/agents/backend/ms-agent-expert.md +2 -1
  9. package/framework/agents/backend/neon-expert.md +397 -0
  10. package/framework/agents/frontend/gsap-animator.md +131 -0
  11. package/framework/agents.json +1175 -1077
  12. package/framework/commands/morph-preflight.md +200 -192
  13. package/framework/hooks/claude-code/session-start/inject-morph-context.js +1 -1
  14. package/framework/rules/gsap-standards.md +13 -0
  15. package/framework/rules/neon-standards.md +25 -0
  16. package/framework/skills/level-0-meta/mcp-registry.json +1 -1
  17. package/framework/skills/level-0-meta/morph-agent-teams/SKILL.md +472 -472
  18. package/framework/skills/level-0-meta/morph-init/SKILL.md +30 -11
  19. package/framework/skills/level-0-meta/morph-post-implementation/SKILL.md +5 -5
  20. package/framework/skills/level-0-meta/morph-tool-usage-guide/SKILL.md +5 -5
  21. package/framework/skills/level-0-meta/morph-tool-usage-guide/references/tools-per-phase.md +7 -7
  22. package/framework/skills/level-1-workflows/morph-phase-codebase-analysis/SKILL.md +24 -24
  23. package/framework/skills/level-1-workflows/morph-phase-design/SKILL.md +12 -12
  24. package/framework/skills/level-1-workflows/morph-phase-implement/SKILL.md +9 -9
  25. package/framework/skills/level-1-workflows/morph-phase-plan/SKILL.md +1 -1
  26. package/framework/skills/level-1-workflows/morph-phase-tasks/SKILL.md +1 -1
  27. package/framework/skills/level-1-workflows/morph-phase-tasks/references/task-planning-patterns.md +143 -143
  28. package/framework/skills/level-1-workflows/morph-phase-uiux/SKILL.md +1 -1
  29. package/framework/skills/level-1-workflows/morph-scope-escalation/SKILL.md +1 -1
  30. package/framework/standards/STANDARDS.json +184 -107
  31. package/framework/standards/ai-agents/production.md +1 -0
  32. package/framework/standards/ai-agents/setup.md +3 -2
  33. package/framework/standards/ai-agents/workflows.md +1 -0
  34. package/framework/standards/architecture/vertical-slice/vertical-slice.md +4 -4
  35. package/framework/standards/backend/database/postgresql/database.md +58 -78
  36. package/framework/standards/backend/dotnet/scalar-ui.md +172 -172
  37. package/framework/standards/backend/dotnet/vsa-handler-patterns.md +274 -274
  38. package/framework/standards/backend/integrations/asaas/asaas-api.md +1 -1
  39. package/framework/standards/backend/integrations/clerk/clerk-auth.md +23 -21
  40. package/framework/standards/frontend/design-system/animations.md +9 -0
  41. package/framework/standards/frontend/gsap/gsap-core.md +463 -0
  42. package/framework/standards/frontend/gsap/gsap-plugins.md +294 -0
  43. package/framework/standards/frontend/gsap/gsap-scrolltrigger.md +318 -0
  44. package/framework/standards/frontend/nextjs/motion-patterns.md +1 -0
  45. package/framework/standards/frontend/nextjs/nextjs-patterns.md +47 -37
  46. package/framework/standards/infrastructure/docker/easypanel-deploy.md +4 -8
  47. package/framework/standards/infrastructure/neon/neon-pgrag.md +239 -0
  48. package/framework/standards/infrastructure/neon/neon-pgvector.md +236 -0
  49. package/framework/standards/infrastructure/neon/neon-semantic-kernel.md +310 -0
  50. package/framework/standards/infrastructure/neon/neon-setup.md +186 -0
  51. package/framework/standards/integration/mcp/mcp-tools.md +32 -34
  52. package/framework/templates/README.md +18 -18
  53. package/framework/templates/REGISTRY.json +49 -96
  54. package/framework/templates/code/dotnet/abstractions/api-endpoint.cs +7 -7
  55. package/framework/templates/code/dotnet/backend/repository.cs +148 -148
  56. package/framework/templates/code/dotnet/contracts/contracts-vsa.cs +2 -2
  57. package/framework/templates/code/dotnet/database/vector-entity.cs +93 -0
  58. package/framework/templates/code/dotnet/feature/endpoint.cs.hbs +1 -1
  59. package/framework/templates/code/sql/{supabase-migration.sql → postgresql-migration.sql} +8 -17
  60. package/framework/templates/code/sql/{supabase-migration.template.sql → postgresql-migration.template.sql} +10 -13
  61. package/framework/templates/code/sql/{rls-policy.sql → postgresql-rls-policy.sql} +8 -8
  62. package/framework/templates/code/typescript/contracts.ts +167 -168
  63. package/framework/templates/context/CONTEXT.md +3 -3
  64. package/framework/templates/docs/proposal.md +6 -6
  65. package/framework/templates/docs/ui-components.md +1 -1
  66. package/framework/templates/feature/decisions.md +121 -121
  67. package/framework/templates/feature/recap.md +145 -145
  68. package/framework/templates/feature/tasks.md +199 -199
  69. package/framework/templates/frontend/nextjs/gsap-scroll-section.tsx.hbs +44 -0
  70. package/framework/templates/infrastructure/docker/docker-compose.template.yml +50 -67
  71. package/framework/templates/infrastructure/docker/dockerfile-api.dockerfile +38 -38
  72. package/framework/templates/infrastructure/docker/dockerfile-web.dockerfile +48 -48
  73. package/framework/templates/infrastructure/docker/easypanel.template.json +46 -54
  74. package/framework/templates/infrastructure/github/README.md +56 -56
  75. package/framework/templates/integrations/semantic-kernel-neon.cs +125 -0
  76. package/framework/workflows/README.md +1 -1
  77. package/framework/workflows/docs/full-morph.md +69 -69
  78. package/package.json +1 -1
  79. package/src/commands/agents/dispatch-agents.js +19 -15
  80. package/src/commands/project/setup-infra-cmd.js +1 -1
  81. package/src/commands/state/advance-phase.js +5 -0
  82. package/src/commands/tasks/task.js +3 -0
  83. package/src/core/state/state-manager.js +45 -1
  84. package/src/core/templates/template-registry.js +1 -66
  85. package/src/lib/detectors/index.js +2 -2
  86. package/src/lib/generators/architecture-scanner.js +640 -640
  87. package/src/lib/installers/mcp-installer.js +1 -1
  88. package/src/lib/tasks/task-classifier.js +15 -1
  89. package/src/lib/tasks/test-runner.js +5 -1
  90. package/src/lib/validators/content/content-validator.js +9 -10
  91. package/src/lib/validators/validation-runner.js +7 -5
  92. package/src/scripts/setup-infra.js +60 -30
  93. package/framework/agents/backend/supabase-expert.md +0 -256
  94. package/framework/rules/supabase-standards.md +0 -29
  95. package/framework/standards/infrastructure/supabase/mcp-setup.md +0 -142
  96. package/framework/standards/infrastructure/supabase/supabase-auth.md +0 -176
  97. package/framework/standards/infrastructure/supabase/supabase-custom-jwt.md +0 -206
  98. package/framework/standards/infrastructure/supabase/supabase-pgvector.md +0 -169
  99. package/framework/standards/infrastructure/supabase/supabase-rls.md +0 -184
  100. package/framework/standards/infrastructure/supabase/supabase-storage.md +0 -153
@@ -1,640 +1,640 @@
1
- /**
2
- * Architecture Scanner - Generates rich architectural context from project filesystem.
3
- *
4
- * Performs fast (<5s) glob-based scanning to produce a snapshot of:
5
- * - .NET entities (sealed class/record)
6
- * - API endpoints (IApiEndpoint implementations)
7
- * - Next.js pages and components
8
- * - Integrations (from appsettings.json)
9
- * - Database schema (from EF migrations)
10
- * - Stack dependencies (.csproj + package.json)
11
- *
12
- * All scanning is regex-based (no AST parsing) for speed.
13
- *
14
- * @module architecture-scanner
15
- */
16
-
17
- import fs from 'fs/promises';
18
- import path from 'path';
19
- import { existsSync, readFileSync } from 'fs';
20
- import { renderTemplate } from '../../core/templates/template-renderer.js';
21
-
22
- const SKIP_DIRS = new Set(['node_modules', 'bin', 'obj', '.git', '.morph', '.next', 'dist', 'out', '.worktrees']);
23
- const MAX_FILES_PER_SCANNER = 200;
24
-
25
- /**
26
- * Recursively walk a directory, returning files matching a filter.
27
- * Skips known heavy directories for performance.
28
- *
29
- * @param {string} dir - Directory to walk
30
- * @param {function} filter - (relativePath) => boolean
31
- * @param {string} [base] - Base path for relative calculation
32
- * @param {number} [limit] - Max files to return
33
- * @returns {Promise<Array<{abs: string, rel: string}>>}
34
- */
35
- async function walkDir(dir, filter, base = dir, limit = MAX_FILES_PER_SCANNER) {
36
- const results = [];
37
-
38
- async function recurse(currentDir) {
39
- if (results.length >= limit) return;
40
-
41
- let entries;
42
- try {
43
- entries = await fs.readdir(currentDir, { withFileTypes: true });
44
- } catch {
45
- return;
46
- }
47
-
48
- for (const entry of entries) {
49
- if (results.length >= limit) break;
50
-
51
- if (entry.isDirectory()) {
52
- if (SKIP_DIRS.has(entry.name)) continue;
53
- await recurse(path.join(currentDir, entry.name));
54
- } else if (entry.isFile()) {
55
- const abs = path.join(currentDir, entry.name);
56
- const rel = path.relative(base, abs).replace(/\\/g, '/');
57
- if (filter(rel, entry.name)) {
58
- results.push({ abs, rel });
59
- }
60
- }
61
- }
62
- }
63
-
64
- await recurse(dir);
65
- return results;
66
- }
67
-
68
- /**
69
- * Scan .NET entities from Entities/ or Features/ directories.
70
- *
71
- * @param {string} projectPath
72
- * @returns {Promise<Array<{name: string, type: string, path: string}>>}
73
- */
74
- export async function scanEntities(projectPath) {
75
- try {
76
- const files = await walkDir(
77
- projectPath,
78
- (rel, name) => name.endsWith('.cs') && (rel.includes('Entities/') || rel.includes('Features/') || rel.includes('Models/'))
79
- );
80
-
81
- const entities = [];
82
- const entityRegex = /(?:public\s+)?(?:sealed\s+)?(class|record)\s+(\w+)/g;
83
-
84
- for (const file of files) {
85
- try {
86
- const content = await fs.readFile(file.abs, 'utf8');
87
- let match;
88
- entityRegex.lastIndex = 0;
89
- while ((match = entityRegex.exec(content)) !== null) {
90
- const line = content.slice(Math.max(0, match.index - 80), match.index + match[0].length);
91
- // Only capture sealed/record types or classes in entity-like directories
92
- if (/sealed|record/.test(line) || file.rel.includes('Entities/')) {
93
- entities.push({
94
- name: match[2],
95
- type: match[1],
96
- path: file.rel
97
- });
98
- }
99
- }
100
- } catch { /* skip unreadable files */ }
101
- }
102
-
103
- return entities;
104
- } catch {
105
- return [];
106
- }
107
- }
108
-
109
- /**
110
- * Scan API endpoints implementing IApiEndpoint.
111
- *
112
- * @param {string} projectPath
113
- * @returns {Promise<Array<{name: string, route: string, method: string, path: string}>>}
114
- */
115
- export async function scanEndpoints(projectPath) {
116
- try {
117
- const files = await walkDir(
118
- projectPath,
119
- (rel, name) => name.endsWith('.cs') && (rel.includes('Endpoints/') || rel.includes('Features/'))
120
- );
121
-
122
- const endpoints = [];
123
- const classRegex = /class\s+(\w+)[^{]*(?:IApiEndpoint|IEndpoint|Endpoint)/;
124
- const routeRegex = /Route\s*(?:=>|=)\s*"([^"]+)"/;
125
- const methodRegex = /(?:Http(Get|Post|Put|Delete|Patch))|(?:\.Map(Get|Post|Put|Delete|Patch))/i;
126
-
127
- for (const file of files) {
128
- try {
129
- const content = await fs.readFile(file.abs, 'utf8');
130
- const classMatch = classRegex.exec(content);
131
- if (!classMatch) continue;
132
-
133
- const routeMatch = routeRegex.exec(content);
134
- const methodMatch = methodRegex.exec(content);
135
-
136
- endpoints.push({
137
- name: classMatch[1],
138
- route: routeMatch ? routeMatch[1] : '(unknown)',
139
- method: methodMatch ? (methodMatch[1] || methodMatch[2] || '').toUpperCase() : '',
140
- path: file.rel
141
- });
142
- } catch { /* skip */ }
143
- }
144
-
145
- return endpoints;
146
- } catch {
147
- return [];
148
- }
149
- }
150
-
151
- /**
152
- * Scan Next.js pages and components.
153
- *
154
- * @param {string} projectPath
155
- * @returns {Promise<{pages: Array<{route: string, path: string}>, layouts: Array<{path: string}>, components: Array<{name: string, path: string}>}>}
156
- */
157
- export async function scanNextjsComponents(projectPath) {
158
- try {
159
- const result = { pages: [], layouts: [], components: [] };
160
-
161
- // Scan pages and layouts from app directory
162
- const appFiles = await walkDir(
163
- projectPath,
164
- (rel, name) =>
165
- (name === 'page.tsx' || name === 'page.jsx' || name === 'layout.tsx' || name === 'layout.jsx') &&
166
- (rel.startsWith('app/') || rel.startsWith('src/app/'))
167
- );
168
-
169
- for (const file of appFiles) {
170
- const isLayout = file.rel.includes('layout.');
171
- const routeDir = path.dirname(file.rel).replace(/^(?:src\/)?app/, '').replace(/\\/g, '/');
172
- const route = routeDir || '/';
173
-
174
- if (isLayout) {
175
- result.layouts.push({ path: file.rel });
176
- } else {
177
- result.pages.push({ route: route === '' ? '/' : route, path: file.rel });
178
- }
179
- }
180
-
181
- // Scan components
182
- const componentFiles = await walkDir(
183
- projectPath,
184
- (rel, name) =>
185
- (name.endsWith('.tsx') || name.endsWith('.jsx')) &&
186
- (rel.startsWith('src/components/') || rel.startsWith('components/') || rel.includes('/components/'))
187
- );
188
-
189
- for (const file of componentFiles) {
190
- const name = path.basename(file.rel, path.extname(file.rel));
191
- // Skip index files and test files
192
- if (name === 'index' || name.includes('.test') || name.includes('.spec')) continue;
193
- result.components.push({ name, path: file.rel });
194
- }
195
-
196
- return result;
197
- } catch {
198
- return { pages: [], layouts: [], components: [] };
199
- }
200
- }
201
-
202
- /**
203
- * Scan integrations from appsettings*.json files.
204
- *
205
- * @param {string} projectPath
206
- * @returns {Promise<Array<{name: string, type: string, configured: boolean}>>}
207
- */
208
- export async function scanIntegrations(projectPath) {
209
- try {
210
- const files = await walkDir(
211
- projectPath,
212
- (rel, name) => /^appsettings(?:\.\w+)?\.json$/.test(name),
213
- projectPath,
214
- 20
215
- );
216
-
217
- // Also check .env files for common integrations
218
- const envFiles = await walkDir(
219
- projectPath,
220
- (rel, name) => name === '.env' || name === '.env.local' || name === '.env.production',
221
- projectPath,
222
- 5
223
- );
224
-
225
- const knownServices = {
226
- 'Clerk': 'auth',
227
- 'AsaaS': 'payment',
228
- 'Resend': 'email',
229
- 'Hangfire': 'background-jobs',
230
- 'Supabase': 'database/auth',
231
- 'ConnectionStrings': 'database',
232
- 'Redis': 'cache',
233
- 'SendGrid': 'email',
234
- 'Stripe': 'payment',
235
- 'AzureAd': 'auth',
236
- 'OpenAI': 'ai',
237
- 'AzureOpenAI': 'ai'
238
- };
239
-
240
- const detected = new Map();
241
-
242
- // Scan appsettings files
243
- for (const file of files) {
244
- try {
245
- const content = JSON.parse(await fs.readFile(file.abs, 'utf8'));
246
- for (const [service, type] of Object.entries(knownServices)) {
247
- if (content[service] || content[service.toLowerCase()]) {
248
- const hasValues = content[service] && typeof content[service] === 'object'
249
- ? Object.values(content[service]).some(v => v && v !== '' && !String(v).startsWith('{{'))
250
- : true;
251
- if (!detected.has(service) || hasValues) {
252
- detected.set(service, { name: service, type, configured: hasValues });
253
- }
254
- }
255
- }
256
- // Check ConnectionStrings specifically
257
- if (content.ConnectionStrings) {
258
- for (const [key, val] of Object.entries(content.ConnectionStrings)) {
259
- if (val && !String(val).startsWith('{{')) {
260
- detected.set(`DB:${key}`, { name: `ConnectionString:${key}`, type: 'database', configured: true });
261
- }
262
- }
263
- }
264
- } catch { /* skip invalid JSON */ }
265
- }
266
-
267
- // Scan .env files for known prefixes
268
- const envPrefixes = {
269
- 'NEXT_PUBLIC_CLERK': 'Clerk',
270
- 'CLERK_': 'Clerk',
271
- 'NEXT_PUBLIC_SUPABASE': 'Supabase',
272
- 'SUPABASE_': 'Supabase',
273
- 'RESEND_': 'Resend',
274
- 'STRIPE_': 'Stripe',
275
- 'OPENAI_': 'OpenAI',
276
- 'ASAAS_': 'AsaaS'
277
- };
278
-
279
- for (const file of envFiles) {
280
- try {
281
- const content = await fs.readFile(file.abs, 'utf8');
282
- for (const [prefix, service] of Object.entries(envPrefixes)) {
283
- if (content.includes(prefix)) {
284
- const type = knownServices[service] || 'integration';
285
- if (!detected.has(service)) {
286
- detected.set(service, { name: service, type, configured: true });
287
- }
288
- }
289
- }
290
- } catch { /* skip */ }
291
- }
292
-
293
- return Array.from(detected.values());
294
- } catch {
295
- return [];
296
- }
297
- }
298
-
299
- /**
300
- * Scan database schema from EF Core migrations.
301
- *
302
- * @param {string} projectPath
303
- * @returns {Promise<Array<{table: string, migration: string}>>}
304
- */
305
- export async function scanDatabaseSchema(projectPath) {
306
- try {
307
- const files = await walkDir(
308
- projectPath,
309
- (rel, name) => name.endsWith('.cs') && rel.includes('Migrations/') && !name.endsWith('.Designer.cs'),
310
- projectPath,
311
- 100
312
- );
313
-
314
- const tables = new Map();
315
- const toTableRegex = /\.ToTable\("(\w+)"/g;
316
- const createTableRegex = /migrationBuilder\.CreateTable\(\s*name:\s*"(\w+)"/g;
317
-
318
- for (const file of files) {
319
- try {
320
- const content = await fs.readFile(file.abs, 'utf8');
321
- const migrationName = path.basename(file.rel, '.cs');
322
-
323
- for (const regex of [toTableRegex, createTableRegex]) {
324
- regex.lastIndex = 0;
325
- let match;
326
- while ((match = regex.exec(content)) !== null) {
327
- if (!tables.has(match[1])) {
328
- tables.set(match[1], { table: match[1], migration: migrationName });
329
- }
330
- }
331
- }
332
- } catch { /* skip */ }
333
- }
334
-
335
- // Also scan Supabase migrations (SQL)
336
- const sqlFiles = await walkDir(
337
- projectPath,
338
- (rel, name) => name.endsWith('.sql') && (rel.includes('migrations/') || rel.includes('supabase/migrations/')),
339
- projectPath,
340
- 100
341
- );
342
-
343
- const createSqlRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?["']?(\w+)["']?/gi;
344
-
345
- for (const file of sqlFiles) {
346
- try {
347
- const content = await fs.readFile(file.abs, 'utf8');
348
- const migrationName = path.basename(file.rel, '.sql');
349
- createSqlRegex.lastIndex = 0;
350
- let match;
351
- while ((match = createSqlRegex.exec(content)) !== null) {
352
- if (!tables.has(match[1])) {
353
- tables.set(match[1], { table: match[1], migration: migrationName });
354
- }
355
- }
356
- } catch { /* skip */ }
357
- }
358
-
359
- return Array.from(tables.values());
360
- } catch {
361
- return [];
362
- }
363
- }
364
-
365
- /**
366
- * Detect stack from .csproj PackageReference and package.json dependencies.
367
- *
368
- * @param {string} projectPath
369
- * @returns {Promise<{dotnet: Array<{name: string, version: string}>, npm: Array<{name: string, version: string}>}>}
370
- */
371
- export async function scanStackDependencies(projectPath) {
372
- try {
373
- const result = { dotnet: [], npm: [] };
374
-
375
- // Scan .csproj files
376
- const csprojFiles = await walkDir(
377
- projectPath,
378
- (rel, name) => name.endsWith('.csproj'),
379
- projectPath,
380
- 10
381
- );
382
-
383
- const packageRefRegex = /<PackageReference\s+Include="([^"]+)"\s+Version="([^"]+)"/g;
384
-
385
- for (const file of csprojFiles) {
386
- try {
387
- const content = await fs.readFile(file.abs, 'utf8');
388
- packageRefRegex.lastIndex = 0;
389
- let match;
390
- while ((match = packageRefRegex.exec(content)) !== null) {
391
- result.dotnet.push({ name: match[1], version: match[2] });
392
- }
393
- } catch { /* skip */ }
394
- }
395
-
396
- // Scan package.json (root only)
397
- const pkgPath = path.join(projectPath, 'package.json');
398
- if (existsSync(pkgPath)) {
399
- try {
400
- const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
401
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
402
- for (const [name, version] of Object.entries(allDeps)) {
403
- result.npm.push({ name, version: String(version) });
404
- }
405
- } catch { /* skip */ }
406
- }
407
-
408
- // Also check web/ or frontend/ subdirectory package.json
409
- for (const subdir of ['web', 'frontend', 'client', 'src']) {
410
- const subPkgPath = path.join(projectPath, subdir, 'package.json');
411
- if (existsSync(subPkgPath)) {
412
- try {
413
- const pkg = JSON.parse(await fs.readFile(subPkgPath, 'utf8'));
414
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
415
- for (const [name, version] of Object.entries(allDeps)) {
416
- // Avoid duplicates
417
- if (!result.npm.some(d => d.name === name)) {
418
- result.npm.push({ name, version: String(version) });
419
- }
420
- }
421
- } catch { /* skip */ }
422
- }
423
- }
424
-
425
- return result;
426
- } catch {
427
- return { dotnet: [], npm: [] };
428
- }
429
- }
430
-
431
- /**
432
- * Master scan — runs all scanners in parallel.
433
- *
434
- * @param {string} projectPath
435
- * @returns {Promise<Object>} ArchitectureScanResult
436
- */
437
- export async function scanArchitecture(projectPath) {
438
- const [entities, endpoints, nextjs, integrations, database, stack] = await Promise.all([
439
- scanEntities(projectPath),
440
- scanEndpoints(projectPath),
441
- scanNextjsComponents(projectPath),
442
- scanIntegrations(projectPath),
443
- scanDatabaseSchema(projectPath),
444
- scanStackDependencies(projectPath)
445
- ]);
446
-
447
- return {
448
- timestamp: new Date().toISOString(),
449
- entities,
450
- endpoints,
451
- nextjs,
452
- integrations,
453
- database,
454
- stack
455
- };
456
- }
457
-
458
- /**
459
- * Resolve a template path: check .morph/framework/templates/ first, then framework/templates/,
460
- * then fall back to the CLI package's own framework/templates/.
461
- *
462
- * @param {string} projectPath
463
- * @param {string} templateRelPath
464
- * @returns {string|null}
465
- */
466
- function resolveTemplatePath(projectPath, templateRelPath) {
467
- // 1. Project-local override
468
- const projectLocal = path.join(projectPath, '.morph/framework/templates', templateRelPath);
469
- if (existsSync(projectLocal)) return projectLocal;
470
-
471
- // 2. CLI package framework/ (for running from source or during init)
472
- const cliFramework = path.join(
473
- path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1')),
474
- '..', '..', '..', 'framework', 'templates', templateRelPath
475
- );
476
- if (existsSync(cliFramework)) return cliFramework;
477
-
478
- return null;
479
- }
480
-
481
- /**
482
- * Render architecture context to .morph/context/README.md
483
- *
484
- * @param {string} projectPath
485
- * @param {Object} scanResult - Result from scanArchitecture()
486
- * @param {Object} [options]
487
- * @param {string} [options.projectName] - Override project name
488
- * @returns {Promise<string>} Path to written file
489
- */
490
- export async function renderArchitectureContext(projectPath, scanResult, options = {}) {
491
- const templatePath = resolveTemplatePath(projectPath, 'context/ARCHITECTURE.md');
492
-
493
- // Determine project name
494
- let projectName = options.projectName;
495
- if (!projectName) {
496
- // Try config.json
497
- const configPath = path.join(projectPath, '.morph/config/config.json');
498
- if (existsSync(configPath)) {
499
- try {
500
- const config = JSON.parse(readFileSync(configPath, 'utf8'));
501
- projectName = config.project?.name;
502
- } catch { /* ignore */ }
503
- }
504
- // Fallback to directory name
505
- if (!projectName) {
506
- projectName = path.basename(projectPath);
507
- }
508
- }
509
-
510
- // Get morph-spec version
511
- let morphVersion = 'unknown';
512
- try {
513
- const pkgPath = path.join(
514
- path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1')),
515
- '..', '..', '..', 'package.json'
516
- );
517
- if (existsSync(pkgPath)) {
518
- morphVersion = JSON.parse(readFileSync(pkgPath, 'utf8')).version;
519
- }
520
- } catch { /* ignore */ }
521
-
522
- const variables = {
523
- projectName,
524
- timestamp: new Date().toISOString().replace('T', ' ').split('.')[0],
525
- morphVersion,
526
- // Entities
527
- hasDotnet: scanResult.entities.length > 0 || scanResult.endpoints.length > 0,
528
- entities: scanResult.entities,
529
- entityCount: scanResult.entities.length,
530
- endpoints: scanResult.endpoints,
531
- endpointCount: scanResult.endpoints.length,
532
- // Next.js
533
- hasNextjs: scanResult.nextjs.pages.length > 0 || scanResult.nextjs.components.length > 0,
534
- pages: scanResult.nextjs.pages,
535
- pageCount: scanResult.nextjs.pages.length,
536
- layouts: scanResult.nextjs.layouts,
537
- components: scanResult.nextjs.components,
538
- componentCount: scanResult.nextjs.components.length,
539
- // Integrations
540
- hasIntegrations: scanResult.integrations.length > 0,
541
- integrations: scanResult.integrations,
542
- // Database
543
- hasTables: scanResult.database.length > 0,
544
- tables: scanResult.database,
545
- tableCount: scanResult.database.length,
546
- // Stack
547
- hasDotnetPackages: scanResult.stack.dotnet.length > 0,
548
- dotnetPackages: scanResult.stack.dotnet,
549
- hasNpmPackages: scanResult.stack.npm.length > 0,
550
- npmPackages: scanResult.stack.npm
551
- };
552
-
553
- let content;
554
- if (templatePath) {
555
- content = renderTemplate(templatePath, variables);
556
- } else {
557
- // Fallback: generate minimal markdown without template
558
- content = generateFallbackMarkdown(variables);
559
- }
560
-
561
- // Write to .morph/context/README.md
562
- const contextDir = path.join(projectPath, '.morph/context');
563
- await fs.mkdir(contextDir, { recursive: true });
564
- const outputPath = path.join(contextDir, 'README.md');
565
- await fs.writeFile(outputPath, content, 'utf8');
566
-
567
- return outputPath;
568
- }
569
-
570
- /**
571
- * Generate minimal markdown when template is not available.
572
- * @param {Object} vars
573
- * @returns {string}
574
- */
575
- function generateFallbackMarkdown(vars) {
576
- const lines = [`# ${vars.projectName} — Architecture Context\n`];
577
- lines.push(`> Auto-generated by morph-spec context refresh`);
578
- lines.push(`> Last updated: ${vars.timestamp}\n`);
579
-
580
- if (vars.hasDotnet) {
581
- lines.push('## .NET Entities\n');
582
- for (const e of vars.entities) {
583
- lines.push(`- \`${e.name}\` (${e.type}) — ${e.path}`);
584
- }
585
- lines.push('\n## API Endpoints\n');
586
- for (const ep of vars.endpoints) {
587
- lines.push(`- ${ep.method ? ep.method + ' ' : ''}\`${ep.route}\` — ${ep.name} (${ep.path})`);
588
- }
589
- lines.push('');
590
- }
591
-
592
- if (vars.hasNextjs) {
593
- lines.push('## Next.js Pages\n');
594
- for (const p of vars.pages) {
595
- lines.push(`- \`${p.route}\` — ${p.path}`);
596
- }
597
- if (vars.components.length > 0) {
598
- lines.push('\n## Components\n');
599
- for (const c of vars.components) {
600
- lines.push(`- \`${c.name}\` — ${c.path}`);
601
- }
602
- }
603
- lines.push('');
604
- }
605
-
606
- if (vars.hasIntegrations) {
607
- lines.push('## Integrations\n');
608
- for (const i of vars.integrations) {
609
- lines.push(`- **${i.name}** (${i.type}) — ${i.configured ? 'configured' : 'not configured'}`);
610
- }
611
- lines.push('');
612
- }
613
-
614
- if (vars.hasTables) {
615
- lines.push('## Database Tables\n');
616
- for (const t of vars.tables) {
617
- lines.push(`- \`${t.table}\` (from ${t.migration})`);
618
- }
619
- lines.push('');
620
- }
621
-
622
- if (vars.hasDotnetPackages) {
623
- lines.push('## .NET Packages\n');
624
- for (const p of vars.dotnetPackages) {
625
- lines.push(`- \`${p.name}\` ${p.version}`);
626
- }
627
- lines.push('');
628
- }
629
-
630
- if (vars.hasNpmPackages) {
631
- lines.push('## NPM Packages\n');
632
- for (const p of vars.npmPackages) {
633
- lines.push(`- \`${p.name}\` ${p.version}`);
634
- }
635
- lines.push('');
636
- }
637
-
638
- lines.push(`---\n*Generated by morph-spec v${vars.morphVersion}*`);
639
- return lines.join('\n');
640
- }
1
+ /**
2
+ * Architecture Scanner - Generates rich architectural context from project filesystem.
3
+ *
4
+ * Performs fast (<5s) glob-based scanning to produce a snapshot of:
5
+ * - .NET entities (sealed class/record)
6
+ * - API endpoints (IApiEndpoint implementations)
7
+ * - Next.js pages and components
8
+ * - Integrations (from appsettings.json)
9
+ * - Database schema (from EF migrations)
10
+ * - Stack dependencies (.csproj + package.json)
11
+ *
12
+ * All scanning is regex-based (no AST parsing) for speed.
13
+ *
14
+ * @module architecture-scanner
15
+ */
16
+
17
+ import fs from 'fs/promises';
18
+ import path from 'path';
19
+ import { existsSync, readFileSync } from 'fs';
20
+ import { renderTemplate } from '../../core/templates/template-renderer.js';
21
+
22
+ const SKIP_DIRS = new Set(['node_modules', 'bin', 'obj', '.git', '.morph', '.next', 'dist', 'out', '.worktrees']);
23
+ const MAX_FILES_PER_SCANNER = 200;
24
+
25
+ /**
26
+ * Recursively walk a directory, returning files matching a filter.
27
+ * Skips known heavy directories for performance.
28
+ *
29
+ * @param {string} dir - Directory to walk
30
+ * @param {function} filter - (relativePath) => boolean
31
+ * @param {string} [base] - Base path for relative calculation
32
+ * @param {number} [limit] - Max files to return
33
+ * @returns {Promise<Array<{abs: string, rel: string}>>}
34
+ */
35
+ async function walkDir(dir, filter, base = dir, limit = MAX_FILES_PER_SCANNER) {
36
+ const results = [];
37
+
38
+ async function recurse(currentDir) {
39
+ if (results.length >= limit) return;
40
+
41
+ let entries;
42
+ try {
43
+ entries = await fs.readdir(currentDir, { withFileTypes: true });
44
+ } catch {
45
+ return;
46
+ }
47
+
48
+ for (const entry of entries) {
49
+ if (results.length >= limit) break;
50
+
51
+ if (entry.isDirectory()) {
52
+ if (SKIP_DIRS.has(entry.name)) continue;
53
+ await recurse(path.join(currentDir, entry.name));
54
+ } else if (entry.isFile()) {
55
+ const abs = path.join(currentDir, entry.name);
56
+ const rel = path.relative(base, abs).replace(/\\/g, '/');
57
+ if (filter(rel, entry.name)) {
58
+ results.push({ abs, rel });
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ await recurse(dir);
65
+ return results;
66
+ }
67
+
68
+ /**
69
+ * Scan .NET entities from Entities/ or Features/ directories.
70
+ *
71
+ * @param {string} projectPath
72
+ * @returns {Promise<Array<{name: string, type: string, path: string}>>}
73
+ */
74
+ export async function scanEntities(projectPath) {
75
+ try {
76
+ const files = await walkDir(
77
+ projectPath,
78
+ (rel, name) => name.endsWith('.cs') && (rel.includes('Entities/') || rel.includes('Features/') || rel.includes('Models/'))
79
+ );
80
+
81
+ const entities = [];
82
+ const entityRegex = /(?:public\s+)?(?:sealed\s+)?(class|record)\s+(\w+)/g;
83
+
84
+ for (const file of files) {
85
+ try {
86
+ const content = await fs.readFile(file.abs, 'utf8');
87
+ let match;
88
+ entityRegex.lastIndex = 0;
89
+ while ((match = entityRegex.exec(content)) !== null) {
90
+ const line = content.slice(Math.max(0, match.index - 80), match.index + match[0].length);
91
+ // Only capture sealed/record types or classes in entity-like directories
92
+ if (/sealed|record/.test(line) || file.rel.includes('Entities/')) {
93
+ entities.push({
94
+ name: match[2],
95
+ type: match[1],
96
+ path: file.rel
97
+ });
98
+ }
99
+ }
100
+ } catch { /* skip unreadable files */ }
101
+ }
102
+
103
+ return entities;
104
+ } catch {
105
+ return [];
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Scan API endpoints implementing IApiEndpoint.
111
+ *
112
+ * @param {string} projectPath
113
+ * @returns {Promise<Array<{name: string, route: string, method: string, path: string}>>}
114
+ */
115
+ export async function scanEndpoints(projectPath) {
116
+ try {
117
+ const files = await walkDir(
118
+ projectPath,
119
+ (rel, name) => name.endsWith('.cs') && (rel.includes('Endpoints/') || rel.includes('Features/'))
120
+ );
121
+
122
+ const endpoints = [];
123
+ const classRegex = /class\s+(\w+)[^{]*(?:IApiEndpoint|IEndpoint|Endpoint)/;
124
+ const routeRegex = /Route\s*(?:=>|=)\s*"([^"]+)"/;
125
+ const methodRegex = /(?:Http(Get|Post|Put|Delete|Patch))|(?:\.Map(Get|Post|Put|Delete|Patch))/i;
126
+
127
+ for (const file of files) {
128
+ try {
129
+ const content = await fs.readFile(file.abs, 'utf8');
130
+ const classMatch = classRegex.exec(content);
131
+ if (!classMatch) continue;
132
+
133
+ const routeMatch = routeRegex.exec(content);
134
+ const methodMatch = methodRegex.exec(content);
135
+
136
+ endpoints.push({
137
+ name: classMatch[1],
138
+ route: routeMatch ? routeMatch[1] : '(unknown)',
139
+ method: methodMatch ? (methodMatch[1] || methodMatch[2] || '').toUpperCase() : '',
140
+ path: file.rel
141
+ });
142
+ } catch { /* skip */ }
143
+ }
144
+
145
+ return endpoints;
146
+ } catch {
147
+ return [];
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Scan Next.js pages and components.
153
+ *
154
+ * @param {string} projectPath
155
+ * @returns {Promise<{pages: Array<{route: string, path: string}>, layouts: Array<{path: string}>, components: Array<{name: string, path: string}>}>}
156
+ */
157
+ export async function scanNextjsComponents(projectPath) {
158
+ try {
159
+ const result = { pages: [], layouts: [], components: [] };
160
+
161
+ // Scan pages and layouts from app directory
162
+ const appFiles = await walkDir(
163
+ projectPath,
164
+ (rel, name) =>
165
+ (name === 'page.tsx' || name === 'page.jsx' || name === 'layout.tsx' || name === 'layout.jsx') &&
166
+ (rel.startsWith('app/') || rel.startsWith('src/app/'))
167
+ );
168
+
169
+ for (const file of appFiles) {
170
+ const isLayout = file.rel.includes('layout.');
171
+ const routeDir = path.dirname(file.rel).replace(/^(?:src\/)?app/, '').replace(/\\/g, '/');
172
+ const route = routeDir || '/';
173
+
174
+ if (isLayout) {
175
+ result.layouts.push({ path: file.rel });
176
+ } else {
177
+ result.pages.push({ route: route === '' ? '/' : route, path: file.rel });
178
+ }
179
+ }
180
+
181
+ // Scan components
182
+ const componentFiles = await walkDir(
183
+ projectPath,
184
+ (rel, name) =>
185
+ (name.endsWith('.tsx') || name.endsWith('.jsx')) &&
186
+ (rel.startsWith('src/components/') || rel.startsWith('components/') || rel.includes('/components/'))
187
+ );
188
+
189
+ for (const file of componentFiles) {
190
+ const name = path.basename(file.rel, path.extname(file.rel));
191
+ // Skip index files and test files
192
+ if (name === 'index' || name.includes('.test') || name.includes('.spec')) continue;
193
+ result.components.push({ name, path: file.rel });
194
+ }
195
+
196
+ return result;
197
+ } catch {
198
+ return { pages: [], layouts: [], components: [] };
199
+ }
200
+ }
201
+
202
+ /**
203
+ * Scan integrations from appsettings*.json files.
204
+ *
205
+ * @param {string} projectPath
206
+ * @returns {Promise<Array<{name: string, type: string, configured: boolean}>>}
207
+ */
208
+ export async function scanIntegrations(projectPath) {
209
+ try {
210
+ const files = await walkDir(
211
+ projectPath,
212
+ (rel, name) => /^appsettings(?:\.\w+)?\.json$/.test(name),
213
+ projectPath,
214
+ 20
215
+ );
216
+
217
+ // Also check .env files for common integrations
218
+ const envFiles = await walkDir(
219
+ projectPath,
220
+ (rel, name) => name === '.env' || name === '.env.local' || name === '.env.production',
221
+ projectPath,
222
+ 5
223
+ );
224
+
225
+ const knownServices = {
226
+ 'Clerk': 'auth',
227
+ 'AsaaS': 'payment',
228
+ 'Resend': 'email',
229
+ 'Hangfire': 'background-jobs',
230
+ 'Neon': 'database',
231
+ 'ConnectionStrings': 'database',
232
+ 'Redis': 'cache',
233
+ 'SendGrid': 'email',
234
+ 'Stripe': 'payment',
235
+ 'AzureAd': 'auth',
236
+ 'OpenAI': 'ai',
237
+ 'AzureOpenAI': 'ai'
238
+ };
239
+
240
+ const detected = new Map();
241
+
242
+ // Scan appsettings files
243
+ for (const file of files) {
244
+ try {
245
+ const content = JSON.parse(await fs.readFile(file.abs, 'utf8'));
246
+ for (const [service, type] of Object.entries(knownServices)) {
247
+ if (content[service] || content[service.toLowerCase()]) {
248
+ const hasValues = content[service] && typeof content[service] === 'object'
249
+ ? Object.values(content[service]).some(v => v && v !== '' && !String(v).startsWith('{{'))
250
+ : true;
251
+ if (!detected.has(service) || hasValues) {
252
+ detected.set(service, { name: service, type, configured: hasValues });
253
+ }
254
+ }
255
+ }
256
+ // Check ConnectionStrings specifically
257
+ if (content.ConnectionStrings) {
258
+ for (const [key, val] of Object.entries(content.ConnectionStrings)) {
259
+ if (val && !String(val).startsWith('{{')) {
260
+ detected.set(`DB:${key}`, { name: `ConnectionString:${key}`, type: 'database', configured: true });
261
+ }
262
+ }
263
+ }
264
+ } catch { /* skip invalid JSON */ }
265
+ }
266
+
267
+ // Scan .env files for known prefixes
268
+ const envPrefixes = {
269
+ 'NEXT_PUBLIC_CLERK': 'Clerk',
270
+ 'CLERK_': 'Clerk',
271
+ 'DATABASE_URL': 'Neon',
272
+ 'NEON_': 'Neon',
273
+ 'RESEND_': 'Resend',
274
+ 'STRIPE_': 'Stripe',
275
+ 'OPENAI_': 'OpenAI',
276
+ 'ASAAS_': 'AsaaS'
277
+ };
278
+
279
+ for (const file of envFiles) {
280
+ try {
281
+ const content = await fs.readFile(file.abs, 'utf8');
282
+ for (const [prefix, service] of Object.entries(envPrefixes)) {
283
+ if (content.includes(prefix)) {
284
+ const type = knownServices[service] || 'integration';
285
+ if (!detected.has(service)) {
286
+ detected.set(service, { name: service, type, configured: true });
287
+ }
288
+ }
289
+ }
290
+ } catch { /* skip */ }
291
+ }
292
+
293
+ return Array.from(detected.values());
294
+ } catch {
295
+ return [];
296
+ }
297
+ }
298
+
299
+ /**
300
+ * Scan database schema from EF Core migrations.
301
+ *
302
+ * @param {string} projectPath
303
+ * @returns {Promise<Array<{table: string, migration: string}>>}
304
+ */
305
+ export async function scanDatabaseSchema(projectPath) {
306
+ try {
307
+ const files = await walkDir(
308
+ projectPath,
309
+ (rel, name) => name.endsWith('.cs') && rel.includes('Migrations/') && !name.endsWith('.Designer.cs'),
310
+ projectPath,
311
+ 100
312
+ );
313
+
314
+ const tables = new Map();
315
+ const toTableRegex = /\.ToTable\("(\w+)"/g;
316
+ const createTableRegex = /migrationBuilder\.CreateTable\(\s*name:\s*"(\w+)"/g;
317
+
318
+ for (const file of files) {
319
+ try {
320
+ const content = await fs.readFile(file.abs, 'utf8');
321
+ const migrationName = path.basename(file.rel, '.cs');
322
+
323
+ for (const regex of [toTableRegex, createTableRegex]) {
324
+ regex.lastIndex = 0;
325
+ let match;
326
+ while ((match = regex.exec(content)) !== null) {
327
+ if (!tables.has(match[1])) {
328
+ tables.set(match[1], { table: match[1], migration: migrationName });
329
+ }
330
+ }
331
+ }
332
+ } catch { /* skip */ }
333
+ }
334
+
335
+ // Also scan database migrations (SQL)
336
+ const sqlFiles = await walkDir(
337
+ projectPath,
338
+ (rel, name) => name.endsWith('.sql') && rel.includes('migrations/'),
339
+ projectPath,
340
+ 100
341
+ );
342
+
343
+ const createSqlRegex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:public\.)?["']?(\w+)["']?/gi;
344
+
345
+ for (const file of sqlFiles) {
346
+ try {
347
+ const content = await fs.readFile(file.abs, 'utf8');
348
+ const migrationName = path.basename(file.rel, '.sql');
349
+ createSqlRegex.lastIndex = 0;
350
+ let match;
351
+ while ((match = createSqlRegex.exec(content)) !== null) {
352
+ if (!tables.has(match[1])) {
353
+ tables.set(match[1], { table: match[1], migration: migrationName });
354
+ }
355
+ }
356
+ } catch { /* skip */ }
357
+ }
358
+
359
+ return Array.from(tables.values());
360
+ } catch {
361
+ return [];
362
+ }
363
+ }
364
+
365
+ /**
366
+ * Detect stack from .csproj PackageReference and package.json dependencies.
367
+ *
368
+ * @param {string} projectPath
369
+ * @returns {Promise<{dotnet: Array<{name: string, version: string}>, npm: Array<{name: string, version: string}>}>}
370
+ */
371
+ export async function scanStackDependencies(projectPath) {
372
+ try {
373
+ const result = { dotnet: [], npm: [] };
374
+
375
+ // Scan .csproj files
376
+ const csprojFiles = await walkDir(
377
+ projectPath,
378
+ (rel, name) => name.endsWith('.csproj'),
379
+ projectPath,
380
+ 10
381
+ );
382
+
383
+ const packageRefRegex = /<PackageReference\s+Include="([^"]+)"\s+Version="([^"]+)"/g;
384
+
385
+ for (const file of csprojFiles) {
386
+ try {
387
+ const content = await fs.readFile(file.abs, 'utf8');
388
+ packageRefRegex.lastIndex = 0;
389
+ let match;
390
+ while ((match = packageRefRegex.exec(content)) !== null) {
391
+ result.dotnet.push({ name: match[1], version: match[2] });
392
+ }
393
+ } catch { /* skip */ }
394
+ }
395
+
396
+ // Scan package.json (root only)
397
+ const pkgPath = path.join(projectPath, 'package.json');
398
+ if (existsSync(pkgPath)) {
399
+ try {
400
+ const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf8'));
401
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
402
+ for (const [name, version] of Object.entries(allDeps)) {
403
+ result.npm.push({ name, version: String(version) });
404
+ }
405
+ } catch { /* skip */ }
406
+ }
407
+
408
+ // Also check web/ or frontend/ subdirectory package.json
409
+ for (const subdir of ['web', 'frontend', 'client', 'src']) {
410
+ const subPkgPath = path.join(projectPath, subdir, 'package.json');
411
+ if (existsSync(subPkgPath)) {
412
+ try {
413
+ const pkg = JSON.parse(await fs.readFile(subPkgPath, 'utf8'));
414
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
415
+ for (const [name, version] of Object.entries(allDeps)) {
416
+ // Avoid duplicates
417
+ if (!result.npm.some(d => d.name === name)) {
418
+ result.npm.push({ name, version: String(version) });
419
+ }
420
+ }
421
+ } catch { /* skip */ }
422
+ }
423
+ }
424
+
425
+ return result;
426
+ } catch {
427
+ return { dotnet: [], npm: [] };
428
+ }
429
+ }
430
+
431
+ /**
432
+ * Master scan — runs all scanners in parallel.
433
+ *
434
+ * @param {string} projectPath
435
+ * @returns {Promise<Object>} ArchitectureScanResult
436
+ */
437
+ export async function scanArchitecture(projectPath) {
438
+ const [entities, endpoints, nextjs, integrations, database, stack] = await Promise.all([
439
+ scanEntities(projectPath),
440
+ scanEndpoints(projectPath),
441
+ scanNextjsComponents(projectPath),
442
+ scanIntegrations(projectPath),
443
+ scanDatabaseSchema(projectPath),
444
+ scanStackDependencies(projectPath)
445
+ ]);
446
+
447
+ return {
448
+ timestamp: new Date().toISOString(),
449
+ entities,
450
+ endpoints,
451
+ nextjs,
452
+ integrations,
453
+ database,
454
+ stack
455
+ };
456
+ }
457
+
458
+ /**
459
+ * Resolve a template path: check .morph/framework/templates/ first, then framework/templates/,
460
+ * then fall back to the CLI package's own framework/templates/.
461
+ *
462
+ * @param {string} projectPath
463
+ * @param {string} templateRelPath
464
+ * @returns {string|null}
465
+ */
466
+ function resolveTemplatePath(projectPath, templateRelPath) {
467
+ // 1. Project-local override
468
+ const projectLocal = path.join(projectPath, '.morph/framework/templates', templateRelPath);
469
+ if (existsSync(projectLocal)) return projectLocal;
470
+
471
+ // 2. CLI package framework/ (for running from source or during init)
472
+ const cliFramework = path.join(
473
+ path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1')),
474
+ '..', '..', '..', 'framework', 'templates', templateRelPath
475
+ );
476
+ if (existsSync(cliFramework)) return cliFramework;
477
+
478
+ return null;
479
+ }
480
+
481
+ /**
482
+ * Render architecture context to .morph/context/README.md
483
+ *
484
+ * @param {string} projectPath
485
+ * @param {Object} scanResult - Result from scanArchitecture()
486
+ * @param {Object} [options]
487
+ * @param {string} [options.projectName] - Override project name
488
+ * @returns {Promise<string>} Path to written file
489
+ */
490
+ export async function renderArchitectureContext(projectPath, scanResult, options = {}) {
491
+ const templatePath = resolveTemplatePath(projectPath, 'context/ARCHITECTURE.md');
492
+
493
+ // Determine project name
494
+ let projectName = options.projectName;
495
+ if (!projectName) {
496
+ // Try config.json
497
+ const configPath = path.join(projectPath, '.morph/config/config.json');
498
+ if (existsSync(configPath)) {
499
+ try {
500
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
501
+ projectName = config.project?.name;
502
+ } catch { /* ignore */ }
503
+ }
504
+ // Fallback to directory name
505
+ if (!projectName) {
506
+ projectName = path.basename(projectPath);
507
+ }
508
+ }
509
+
510
+ // Get morph-spec version
511
+ let morphVersion = 'unknown';
512
+ try {
513
+ const pkgPath = path.join(
514
+ path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Z]:)/, '$1')),
515
+ '..', '..', '..', 'package.json'
516
+ );
517
+ if (existsSync(pkgPath)) {
518
+ morphVersion = JSON.parse(readFileSync(pkgPath, 'utf8')).version;
519
+ }
520
+ } catch { /* ignore */ }
521
+
522
+ const variables = {
523
+ projectName,
524
+ timestamp: new Date().toISOString().replace('T', ' ').split('.')[0],
525
+ morphVersion,
526
+ // Entities
527
+ hasDotnet: scanResult.entities.length > 0 || scanResult.endpoints.length > 0,
528
+ entities: scanResult.entities,
529
+ entityCount: scanResult.entities.length,
530
+ endpoints: scanResult.endpoints,
531
+ endpointCount: scanResult.endpoints.length,
532
+ // Next.js
533
+ hasNextjs: scanResult.nextjs.pages.length > 0 || scanResult.nextjs.components.length > 0,
534
+ pages: scanResult.nextjs.pages,
535
+ pageCount: scanResult.nextjs.pages.length,
536
+ layouts: scanResult.nextjs.layouts,
537
+ components: scanResult.nextjs.components,
538
+ componentCount: scanResult.nextjs.components.length,
539
+ // Integrations
540
+ hasIntegrations: scanResult.integrations.length > 0,
541
+ integrations: scanResult.integrations,
542
+ // Database
543
+ hasTables: scanResult.database.length > 0,
544
+ tables: scanResult.database,
545
+ tableCount: scanResult.database.length,
546
+ // Stack
547
+ hasDotnetPackages: scanResult.stack.dotnet.length > 0,
548
+ dotnetPackages: scanResult.stack.dotnet,
549
+ hasNpmPackages: scanResult.stack.npm.length > 0,
550
+ npmPackages: scanResult.stack.npm
551
+ };
552
+
553
+ let content;
554
+ if (templatePath) {
555
+ content = renderTemplate(templatePath, variables);
556
+ } else {
557
+ // Fallback: generate minimal markdown without template
558
+ content = generateFallbackMarkdown(variables);
559
+ }
560
+
561
+ // Write to .morph/context/README.md
562
+ const contextDir = path.join(projectPath, '.morph/context');
563
+ await fs.mkdir(contextDir, { recursive: true });
564
+ const outputPath = path.join(contextDir, 'README.md');
565
+ await fs.writeFile(outputPath, content, 'utf8');
566
+
567
+ return outputPath;
568
+ }
569
+
570
+ /**
571
+ * Generate minimal markdown when template is not available.
572
+ * @param {Object} vars
573
+ * @returns {string}
574
+ */
575
+ function generateFallbackMarkdown(vars) {
576
+ const lines = [`# ${vars.projectName} — Architecture Context\n`];
577
+ lines.push(`> Auto-generated by morph-spec context refresh`);
578
+ lines.push(`> Last updated: ${vars.timestamp}\n`);
579
+
580
+ if (vars.hasDotnet) {
581
+ lines.push('## .NET Entities\n');
582
+ for (const e of vars.entities) {
583
+ lines.push(`- \`${e.name}\` (${e.type}) — ${e.path}`);
584
+ }
585
+ lines.push('\n## API Endpoints\n');
586
+ for (const ep of vars.endpoints) {
587
+ lines.push(`- ${ep.method ? ep.method + ' ' : ''}\`${ep.route}\` — ${ep.name} (${ep.path})`);
588
+ }
589
+ lines.push('');
590
+ }
591
+
592
+ if (vars.hasNextjs) {
593
+ lines.push('## Next.js Pages\n');
594
+ for (const p of vars.pages) {
595
+ lines.push(`- \`${p.route}\` — ${p.path}`);
596
+ }
597
+ if (vars.components.length > 0) {
598
+ lines.push('\n## Components\n');
599
+ for (const c of vars.components) {
600
+ lines.push(`- \`${c.name}\` — ${c.path}`);
601
+ }
602
+ }
603
+ lines.push('');
604
+ }
605
+
606
+ if (vars.hasIntegrations) {
607
+ lines.push('## Integrations\n');
608
+ for (const i of vars.integrations) {
609
+ lines.push(`- **${i.name}** (${i.type}) — ${i.configured ? 'configured' : 'not configured'}`);
610
+ }
611
+ lines.push('');
612
+ }
613
+
614
+ if (vars.hasTables) {
615
+ lines.push('## Database Tables\n');
616
+ for (const t of vars.tables) {
617
+ lines.push(`- \`${t.table}\` (from ${t.migration})`);
618
+ }
619
+ lines.push('');
620
+ }
621
+
622
+ if (vars.hasDotnetPackages) {
623
+ lines.push('## .NET Packages\n');
624
+ for (const p of vars.dotnetPackages) {
625
+ lines.push(`- \`${p.name}\` ${p.version}`);
626
+ }
627
+ lines.push('');
628
+ }
629
+
630
+ if (vars.hasNpmPackages) {
631
+ lines.push('## NPM Packages\n');
632
+ for (const p of vars.npmPackages) {
633
+ lines.push(`- \`${p.name}\` ${p.version}`);
634
+ }
635
+ lines.push('');
636
+ }
637
+
638
+ lines.push(`---\n*Generated by morph-spec v${vars.morphVersion}*`);
639
+ return lines.join('\n');
640
+ }