@aiready/context-analyzer 0.9.41 → 0.9.42

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 (52) hide show
  1. package/.turbo/turbo-build.log +10 -10
  2. package/.turbo/turbo-test.log +19 -19
  3. package/dist/chunk-4SYIJ7CU.mjs +1538 -0
  4. package/dist/chunk-4XQVYYPC.mjs +1470 -0
  5. package/dist/chunk-5CLU3HYU.mjs +1475 -0
  6. package/dist/chunk-5K73Q3OQ.mjs +1520 -0
  7. package/dist/chunk-6AVS4KTM.mjs +1536 -0
  8. package/dist/chunk-6I4552YB.mjs +1467 -0
  9. package/dist/chunk-6LPITDKG.mjs +1539 -0
  10. package/dist/chunk-AECWO7NQ.mjs +1539 -0
  11. package/dist/chunk-AJC3FR6G.mjs +1509 -0
  12. package/dist/chunk-CVGIDSMN.mjs +1522 -0
  13. package/dist/chunk-DXG5NIYL.mjs +1527 -0
  14. package/dist/chunk-G3CCJCBI.mjs +1521 -0
  15. package/dist/chunk-GFADGYXZ.mjs +1752 -0
  16. package/dist/chunk-GTRIBVS6.mjs +1467 -0
  17. package/dist/chunk-H4HWBQU6.mjs +1530 -0
  18. package/dist/chunk-JH535NPP.mjs +1619 -0
  19. package/dist/chunk-KGFWKSGJ.mjs +1442 -0
  20. package/dist/chunk-N2GQWNFG.mjs +1527 -0
  21. package/dist/chunk-NQA3F2HJ.mjs +1532 -0
  22. package/dist/chunk-NXXQ2U73.mjs +1467 -0
  23. package/dist/chunk-QDGPR3L6.mjs +1518 -0
  24. package/dist/chunk-SAVOSPM3.mjs +1522 -0
  25. package/dist/chunk-SIX4KMF2.mjs +1468 -0
  26. package/dist/chunk-SPAM2YJE.mjs +1537 -0
  27. package/dist/chunk-UG7OPVHB.mjs +1521 -0
  28. package/dist/chunk-VIJTZPBI.mjs +1470 -0
  29. package/dist/chunk-W37E7MW5.mjs +1403 -0
  30. package/dist/chunk-W76FEISE.mjs +1538 -0
  31. package/dist/chunk-WCFQYXQA.mjs +1532 -0
  32. package/dist/chunk-XY77XABG.mjs +1545 -0
  33. package/dist/chunk-YCGDIGOG.mjs +1467 -0
  34. package/dist/cli.js +768 -1160
  35. package/dist/cli.mjs +1 -1
  36. package/dist/index.d.mts +196 -64
  37. package/dist/index.d.ts +196 -64
  38. package/dist/index.js +937 -1209
  39. package/dist/index.mjs +65 -3
  40. package/package.json +2 -2
  41. package/src/analyzer.ts +143 -2177
  42. package/src/ast-utils.ts +94 -0
  43. package/src/classifier.ts +497 -0
  44. package/src/cluster-detector.ts +100 -0
  45. package/src/defaults.ts +59 -0
  46. package/src/graph-builder.ts +272 -0
  47. package/src/index.ts +30 -519
  48. package/src/metrics.ts +231 -0
  49. package/src/remediation.ts +139 -0
  50. package/src/scoring.ts +12 -34
  51. package/src/semantic-analysis.ts +192 -126
  52. package/src/summary.ts +168 -0
@@ -0,0 +1,1521 @@
1
+ // src/index.ts
2
+ import { scanFiles as scanFiles2, readFileContent } from "@aiready/core";
3
+
4
+ // src/graph-builder.ts
5
+ import { estimateTokens } from "@aiready/core";
6
+
7
+ // src/semantic-analysis.ts
8
+ function buildCoUsageMatrix(graph) {
9
+ const coUsageMatrix = /* @__PURE__ */ new Map();
10
+ for (const [, node] of graph.nodes) {
11
+ const imports = node.imports;
12
+ for (let i = 0; i < imports.length; i++) {
13
+ const fileA = imports[i];
14
+ if (!coUsageMatrix.has(fileA)) coUsageMatrix.set(fileA, /* @__PURE__ */ new Map());
15
+ for (let j = i + 1; j < imports.length; j++) {
16
+ const fileB = imports[j];
17
+ const fileAUsage = coUsageMatrix.get(fileA);
18
+ fileAUsage.set(fileB, (fileAUsage.get(fileB) || 0) + 1);
19
+ if (!coUsageMatrix.has(fileB)) coUsageMatrix.set(fileB, /* @__PURE__ */ new Map());
20
+ const fileBUsage = coUsageMatrix.get(fileB);
21
+ fileBUsage.set(fileA, (fileBUsage.get(fileA) || 0) + 1);
22
+ }
23
+ }
24
+ }
25
+ return coUsageMatrix;
26
+ }
27
+ function buildTypeGraph(graph) {
28
+ const typeGraph = /* @__PURE__ */ new Map();
29
+ for (const [file, node] of graph.nodes) {
30
+ for (const exp of node.exports) {
31
+ if (exp.typeReferences) {
32
+ for (const typeRef of exp.typeReferences) {
33
+ if (!typeGraph.has(typeRef)) typeGraph.set(typeRef, /* @__PURE__ */ new Set());
34
+ typeGraph.get(typeRef).add(file);
35
+ }
36
+ }
37
+ }
38
+ }
39
+ return typeGraph;
40
+ }
41
+ function findSemanticClusters(coUsageMatrix, minCoUsage = 3) {
42
+ const clusters = /* @__PURE__ */ new Map();
43
+ const visited = /* @__PURE__ */ new Set();
44
+ for (const [file, coUsages] of coUsageMatrix) {
45
+ if (visited.has(file)) continue;
46
+ const cluster = [file];
47
+ visited.add(file);
48
+ for (const [relatedFile, count] of coUsages) {
49
+ if (count >= minCoUsage && !visited.has(relatedFile)) {
50
+ cluster.push(relatedFile);
51
+ visited.add(relatedFile);
52
+ }
53
+ }
54
+ if (cluster.length > 1) clusters.set(file, cluster);
55
+ }
56
+ return clusters;
57
+ }
58
+ function inferDomainFromSemantics(file, exportName, graph, coUsageMatrix, typeGraph, exportTypeRefs) {
59
+ const domainSignals = /* @__PURE__ */ new Map();
60
+ const coUsages = coUsageMatrix.get(file) || /* @__PURE__ */ new Map();
61
+ const strongCoUsages = Array.from(coUsages.entries()).filter(([, count]) => count >= 3).map(([coFile]) => coFile);
62
+ for (const coFile of strongCoUsages) {
63
+ const coNode = graph.nodes.get(coFile);
64
+ if (coNode) {
65
+ for (const exp of coNode.exports) {
66
+ if (exp.inferredDomain && exp.inferredDomain !== "unknown") {
67
+ const domain = exp.inferredDomain;
68
+ if (!domainSignals.has(domain)) {
69
+ domainSignals.set(domain, {
70
+ coUsage: false,
71
+ typeReference: false,
72
+ exportName: false,
73
+ importPath: false,
74
+ folderStructure: false
75
+ });
76
+ }
77
+ domainSignals.get(domain).coUsage = true;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ if (exportTypeRefs) {
83
+ for (const typeRef of exportTypeRefs) {
84
+ const filesWithType = typeGraph.get(typeRef);
85
+ if (filesWithType) {
86
+ for (const typeFile of filesWithType) {
87
+ if (typeFile === file) continue;
88
+ const typeNode = graph.nodes.get(typeFile);
89
+ if (typeNode) {
90
+ for (const exp of typeNode.exports) {
91
+ if (exp.inferredDomain && exp.inferredDomain !== "unknown") {
92
+ const domain = exp.inferredDomain;
93
+ if (!domainSignals.has(domain)) {
94
+ domainSignals.set(domain, {
95
+ coUsage: false,
96
+ typeReference: false,
97
+ exportName: false,
98
+ importPath: false,
99
+ folderStructure: false
100
+ });
101
+ }
102
+ domainSignals.get(domain).typeReference = true;
103
+ }
104
+ }
105
+ }
106
+ }
107
+ }
108
+ }
109
+ }
110
+ const assignments = [];
111
+ for (const [domain, signals] of domainSignals) {
112
+ const confidence = calculateDomainConfidence(signals);
113
+ if (confidence >= 0.3) assignments.push({ domain, confidence, signals });
114
+ }
115
+ assignments.sort((a, b) => b.confidence - a.confidence);
116
+ return assignments;
117
+ }
118
+ function calculateDomainConfidence(signals) {
119
+ const weights = { coUsage: 0.35, typeReference: 0.3, exportName: 0.15, importPath: 0.1, folderStructure: 0.1 };
120
+ let confidence = 0;
121
+ if (signals.coUsage) confidence += weights.coUsage;
122
+ if (signals.typeReference) confidence += weights.typeReference;
123
+ if (signals.exportName) confidence += weights.exportName;
124
+ if (signals.importPath) confidence += weights.importPath;
125
+ if (signals.folderStructure) confidence += weights.folderStructure;
126
+ return confidence;
127
+ }
128
+ function extractExports(content, filePath, domainOptions, fileImports) {
129
+ const exports = [];
130
+ const patterns = [
131
+ /export\s+function\s+(\w+)/g,
132
+ /export\s+class\s+(\w+)/g,
133
+ /export\s+const\s+(\w+)/g,
134
+ /export\s+type\s+(\w+)/g,
135
+ /export\s+interface\s+(\w+)/g,
136
+ /export\s+default/g
137
+ ];
138
+ const types = ["function", "class", "const", "type", "interface", "default"];
139
+ patterns.forEach((pattern, index) => {
140
+ let match;
141
+ while ((match = pattern.exec(content)) !== null) {
142
+ const name = match[1] || "default";
143
+ const type = types[index];
144
+ const inferredDomain = inferDomain(name, filePath, domainOptions, fileImports);
145
+ exports.push({ name, type, inferredDomain });
146
+ }
147
+ });
148
+ return exports;
149
+ }
150
+ function inferDomain(name, filePath, domainOptions, fileImports) {
151
+ const lower = name.toLowerCase();
152
+ const tokens = Array.from(new Set(lower.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[^a-z0-9]+/gi, " ").split(" ").filter(Boolean)));
153
+ const defaultKeywords = [
154
+ "authentication",
155
+ "authorization",
156
+ "payment",
157
+ "invoice",
158
+ "customer",
159
+ "product",
160
+ "order",
161
+ "cart",
162
+ "user",
163
+ "admin",
164
+ "repository",
165
+ "controller",
166
+ "service",
167
+ "config",
168
+ "model",
169
+ "view",
170
+ "auth"
171
+ ];
172
+ const domainKeywords = domainOptions?.domainKeywords?.length ? [...domainOptions.domainKeywords, ...defaultKeywords] : defaultKeywords;
173
+ for (const keyword of domainKeywords) {
174
+ if (tokens.includes(keyword)) return keyword;
175
+ }
176
+ for (const keyword of domainKeywords) {
177
+ if (lower.includes(keyword)) return keyword;
178
+ }
179
+ if (fileImports) {
180
+ for (const importPath of fileImports) {
181
+ const segments = importPath.split("/");
182
+ for (const segment of segments) {
183
+ const segLower = segment.toLowerCase();
184
+ const singularSegment = singularize(segLower);
185
+ for (const keyword of domainKeywords) {
186
+ if (singularSegment === keyword || segLower === keyword || segLower.includes(keyword)) return keyword;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ if (filePath) {
192
+ const segments = filePath.split("/");
193
+ for (const segment of segments) {
194
+ const segLower = segment.toLowerCase();
195
+ const singularSegment = singularize(segLower);
196
+ for (const keyword of domainKeywords) {
197
+ if (singularSegment === keyword || segLower === keyword) return keyword;
198
+ }
199
+ }
200
+ }
201
+ return "unknown";
202
+ }
203
+ function singularize(word) {
204
+ const irregulars = { people: "person", children: "child", men: "man", women: "woman" };
205
+ if (irregulars[word]) return irregulars[word];
206
+ if (word.endsWith("ies")) return word.slice(0, -3) + "y";
207
+ if (word.endsWith("ses")) return word.slice(0, -2);
208
+ if (word.endsWith("s") && word.length > 3) return word.slice(0, -1);
209
+ return word;
210
+ }
211
+ function getCoUsageData(file, coUsageMatrix) {
212
+ return { file, coImportedWith: coUsageMatrix.get(file) || /* @__PURE__ */ new Map(), sharedImporters: [] };
213
+ }
214
+ function findConsolidationCandidates(graph, coUsageMatrix, typeGraph, minCoUsage = 5, minSharedTypes = 2) {
215
+ const candidates = [];
216
+ for (const [fileA, coUsages] of coUsageMatrix) {
217
+ const nodeA = graph.nodes.get(fileA);
218
+ if (!nodeA) continue;
219
+ for (const [fileB, count] of coUsages) {
220
+ if (fileB <= fileA || count < minCoUsage) continue;
221
+ const nodeB = graph.nodes.get(fileB);
222
+ if (!nodeB) continue;
223
+ const typesA = new Set(nodeA.exports.flatMap((e) => e.typeReferences || []));
224
+ const typesB = new Set(nodeB.exports.flatMap((e) => e.typeReferences || []));
225
+ const sharedTypes = Array.from(typesA).filter((t) => typesB.has(t));
226
+ if (sharedTypes.length >= minSharedTypes || count >= minCoUsage * 2) {
227
+ candidates.push({ files: [fileA, fileB], reason: `High co-usage (${count}x)`, strength: count / 10 });
228
+ }
229
+ }
230
+ }
231
+ return candidates.sort((a, b) => b.strength - a.strength);
232
+ }
233
+
234
+ // src/ast-utils.ts
235
+ import { parseFileExports } from "@aiready/core";
236
+ function extractExportsWithAST(content, filePath, domainOptions, fileImports) {
237
+ try {
238
+ const { exports: astExports } = parseFileExports(content, filePath);
239
+ return astExports.map((exp) => ({
240
+ name: exp.name,
241
+ type: exp.type,
242
+ inferredDomain: inferDomain(
243
+ exp.name,
244
+ filePath,
245
+ domainOptions,
246
+ fileImports
247
+ ),
248
+ imports: exp.imports,
249
+ dependencies: exp.dependencies,
250
+ typeReferences: exp.typeReferences
251
+ }));
252
+ } catch (error) {
253
+ void error;
254
+ return extractExports(content, filePath, domainOptions, fileImports);
255
+ }
256
+ }
257
+ function isTestFile(filePath) {
258
+ const lower = filePath.toLowerCase();
259
+ return lower.includes(".test.") || lower.includes(".spec.") || lower.includes("/__tests__/") || lower.includes("/tests/") || lower.includes("/test/") || lower.includes("/__mocks__/") || lower.includes("/mocks/") || lower.includes("/fixtures/") || lower.includes(".mock.") || lower.includes(".fixture.") || lower.includes("/test-utils/");
260
+ }
261
+
262
+ // src/graph-builder.ts
263
+ function extractDomainKeywordsFromPaths(files) {
264
+ const folderNames = /* @__PURE__ */ new Set();
265
+ for (const { file } of files) {
266
+ const segments = file.split("/");
267
+ const skipFolders = /* @__PURE__ */ new Set([
268
+ "src",
269
+ "lib",
270
+ "dist",
271
+ "build",
272
+ "node_modules",
273
+ "test",
274
+ "tests",
275
+ "__tests__",
276
+ "spec",
277
+ "e2e",
278
+ "scripts",
279
+ "components",
280
+ "utils",
281
+ "helpers",
282
+ "util",
283
+ "helper",
284
+ "api",
285
+ "apis"
286
+ ]);
287
+ for (const segment of segments) {
288
+ const normalized = segment.toLowerCase();
289
+ if (normalized && !skipFolders.has(normalized) && !normalized.includes(".")) {
290
+ folderNames.add(singularize2(normalized));
291
+ }
292
+ }
293
+ }
294
+ return Array.from(folderNames);
295
+ }
296
+ function singularize2(word) {
297
+ const irregulars = {
298
+ people: "person",
299
+ children: "child",
300
+ men: "man",
301
+ women: "woman"
302
+ };
303
+ if (irregulars[word]) return irregulars[word];
304
+ if (word.endsWith("ies")) return word.slice(0, -3) + "y";
305
+ if (word.endsWith("ses")) return word.slice(0, -2);
306
+ if (word.endsWith("s") && word.length > 3) return word.slice(0, -1);
307
+ return word;
308
+ }
309
+ function buildDependencyGraph(files, options) {
310
+ const nodes = /* @__PURE__ */ new Map();
311
+ const edges = /* @__PURE__ */ new Map();
312
+ const autoDetectedKeywords = options?.domainKeywords ?? extractDomainKeywordsFromPaths(files);
313
+ for (const { file, content } of files) {
314
+ const imports = extractImportsFromContent(content);
315
+ const exports = extractExportsWithAST(
316
+ content,
317
+ file,
318
+ { domainKeywords: autoDetectedKeywords },
319
+ imports
320
+ );
321
+ const tokenCost = estimateTokens(content);
322
+ const linesOfCode = content.split("\n").length;
323
+ nodes.set(file, { file, imports, exports, tokenCost, linesOfCode });
324
+ edges.set(file, new Set(imports));
325
+ }
326
+ const graph = { nodes, edges };
327
+ const coUsageMatrix = buildCoUsageMatrix(graph);
328
+ const typeGraph = buildTypeGraph(graph);
329
+ graph.coUsageMatrix = coUsageMatrix;
330
+ graph.typeGraph = typeGraph;
331
+ for (const [file, node] of nodes) {
332
+ for (const exp of node.exports) {
333
+ const semanticAssignments = inferDomainFromSemantics(
334
+ file,
335
+ exp.name,
336
+ graph,
337
+ coUsageMatrix,
338
+ typeGraph,
339
+ exp.typeReferences
340
+ );
341
+ exp.domains = semanticAssignments;
342
+ if (semanticAssignments.length > 0) {
343
+ exp.inferredDomain = semanticAssignments[0].domain;
344
+ }
345
+ }
346
+ }
347
+ return graph;
348
+ }
349
+ function extractImportsFromContent(content) {
350
+ const imports = [];
351
+ const patterns = [
352
+ /import\s+.*?\s+from\s+['"](.+?)['"]/g,
353
+ /import\s+['"](.+?)['"]/g,
354
+ /require\(['"](.+?)['"]\)/g
355
+ ];
356
+ for (const pattern of patterns) {
357
+ let match;
358
+ while ((match = pattern.exec(content)) !== null) {
359
+ const importPath = match[1];
360
+ if (importPath && !importPath.startsWith("node:")) {
361
+ imports.push(importPath);
362
+ }
363
+ }
364
+ }
365
+ return [...new Set(imports)];
366
+ }
367
+ function calculateImportDepth(file, graph, visited = /* @__PURE__ */ new Set(), depth = 0) {
368
+ if (visited.has(file)) return depth;
369
+ const dependencies = graph.edges.get(file);
370
+ if (!dependencies || dependencies.size === 0) return depth;
371
+ visited.add(file);
372
+ let maxDepth = depth;
373
+ for (const dep of dependencies) {
374
+ maxDepth = Math.max(
375
+ maxDepth,
376
+ calculateImportDepth(dep, graph, visited, depth + 1)
377
+ );
378
+ }
379
+ visited.delete(file);
380
+ return maxDepth;
381
+ }
382
+ function getTransitiveDependencies(file, graph, visited = /* @__PURE__ */ new Set()) {
383
+ if (visited.has(file)) return [];
384
+ visited.add(file);
385
+ const dependencies = graph.edges.get(file);
386
+ if (!dependencies || dependencies.size === 0) return [];
387
+ const allDeps = [];
388
+ for (const dep of dependencies) {
389
+ allDeps.push(dep);
390
+ allDeps.push(...getTransitiveDependencies(dep, graph, visited));
391
+ }
392
+ return [...new Set(allDeps)];
393
+ }
394
+ function calculateContextBudget(file, graph) {
395
+ const node = graph.nodes.get(file);
396
+ if (!node) return 0;
397
+ let totalTokens = node.tokenCost;
398
+ const deps = getTransitiveDependencies(file, graph);
399
+ for (const dep of deps) {
400
+ const depNode = graph.nodes.get(dep);
401
+ if (depNode) {
402
+ totalTokens += depNode.tokenCost;
403
+ }
404
+ }
405
+ return totalTokens;
406
+ }
407
+ function detectCircularDependencies(graph) {
408
+ const cycles = [];
409
+ const visited = /* @__PURE__ */ new Set();
410
+ const recursionStack = /* @__PURE__ */ new Set();
411
+ function dfs(file, path) {
412
+ if (recursionStack.has(file)) {
413
+ const cycleStart = path.indexOf(file);
414
+ if (cycleStart !== -1) {
415
+ cycles.push([...path.slice(cycleStart), file]);
416
+ }
417
+ return;
418
+ }
419
+ if (visited.has(file)) return;
420
+ visited.add(file);
421
+ recursionStack.add(file);
422
+ path.push(file);
423
+ const dependencies = graph.edges.get(file);
424
+ if (dependencies) {
425
+ for (const dep of dependencies) {
426
+ dfs(dep, [...path]);
427
+ }
428
+ }
429
+ recursionStack.delete(file);
430
+ }
431
+ for (const file of graph.nodes.keys()) {
432
+ if (!visited.has(file)) {
433
+ dfs(file, []);
434
+ }
435
+ }
436
+ return cycles;
437
+ }
438
+
439
+ // src/metrics.ts
440
+ import { calculateImportSimilarity } from "@aiready/core";
441
+ function calculateEnhancedCohesion(exports, filePath, options) {
442
+ if (exports.length <= 1) return 1;
443
+ if (filePath && isTestFile(filePath)) return 1;
444
+ const weights = {
445
+ importBased: options?.weights?.importBased ?? 0.4,
446
+ structural: options?.weights?.structural ?? 0.3,
447
+ domainBased: options?.weights?.domainBased ?? 0.3
448
+ };
449
+ const domains = exports.map((e) => e.inferredDomain || "unknown");
450
+ const domainCounts = /* @__PURE__ */ new Map();
451
+ for (const d of domains) domainCounts.set(d, (domainCounts.get(d) || 0) + 1);
452
+ if (domainCounts.size === 1 && domains[0] !== "unknown") {
453
+ return 1;
454
+ }
455
+ const probs = Array.from(domainCounts.values()).map((c) => c / exports.length);
456
+ let domainEntropy = 0;
457
+ for (const p of probs) {
458
+ if (p > 0) domainEntropy -= p * Math.log2(p);
459
+ }
460
+ const maxEntropy = Math.log2(Math.max(2, domainCounts.size));
461
+ const domainScore = 1 - domainEntropy / maxEntropy;
462
+ let importScore = 0;
463
+ let pairs = 0;
464
+ for (let i = 0; i < exports.length; i++) {
465
+ for (let j = i + 1; j < exports.length; j++) {
466
+ const exp1 = { ...exports[i], imports: exports[i].imports || [] };
467
+ const exp2 = { ...exports[j], imports: exports[j].imports || [] };
468
+ const sim = calculateImportSimilarity(
469
+ exp1,
470
+ exp2
471
+ );
472
+ importScore += sim;
473
+ pairs++;
474
+ }
475
+ }
476
+ const avgImportScore = pairs > 0 ? importScore / pairs : 0;
477
+ let structuralScore = 0;
478
+ for (const exp of exports) {
479
+ if (exp.dependencies && exp.dependencies.length > 0) {
480
+ structuralScore += 1;
481
+ }
482
+ }
483
+ const avgStructuralScore = exports.length > 0 ? structuralScore / exports.length : 0;
484
+ let score = domainScore * weights.domainBased + avgImportScore * weights.importBased + Math.min(1, avgStructuralScore * 2) * weights.structural;
485
+ if (!options?.weights) {
486
+ if (avgImportScore === 0) return domainScore;
487
+ return score;
488
+ }
489
+ return score;
490
+ }
491
+ function calculateStructuralCohesionFromCoUsage(file, coUsageMatrix) {
492
+ if (!coUsageMatrix) return 1;
493
+ const coUsages = coUsageMatrix.get(file);
494
+ if (!coUsages || coUsages.size === 0) return 1;
495
+ let total = 0;
496
+ for (const count of coUsages.values()) total += count;
497
+ if (total === 0) return 1;
498
+ const probs = [];
499
+ for (const count of coUsages.values()) {
500
+ if (count > 0) probs.push(count / total);
501
+ }
502
+ if (probs.length <= 1) return 1;
503
+ let entropy = 0;
504
+ for (const prob of probs) {
505
+ entropy -= prob * Math.log2(prob);
506
+ }
507
+ const maxEntropy = Math.log2(probs.length);
508
+ return maxEntropy > 0 ? 1 - entropy / maxEntropy : 1;
509
+ }
510
+ function calculateFragmentation(files, domain, options) {
511
+ if (files.length <= 1) return 0;
512
+ const directories = new Set(files.map((f) => f.split("/").slice(0, -1).join("/")));
513
+ const uniqueDirs = directories.size;
514
+ let score = 0;
515
+ if (options?.useLogScale) {
516
+ if (uniqueDirs <= 1) score = 0;
517
+ else {
518
+ const total = files.length;
519
+ const base = options.logBase || Math.E;
520
+ const num = Math.log(uniqueDirs) / Math.log(base);
521
+ const den = Math.log(total) / Math.log(base);
522
+ score = den > 0 ? num / den : 0;
523
+ }
524
+ } else {
525
+ score = (uniqueDirs - 1) / (files.length - 1);
526
+ }
527
+ if (options?.sharedImportRatio && options.sharedImportRatio > 0.5) {
528
+ const discount = Math.min(0.2, (options.sharedImportRatio - 0.5) * 0.4);
529
+ score = score * (1 - discount);
530
+ }
531
+ return score;
532
+ }
533
+ function calculatePathEntropy(files) {
534
+ if (!files || files.length === 0) return 0;
535
+ const dirCounts = /* @__PURE__ */ new Map();
536
+ for (const f of files) {
537
+ const dir = f.split("/").slice(0, -1).join("/") || ".";
538
+ dirCounts.set(dir, (dirCounts.get(dir) || 0) + 1);
539
+ }
540
+ const counts = Array.from(dirCounts.values());
541
+ if (counts.length <= 1) return 0;
542
+ const total = counts.reduce((s, v) => s + v, 0);
543
+ let entropy = 0;
544
+ for (const count of counts) {
545
+ const prob = count / total;
546
+ entropy -= prob * Math.log2(prob);
547
+ }
548
+ const maxEntropy = Math.log2(counts.length);
549
+ return maxEntropy > 0 ? entropy / maxEntropy : 0;
550
+ }
551
+ function calculateDirectoryDistance(files) {
552
+ if (!files || files.length <= 1) return 0;
553
+ const pathSegments = (p) => p.split("/").filter(Boolean);
554
+ const commonAncestorDepth = (a, b) => {
555
+ const minLen = Math.min(a.length, b.length);
556
+ let i = 0;
557
+ while (i < minLen && a[i] === b[i]) i++;
558
+ return i;
559
+ };
560
+ let totalNormalized = 0;
561
+ let comparisons = 0;
562
+ for (let i = 0; i < files.length; i++) {
563
+ for (let j = i + 1; j < files.length; j++) {
564
+ const segA = pathSegments(files[i]);
565
+ const segB = pathSegments(files[j]);
566
+ const shared = commonAncestorDepth(segA, segB);
567
+ const maxDepth = Math.max(segA.length, segB.length);
568
+ totalNormalized += 1 - (maxDepth > 0 ? shared / maxDepth : 0);
569
+ comparisons++;
570
+ }
571
+ }
572
+ return comparisons > 0 ? totalNormalized / comparisons : 0;
573
+ }
574
+
575
+ // src/classifier.ts
576
+ function classifyFile(node, cohesionScore = 1, domains = []) {
577
+ if (isBarrelExport(node)) {
578
+ return "barrel-export";
579
+ }
580
+ if (isTypeDefinition(node)) {
581
+ return "type-definition";
582
+ }
583
+ if (isNextJsPage(node)) {
584
+ return "nextjs-page";
585
+ }
586
+ if (isLambdaHandler(node)) {
587
+ return "lambda-handler";
588
+ }
589
+ if (isServiceFile(node)) {
590
+ return "service-file";
591
+ }
592
+ if (isEmailTemplate(node)) {
593
+ return "email-template";
594
+ }
595
+ if (isParserFile(node)) {
596
+ return "parser-file";
597
+ }
598
+ if (isSessionFile(node)) {
599
+ if (cohesionScore >= 0.25 && domains.length <= 1) return "cohesive-module";
600
+ return "utility-module";
601
+ }
602
+ if (isUtilityModule(node)) {
603
+ return "utility-module";
604
+ }
605
+ if (isConfigFile(node)) {
606
+ return "cohesive-module";
607
+ }
608
+ if (domains.length <= 1 && domains[0] !== "unknown") {
609
+ return "cohesive-module";
610
+ }
611
+ if (domains.length > 1 && cohesionScore < 0.4) {
612
+ return "mixed-concerns";
613
+ }
614
+ if (cohesionScore >= 0.7) {
615
+ return "cohesive-module";
616
+ }
617
+ return "unknown";
618
+ }
619
+ function isBarrelExport(node) {
620
+ const { file, exports } = node;
621
+ const fileName = file.split("/").pop()?.toLowerCase();
622
+ const isIndexFile = fileName === "index.ts" || fileName === "index.js";
623
+ const isSmallAndManyExports = node.tokenCost < 1e3 && (exports || []).length >= 10;
624
+ const isReexportFile = (exports || []).every((e) => e.type === "const" || e.type === "function") && (exports || []).length > 5;
625
+ return !!isIndexFile || !!isSmallAndManyExports;
626
+ }
627
+ function isTypeDefinition(node) {
628
+ const { file } = node;
629
+ if (file.endsWith(".d.ts")) return true;
630
+ const nodeExports = node.exports || [];
631
+ const hasExports = nodeExports.length > 0;
632
+ const areAllTypes = hasExports && nodeExports.every((e) => e.type === "type" || e.type === "interface");
633
+ const allTypes = !!areAllTypes;
634
+ const isTypePath = file.toLowerCase().includes("/types/") || file.toLowerCase().includes("/interfaces/") || file.toLowerCase().includes("/models/");
635
+ return allTypes || isTypePath && hasExports;
636
+ }
637
+ function isUtilityModule(node) {
638
+ const { file } = node;
639
+ const isUtilPath = file.toLowerCase().includes("/utils/") || file.toLowerCase().includes("/helpers/") || file.toLowerCase().includes("/util/") || file.toLowerCase().includes("/helper/");
640
+ const fileName = file.split("/").pop()?.toLowerCase();
641
+ const isUtilName = fileName?.includes("utils.") || fileName?.includes("helpers.") || fileName?.includes("util.") || fileName?.includes("helper.");
642
+ return !!isUtilPath || !!isUtilName;
643
+ }
644
+ function isLambdaHandler(node) {
645
+ const { file, exports } = node;
646
+ const fileName = file.split("/").pop()?.toLowerCase();
647
+ const handlerPatterns = ["handler", ".handler.", "-handler.", "lambda", ".lambda.", "-lambda."];
648
+ const isHandlerName = handlerPatterns.some((pattern) => fileName?.includes(pattern));
649
+ const isHandlerPath = file.toLowerCase().includes("/handlers/") || file.toLowerCase().includes("/lambdas/") || file.toLowerCase().includes("/lambda/") || file.toLowerCase().includes("/functions/");
650
+ const hasHandlerExport = (exports || []).some(
651
+ (e) => e.name.toLowerCase() === "handler" || e.name.toLowerCase() === "main" || e.name.toLowerCase() === "lambdahandler" || e.name.toLowerCase().endsWith("handler")
652
+ );
653
+ return !!isHandlerName || !!isHandlerPath || !!hasHandlerExport;
654
+ }
655
+ function isServiceFile(node) {
656
+ const { file, exports } = node;
657
+ const fileName = file.split("/").pop()?.toLowerCase();
658
+ const servicePatterns = ["service", ".service.", "-service.", "_service."];
659
+ const isServiceName = servicePatterns.some((pattern) => fileName?.includes(pattern));
660
+ const isServicePath = file.toLowerCase().includes("/services/");
661
+ const hasServiceNamedExport = (exports || []).some(
662
+ (e) => e.name.toLowerCase().includes("service") || e.name.toLowerCase().endsWith("service")
663
+ );
664
+ const hasClassExport = (exports || []).some((e) => e.type === "class");
665
+ return !!isServiceName || !!isServicePath || !!hasServiceNamedExport && !!hasClassExport;
666
+ }
667
+ function isEmailTemplate(node) {
668
+ const { file, exports } = node;
669
+ const fileName = file.split("/").pop()?.toLowerCase();
670
+ const emailTemplatePatterns = ["-email-", ".email.", "_email_", "-template", ".template.", "_template", "-mail.", ".mail."];
671
+ const isEmailTemplateName = emailTemplatePatterns.some((pattern) => fileName?.includes(pattern));
672
+ const isEmailPath = file.toLowerCase().includes("/emails/") || file.toLowerCase().includes("/mail/") || file.toLowerCase().includes("/notifications/");
673
+ const hasTemplateFunction = (exports || []).some(
674
+ (e) => e.type === "function" && (e.name.toLowerCase().startsWith("render") || e.name.toLowerCase().startsWith("generate") || e.name.toLowerCase().includes("template") && e.name.toLowerCase().includes("email"))
675
+ );
676
+ return !!isEmailPath || !!isEmailTemplateName || !!hasTemplateFunction;
677
+ }
678
+ function isParserFile(node) {
679
+ const { file, exports } = node;
680
+ const fileName = file.split("/").pop()?.toLowerCase();
681
+ const parserPatterns = ["parser", ".parser.", "-parser.", "_parser.", "transform", ".transform.", "converter", "mapper", "serializer"];
682
+ const isParserName = parserPatterns.some((pattern) => fileName?.includes(pattern));
683
+ const isParserPath = file.toLowerCase().includes("/parsers/") || file.toLowerCase().includes("/transformers/");
684
+ const hasParseFunction = (exports || []).some(
685
+ (e) => e.type === "function" && (e.name.toLowerCase().startsWith("parse") || e.name.toLowerCase().startsWith("transform") || e.name.toLowerCase().startsWith("extract"))
686
+ );
687
+ return !!isParserName || !!isParserPath || !!hasParseFunction;
688
+ }
689
+ function isSessionFile(node) {
690
+ const { file, exports } = node;
691
+ const fileName = file.split("/").pop()?.toLowerCase();
692
+ const sessionPatterns = ["session", "state", "context", "store"];
693
+ const isSessionName = sessionPatterns.some((pattern) => fileName?.includes(pattern));
694
+ const isSessionPath = file.toLowerCase().includes("/sessions/") || file.toLowerCase().includes("/state/");
695
+ const hasSessionExport = (exports || []).some(
696
+ (e) => e.name.toLowerCase().includes("session") || e.name.toLowerCase().includes("state") || e.name.toLowerCase().includes("store")
697
+ );
698
+ return !!isSessionName || !!isSessionPath || !!hasSessionExport;
699
+ }
700
+ function isConfigFile(node) {
701
+ const { file, exports } = node;
702
+ const lowerPath = file.toLowerCase();
703
+ const fileName = file.split("/").pop()?.toLowerCase();
704
+ const configPatterns = [
705
+ ".config.",
706
+ "tsconfig",
707
+ "jest.config",
708
+ "package.json",
709
+ "aiready.json",
710
+ "next.config",
711
+ "sst.config"
712
+ ];
713
+ const isConfigName = configPatterns.some((p) => fileName?.includes(p));
714
+ const isConfigPath = lowerPath.includes("/config/") || lowerPath.includes("/settings/") || lowerPath.includes("/schemas/");
715
+ const hasSchemaExports = (exports || []).some(
716
+ (e) => e.name.toLowerCase().includes("schema") || e.name.toLowerCase().includes("config") || e.name.toLowerCase().includes("setting")
717
+ );
718
+ return !!isConfigName || !!isConfigPath || !!hasSchemaExports;
719
+ }
720
+ function isNextJsPage(node) {
721
+ const { file, exports } = node;
722
+ const lowerPath = file.toLowerCase();
723
+ const fileName = file.split("/").pop()?.toLowerCase();
724
+ const isInAppDir = lowerPath.includes("/app/") || lowerPath.startsWith("app/");
725
+ const isPageFile = fileName === "page.tsx" || fileName === "page.ts";
726
+ if (!isInAppDir || !isPageFile) return false;
727
+ const hasDefaultExport = (exports || []).some((e) => e.type === "default");
728
+ const nextJsExports = ["metadata", "generatemetadata", "faqjsonld", "jsonld", "icon"];
729
+ const hasNextJsExports = (exports || []).some((e) => nextJsExports.includes(e.name.toLowerCase()));
730
+ return !!hasDefaultExport || !!hasNextJsExports;
731
+ }
732
+ function adjustCohesionForClassification(baseCohesion, classification, node) {
733
+ switch (classification) {
734
+ case "barrel-export":
735
+ return 1;
736
+ case "type-definition":
737
+ return 1;
738
+ case "nextjs-page":
739
+ return 1;
740
+ case "utility-module": {
741
+ if (node && hasRelatedExportNames((node.exports || []).map((e) => e.name.toLowerCase()))) {
742
+ return Math.max(0.8, Math.min(1, baseCohesion + 0.45));
743
+ }
744
+ return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
745
+ }
746
+ case "service-file":
747
+ return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
748
+ case "lambda-handler":
749
+ return Math.max(0.75, Math.min(1, baseCohesion + 0.35));
750
+ case "email-template":
751
+ return Math.max(0.72, Math.min(1, baseCohesion + 0.3));
752
+ case "parser-file":
753
+ return Math.max(0.7, Math.min(1, baseCohesion + 0.3));
754
+ case "cohesive-module":
755
+ return Math.max(baseCohesion, 0.7);
756
+ case "mixed-concerns":
757
+ return baseCohesion;
758
+ default:
759
+ return Math.min(1, baseCohesion + 0.1);
760
+ }
761
+ }
762
+ function hasRelatedExportNames(exportNames) {
763
+ if (exportNames.length < 2) return true;
764
+ const stems = /* @__PURE__ */ new Set();
765
+ const domains = /* @__PURE__ */ new Set();
766
+ const verbs = ["get", "set", "create", "update", "delete", "fetch", "save", "load", "parse", "format", "validate"];
767
+ const domainPatterns = ["user", "order", "product", "session", "email", "file", "db", "api", "config"];
768
+ for (const name of exportNames) {
769
+ for (const verb of verbs) {
770
+ if (name.startsWith(verb) && name.length > verb.length) {
771
+ stems.add(name.slice(verb.length).toLowerCase());
772
+ }
773
+ }
774
+ for (const domain of domainPatterns) {
775
+ if (name.includes(domain)) domains.add(domain);
776
+ }
777
+ }
778
+ if (stems.size === 1 || domains.size === 1) return true;
779
+ return false;
780
+ }
781
+ function adjustFragmentationForClassification(baseFragmentation, classification) {
782
+ switch (classification) {
783
+ case "barrel-export":
784
+ return 0;
785
+ case "type-definition":
786
+ return 0;
787
+ case "utility-module":
788
+ case "service-file":
789
+ case "lambda-handler":
790
+ case "email-template":
791
+ case "parser-file":
792
+ case "nextjs-page":
793
+ return baseFragmentation * 0.2;
794
+ case "cohesive-module":
795
+ return baseFragmentation * 0.3;
796
+ case "mixed-concerns":
797
+ return baseFragmentation;
798
+ default:
799
+ return baseFragmentation * 0.7;
800
+ }
801
+ }
802
+
803
+ // src/cluster-detector.ts
804
+ function detectModuleClusters(graph, options) {
805
+ const domainMap = /* @__PURE__ */ new Map();
806
+ for (const [file, node] of graph.nodes.entries()) {
807
+ const primaryDomain = node.exports[0]?.inferredDomain || "unknown";
808
+ if (!domainMap.has(primaryDomain)) {
809
+ domainMap.set(primaryDomain, []);
810
+ }
811
+ domainMap.get(primaryDomain).push(file);
812
+ }
813
+ const clusters = [];
814
+ for (const [domain, files] of domainMap.entries()) {
815
+ if (files.length < 2 || domain === "unknown") continue;
816
+ const totalTokens = files.reduce((sum, file) => {
817
+ const node = graph.nodes.get(file);
818
+ return sum + (node?.tokenCost || 0);
819
+ }, 0);
820
+ const fragmentation = calculateFragmentation(files, domain, options);
821
+ let totalCohesion = 0;
822
+ files.forEach((f) => {
823
+ const node = graph.nodes.get(f);
824
+ if (node) totalCohesion += calculateEnhancedCohesion(node.exports);
825
+ });
826
+ const avgCohesion = totalCohesion / files.length;
827
+ clusters.push({
828
+ domain,
829
+ files,
830
+ totalTokens,
831
+ fragmentationScore: fragmentation,
832
+ avgCohesion,
833
+ suggestedStructure: generateSuggestedStructure(
834
+ files,
835
+ totalTokens,
836
+ fragmentation
837
+ )
838
+ });
839
+ }
840
+ return clusters;
841
+ }
842
+ function generateSuggestedStructure(files, tokens, fragmentation) {
843
+ const targetFiles = Math.max(1, Math.ceil(tokens / 1e4));
844
+ const plan = [];
845
+ if (fragmentation > 0.5) {
846
+ plan.push(
847
+ `Consolidate ${files.length} files scattered across multiple directories into ${targetFiles} core module(s)`
848
+ );
849
+ }
850
+ if (tokens > 2e4) {
851
+ plan.push(
852
+ `Domain logic is very large (${Math.round(tokens / 1e3)}k tokens). Ensure clear sub-domain boundaries.`
853
+ );
854
+ }
855
+ return { targetFiles, consolidationPlan: plan };
856
+ }
857
+
858
+ // src/remediation.ts
859
+ function getClassificationRecommendations(classification, file, issues) {
860
+ switch (classification) {
861
+ case "barrel-export":
862
+ return [
863
+ "Barrel export file detected - multiple domains are expected here",
864
+ "Consider if this barrel export improves or hinders discoverability"
865
+ ];
866
+ case "type-definition":
867
+ return [
868
+ "Type definition file - centralized types improve consistency",
869
+ "Consider splitting if file becomes too large (>500 lines)"
870
+ ];
871
+ case "cohesive-module":
872
+ return [
873
+ "Module has good cohesion despite its size",
874
+ "Consider documenting the module boundaries for AI assistants"
875
+ ];
876
+ case "utility-module":
877
+ return [
878
+ "Utility module detected - multiple domains are acceptable here",
879
+ "Consider grouping related utilities by prefix or domain for better discoverability"
880
+ ];
881
+ case "service-file":
882
+ return [
883
+ "Service file detected - orchestration of multiple dependencies is expected",
884
+ "Consider documenting service boundaries and dependencies"
885
+ ];
886
+ case "lambda-handler":
887
+ return [
888
+ "Lambda handler detected - coordination of services is expected",
889
+ "Ensure handler has clear single responsibility"
890
+ ];
891
+ case "email-template":
892
+ return [
893
+ "Email template detected - references multiple domains for rendering",
894
+ "Template structure is cohesive by design"
895
+ ];
896
+ case "parser-file":
897
+ return [
898
+ "Parser/transformer file detected - handles multiple data sources",
899
+ "Consider documenting input/output schemas"
900
+ ];
901
+ case "nextjs-page":
902
+ return [
903
+ "Next.js App Router page detected - metadata/JSON-LD/component pattern is cohesive",
904
+ "Multiple exports (metadata, faqJsonLd, default) serve single page purpose"
905
+ ];
906
+ case "mixed-concerns":
907
+ return [
908
+ "Consider splitting this file by domain",
909
+ "Identify independent responsibilities and extract them",
910
+ "Review import dependencies to understand coupling"
911
+ ];
912
+ default:
913
+ return issues;
914
+ }
915
+ }
916
+ function getGeneralRecommendations(metrics, thresholds) {
917
+ const recommendations = [];
918
+ const issues = [];
919
+ let severity = "info";
920
+ if (metrics.contextBudget > thresholds.maxContextBudget) {
921
+ issues.push(
922
+ `High context budget: ${Math.round(metrics.contextBudget / 1e3)}k tokens`
923
+ );
924
+ recommendations.push(
925
+ "Reduce dependencies or split the file to lower context window requirements"
926
+ );
927
+ severity = "major";
928
+ }
929
+ if (metrics.importDepth > thresholds.maxDepth) {
930
+ issues.push(`Deep import chain: ${metrics.importDepth} levels`);
931
+ recommendations.push("Flatten the dependency graph by reducing nesting");
932
+ if (severity !== "critical") severity = "major";
933
+ }
934
+ if (metrics.circularDeps.length > 0) {
935
+ issues.push(
936
+ `Circular dependencies detected: ${metrics.circularDeps.length}`
937
+ );
938
+ recommendations.push(
939
+ "Refactor to remove circular imports (use dependency injection or interfaces)"
940
+ );
941
+ severity = "critical";
942
+ }
943
+ if (metrics.cohesionScore < thresholds.minCohesion) {
944
+ issues.push(`Low cohesion score: ${metrics.cohesionScore.toFixed(2)}`);
945
+ recommendations.push(
946
+ "Extract unrelated exports into separate domain-specific modules"
947
+ );
948
+ if (severity === "info") severity = "minor";
949
+ }
950
+ if (metrics.fragmentationScore > thresholds.maxFragmentation) {
951
+ issues.push(
952
+ `High domain fragmentation: ${metrics.fragmentationScore.toFixed(2)}`
953
+ );
954
+ recommendations.push(
955
+ "Consolidate domain-related files into fewer directories"
956
+ );
957
+ if (severity === "info") severity = "minor";
958
+ }
959
+ return { recommendations, issues, severity };
960
+ }
961
+
962
+ // src/analyzer.ts
963
+ function calculateCohesion(exports, filePath, options) {
964
+ return calculateEnhancedCohesion(exports, filePath, options);
965
+ }
966
+ function analyzeIssues(params) {
967
+ const {
968
+ file,
969
+ importDepth,
970
+ contextBudget,
971
+ cohesionScore,
972
+ fragmentationScore,
973
+ maxDepth,
974
+ maxContextBudget,
975
+ minCohesion,
976
+ maxFragmentation,
977
+ circularDeps
978
+ } = params;
979
+ const issues = [];
980
+ const recommendations = [];
981
+ let severity = "info";
982
+ let potentialSavings = 0;
983
+ if (circularDeps.length > 0) {
984
+ severity = "critical";
985
+ issues.push(`Part of ${circularDeps.length} circular dependency chain(s)`);
986
+ recommendations.push(
987
+ "Break circular dependencies by extracting interfaces or using dependency injection"
988
+ );
989
+ potentialSavings += contextBudget * 0.2;
990
+ }
991
+ if (importDepth > maxDepth * 1.5) {
992
+ severity = "critical";
993
+ issues.push(`Import depth ${importDepth} exceeds limit by 50%`);
994
+ recommendations.push("Flatten dependency tree or use facade pattern");
995
+ potentialSavings += contextBudget * 0.3;
996
+ } else if (importDepth > maxDepth) {
997
+ if (severity !== "critical") severity = "major";
998
+ issues.push(
999
+ `Import depth ${importDepth} exceeds recommended maximum ${maxDepth}`
1000
+ );
1001
+ recommendations.push("Consider reducing dependency depth");
1002
+ potentialSavings += contextBudget * 0.15;
1003
+ }
1004
+ if (contextBudget > maxContextBudget * 1.5) {
1005
+ severity = "critical";
1006
+ issues.push(
1007
+ `Context budget ${contextBudget.toLocaleString()} tokens is 50% over limit`
1008
+ );
1009
+ recommendations.push(
1010
+ "Split into smaller modules or reduce dependency tree"
1011
+ );
1012
+ potentialSavings += contextBudget * 0.4;
1013
+ } else if (contextBudget > maxContextBudget) {
1014
+ if (severity !== "critical") severity = "major";
1015
+ issues.push(
1016
+ `Context budget ${contextBudget.toLocaleString()} exceeds ${maxContextBudget.toLocaleString()}`
1017
+ );
1018
+ recommendations.push("Reduce file size or dependencies");
1019
+ potentialSavings += contextBudget * 0.2;
1020
+ }
1021
+ if (cohesionScore < minCohesion * 0.5) {
1022
+ if (severity !== "critical") severity = "major";
1023
+ issues.push(
1024
+ `Very low cohesion (${(cohesionScore * 100).toFixed(0)}%) - mixed concerns`
1025
+ );
1026
+ recommendations.push(
1027
+ "Split file by domain - separate unrelated functionality"
1028
+ );
1029
+ potentialSavings += contextBudget * 0.25;
1030
+ } else if (cohesionScore < minCohesion) {
1031
+ if (severity === "info") severity = "minor";
1032
+ issues.push(`Low cohesion (${(cohesionScore * 100).toFixed(0)}%)`);
1033
+ recommendations.push("Consider grouping related exports together");
1034
+ potentialSavings += contextBudget * 0.1;
1035
+ }
1036
+ if (fragmentationScore > maxFragmentation) {
1037
+ if (severity === "info" || severity === "minor") severity = "minor";
1038
+ issues.push(
1039
+ `High fragmentation (${(fragmentationScore * 100).toFixed(0)}%) - scattered implementation`
1040
+ );
1041
+ recommendations.push("Consolidate with related files in same domain");
1042
+ potentialSavings += contextBudget * 0.3;
1043
+ }
1044
+ if (issues.length === 0) {
1045
+ issues.push("No significant issues detected");
1046
+ recommendations.push("File is well-structured for AI context usage");
1047
+ }
1048
+ if (isBuildArtifact(file)) {
1049
+ issues.push("Detected build artifact (bundled/output file)");
1050
+ recommendations.push("Exclude build outputs from analysis");
1051
+ severity = "info";
1052
+ potentialSavings = 0;
1053
+ }
1054
+ return {
1055
+ severity,
1056
+ issues,
1057
+ recommendations,
1058
+ potentialSavings: Math.floor(potentialSavings)
1059
+ };
1060
+ }
1061
+ function isBuildArtifact(filePath) {
1062
+ const lower = filePath.toLowerCase();
1063
+ return lower.includes("/node_modules/") || lower.includes("/dist/") || lower.includes("/build/") || lower.includes("/out/") || lower.includes("/.next/");
1064
+ }
1065
+
1066
+ // src/scoring.ts
1067
+ function calculateContextScore(resultsOrSummary, importDepth, fragmentation, cohesion) {
1068
+ if (Array.isArray(resultsOrSummary)) {
1069
+ const results = resultsOrSummary;
1070
+ if (results.length === 0) return 100;
1071
+ const criticalIssues = results.filter((r) => r.severity === "critical").length;
1072
+ const majorIssues = results.filter((r) => r.severity === "major").length;
1073
+ const penalty = criticalIssues * 10 + majorIssues * 5;
1074
+ return Math.max(0, 100 - penalty);
1075
+ }
1076
+ const isSummary = resultsOrSummary && typeof resultsOrSummary === "object" && "avgContextBudget" in resultsOrSummary;
1077
+ const budget = isSummary ? resultsOrSummary.maxContextBudget : typeof resultsOrSummary === "number" ? resultsOrSummary : 0;
1078
+ const depth = isSummary ? resultsOrSummary.maxImportDepth : importDepth || 0;
1079
+ const frag = isSummary ? resultsOrSummary.avgFragmentation : fragmentation || 0;
1080
+ const coh = isSummary ? resultsOrSummary.avgCohesion : cohesion !== void 0 ? cohesion : 1;
1081
+ const budgetScore = Math.max(0, 100 - budget / 500);
1082
+ const depthScore = depth > 5 ? Math.max(0, 100 - (depth - 5) * 10) : 100;
1083
+ const cohesionScore = coh * 100;
1084
+ const fragPenalty = frag > 0.5 ? (frag - 0.5) * 100 : 0;
1085
+ const rawScore = budgetScore * 0.4 + depthScore * 0.3 + cohesionScore * 0.3;
1086
+ const score = Math.round(rawScore - fragPenalty);
1087
+ const factors = [
1088
+ { name: "Context Budget", impact: Math.round(budgetScore - 50), description: `${Math.round(budget)} tokens` },
1089
+ { name: "Import Depth", impact: Math.round(depthScore - 50), description: `${depth} levels` },
1090
+ { name: "Fragmentation", impact: Math.round(-fragPenalty), description: `${(frag * 100).toFixed(0)}% scattered` }
1091
+ ];
1092
+ if (budget > 5e4) {
1093
+ factors.push({ name: "Extreme File Detected", impact: -20, description: "Budget > 50k" });
1094
+ }
1095
+ const criticalCount = isSummary ? resultsOrSummary.criticalIssues || 0 : 0;
1096
+ if (criticalCount > 0) {
1097
+ factors.push({ name: "Critical Issues", impact: -criticalCount * 10, description: `${criticalCount} blockers` });
1098
+ }
1099
+ const recommendations = [];
1100
+ if (score < 70) recommendations.push({ action: "Reduce context budget of expensive files", priority: "high", estimatedImpact: 10 });
1101
+ const finalScore = Math.max(0, Math.min(100, score - criticalCount * 10 - (budget > 5e4 ? 20 : 0)));
1102
+ return {
1103
+ toolName: "context-analyzer",
1104
+ score: finalScore,
1105
+ rawMetrics: { budget, depth, fragmentation: frag, cohesion: coh },
1106
+ factors,
1107
+ recommendations
1108
+ };
1109
+ }
1110
+ function mapScoreToRating(score) {
1111
+ if (score >= 90) return "excellent";
1112
+ if (score >= 75) return "good";
1113
+ if (score >= 60) return "fair";
1114
+ if (score >= 40) return "needs work";
1115
+ return "critical";
1116
+ }
1117
+
1118
+ // src/defaults.ts
1119
+ import { scanFiles } from "@aiready/core";
1120
+ async function getSmartDefaults(directory, userOptions) {
1121
+ const files = await scanFiles({
1122
+ rootDir: directory,
1123
+ include: userOptions.include,
1124
+ exclude: userOptions.exclude
1125
+ });
1126
+ const estimatedBlocks = files.length;
1127
+ let maxDepth;
1128
+ let maxContextBudget;
1129
+ let minCohesion;
1130
+ let maxFragmentation;
1131
+ if (estimatedBlocks < 100) {
1132
+ maxDepth = 4;
1133
+ maxContextBudget = 8e3;
1134
+ minCohesion = 0.5;
1135
+ maxFragmentation = 0.5;
1136
+ } else if (estimatedBlocks < 500) {
1137
+ maxDepth = 5;
1138
+ maxContextBudget = 15e3;
1139
+ minCohesion = 0.45;
1140
+ maxFragmentation = 0.6;
1141
+ } else if (estimatedBlocks < 2e3) {
1142
+ maxDepth = 7;
1143
+ maxContextBudget = 25e3;
1144
+ minCohesion = 0.4;
1145
+ maxFragmentation = 0.7;
1146
+ } else {
1147
+ maxDepth = 10;
1148
+ maxContextBudget = 4e4;
1149
+ minCohesion = 0.35;
1150
+ maxFragmentation = 0.8;
1151
+ }
1152
+ return {
1153
+ maxDepth,
1154
+ maxContextBudget,
1155
+ minCohesion,
1156
+ maxFragmentation,
1157
+ focus: "all",
1158
+ includeNodeModules: false,
1159
+ rootDir: userOptions.rootDir || directory,
1160
+ include: userOptions.include,
1161
+ exclude: userOptions.exclude
1162
+ };
1163
+ }
1164
+
1165
+ // src/summary.ts
1166
+ function generateSummary(results) {
1167
+ if (results.length === 0) {
1168
+ return {
1169
+ totalFiles: 0,
1170
+ totalTokens: 0,
1171
+ avgContextBudget: 0,
1172
+ maxContextBudget: 0,
1173
+ avgImportDepth: 0,
1174
+ maxImportDepth: 0,
1175
+ deepFiles: [],
1176
+ avgFragmentation: 0,
1177
+ fragmentedModules: [],
1178
+ avgCohesion: 0,
1179
+ lowCohesionFiles: [],
1180
+ criticalIssues: 0,
1181
+ majorIssues: 0,
1182
+ minorIssues: 0,
1183
+ totalPotentialSavings: 0,
1184
+ topExpensiveFiles: []
1185
+ };
1186
+ }
1187
+ const totalFiles = results.length;
1188
+ const totalTokens = results.reduce((sum, r) => sum + r.tokenCost, 0);
1189
+ const totalContextBudget = results.reduce(
1190
+ (sum, r) => sum + r.contextBudget,
1191
+ 0
1192
+ );
1193
+ const avgContextBudget = totalContextBudget / totalFiles;
1194
+ const maxContextBudget = Math.max(...results.map((r) => r.contextBudget));
1195
+ const avgImportDepth = results.reduce((sum, r) => sum + r.importDepth, 0) / totalFiles;
1196
+ const maxImportDepth = Math.max(...results.map((r) => r.importDepth));
1197
+ 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);
1198
+ const avgFragmentation = results.reduce((sum, r) => sum + r.fragmentationScore, 0) / totalFiles;
1199
+ const moduleMap = /* @__PURE__ */ new Map();
1200
+ for (const result of results) {
1201
+ for (const domain of result.domains) {
1202
+ if (!moduleMap.has(domain)) moduleMap.set(domain, []);
1203
+ moduleMap.get(domain).push(result);
1204
+ }
1205
+ }
1206
+ const fragmentedModules = [];
1207
+ for (const [domain, files] of moduleMap.entries()) {
1208
+ let jaccard2 = function(a, b) {
1209
+ const s1 = new Set(a || []);
1210
+ const s2 = new Set(b || []);
1211
+ if (s1.size === 0 && s2.size === 0) return 0;
1212
+ const inter = new Set([...s1].filter((x) => s2.has(x)));
1213
+ const uni = /* @__PURE__ */ new Set([...s1, ...s2]);
1214
+ return uni.size === 0 ? 0 : inter.size / uni.size;
1215
+ };
1216
+ var jaccard = jaccard2;
1217
+ if (files.length < 2) continue;
1218
+ const fragmentationScore = files.reduce((sum, f) => sum + f.fragmentationScore, 0) / files.length;
1219
+ if (fragmentationScore < 0.3) continue;
1220
+ const totalTokens2 = files.reduce((sum, f) => sum + f.tokenCost, 0);
1221
+ const avgCohesion2 = files.reduce((sum, f) => sum + f.cohesionScore, 0) / files.length;
1222
+ const targetFiles = Math.max(1, Math.ceil(files.length / 3));
1223
+ const filePaths = files.map((f) => f.file);
1224
+ const pathEntropy = calculatePathEntropy(filePaths);
1225
+ const directoryDistance = calculateDirectoryDistance(filePaths);
1226
+ let importSimTotal = 0;
1227
+ let importPairs = 0;
1228
+ for (let i = 0; i < files.length; i++) {
1229
+ for (let j = i + 1; j < files.length; j++) {
1230
+ importSimTotal += jaccard2(
1231
+ files[i].dependencyList || [],
1232
+ files[j].dependencyList || []
1233
+ );
1234
+ importPairs++;
1235
+ }
1236
+ }
1237
+ const importCohesion = importPairs > 0 ? importSimTotal / importPairs : 0;
1238
+ fragmentedModules.push({
1239
+ domain,
1240
+ files: files.map((f) => f.file),
1241
+ totalTokens: totalTokens2,
1242
+ fragmentationScore,
1243
+ avgCohesion: avgCohesion2,
1244
+ importCohesion,
1245
+ pathEntropy,
1246
+ directoryDistance,
1247
+ suggestedStructure: {
1248
+ targetFiles,
1249
+ consolidationPlan: [
1250
+ `Consolidate ${files.length} files across ${new Set(files.map((f) => f.file.split("/").slice(0, -1).join("/"))).size} directories`,
1251
+ `Target ~${targetFiles} core modules to reduce context switching`
1252
+ ]
1253
+ }
1254
+ });
1255
+ }
1256
+ const avgCohesion = results.reduce((sum, r) => sum + r.cohesionScore, 0) / totalFiles;
1257
+ const lowCohesionFiles = results.filter((r) => r.cohesionScore < 0.4).map((r) => ({ file: r.file, score: r.cohesionScore })).sort((a, b) => a.score - b.score).slice(0, 10);
1258
+ const criticalIssues = results.filter(
1259
+ (r) => r.severity === "critical"
1260
+ ).length;
1261
+ const majorIssues = results.filter((r) => r.severity === "major").length;
1262
+ const minorIssues = results.filter((r) => r.severity === "minor").length;
1263
+ const totalPotentialSavings = results.reduce(
1264
+ (sum, r) => sum + r.potentialSavings,
1265
+ 0
1266
+ );
1267
+ const topExpensiveFiles = results.sort((a, b) => b.contextBudget - a.contextBudget).slice(0, 10).map((r) => ({
1268
+ file: r.file,
1269
+ contextBudget: r.contextBudget,
1270
+ severity: r.severity
1271
+ }));
1272
+ return {
1273
+ totalFiles,
1274
+ totalTokens,
1275
+ avgContextBudget,
1276
+ maxContextBudget,
1277
+ avgImportDepth,
1278
+ maxImportDepth,
1279
+ deepFiles,
1280
+ avgFragmentation,
1281
+ fragmentedModules,
1282
+ avgCohesion,
1283
+ lowCohesionFiles,
1284
+ criticalIssues,
1285
+ majorIssues,
1286
+ minorIssues,
1287
+ totalPotentialSavings,
1288
+ topExpensiveFiles
1289
+ };
1290
+ }
1291
+
1292
+ // src/index.ts
1293
+ async function analyzeContext(options) {
1294
+ const {
1295
+ maxDepth = 5,
1296
+ maxContextBudget = 1e4,
1297
+ minCohesion = 0.6,
1298
+ maxFragmentation = 0.5,
1299
+ focus = "all",
1300
+ includeNodeModules = false,
1301
+ ...scanOptions
1302
+ } = options;
1303
+ const files = await scanFiles2({
1304
+ ...scanOptions,
1305
+ exclude: includeNodeModules && scanOptions.exclude ? scanOptions.exclude.filter(
1306
+ (pattern) => pattern !== "**/node_modules/**"
1307
+ ) : scanOptions.exclude
1308
+ });
1309
+ const pythonFiles = files.filter((f) => f.toLowerCase().endsWith(".py"));
1310
+ const fileContents = await Promise.all(
1311
+ files.map(async (file) => ({
1312
+ file,
1313
+ content: await readFileContent(file)
1314
+ }))
1315
+ );
1316
+ const graph = buildDependencyGraph(
1317
+ fileContents.filter((f) => !f.file.toLowerCase().endsWith(".py"))
1318
+ );
1319
+ let pythonResults = [];
1320
+ if (pythonFiles.length > 0) {
1321
+ const { analyzePythonContext } = await import("./python-context-TBI5FVFY.mjs");
1322
+ const pythonMetrics = await analyzePythonContext(
1323
+ pythonFiles,
1324
+ scanOptions.rootDir || options.rootDir || "."
1325
+ );
1326
+ pythonResults = pythonMetrics.map((metric) => {
1327
+ const { severity, issues, recommendations, potentialSavings } = analyzeIssues({
1328
+ file: metric.file,
1329
+ importDepth: metric.importDepth,
1330
+ contextBudget: metric.contextBudget,
1331
+ cohesionScore: metric.cohesion,
1332
+ fragmentationScore: 0,
1333
+ maxDepth,
1334
+ maxContextBudget,
1335
+ minCohesion,
1336
+ maxFragmentation,
1337
+ circularDeps: metric.metrics.circularDependencies.map(
1338
+ (cycle) => cycle.split(" \u2192 ")
1339
+ )
1340
+ });
1341
+ return {
1342
+ file: metric.file,
1343
+ tokenCost: Math.floor(
1344
+ metric.contextBudget / (1 + metric.imports.length || 1)
1345
+ ),
1346
+ linesOfCode: metric.metrics.linesOfCode,
1347
+ importDepth: metric.importDepth,
1348
+ dependencyCount: metric.imports.length,
1349
+ dependencyList: metric.imports.map(
1350
+ (imp) => imp.resolvedPath || imp.source
1351
+ ),
1352
+ circularDeps: metric.metrics.circularDependencies.map(
1353
+ (cycle) => cycle.split(" \u2192 ")
1354
+ ),
1355
+ cohesionScore: metric.cohesion,
1356
+ domains: ["python"],
1357
+ exportCount: metric.exports.length,
1358
+ contextBudget: metric.contextBudget,
1359
+ fragmentationScore: 0,
1360
+ relatedFiles: [],
1361
+ fileClassification: "unknown",
1362
+ severity,
1363
+ issues,
1364
+ recommendations,
1365
+ potentialSavings
1366
+ };
1367
+ });
1368
+ }
1369
+ const circularDeps = detectCircularDependencies(graph);
1370
+ const useLogScale = files.length >= 500;
1371
+ const clusters = detectModuleClusters(graph, { useLogScale });
1372
+ const fragmentationMap = /* @__PURE__ */ new Map();
1373
+ for (const cluster of clusters) {
1374
+ for (const file of cluster.files) {
1375
+ fragmentationMap.set(file, cluster.fragmentationScore);
1376
+ }
1377
+ }
1378
+ const results = [];
1379
+ for (const { file } of fileContents) {
1380
+ const node = graph.nodes.get(file);
1381
+ if (!node) continue;
1382
+ const importDepth = focus === "depth" || focus === "all" ? calculateImportDepth(file, graph) : 0;
1383
+ const dependencyList = focus === "depth" || focus === "all" ? getTransitiveDependencies(file, graph) : [];
1384
+ const contextBudget = focus === "all" ? calculateContextBudget(file, graph) : node.tokenCost;
1385
+ const cohesionScore = focus === "cohesion" || focus === "all" ? calculateCohesion(node.exports, file, {
1386
+ coUsageMatrix: graph.coUsageMatrix
1387
+ }) : 1;
1388
+ const fragmentationScore = fragmentationMap.get(file) || 0;
1389
+ const relatedFiles = [];
1390
+ for (const cluster of clusters) {
1391
+ if (cluster.files.includes(file)) {
1392
+ relatedFiles.push(...cluster.files.filter((f) => f !== file));
1393
+ break;
1394
+ }
1395
+ }
1396
+ const { issues } = analyzeIssues({
1397
+ file,
1398
+ importDepth,
1399
+ contextBudget,
1400
+ cohesionScore,
1401
+ fragmentationScore,
1402
+ maxDepth,
1403
+ maxContextBudget,
1404
+ minCohesion,
1405
+ maxFragmentation,
1406
+ circularDeps
1407
+ });
1408
+ const domains = [
1409
+ ...new Set(node.exports.map((e) => e.inferredDomain || "unknown"))
1410
+ ];
1411
+ const fileClassification = classifyFile(node);
1412
+ const adjustedCohesionScore = adjustCohesionForClassification(
1413
+ cohesionScore,
1414
+ fileClassification,
1415
+ node
1416
+ );
1417
+ const adjustedFragmentationScore = adjustFragmentationForClassification(
1418
+ fragmentationScore,
1419
+ fileClassification
1420
+ );
1421
+ const classificationRecommendations = getClassificationRecommendations(
1422
+ fileClassification,
1423
+ file,
1424
+ issues
1425
+ );
1426
+ const {
1427
+ severity: adjustedSeverity,
1428
+ issues: adjustedIssues,
1429
+ recommendations: finalRecommendations,
1430
+ potentialSavings: adjustedSavings
1431
+ } = analyzeIssues({
1432
+ file,
1433
+ importDepth,
1434
+ contextBudget,
1435
+ cohesionScore: adjustedCohesionScore,
1436
+ fragmentationScore: adjustedFragmentationScore,
1437
+ maxDepth,
1438
+ maxContextBudget,
1439
+ minCohesion,
1440
+ maxFragmentation,
1441
+ circularDeps
1442
+ });
1443
+ results.push({
1444
+ file,
1445
+ tokenCost: node.tokenCost,
1446
+ linesOfCode: node.linesOfCode,
1447
+ importDepth,
1448
+ dependencyCount: dependencyList.length,
1449
+ dependencyList,
1450
+ circularDeps: circularDeps.filter((cycle) => cycle.includes(file)),
1451
+ cohesionScore: adjustedCohesionScore,
1452
+ domains,
1453
+ exportCount: node.exports.length,
1454
+ contextBudget,
1455
+ fragmentationScore: adjustedFragmentationScore,
1456
+ relatedFiles,
1457
+ fileClassification,
1458
+ severity: adjustedSeverity,
1459
+ issues: adjustedIssues,
1460
+ recommendations: [
1461
+ ...finalRecommendations,
1462
+ ...classificationRecommendations.slice(0, 1)
1463
+ ],
1464
+ potentialSavings: adjustedSavings
1465
+ });
1466
+ }
1467
+ const allResults = [...results, ...pythonResults];
1468
+ return allResults.sort((a, b) => {
1469
+ const severityOrder = { critical: 0, major: 1, minor: 2, info: 3 };
1470
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
1471
+ if (severityDiff !== 0) return severityDiff;
1472
+ return b.contextBudget - a.contextBudget;
1473
+ });
1474
+ }
1475
+
1476
+ export {
1477
+ buildCoUsageMatrix,
1478
+ buildTypeGraph,
1479
+ findSemanticClusters,
1480
+ inferDomainFromSemantics,
1481
+ calculateDomainConfidence,
1482
+ extractExports,
1483
+ inferDomain,
1484
+ getCoUsageData,
1485
+ findConsolidationCandidates,
1486
+ extractDomainKeywordsFromPaths,
1487
+ buildDependencyGraph,
1488
+ extractImportsFromContent,
1489
+ calculateImportDepth,
1490
+ getTransitiveDependencies,
1491
+ calculateContextBudget,
1492
+ detectCircularDependencies,
1493
+ calculateEnhancedCohesion,
1494
+ calculateStructuralCohesionFromCoUsage,
1495
+ calculateFragmentation,
1496
+ calculatePathEntropy,
1497
+ calculateDirectoryDistance,
1498
+ classifyFile,
1499
+ isBarrelExport,
1500
+ isTypeDefinition,
1501
+ isUtilityModule,
1502
+ isLambdaHandler,
1503
+ isServiceFile,
1504
+ isEmailTemplate,
1505
+ isParserFile,
1506
+ isSessionFile,
1507
+ isConfigFile,
1508
+ isNextJsPage,
1509
+ adjustCohesionForClassification,
1510
+ adjustFragmentationForClassification,
1511
+ detectModuleClusters,
1512
+ getClassificationRecommendations,
1513
+ getGeneralRecommendations,
1514
+ calculateCohesion,
1515
+ analyzeIssues,
1516
+ calculateContextScore,
1517
+ mapScoreToRating,
1518
+ getSmartDefaults,
1519
+ generateSummary,
1520
+ analyzeContext
1521
+ };