@aiready/context-analyzer 0.22.9 → 0.22.12

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