@aiready/context-analyzer 0.6.0 → 0.7.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,779 @@
1
+ // src/index.ts
2
+ import { scanFiles, readFileContent } from "@aiready/core";
3
+
4
+ // src/analyzer.ts
5
+ import { estimateTokens, parseFileExports } from "@aiready/core";
6
+ function extractDomainKeywordsFromPaths(files) {
7
+ const folderNames = /* @__PURE__ */ new Set();
8
+ for (const { file } of files) {
9
+ const segments = file.split("/");
10
+ const skipFolders = /* @__PURE__ */ new Set(["src", "lib", "dist", "build", "node_modules", "test", "tests", "__tests__", "spec", "e2e", "scripts", "components", "utils", "helpers", "util", "helper"]);
11
+ for (const segment of segments) {
12
+ const normalized = segment.toLowerCase();
13
+ if (normalized && !skipFolders.has(normalized) && !normalized.includes(".")) {
14
+ const singular = singularize(normalized);
15
+ folderNames.add(singular);
16
+ }
17
+ }
18
+ }
19
+ return Array.from(folderNames);
20
+ }
21
+ function singularize(word) {
22
+ const irregulars = {
23
+ people: "person",
24
+ children: "child",
25
+ men: "man",
26
+ women: "woman"
27
+ };
28
+ if (irregulars[word]) {
29
+ return irregulars[word];
30
+ }
31
+ if (word.endsWith("ies")) {
32
+ return word.slice(0, -3) + "y";
33
+ }
34
+ if (word.endsWith("ses")) {
35
+ return word.slice(0, -2);
36
+ }
37
+ if (word.endsWith("s") && word.length > 3) {
38
+ return word.slice(0, -1);
39
+ }
40
+ return word;
41
+ }
42
+ function buildDependencyGraph(files, domainOptions) {
43
+ const nodes = /* @__PURE__ */ new Map();
44
+ const edges = /* @__PURE__ */ new Map();
45
+ const autoDetectedKeywords = extractDomainKeywordsFromPaths(files);
46
+ const enhancedOptions = {
47
+ ...domainOptions,
48
+ domainKeywords: [
49
+ ...domainOptions?.domainKeywords || [],
50
+ ...autoDetectedKeywords
51
+ ]
52
+ };
53
+ for (const { file, content } of files) {
54
+ const imports = extractImportsFromContent(content);
55
+ const exports = extractExportsWithAST(content, file, enhancedOptions, imports);
56
+ const tokenCost = estimateTokens(content);
57
+ const linesOfCode = content.split("\n").length;
58
+ nodes.set(file, {
59
+ file,
60
+ imports,
61
+ exports,
62
+ tokenCost,
63
+ linesOfCode
64
+ });
65
+ edges.set(file, new Set(imports));
66
+ }
67
+ return { nodes, edges };
68
+ }
69
+ function extractImportsFromContent(content) {
70
+ const imports = [];
71
+ const patterns = [
72
+ /import\s+.*?\s+from\s+['"](.+?)['"]/g,
73
+ // import ... from '...'
74
+ /import\s+['"](.+?)['"]/g,
75
+ // import '...'
76
+ /require\(['"](.+?)['"]\)/g
77
+ // require('...')
78
+ ];
79
+ for (const pattern of patterns) {
80
+ let match;
81
+ while ((match = pattern.exec(content)) !== null) {
82
+ const importPath = match[1];
83
+ if (importPath && !importPath.startsWith("@") && !importPath.startsWith("node:")) {
84
+ imports.push(importPath);
85
+ }
86
+ }
87
+ }
88
+ return [...new Set(imports)];
89
+ }
90
+ function calculateImportDepth(file, graph, visited = /* @__PURE__ */ new Set(), depth = 0) {
91
+ if (visited.has(file)) {
92
+ return depth;
93
+ }
94
+ const dependencies = graph.edges.get(file);
95
+ if (!dependencies || dependencies.size === 0) {
96
+ return depth;
97
+ }
98
+ visited.add(file);
99
+ let maxDepth = depth;
100
+ for (const dep of dependencies) {
101
+ const depDepth = calculateImportDepth(dep, graph, visited, depth + 1);
102
+ maxDepth = Math.max(maxDepth, depDepth);
103
+ }
104
+ visited.delete(file);
105
+ return maxDepth;
106
+ }
107
+ function getTransitiveDependencies(file, graph, visited = /* @__PURE__ */ new Set()) {
108
+ if (visited.has(file)) {
109
+ return [];
110
+ }
111
+ visited.add(file);
112
+ const dependencies = graph.edges.get(file);
113
+ if (!dependencies || dependencies.size === 0) {
114
+ return [];
115
+ }
116
+ const allDeps = [];
117
+ for (const dep of dependencies) {
118
+ allDeps.push(dep);
119
+ allDeps.push(...getTransitiveDependencies(dep, graph, visited));
120
+ }
121
+ return [...new Set(allDeps)];
122
+ }
123
+ function calculateContextBudget(file, graph) {
124
+ const node = graph.nodes.get(file);
125
+ if (!node) return 0;
126
+ let totalTokens = node.tokenCost;
127
+ const deps = getTransitiveDependencies(file, graph);
128
+ for (const dep of deps) {
129
+ const depNode = graph.nodes.get(dep);
130
+ if (depNode) {
131
+ totalTokens += depNode.tokenCost;
132
+ }
133
+ }
134
+ return totalTokens;
135
+ }
136
+ function detectCircularDependencies(graph) {
137
+ const cycles = [];
138
+ const visited = /* @__PURE__ */ new Set();
139
+ const recursionStack = /* @__PURE__ */ new Set();
140
+ function dfs(file, path) {
141
+ if (recursionStack.has(file)) {
142
+ const cycleStart = path.indexOf(file);
143
+ if (cycleStart !== -1) {
144
+ cycles.push([...path.slice(cycleStart), file]);
145
+ }
146
+ return;
147
+ }
148
+ if (visited.has(file)) {
149
+ return;
150
+ }
151
+ visited.add(file);
152
+ recursionStack.add(file);
153
+ path.push(file);
154
+ const dependencies = graph.edges.get(file);
155
+ if (dependencies) {
156
+ for (const dep of dependencies) {
157
+ dfs(dep, [...path]);
158
+ }
159
+ }
160
+ recursionStack.delete(file);
161
+ }
162
+ for (const file of graph.nodes.keys()) {
163
+ if (!visited.has(file)) {
164
+ dfs(file, []);
165
+ }
166
+ }
167
+ return cycles;
168
+ }
169
+ function calculateCohesion(exports, filePath) {
170
+ return calculateEnhancedCohesion(exports, filePath);
171
+ }
172
+ function isTestFile(filePath) {
173
+ const lower = filePath.toLowerCase();
174
+ return lower.includes("test") || lower.includes("spec") || lower.includes("mock") || lower.includes("fixture") || lower.includes("__tests__") || lower.includes(".test.") || lower.includes(".spec.");
175
+ }
176
+ function calculateFragmentation(files, domain) {
177
+ if (files.length <= 1) return 0;
178
+ const directories = new Set(files.map((f) => f.split("/").slice(0, -1).join("/")));
179
+ return (directories.size - 1) / (files.length - 1);
180
+ }
181
+ function detectModuleClusters(graph) {
182
+ const domainMap = /* @__PURE__ */ new Map();
183
+ for (const [file, node] of graph.nodes.entries()) {
184
+ const domains = node.exports.map((e) => e.inferredDomain || "unknown");
185
+ const primaryDomain = domains[0] || "unknown";
186
+ if (!domainMap.has(primaryDomain)) {
187
+ domainMap.set(primaryDomain, []);
188
+ }
189
+ domainMap.get(primaryDomain).push(file);
190
+ }
191
+ const clusters = [];
192
+ for (const [domain, files] of domainMap.entries()) {
193
+ if (files.length < 2) continue;
194
+ const totalTokens = files.reduce((sum, file) => {
195
+ const node = graph.nodes.get(file);
196
+ return sum + (node?.tokenCost || 0);
197
+ }, 0);
198
+ const fragmentationScore = calculateFragmentation(files, domain);
199
+ const avgCohesion = files.reduce((sum, file) => {
200
+ const node = graph.nodes.get(file);
201
+ return sum + (node ? calculateCohesion(node.exports, file) : 0);
202
+ }, 0) / files.length;
203
+ const targetFiles = Math.max(1, Math.ceil(files.length / 3));
204
+ const consolidationPlan = generateConsolidationPlan(
205
+ domain,
206
+ files,
207
+ targetFiles
208
+ );
209
+ clusters.push({
210
+ domain,
211
+ files,
212
+ totalTokens,
213
+ fragmentationScore,
214
+ avgCohesion,
215
+ suggestedStructure: {
216
+ targetFiles,
217
+ consolidationPlan
218
+ }
219
+ });
220
+ }
221
+ return clusters.sort((a, b) => b.fragmentationScore - a.fragmentationScore);
222
+ }
223
+ function extractExports(content, filePath, domainOptions, fileImports) {
224
+ const exports = [];
225
+ const patterns = [
226
+ /export\s+function\s+(\w+)/g,
227
+ /export\s+class\s+(\w+)/g,
228
+ /export\s+const\s+(\w+)/g,
229
+ /export\s+type\s+(\w+)/g,
230
+ /export\s+interface\s+(\w+)/g,
231
+ /export\s+default/g
232
+ ];
233
+ const types = [
234
+ "function",
235
+ "class",
236
+ "const",
237
+ "type",
238
+ "interface",
239
+ "default"
240
+ ];
241
+ patterns.forEach((pattern, index) => {
242
+ let match;
243
+ while ((match = pattern.exec(content)) !== null) {
244
+ const name = match[1] || "default";
245
+ const type = types[index];
246
+ const inferredDomain = inferDomain(name, filePath, domainOptions, fileImports);
247
+ exports.push({ name, type, inferredDomain });
248
+ }
249
+ });
250
+ return exports;
251
+ }
252
+ function inferDomain(name, filePath, domainOptions, fileImports) {
253
+ const lower = name.toLowerCase();
254
+ const tokens = Array.from(
255
+ new Set(
256
+ lower.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^a-z0-9]+/gi, " ").split(" ").filter(Boolean)
257
+ )
258
+ );
259
+ const defaultKeywords = [
260
+ "authentication",
261
+ "authorization",
262
+ "payment",
263
+ "invoice",
264
+ "customer",
265
+ "product",
266
+ "order",
267
+ "cart",
268
+ "user",
269
+ "admin",
270
+ "repository",
271
+ "controller",
272
+ "service",
273
+ "config",
274
+ "model",
275
+ "view",
276
+ "auth",
277
+ "api",
278
+ "helper",
279
+ "util"
280
+ ];
281
+ const domainKeywords = domainOptions?.domainKeywords && domainOptions.domainKeywords.length ? [...domainOptions.domainKeywords, ...defaultKeywords] : defaultKeywords;
282
+ const patterns = (domainOptions?.domainPatterns || []).map((p) => {
283
+ try {
284
+ return new RegExp(p, "i");
285
+ } catch {
286
+ return null;
287
+ }
288
+ }).filter((r) => !!r);
289
+ for (const re of patterns) {
290
+ if (re.test(lower)) {
291
+ const matched = domainKeywords.find((k) => re.test(k));
292
+ if (matched) return matched;
293
+ return "unknown";
294
+ }
295
+ }
296
+ for (const keyword of domainKeywords) {
297
+ if (tokens.includes(keyword)) {
298
+ return keyword;
299
+ }
300
+ }
301
+ for (const keyword of domainKeywords) {
302
+ if (lower.includes(keyword)) {
303
+ return keyword;
304
+ }
305
+ }
306
+ if (fileImports && fileImports.length > 0) {
307
+ for (const importPath of fileImports) {
308
+ const importLower = importPath.toLowerCase();
309
+ const importSegments = importPath.split("/").filter((s) => s && !s.startsWith("@") && !s.startsWith("."));
310
+ for (const segment of importSegments) {
311
+ const segLower = segment.toLowerCase();
312
+ const singularSegment = singularize(segLower);
313
+ for (const keyword of domainKeywords) {
314
+ if (singularSegment === keyword || segLower === keyword || segLower.includes(keyword)) {
315
+ return keyword;
316
+ }
317
+ }
318
+ }
319
+ }
320
+ }
321
+ if (filePath) {
322
+ if (domainOptions?.pathDomainMap) {
323
+ const segments = filePath.toLowerCase().split("/");
324
+ for (const seg of segments) {
325
+ if (domainOptions.pathDomainMap[seg]) {
326
+ return domainOptions.pathDomainMap[seg];
327
+ }
328
+ }
329
+ }
330
+ const pathSegments = filePath.toLowerCase().split("/");
331
+ for (const segment of pathSegments) {
332
+ const singularSegment = singularize(segment);
333
+ for (const keyword of domainKeywords) {
334
+ if (singularSegment === keyword || segment === keyword || segment.includes(keyword)) {
335
+ return keyword;
336
+ }
337
+ }
338
+ }
339
+ }
340
+ return "unknown";
341
+ }
342
+ function generateConsolidationPlan(domain, files, targetFiles) {
343
+ const plan = [];
344
+ if (files.length <= targetFiles) {
345
+ return [`No consolidation needed for ${domain}`];
346
+ }
347
+ plan.push(
348
+ `Consolidate ${files.length} ${domain} files into ${targetFiles} cohesive file(s):`
349
+ );
350
+ const dirGroups = /* @__PURE__ */ new Map();
351
+ for (const file of files) {
352
+ const dir = file.split("/").slice(0, -1).join("/");
353
+ if (!dirGroups.has(dir)) {
354
+ dirGroups.set(dir, []);
355
+ }
356
+ dirGroups.get(dir).push(file);
357
+ }
358
+ plan.push(`1. Create unified ${domain} module file`);
359
+ plan.push(
360
+ `2. Move related functionality from ${files.length} scattered files`
361
+ );
362
+ plan.push(`3. Update imports in dependent files`);
363
+ plan.push(
364
+ `4. Remove old files after consolidation (verify with tests first)`
365
+ );
366
+ return plan;
367
+ }
368
+ function extractExportsWithAST(content, filePath, domainOptions, fileImports) {
369
+ try {
370
+ const { exports: astExports } = parseFileExports(content, filePath);
371
+ return astExports.map((exp) => ({
372
+ name: exp.name,
373
+ type: exp.type,
374
+ inferredDomain: inferDomain(exp.name, filePath, domainOptions, fileImports),
375
+ imports: exp.imports,
376
+ dependencies: exp.dependencies
377
+ }));
378
+ } catch (error) {
379
+ return extractExports(content, filePath, domainOptions, fileImports);
380
+ }
381
+ }
382
+ function calculateEnhancedCohesion(exports, filePath) {
383
+ if (exports.length === 0) return 1;
384
+ if (exports.length === 1) return 1;
385
+ if (filePath && isTestFile(filePath)) {
386
+ return 1;
387
+ }
388
+ const domainCohesion = calculateDomainCohesion(exports);
389
+ const hasImportData = exports.some((e) => e.imports && e.imports.length > 0);
390
+ if (!hasImportData) {
391
+ return domainCohesion;
392
+ }
393
+ const importCohesion = calculateImportBasedCohesion(exports);
394
+ return importCohesion * 0.6 + domainCohesion * 0.4;
395
+ }
396
+ function calculateImportBasedCohesion(exports) {
397
+ const exportsWithImports = exports.filter((e) => e.imports && e.imports.length > 0);
398
+ if (exportsWithImports.length < 2) {
399
+ return 1;
400
+ }
401
+ let totalSimilarity = 0;
402
+ let comparisons = 0;
403
+ for (let i = 0; i < exportsWithImports.length; i++) {
404
+ for (let j = i + 1; j < exportsWithImports.length; j++) {
405
+ const exp1 = exportsWithImports[i];
406
+ const exp2 = exportsWithImports[j];
407
+ const similarity = calculateJaccardSimilarity(exp1.imports, exp2.imports);
408
+ totalSimilarity += similarity;
409
+ comparisons++;
410
+ }
411
+ }
412
+ return comparisons > 0 ? totalSimilarity / comparisons : 1;
413
+ }
414
+ function calculateJaccardSimilarity(arr1, arr2) {
415
+ if (arr1.length === 0 && arr2.length === 0) return 1;
416
+ if (arr1.length === 0 || arr2.length === 0) return 0;
417
+ const set1 = new Set(arr1);
418
+ const set2 = new Set(arr2);
419
+ const intersection = new Set([...set1].filter((x) => set2.has(x)));
420
+ const union = /* @__PURE__ */ new Set([...set1, ...set2]);
421
+ return intersection.size / union.size;
422
+ }
423
+ function calculateDomainCohesion(exports) {
424
+ const domains = exports.map((e) => e.inferredDomain || "unknown");
425
+ const domainCounts = /* @__PURE__ */ new Map();
426
+ for (const domain of domains) {
427
+ domainCounts.set(domain, (domainCounts.get(domain) || 0) + 1);
428
+ }
429
+ const total = domains.length;
430
+ let entropy = 0;
431
+ for (const count of domainCounts.values()) {
432
+ const p = count / total;
433
+ if (p > 0) {
434
+ entropy -= p * Math.log2(p);
435
+ }
436
+ }
437
+ const maxEntropy = Math.log2(total);
438
+ return maxEntropy > 0 ? 1 - entropy / maxEntropy : 1;
439
+ }
440
+
441
+ // src/index.ts
442
+ async function getSmartDefaults(directory, userOptions) {
443
+ const files = await scanFiles({
444
+ rootDir: directory,
445
+ include: userOptions.include,
446
+ exclude: userOptions.exclude
447
+ });
448
+ const estimatedBlocks = files.length;
449
+ let maxDepth;
450
+ let maxContextBudget;
451
+ let minCohesion;
452
+ let maxFragmentation;
453
+ if (estimatedBlocks < 100) {
454
+ maxDepth = 4;
455
+ maxContextBudget = 8e3;
456
+ minCohesion = 0.5;
457
+ maxFragmentation = 0.5;
458
+ } else if (estimatedBlocks < 500) {
459
+ maxDepth = 5;
460
+ maxContextBudget = 15e3;
461
+ minCohesion = 0.45;
462
+ maxFragmentation = 0.6;
463
+ } else if (estimatedBlocks < 2e3) {
464
+ maxDepth = 7;
465
+ maxContextBudget = 25e3;
466
+ minCohesion = 0.4;
467
+ maxFragmentation = 0.7;
468
+ } else {
469
+ maxDepth = 10;
470
+ maxContextBudget = 4e4;
471
+ minCohesion = 0.35;
472
+ maxFragmentation = 0.8;
473
+ }
474
+ return {
475
+ maxDepth,
476
+ maxContextBudget,
477
+ minCohesion,
478
+ maxFragmentation,
479
+ focus: "all",
480
+ includeNodeModules: false,
481
+ rootDir: userOptions.rootDir || directory,
482
+ include: userOptions.include,
483
+ exclude: userOptions.exclude
484
+ };
485
+ }
486
+ async function analyzeContext(options) {
487
+ const {
488
+ maxDepth = 5,
489
+ maxContextBudget = 1e4,
490
+ minCohesion = 0.6,
491
+ maxFragmentation = 0.5,
492
+ focus = "all",
493
+ includeNodeModules = false,
494
+ ...scanOptions
495
+ } = options;
496
+ const files = await scanFiles({
497
+ ...scanOptions,
498
+ // Only add node_modules to exclude if includeNodeModules is false
499
+ // The DEFAULT_EXCLUDE already includes node_modules, so this is only needed
500
+ // if user overrides the default exclude list
501
+ exclude: includeNodeModules && scanOptions.exclude ? scanOptions.exclude.filter((pattern) => pattern !== "**/node_modules/**") : scanOptions.exclude
502
+ });
503
+ const fileContents = await Promise.all(
504
+ files.map(async (file) => ({
505
+ file,
506
+ content: await readFileContent(file)
507
+ }))
508
+ );
509
+ const graph = buildDependencyGraph(fileContents, {
510
+ domainKeywords: options.domainKeywords,
511
+ domainPatterns: options.domainPatterns,
512
+ pathDomainMap: options.pathDomainMap
513
+ });
514
+ const circularDeps = detectCircularDependencies(graph);
515
+ const clusters = detectModuleClusters(graph);
516
+ const fragmentationMap = /* @__PURE__ */ new Map();
517
+ for (const cluster of clusters) {
518
+ for (const file of cluster.files) {
519
+ fragmentationMap.set(file, cluster.fragmentationScore);
520
+ }
521
+ }
522
+ const results = [];
523
+ for (const { file } of fileContents) {
524
+ const node = graph.nodes.get(file);
525
+ if (!node) continue;
526
+ const importDepth = focus === "depth" || focus === "all" ? calculateImportDepth(file, graph) : 0;
527
+ const dependencyList = focus === "depth" || focus === "all" ? getTransitiveDependencies(file, graph) : [];
528
+ const contextBudget = focus === "all" ? calculateContextBudget(file, graph) : node.tokenCost;
529
+ const cohesionScore = focus === "cohesion" || focus === "all" ? calculateCohesion(node.exports, file) : 1;
530
+ const fragmentationScore = fragmentationMap.get(file) || 0;
531
+ const relatedFiles = [];
532
+ for (const cluster of clusters) {
533
+ if (cluster.files.includes(file)) {
534
+ relatedFiles.push(...cluster.files.filter((f) => f !== file));
535
+ break;
536
+ }
537
+ }
538
+ const { severity, issues, recommendations, potentialSavings } = analyzeIssues({
539
+ file,
540
+ importDepth,
541
+ contextBudget,
542
+ cohesionScore,
543
+ fragmentationScore,
544
+ maxDepth,
545
+ maxContextBudget,
546
+ minCohesion,
547
+ maxFragmentation,
548
+ circularDeps
549
+ });
550
+ const domains = [
551
+ ...new Set(node.exports.map((e) => e.inferredDomain || "unknown"))
552
+ ];
553
+ results.push({
554
+ file,
555
+ tokenCost: node.tokenCost,
556
+ linesOfCode: node.linesOfCode,
557
+ importDepth,
558
+ dependencyCount: dependencyList.length,
559
+ dependencyList,
560
+ circularDeps: circularDeps.filter((cycle) => cycle.includes(file)),
561
+ cohesionScore,
562
+ domains,
563
+ exportCount: node.exports.length,
564
+ contextBudget,
565
+ fragmentationScore,
566
+ relatedFiles,
567
+ severity,
568
+ issues,
569
+ recommendations,
570
+ potentialSavings
571
+ });
572
+ }
573
+ const issuesOnly = results.filter((r) => r.severity !== "info");
574
+ const sorted = issuesOnly.sort((a, b) => {
575
+ const severityOrder = { critical: 0, major: 1, minor: 2, info: 3 };
576
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
577
+ if (severityDiff !== 0) return severityDiff;
578
+ return b.contextBudget - a.contextBudget;
579
+ });
580
+ return sorted.length > 0 ? sorted : results;
581
+ }
582
+ function generateSummary(results) {
583
+ if (results.length === 0) {
584
+ return {
585
+ totalFiles: 0,
586
+ totalTokens: 0,
587
+ avgContextBudget: 0,
588
+ maxContextBudget: 0,
589
+ avgImportDepth: 0,
590
+ maxImportDepth: 0,
591
+ deepFiles: [],
592
+ avgFragmentation: 0,
593
+ fragmentedModules: [],
594
+ avgCohesion: 0,
595
+ lowCohesionFiles: [],
596
+ criticalIssues: 0,
597
+ majorIssues: 0,
598
+ minorIssues: 0,
599
+ totalPotentialSavings: 0,
600
+ topExpensiveFiles: []
601
+ };
602
+ }
603
+ const totalFiles = results.length;
604
+ const totalTokens = results.reduce((sum, r) => sum + r.tokenCost, 0);
605
+ const totalContextBudget = results.reduce(
606
+ (sum, r) => sum + r.contextBudget,
607
+ 0
608
+ );
609
+ const avgContextBudget = totalContextBudget / totalFiles;
610
+ const maxContextBudget = Math.max(...results.map((r) => r.contextBudget));
611
+ const avgImportDepth = results.reduce((sum, r) => sum + r.importDepth, 0) / totalFiles;
612
+ const maxImportDepth = Math.max(...results.map((r) => r.importDepth));
613
+ const deepFiles = results.filter((r) => r.importDepth >= 5).map((r) => ({ file: r.file, depth: r.importDepth })).sort((a, b) => b.depth - a.depth).slice(0, 10);
614
+ const avgFragmentation = results.reduce((sum, r) => sum + r.fragmentationScore, 0) / totalFiles;
615
+ const moduleMap = /* @__PURE__ */ new Map();
616
+ for (const result of results) {
617
+ for (const domain of result.domains) {
618
+ if (!moduleMap.has(domain)) {
619
+ moduleMap.set(domain, []);
620
+ }
621
+ moduleMap.get(domain).push(result);
622
+ }
623
+ }
624
+ const fragmentedModules = [];
625
+ for (const [domain, files] of moduleMap.entries()) {
626
+ if (files.length < 2) continue;
627
+ const fragmentationScore = files.reduce((sum, f) => sum + f.fragmentationScore, 0) / files.length;
628
+ if (fragmentationScore < 0.3) continue;
629
+ const totalTokens2 = files.reduce((sum, f) => sum + f.tokenCost, 0);
630
+ const avgCohesion2 = files.reduce((sum, f) => sum + f.cohesionScore, 0) / files.length;
631
+ const targetFiles = Math.max(1, Math.ceil(files.length / 3));
632
+ fragmentedModules.push({
633
+ domain,
634
+ files: files.map((f) => f.file),
635
+ totalTokens: totalTokens2,
636
+ fragmentationScore,
637
+ avgCohesion: avgCohesion2,
638
+ suggestedStructure: {
639
+ targetFiles,
640
+ consolidationPlan: [
641
+ `Consolidate ${files.length} ${domain} files into ${targetFiles} cohesive file(s)`,
642
+ `Current token cost: ${totalTokens2.toLocaleString()}`,
643
+ `Estimated savings: ${Math.floor(totalTokens2 * 0.3).toLocaleString()} tokens (30%)`
644
+ ]
645
+ }
646
+ });
647
+ }
648
+ fragmentedModules.sort((a, b) => b.fragmentationScore - a.fragmentationScore);
649
+ const avgCohesion = results.reduce((sum, r) => sum + r.cohesionScore, 0) / totalFiles;
650
+ const lowCohesionFiles = results.filter((r) => r.cohesionScore < 0.6).map((r) => ({ file: r.file, score: r.cohesionScore })).sort((a, b) => a.score - b.score).slice(0, 10);
651
+ const criticalIssues = results.filter((r) => r.severity === "critical").length;
652
+ const majorIssues = results.filter((r) => r.severity === "major").length;
653
+ const minorIssues = results.filter((r) => r.severity === "minor").length;
654
+ const totalPotentialSavings = results.reduce(
655
+ (sum, r) => sum + r.potentialSavings,
656
+ 0
657
+ );
658
+ const topExpensiveFiles = results.sort((a, b) => b.contextBudget - a.contextBudget).slice(0, 10).map((r) => ({
659
+ file: r.file,
660
+ contextBudget: r.contextBudget,
661
+ severity: r.severity
662
+ }));
663
+ return {
664
+ totalFiles,
665
+ totalTokens,
666
+ avgContextBudget,
667
+ maxContextBudget,
668
+ avgImportDepth,
669
+ maxImportDepth,
670
+ deepFiles,
671
+ avgFragmentation,
672
+ fragmentedModules: fragmentedModules.slice(0, 10),
673
+ avgCohesion,
674
+ lowCohesionFiles,
675
+ criticalIssues,
676
+ majorIssues,
677
+ minorIssues,
678
+ totalPotentialSavings,
679
+ topExpensiveFiles
680
+ };
681
+ }
682
+ function analyzeIssues(params) {
683
+ const {
684
+ file,
685
+ importDepth,
686
+ contextBudget,
687
+ cohesionScore,
688
+ fragmentationScore,
689
+ maxDepth,
690
+ maxContextBudget,
691
+ minCohesion,
692
+ maxFragmentation,
693
+ circularDeps
694
+ } = params;
695
+ const issues = [];
696
+ const recommendations = [];
697
+ let severity = "info";
698
+ let potentialSavings = 0;
699
+ if (circularDeps.length > 0) {
700
+ severity = "critical";
701
+ issues.push(
702
+ `Part of ${circularDeps.length} circular dependency chain(s)`
703
+ );
704
+ recommendations.push("Break circular dependencies by extracting interfaces or using dependency injection");
705
+ potentialSavings += contextBudget * 0.2;
706
+ }
707
+ if (importDepth > maxDepth * 1.5) {
708
+ severity = severity === "critical" ? "critical" : "critical";
709
+ issues.push(`Import depth ${importDepth} exceeds limit by 50%`);
710
+ recommendations.push("Flatten dependency tree or use facade pattern");
711
+ potentialSavings += contextBudget * 0.3;
712
+ } else if (importDepth > maxDepth) {
713
+ severity = severity === "critical" ? "critical" : "major";
714
+ issues.push(`Import depth ${importDepth} exceeds recommended maximum ${maxDepth}`);
715
+ recommendations.push("Consider reducing dependency depth");
716
+ potentialSavings += contextBudget * 0.15;
717
+ }
718
+ if (contextBudget > maxContextBudget * 1.5) {
719
+ severity = severity === "critical" ? "critical" : "critical";
720
+ issues.push(`Context budget ${contextBudget.toLocaleString()} tokens is 50% over limit`);
721
+ recommendations.push("Split into smaller modules or reduce dependency tree");
722
+ potentialSavings += contextBudget * 0.4;
723
+ } else if (contextBudget > maxContextBudget) {
724
+ severity = severity === "critical" || severity === "major" ? severity : "major";
725
+ issues.push(`Context budget ${contextBudget.toLocaleString()} exceeds ${maxContextBudget.toLocaleString()}`);
726
+ recommendations.push("Reduce file size or dependencies");
727
+ potentialSavings += contextBudget * 0.2;
728
+ }
729
+ if (cohesionScore < minCohesion * 0.5) {
730
+ severity = severity === "critical" ? "critical" : "major";
731
+ issues.push(`Very low cohesion (${(cohesionScore * 100).toFixed(0)}%) - mixed concerns`);
732
+ recommendations.push("Split file by domain - separate unrelated functionality");
733
+ potentialSavings += contextBudget * 0.25;
734
+ } else if (cohesionScore < minCohesion) {
735
+ severity = severity === "critical" || severity === "major" ? severity : "minor";
736
+ issues.push(`Low cohesion (${(cohesionScore * 100).toFixed(0)}%)`);
737
+ recommendations.push("Consider grouping related exports together");
738
+ potentialSavings += contextBudget * 0.1;
739
+ }
740
+ if (fragmentationScore > maxFragmentation) {
741
+ severity = severity === "critical" || severity === "major" ? severity : "minor";
742
+ issues.push(`High fragmentation (${(fragmentationScore * 100).toFixed(0)}%) - scattered implementation`);
743
+ recommendations.push("Consolidate with related files in same domain");
744
+ potentialSavings += contextBudget * 0.3;
745
+ }
746
+ if (issues.length === 0) {
747
+ issues.push("No significant issues detected");
748
+ recommendations.push("File is well-structured for AI context usage");
749
+ }
750
+ if (isBuildArtifact(file)) {
751
+ issues.push("Detected build artifact (bundled/output file)");
752
+ recommendations.push("Exclude build outputs (e.g., cdk.out, dist, build, .next) from analysis");
753
+ severity = downgradeSeverity(severity);
754
+ potentialSavings = 0;
755
+ }
756
+ return { severity, issues, recommendations, potentialSavings: Math.floor(potentialSavings) };
757
+ }
758
+ function isBuildArtifact(filePath) {
759
+ const lower = filePath.toLowerCase();
760
+ return lower.includes("/node_modules/") || lower.includes("/dist/") || lower.includes("/build/") || lower.includes("/out/") || lower.includes("/output/") || lower.includes("/cdk.out/") || lower.includes("/.next/") || /\/asset\.[^/]+\//.test(lower);
761
+ }
762
+ function downgradeSeverity(s) {
763
+ switch (s) {
764
+ case "critical":
765
+ return "minor";
766
+ case "major":
767
+ return "minor";
768
+ case "minor":
769
+ return "info";
770
+ default:
771
+ return "info";
772
+ }
773
+ }
774
+
775
+ export {
776
+ getSmartDefaults,
777
+ analyzeContext,
778
+ generateSummary
779
+ };