specialist-agent 2.9.0 → 2.10.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.
@@ -0,0 +1,752 @@
1
+ /**
2
+ * Architecture Detection Engine
3
+ *
4
+ * Scans a project directory to detect:
5
+ * 1. Monorepo pattern (Turborepo, Nx, Lerna, pnpm, npm/yarn workspaces)
6
+ * 2. Framework (Next.js, React, Vue, Nuxt, Svelte, Angular, Astro)
7
+ * 3. Architecture pattern with confidence score
8
+ * 4. Sub-project architectures (for monorepos)
9
+ *
10
+ * Returns structured detection result with migration suggestions.
11
+ */
12
+
13
+ import { existsSync, readdirSync, readFileSync, statSync } from 'fs'
14
+ import { join, relative } from 'path'
15
+ import { ARCHITECTURE_PATTERNS, MONOREPO_PATTERNS, getSuggestedArchitectures } from './architectures.mjs'
16
+
17
+ // ── Main Detection Function ───────────────────────────
18
+
19
+ export function detectProjectArchitecture(cwd, options = {}) {
20
+ const { framework = null, verbose = false } = options
21
+
22
+ const result = {
23
+ monorepo: detectMonorepo(cwd),
24
+ framework: framework,
25
+ architecture: null,
26
+ confidence: 0,
27
+ scores: {},
28
+ subProjects: [],
29
+ nextjsRouter: null,
30
+ projectInfo: {
31
+ hasTypeScript: false,
32
+ hasSrc: false,
33
+ totalDirs: 0,
34
+ totalFiles: 0,
35
+ srcRoot: '',
36
+ },
37
+ }
38
+
39
+ // Gather project info
40
+ result.projectInfo = gatherProjectInfo(cwd)
41
+
42
+ // Detect Next.js router type if applicable
43
+ if (framework === 'nextjs') {
44
+ result.nextjsRouter = detectNextjsRouterType(cwd)
45
+ }
46
+
47
+ // Detect architecture
48
+ const srcRoot = result.projectInfo.srcRoot
49
+ const detectionResult = scoreAllPatterns(cwd, srcRoot)
50
+ result.scores = detectionResult.scores
51
+ result.architecture = detectionResult.bestMatch
52
+ result.confidence = detectionResult.bestScore
53
+
54
+ // For monorepos, also detect sub-project architectures
55
+ if (result.monorepo) {
56
+ result.subProjects = detectSubProjectArchitectures(cwd, result.monorepo)
57
+ }
58
+
59
+ return result
60
+ }
61
+
62
+ // ── Monorepo Detection ────────────────────────────────
63
+
64
+ export function detectMonorepo(cwd) {
65
+ // Check in priority order
66
+ for (const [id, pattern] of Object.entries(MONOREPO_PATTERNS)) {
67
+ // Check detect files
68
+ if (pattern.detectFiles?.length > 0) {
69
+ const hasFile = pattern.detectFiles.some(f => existsSync(join(cwd, f)))
70
+ if (hasFile) {
71
+ return {
72
+ type: id,
73
+ name: pattern.name,
74
+ workspaceConfig: pattern.workspaceConfig,
75
+ apps: findMonorepoApps(cwd, id),
76
+ }
77
+ }
78
+ }
79
+
80
+ // Check detect deps
81
+ if (pattern.detectDeps?.length > 0) {
82
+ const pkgPath = join(cwd, 'package.json')
83
+ if (existsSync(pkgPath)) {
84
+ try {
85
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
86
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }
87
+ const hasDep = pattern.detectDeps.some(d => deps[d])
88
+ if (hasDep) {
89
+ return {
90
+ type: id,
91
+ name: pattern.name,
92
+ workspaceConfig: pattern.workspaceConfig,
93
+ apps: findMonorepoApps(cwd, id),
94
+ }
95
+ }
96
+ } catch {}
97
+ }
98
+ }
99
+
100
+ // Check custom rules
101
+ if (pattern.customRule === 'package-json-workspaces') {
102
+ const pkgPath = join(cwd, 'package.json')
103
+ if (existsSync(pkgPath)) {
104
+ try {
105
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
106
+ if (pkg.workspaces) {
107
+ // Make sure it's not already detected as turborepo/nx/lerna
108
+ const alreadyDetected = ['turbo.json', 'nx.json', 'lerna.json', 'pnpm-workspace.yaml']
109
+ .some(f => existsSync(join(cwd, f)))
110
+ if (!alreadyDetected) {
111
+ return {
112
+ type: id,
113
+ name: pattern.name,
114
+ workspaceConfig: 'package.json',
115
+ apps: findMonorepoApps(cwd, id),
116
+ }
117
+ }
118
+ }
119
+ } catch {}
120
+ }
121
+ }
122
+ }
123
+
124
+ return null
125
+ }
126
+
127
+ function findMonorepoApps(cwd, type) {
128
+ const apps = []
129
+ const searchDirs = []
130
+
131
+ switch (type) {
132
+ case 'turborepo':
133
+ case 'workspaces':
134
+ searchDirs.push('apps', 'packages')
135
+ break
136
+ case 'nx':
137
+ searchDirs.push('apps', 'libs')
138
+ break
139
+ case 'lerna':
140
+ searchDirs.push('packages')
141
+ break
142
+ case 'pnpm':
143
+ // Read pnpm-workspace.yaml for workspace patterns
144
+ try {
145
+ const content = readFileSync(join(cwd, 'pnpm-workspace.yaml'), 'utf-8')
146
+ const match = content.match(/packages:\s*\n((?:\s+-\s+.*\n?)*)/m)
147
+ if (match) {
148
+ const patterns = match[1].match(/'([^']+)'|"([^"]+)"|(\S+)/g)
149
+ if (patterns) {
150
+ for (const p of patterns) {
151
+ const clean = p.replace(/['"]/g, '').replace(/\/\*$/, '').replace(/^\s*-\s*/, '')
152
+ if (clean && !clean.startsWith('#')) searchDirs.push(clean)
153
+ }
154
+ }
155
+ }
156
+ } catch {}
157
+ if (searchDirs.length === 0) searchDirs.push('apps', 'packages')
158
+ break
159
+ }
160
+
161
+ for (const dir of searchDirs) {
162
+ const fullPath = join(cwd, dir)
163
+ if (!existsSync(fullPath)) continue
164
+
165
+ try {
166
+ const entries = readdirSync(fullPath, { withFileTypes: true })
167
+ for (const entry of entries) {
168
+ if (!entry.isDirectory()) continue
169
+ const appPath = join(fullPath, entry.name)
170
+ const appPkgPath = join(appPath, 'package.json')
171
+ if (existsSync(appPkgPath)) {
172
+ try {
173
+ const pkg = JSON.parse(readFileSync(appPkgPath, 'utf-8'))
174
+ apps.push({
175
+ name: pkg.name || entry.name,
176
+ path: relative(cwd, appPath),
177
+ hasPackageJson: true,
178
+ })
179
+ } catch {
180
+ apps.push({ name: entry.name, path: relative(cwd, appPath), hasPackageJson: true })
181
+ }
182
+ }
183
+ }
184
+ } catch {}
185
+ }
186
+
187
+ return apps
188
+ }
189
+
190
+ // ── Project Info Gathering ────────────────────────────
191
+
192
+ function gatherProjectInfo(cwd) {
193
+ const info = {
194
+ hasTypeScript: false,
195
+ hasSrc: false,
196
+ totalDirs: 0,
197
+ totalFiles: 0,
198
+ srcRoot: '',
199
+ }
200
+
201
+ // Check for TypeScript
202
+ info.hasTypeScript = existsSync(join(cwd, 'tsconfig.json')) ||
203
+ existsSync(join(cwd, 'tsconfig.app.json'))
204
+
205
+ // Check for src directory
206
+ info.hasSrc = existsSync(join(cwd, 'src'))
207
+ info.srcRoot = info.hasSrc ? join(cwd, 'src') : cwd
208
+
209
+ // Count dirs/files (shallow, for project size estimation)
210
+ try {
211
+ const entries = readdirSync(info.srcRoot, { withFileTypes: true })
212
+ for (const entry of entries) {
213
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
214
+ if (entry.isDirectory()) info.totalDirs++
215
+ else info.totalFiles++
216
+ }
217
+ } catch {}
218
+
219
+ return info
220
+ }
221
+
222
+ // ── Next.js Router Detection ──────────────────────────
223
+
224
+ function detectNextjsRouterType(cwd) {
225
+ const appRouterPaths = [
226
+ join(cwd, 'src', 'app', 'layout.tsx'),
227
+ join(cwd, 'src', 'app', 'layout.ts'),
228
+ join(cwd, 'src', 'app', 'layout.jsx'),
229
+ join(cwd, 'app', 'layout.tsx'),
230
+ join(cwd, 'app', 'layout.ts'),
231
+ ]
232
+
233
+ const pagesRouterPaths = [
234
+ join(cwd, 'src', 'pages', '_app.tsx'),
235
+ join(cwd, 'src', 'pages', '_app.ts'),
236
+ join(cwd, 'src', 'pages', '_app.jsx'),
237
+ join(cwd, 'pages', '_app.tsx'),
238
+ join(cwd, 'pages', '_app.ts'),
239
+ ]
240
+
241
+ const hasAppRouter = appRouterPaths.some(p => existsSync(p))
242
+ const hasPagesRouter = pagesRouterPaths.some(p => existsSync(p))
243
+
244
+ if (hasAppRouter && hasPagesRouter) return 'hybrid'
245
+ if (hasAppRouter) return 'app-router'
246
+ if (hasPagesRouter) return 'pages-router'
247
+ return 'unknown'
248
+ }
249
+
250
+ // ── Architecture Scoring Engine ───────────────────────
251
+
252
+ function scoreAllPatterns(cwd, srcRoot) {
253
+ const scores = {}
254
+ let bestMatch = 'unstructured'
255
+ let bestScore = 0
256
+
257
+ // Get directories at srcRoot level
258
+ const srcDirs = listDirs(srcRoot)
259
+ const rootDirs = srcRoot !== cwd ? listDirs(cwd) : srcDirs
260
+ const allDirs = new Set([...srcDirs, ...rootDirs])
261
+
262
+ for (const [patternId, pattern] of Object.entries(ARCHITECTURE_PATTERNS)) {
263
+ if (patternId === 'unstructured') continue
264
+
265
+ let score = 0
266
+ const details = { matched: [], missed: [] }
267
+
268
+ const detection = pattern.detection
269
+
270
+ // Score required dirs (+3 each, all must be present for valid match)
271
+ let allRequiredFound = true
272
+ for (const dir of detection.requiredDirs) {
273
+ if (dirExists(srcRoot, dir) || dirExists(cwd, dir)) {
274
+ score += 3
275
+ details.matched.push(`required dir: ${dir}`)
276
+ } else {
277
+ allRequiredFound = false
278
+ details.missed.push(`required dir: ${dir}`)
279
+ }
280
+ }
281
+
282
+ // If required dirs not all found and there are required dirs, heavily penalize
283
+ if (detection.requiredDirs.length > 0 && !allRequiredFound) {
284
+ score -= 10
285
+ }
286
+
287
+ // Score optional dirs (+1.5 each)
288
+ for (const dir of detection.optionalDirs) {
289
+ if (dirExists(srcRoot, dir) || dirExists(cwd, dir)) {
290
+ score += 1.5
291
+ details.matched.push(`optional dir: ${dir}`)
292
+ }
293
+ }
294
+
295
+ // Score module sub-dirs (check inside modules/* or features/*)
296
+ const moduleDirNames = ['modules', 'features', 'domains', 'bounded-contexts']
297
+ let foundModuleDir = null
298
+ for (const mDir of moduleDirNames) {
299
+ if (dirExists(srcRoot, mDir)) { foundModuleDir = join(srcRoot, mDir); break }
300
+ if (dirExists(cwd, mDir)) { foundModuleDir = join(cwd, mDir); break }
301
+ }
302
+
303
+ if (foundModuleDir && detection.moduleSubDirs.length > 0) {
304
+ const moduleExamples = listDirs(foundModuleDir).slice(0, 3)
305
+ for (const example of moduleExamples) {
306
+ const examplePath = join(foundModuleDir, example)
307
+ for (const subDir of detection.moduleSubDirs) {
308
+ if (dirExists(examplePath, subDir)) {
309
+ score += 2
310
+ details.matched.push(`module subdir: ${example}/${subDir}`)
311
+ }
312
+ }
313
+ for (const subDir of detection.optionalModuleSubDirs) {
314
+ if (dirExists(examplePath, subDir)) {
315
+ score += 1
316
+ details.matched.push(`optional module subdir: ${example}/${subDir}`)
317
+ }
318
+ }
319
+ }
320
+ }
321
+
322
+ // Score file patterns (+1 each)
323
+ for (const filePattern of detection.filePatterns) {
324
+ if (hasFileMatchingPattern(cwd, filePattern)) {
325
+ score += 1
326
+ details.matched.push(`file pattern: ${filePattern}`)
327
+ }
328
+ }
329
+
330
+ // Anti-patterns (-2 each)
331
+ for (const antiDir of detection.antiPatterns) {
332
+ if (dirExists(srcRoot, antiDir) || dirExists(cwd, antiDir)) {
333
+ score -= 2
334
+ details.missed.push(`anti-pattern: ${antiDir}`)
335
+ }
336
+ }
337
+
338
+ // Custom rules
339
+ if (detection.customRule) {
340
+ const customScore = evaluateCustomRule(detection.customRule, cwd, srcRoot, allDirs)
341
+ score += customScore.score
342
+ details.matched.push(...customScore.matched)
343
+ }
344
+
345
+ // Only consider if score meets minimum
346
+ if (score >= detection.minScore) {
347
+ scores[patternId] = { score, details, name: pattern.name }
348
+ if (score > bestScore) {
349
+ bestScore = score
350
+ bestMatch = patternId
351
+ }
352
+ } else {
353
+ scores[patternId] = { score, details, name: pattern.name, belowThreshold: true }
354
+ }
355
+ }
356
+
357
+ return { scores, bestMatch, bestScore }
358
+ }
359
+
360
+ function evaluateCustomRule(rule, cwd, srcRoot, allDirs) {
361
+ const result = { score: 0, matched: [] }
362
+
363
+ switch (rule) {
364
+ case 'fsd-layers': {
365
+ const fsdLayers = ['app', 'processes', 'pages', 'widgets', 'features', 'entities', 'shared']
366
+ let count = 0
367
+ for (const layer of fsdLayers) {
368
+ if (dirExists(srcRoot, layer) || dirExists(cwd, layer)) count++
369
+ }
370
+ if (count >= 3) {
371
+ result.score = count * 2
372
+ result.matched.push(`FSD: ${count}/7 layers found`)
373
+ } else {
374
+ result.score = -5
375
+ }
376
+ break
377
+ }
378
+
379
+ case 'atomic-layers': {
380
+ const atomicLayers = ['atoms', 'molecules', 'organisms', 'templates']
381
+ let count = 0
382
+ for (const layer of atomicLayers) {
383
+ if (findDirRecursive(srcRoot, layer, 2) || findDirRecursive(cwd, layer, 2)) count++
384
+ }
385
+ if (count >= 2) {
386
+ result.score = count * 2
387
+ result.matched.push(`Atomic: ${count}/4 layers found`)
388
+ } else {
389
+ result.score = -5
390
+ }
391
+ break
392
+ }
393
+
394
+ case 'flat-components': {
395
+ const componentsDir = join(srcRoot, 'components')
396
+ if (existsSync(componentsDir)) {
397
+ try {
398
+ const files = readdirSync(componentsDir).filter(f => !f.startsWith('.'))
399
+ const componentFiles = files.filter(f =>
400
+ f.endsWith('.tsx') || f.endsWith('.jsx') || f.endsWith('.vue') || f.endsWith('.svelte') || f.endsWith('.astro')
401
+ )
402
+ if (componentFiles.length > 5) {
403
+ result.score = 3
404
+ result.matched.push(`Flat: ${componentFiles.length} component files in src/components/`)
405
+ }
406
+ } catch {}
407
+ }
408
+ break
409
+ }
410
+
411
+ case 'screaming-domains': {
412
+ // Check if top-level dirs in src are business nouns (not technical names)
413
+ const technicalDirs = new Set([
414
+ 'components', 'utils', 'helpers', 'hooks', 'services', 'types', 'config',
415
+ 'constants', 'assets', 'styles', 'lib', 'shared', 'common', 'core',
416
+ 'app', 'pages', 'routes', 'api', '__tests__', 'test', 'tests',
417
+ 'public', 'static', 'vendor', 'plugins', 'middleware', 'store',
418
+ 'stores', 'adapters', 'providers', 'layouts', 'modules', 'features',
419
+ 'domain', 'infrastructure', 'presentation', 'application',
420
+ ])
421
+ const srcEntries = listDirs(srcRoot)
422
+ let domainCount = 0
423
+ let technicalCount = 0
424
+ for (const dir of srcEntries) {
425
+ if (technicalDirs.has(dir.toLowerCase())) technicalCount++
426
+ else domainCount++
427
+ }
428
+ if (domainCount >= 3 && domainCount > technicalCount) {
429
+ result.score = domainCount * 1.5
430
+ result.matched.push(`Screaming: ${domainCount} domain dirs vs ${technicalCount} technical dirs`)
431
+ } else {
432
+ result.score = -3
433
+ }
434
+ break
435
+ }
436
+
437
+ case 'microservices-check': {
438
+ // Multiple package.json files in subdirectories
439
+ let serviceCount = 0
440
+ for (const dir of ['services', 'apps', 'packages']) {
441
+ const fullPath = join(cwd, dir)
442
+ if (existsSync(fullPath)) {
443
+ try {
444
+ const entries = readdirSync(fullPath, { withFileTypes: true })
445
+ for (const entry of entries) {
446
+ if (entry.isDirectory()) {
447
+ if (existsSync(join(fullPath, entry.name, 'package.json'))) {
448
+ serviceCount++
449
+ }
450
+ }
451
+ }
452
+ } catch {}
453
+ }
454
+ }
455
+ // Also check for multiple Dockerfiles
456
+ let dockerfileCount = 0
457
+ for (const dir of ['services', 'apps', '.']) {
458
+ const fullPath = dir === '.' ? cwd : join(cwd, dir)
459
+ if (existsSync(fullPath)) {
460
+ try {
461
+ const entries = readdirSync(fullPath, { withFileTypes: true })
462
+ for (const entry of entries) {
463
+ if (entry.isDirectory() && existsSync(join(fullPath, entry.name, 'Dockerfile'))) {
464
+ dockerfileCount++
465
+ }
466
+ }
467
+ } catch {}
468
+ }
469
+ }
470
+ if (serviceCount >= 2 || dockerfileCount >= 2) {
471
+ result.score = serviceCount + dockerfileCount
472
+ result.matched.push(`Microservices: ${serviceCount} services, ${dockerfileCount} Dockerfiles`)
473
+ }
474
+ break
475
+ }
476
+
477
+ case 'modular-monolith-check': {
478
+ // Single package.json but modules with internal layering
479
+ const singlePkg = existsSync(join(cwd, 'package.json'))
480
+ const moduleDirNames = ['modules', 'bounded-contexts']
481
+ let foundModuleDir = null
482
+ for (const mDir of moduleDirNames) {
483
+ if (dirExists(srcRoot, mDir)) { foundModuleDir = join(srcRoot, mDir); break }
484
+ if (dirExists(cwd, mDir)) { foundModuleDir = join(cwd, mDir); break }
485
+ }
486
+ if (singlePkg && foundModuleDir) {
487
+ const moduleExamples = listDirs(foundModuleDir).slice(0, 3)
488
+ let hasInternalLayers = 0
489
+ for (const example of moduleExamples) {
490
+ const examplePath = join(foundModuleDir, example)
491
+ if (dirExists(examplePath, 'domain') || dirExists(examplePath, 'application') || dirExists(examplePath, 'infrastructure')) {
492
+ hasInternalLayers++
493
+ }
494
+ }
495
+ if (hasInternalLayers >= 1) {
496
+ result.score = 4 + hasInternalLayers
497
+ result.matched.push(`Modular Monolith: ${hasInternalLayers} modules with internal layering`)
498
+ }
499
+ }
500
+ break
501
+ }
502
+
503
+ case 'unstructured-fallback': {
504
+ result.score = 1
505
+ result.matched.push('Fallback: no clear pattern detected')
506
+ break
507
+ }
508
+ }
509
+
510
+ return result
511
+ }
512
+
513
+ // ── Sub-Project Detection (Monorepos) ─────────────────
514
+
515
+ function detectSubProjectArchitectures(cwd, monorepo) {
516
+ const subProjects = []
517
+
518
+ for (const app of monorepo.apps) {
519
+ const appPath = join(cwd, app.path)
520
+ const appInfo = gatherProjectInfo(appPath)
521
+ const detection = scoreAllPatterns(appPath, appInfo.srcRoot)
522
+
523
+ // Detect framework for this sub-project
524
+ let framework = null
525
+ const pkgPath = join(appPath, 'package.json')
526
+ if (existsSync(pkgPath)) {
527
+ try {
528
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8'))
529
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) }
530
+ if (deps['nuxt']) framework = 'nuxt'
531
+ else if (deps['next']) framework = 'nextjs'
532
+ else if (deps['@sveltejs/kit'] || deps['svelte']) framework = 'svelte'
533
+ else if (deps['@angular/core']) framework = 'angular'
534
+ else if (deps['astro']) framework = 'astro'
535
+ else if (deps['vue']) framework = 'vue'
536
+ else if (deps['react']) framework = 'react'
537
+ } catch {}
538
+ }
539
+
540
+ subProjects.push({
541
+ ...app,
542
+ framework,
543
+ architecture: detection.bestMatch,
544
+ confidence: detection.bestScore,
545
+ })
546
+ }
547
+
548
+ return subProjects
549
+ }
550
+
551
+ // ── Utility Functions ─────────────────────────────────
552
+
553
+ function listDirs(dirPath) {
554
+ if (!existsSync(dirPath)) return []
555
+ try {
556
+ return readdirSync(dirPath, { withFileTypes: true })
557
+ .filter(d => d.isDirectory() && !d.name.startsWith('.') && d.name !== 'node_modules')
558
+ .map(d => d.name)
559
+ } catch {
560
+ return []
561
+ }
562
+ }
563
+
564
+ function dirExists(base, name) {
565
+ return existsSync(join(base, name)) && isDir(join(base, name))
566
+ }
567
+
568
+ function isDir(path) {
569
+ try {
570
+ return statSync(path).isDirectory()
571
+ } catch {
572
+ return false
573
+ }
574
+ }
575
+
576
+ function findDirRecursive(base, name, maxDepth) {
577
+ if (maxDepth <= 0 || !existsSync(base)) return false
578
+ try {
579
+ const entries = readdirSync(base, { withFileTypes: true })
580
+ for (const entry of entries) {
581
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
582
+ if (entry.isDirectory()) {
583
+ if (entry.name === name) return true
584
+ if (maxDepth > 1 && findDirRecursive(join(base, entry.name), name, maxDepth - 1)) return true
585
+ }
586
+ }
587
+ } catch {}
588
+ return false
589
+ }
590
+
591
+ function hasFileMatchingPattern(cwd, pattern) {
592
+ // Simple glob matching: check if any file matches the pattern
593
+ // Handles: **/dir/file, dir/*/file, specific files
594
+ const parts = pattern.split('/')
595
+
596
+ if (pattern.startsWith('**/')) {
597
+ const rest = pattern.slice(3)
598
+ return findFileRecursive(cwd, rest, 3)
599
+ }
600
+
601
+ // Check as direct path (with glob expansion for * in directory names)
602
+ if (parts.includes('*')) {
603
+ // e.g., services/*/package.json
604
+ return expandGlobPath(cwd, parts)
605
+ }
606
+
607
+ // Direct file check
608
+ return existsSync(join(cwd, pattern))
609
+ }
610
+
611
+ function findFileRecursive(base, pattern, maxDepth) {
612
+ if (maxDepth <= 0 || !existsSync(base)) return false
613
+
614
+ const parts = pattern.split('/')
615
+ const fileName = parts[parts.length - 1]
616
+ const dirName = parts.length > 1 ? parts[0] : null
617
+
618
+ try {
619
+ const entries = readdirSync(base, { withFileTypes: true })
620
+ for (const entry of entries) {
621
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
622
+
623
+ if (entry.isDirectory()) {
624
+ if (dirName && entry.name === dirName) {
625
+ // Found the directory, check deeper
626
+ const restPattern = parts.slice(1).join('/')
627
+ if (findFileRecursive(join(base, entry.name), restPattern, maxDepth - 1)) return true
628
+ }
629
+ // Also check recursively
630
+ if (findFileRecursive(join(base, entry.name), pattern, maxDepth - 1)) return true
631
+ } else if (!dirName) {
632
+ // Check file name matching
633
+ if (matchFileName(entry.name, fileName)) return true
634
+ }
635
+ }
636
+ } catch {}
637
+ return false
638
+ }
639
+
640
+ function expandGlobPath(base, parts) {
641
+ if (parts.length === 0) return true
642
+ if (!existsSync(base)) return false
643
+
644
+ const [current, ...rest] = parts
645
+
646
+ if (current === '*') {
647
+ try {
648
+ const entries = readdirSync(base, { withFileTypes: true })
649
+ for (const entry of entries) {
650
+ if (entry.name.startsWith('.') || entry.name === 'node_modules') continue
651
+ if (entry.isDirectory() && rest.length > 0) {
652
+ if (expandGlobPath(join(base, entry.name), rest)) return true
653
+ } else if (!entry.isDirectory() && rest.length === 0) {
654
+ return true
655
+ }
656
+ }
657
+ } catch {}
658
+ return false
659
+ }
660
+
661
+ if (rest.length === 0) {
662
+ // Last part - check if file exists
663
+ return existsSync(join(base, current))
664
+ }
665
+
666
+ return expandGlobPath(join(base, current), rest)
667
+ }
668
+
669
+ function matchFileName(actual, pattern) {
670
+ if (!pattern.includes('*')) return actual === pattern
671
+ const regex = new RegExp('^' + pattern.replace(/\*/g, '.*').replace(/\?/g, '.') + '$')
672
+ return regex.test(actual)
673
+ }
674
+
675
+ // ── Report Generation ─────────────────────────────────
676
+
677
+ export function generateDetectionReport(result) {
678
+ const lines = []
679
+
680
+ lines.push('Architecture Detection Report')
681
+ lines.push('─'.repeat(40))
682
+ lines.push('')
683
+
684
+ // Monorepo
685
+ if (result.monorepo) {
686
+ lines.push(`Monorepo: ${result.monorepo.name}`)
687
+ lines.push(` Config: ${result.monorepo.workspaceConfig}`)
688
+ if (result.monorepo.apps.length > 0) {
689
+ lines.push(` Apps/Packages: ${result.monorepo.apps.length}`)
690
+ for (const app of result.monorepo.apps) {
691
+ lines.push(` - ${app.name} (${app.path})`)
692
+ }
693
+ }
694
+ lines.push('')
695
+ }
696
+
697
+ // Framework
698
+ if (result.framework) {
699
+ const labels = { vue: 'Vue 3', react: 'React', nextjs: 'Next.js', svelte: 'SvelteKit', angular: 'Angular', astro: 'Astro', nuxt: 'Nuxt' }
700
+ lines.push(`Framework: ${labels[result.framework] || result.framework}`)
701
+ if (result.nextjsRouter) {
702
+ lines.push(` Router: ${result.nextjsRouter}`)
703
+ }
704
+ lines.push('')
705
+ }
706
+
707
+ // Architecture
708
+ const pattern = ARCHITECTURE_PATTERNS[result.architecture]
709
+ if (pattern) {
710
+ const confidenceLabel = result.confidence >= 8 ? 'high' : result.confidence >= 5 ? 'medium' : 'low'
711
+ lines.push(`Architecture: ${pattern.name}`)
712
+ lines.push(` Confidence: ${confidenceLabel} (score: ${result.confidence.toFixed(1)})`)
713
+ lines.push(` Category: ${pattern.category}`)
714
+ lines.push(` ${pattern.description}`)
715
+ lines.push('')
716
+ }
717
+
718
+ // Top scored patterns
719
+ const sortedScores = Object.entries(result.scores)
720
+ .filter(([, s]) => !s.belowThreshold)
721
+ .sort(([, a], [, b]) => b.score - a.score)
722
+ .slice(0, 5)
723
+
724
+ if (sortedScores.length > 1) {
725
+ lines.push('Pattern Scores:')
726
+ for (const [id, info] of sortedScores) {
727
+ const marker = id === result.architecture ? ' <-- detected' : ''
728
+ lines.push(` ${info.name}: ${info.score.toFixed(1)}${marker}`)
729
+ }
730
+ lines.push('')
731
+ }
732
+
733
+ // Sub-projects
734
+ if (result.subProjects.length > 0) {
735
+ lines.push('Sub-Project Architectures:')
736
+ for (const sub of result.subProjects) {
737
+ const subPattern = ARCHITECTURE_PATTERNS[sub.architecture]
738
+ const labels = { vue: 'Vue', react: 'React', nextjs: 'Next.js', svelte: 'Svelte', angular: 'Angular', astro: 'Astro', nuxt: 'Nuxt' }
739
+ const fw = sub.framework ? ` [${labels[sub.framework] || sub.framework}]` : ''
740
+ lines.push(` ${sub.name} (${sub.path})${fw}: ${subPattern?.name || 'Unknown'}`)
741
+ }
742
+ lines.push('')
743
+ }
744
+
745
+ // Project info
746
+ lines.push('Project Info:')
747
+ lines.push(` TypeScript: ${result.projectInfo.hasTypeScript ? 'Yes' : 'No'}`)
748
+ lines.push(` src/ directory: ${result.projectInfo.hasSrc ? 'Yes' : 'No'}`)
749
+ lines.push('')
750
+
751
+ return lines.join('\n')
752
+ }