@aiready/context-analyzer 0.3.7 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,581 @@
1
+ // src/index.ts
2
+ import { scanFiles, readFileContent } from "@aiready/core";
3
+
4
+ // src/analyzer.ts
5
+ import { estimateTokens } from "@aiready/core";
6
+ function buildDependencyGraph(files) {
7
+ const nodes = /* @__PURE__ */ new Map();
8
+ const edges = /* @__PURE__ */ new Map();
9
+ for (const { file, content } of files) {
10
+ const imports = extractImportsFromContent(content);
11
+ const exports = extractExports(content);
12
+ const tokenCost = estimateTokens(content);
13
+ const linesOfCode = content.split("\n").length;
14
+ nodes.set(file, {
15
+ file,
16
+ imports,
17
+ exports,
18
+ tokenCost,
19
+ linesOfCode
20
+ });
21
+ edges.set(file, new Set(imports));
22
+ }
23
+ return { nodes, edges };
24
+ }
25
+ function extractImportsFromContent(content) {
26
+ const imports = [];
27
+ const patterns = [
28
+ /import\s+.*?\s+from\s+['"](.+?)['"]/g,
29
+ // import ... from '...'
30
+ /import\s+['"](.+?)['"]/g,
31
+ // import '...'
32
+ /require\(['"](.+?)['"]\)/g
33
+ // require('...')
34
+ ];
35
+ for (const pattern of patterns) {
36
+ let match;
37
+ while ((match = pattern.exec(content)) !== null) {
38
+ const importPath = match[1];
39
+ if (importPath && !importPath.startsWith("@") && !importPath.startsWith("node:")) {
40
+ imports.push(importPath);
41
+ }
42
+ }
43
+ }
44
+ return [...new Set(imports)];
45
+ }
46
+ function calculateImportDepth(file, graph, visited = /* @__PURE__ */ new Set(), depth = 0) {
47
+ if (visited.has(file)) {
48
+ return depth;
49
+ }
50
+ const dependencies = graph.edges.get(file);
51
+ if (!dependencies || dependencies.size === 0) {
52
+ return depth;
53
+ }
54
+ visited.add(file);
55
+ let maxDepth = depth;
56
+ for (const dep of dependencies) {
57
+ const depDepth = calculateImportDepth(dep, graph, visited, depth + 1);
58
+ maxDepth = Math.max(maxDepth, depDepth);
59
+ }
60
+ visited.delete(file);
61
+ return maxDepth;
62
+ }
63
+ function getTransitiveDependencies(file, graph, visited = /* @__PURE__ */ new Set()) {
64
+ if (visited.has(file)) {
65
+ return [];
66
+ }
67
+ visited.add(file);
68
+ const dependencies = graph.edges.get(file);
69
+ if (!dependencies || dependencies.size === 0) {
70
+ return [];
71
+ }
72
+ const allDeps = [];
73
+ for (const dep of dependencies) {
74
+ allDeps.push(dep);
75
+ allDeps.push(...getTransitiveDependencies(dep, graph, visited));
76
+ }
77
+ return [...new Set(allDeps)];
78
+ }
79
+ function calculateContextBudget(file, graph) {
80
+ const node = graph.nodes.get(file);
81
+ if (!node) return 0;
82
+ let totalTokens = node.tokenCost;
83
+ const deps = getTransitiveDependencies(file, graph);
84
+ for (const dep of deps) {
85
+ const depNode = graph.nodes.get(dep);
86
+ if (depNode) {
87
+ totalTokens += depNode.tokenCost;
88
+ }
89
+ }
90
+ return totalTokens;
91
+ }
92
+ function detectCircularDependencies(graph) {
93
+ const cycles = [];
94
+ const visited = /* @__PURE__ */ new Set();
95
+ const recursionStack = /* @__PURE__ */ new Set();
96
+ function dfs(file, path) {
97
+ if (recursionStack.has(file)) {
98
+ const cycleStart = path.indexOf(file);
99
+ if (cycleStart !== -1) {
100
+ cycles.push([...path.slice(cycleStart), file]);
101
+ }
102
+ return;
103
+ }
104
+ if (visited.has(file)) {
105
+ return;
106
+ }
107
+ visited.add(file);
108
+ recursionStack.add(file);
109
+ path.push(file);
110
+ const dependencies = graph.edges.get(file);
111
+ if (dependencies) {
112
+ for (const dep of dependencies) {
113
+ dfs(dep, [...path]);
114
+ }
115
+ }
116
+ recursionStack.delete(file);
117
+ }
118
+ for (const file of graph.nodes.keys()) {
119
+ if (!visited.has(file)) {
120
+ dfs(file, []);
121
+ }
122
+ }
123
+ return cycles;
124
+ }
125
+ function calculateCohesion(exports) {
126
+ if (exports.length === 0) return 1;
127
+ if (exports.length === 1) return 1;
128
+ const domains = exports.map((e) => e.inferredDomain || "unknown");
129
+ const domainCounts = /* @__PURE__ */ new Map();
130
+ for (const domain of domains) {
131
+ domainCounts.set(domain, (domainCounts.get(domain) || 0) + 1);
132
+ }
133
+ const total = domains.length;
134
+ let entropy = 0;
135
+ for (const count of domainCounts.values()) {
136
+ const p = count / total;
137
+ if (p > 0) {
138
+ entropy -= p * Math.log2(p);
139
+ }
140
+ }
141
+ const maxEntropy = Math.log2(total);
142
+ return maxEntropy > 0 ? 1 - entropy / maxEntropy : 1;
143
+ }
144
+ function calculateFragmentation(files, domain) {
145
+ if (files.length <= 1) return 0;
146
+ const directories = new Set(files.map((f) => f.split("/").slice(0, -1).join("/")));
147
+ return (directories.size - 1) / (files.length - 1);
148
+ }
149
+ function detectModuleClusters(graph) {
150
+ const domainMap = /* @__PURE__ */ new Map();
151
+ for (const [file, node] of graph.nodes.entries()) {
152
+ const domains = node.exports.map((e) => e.inferredDomain || "unknown");
153
+ const primaryDomain = domains[0] || "unknown";
154
+ if (!domainMap.has(primaryDomain)) {
155
+ domainMap.set(primaryDomain, []);
156
+ }
157
+ domainMap.get(primaryDomain).push(file);
158
+ }
159
+ const clusters = [];
160
+ for (const [domain, files] of domainMap.entries()) {
161
+ if (files.length < 2) continue;
162
+ const totalTokens = files.reduce((sum, file) => {
163
+ const node = graph.nodes.get(file);
164
+ return sum + (node?.tokenCost || 0);
165
+ }, 0);
166
+ const fragmentationScore = calculateFragmentation(files, domain);
167
+ const avgCohesion = files.reduce((sum, file) => {
168
+ const node = graph.nodes.get(file);
169
+ return sum + (node ? calculateCohesion(node.exports) : 0);
170
+ }, 0) / files.length;
171
+ const targetFiles = Math.max(1, Math.ceil(files.length / 3));
172
+ const consolidationPlan = generateConsolidationPlan(
173
+ domain,
174
+ files,
175
+ targetFiles
176
+ );
177
+ clusters.push({
178
+ domain,
179
+ files,
180
+ totalTokens,
181
+ fragmentationScore,
182
+ avgCohesion,
183
+ suggestedStructure: {
184
+ targetFiles,
185
+ consolidationPlan
186
+ }
187
+ });
188
+ }
189
+ return clusters.sort((a, b) => b.fragmentationScore - a.fragmentationScore);
190
+ }
191
+ function extractExports(content) {
192
+ const exports = [];
193
+ const patterns = [
194
+ /export\s+function\s+(\w+)/g,
195
+ /export\s+class\s+(\w+)/g,
196
+ /export\s+const\s+(\w+)/g,
197
+ /export\s+type\s+(\w+)/g,
198
+ /export\s+interface\s+(\w+)/g,
199
+ /export\s+default/g
200
+ ];
201
+ const types = [
202
+ "function",
203
+ "class",
204
+ "const",
205
+ "type",
206
+ "interface",
207
+ "default"
208
+ ];
209
+ patterns.forEach((pattern, index) => {
210
+ let match;
211
+ while ((match = pattern.exec(content)) !== null) {
212
+ const name = match[1] || "default";
213
+ const type = types[index];
214
+ const inferredDomain = inferDomain(name);
215
+ exports.push({ name, type, inferredDomain });
216
+ }
217
+ });
218
+ return exports;
219
+ }
220
+ function inferDomain(name) {
221
+ const lower = name.toLowerCase();
222
+ const domainKeywords = [
223
+ "user",
224
+ "auth",
225
+ "order",
226
+ "product",
227
+ "payment",
228
+ "cart",
229
+ "invoice",
230
+ "customer",
231
+ "admin",
232
+ "api",
233
+ "util",
234
+ "helper",
235
+ "config",
236
+ "service",
237
+ "repository",
238
+ "controller",
239
+ "model",
240
+ "view"
241
+ ];
242
+ for (const keyword of domainKeywords) {
243
+ if (lower.includes(keyword)) {
244
+ return keyword;
245
+ }
246
+ }
247
+ return "unknown";
248
+ }
249
+ function generateConsolidationPlan(domain, files, targetFiles) {
250
+ const plan = [];
251
+ if (files.length <= targetFiles) {
252
+ return [`No consolidation needed for ${domain}`];
253
+ }
254
+ plan.push(
255
+ `Consolidate ${files.length} ${domain} files into ${targetFiles} cohesive file(s):`
256
+ );
257
+ const dirGroups = /* @__PURE__ */ new Map();
258
+ for (const file of files) {
259
+ const dir = file.split("/").slice(0, -1).join("/");
260
+ if (!dirGroups.has(dir)) {
261
+ dirGroups.set(dir, []);
262
+ }
263
+ dirGroups.get(dir).push(file);
264
+ }
265
+ plan.push(`1. Create unified ${domain} module file`);
266
+ plan.push(
267
+ `2. Move related functionality from ${files.length} scattered files`
268
+ );
269
+ plan.push(`3. Update imports in dependent files`);
270
+ plan.push(
271
+ `4. Remove old files after consolidation (verify with tests first)`
272
+ );
273
+ return plan;
274
+ }
275
+
276
+ // src/index.ts
277
+ async function getSmartDefaults(directory, userOptions) {
278
+ const files = await scanFiles({
279
+ rootDir: directory,
280
+ include: userOptions.include,
281
+ exclude: userOptions.exclude
282
+ });
283
+ const estimatedBlocks = files.length;
284
+ let maxDepth;
285
+ let maxContextBudget;
286
+ let minCohesion;
287
+ let maxFragmentation;
288
+ if (estimatedBlocks < 100) {
289
+ maxDepth = 3;
290
+ maxContextBudget = 5e3;
291
+ minCohesion = 0.7;
292
+ maxFragmentation = 0.3;
293
+ } else if (estimatedBlocks < 500) {
294
+ maxDepth = 4;
295
+ maxContextBudget = 8e3;
296
+ minCohesion = 0.65;
297
+ maxFragmentation = 0.4;
298
+ } else if (estimatedBlocks < 2e3) {
299
+ maxDepth = 5;
300
+ maxContextBudget = 12e3;
301
+ minCohesion = 0.6;
302
+ maxFragmentation = 0.5;
303
+ } else {
304
+ maxDepth = 6;
305
+ maxContextBudget = 2e4;
306
+ minCohesion = 0.55;
307
+ maxFragmentation = 0.6;
308
+ }
309
+ return {
310
+ maxDepth,
311
+ maxContextBudget,
312
+ minCohesion,
313
+ maxFragmentation,
314
+ focus: "all",
315
+ includeNodeModules: false,
316
+ ...userOptions
317
+ };
318
+ }
319
+ async function analyzeContext(options) {
320
+ const {
321
+ maxDepth = 5,
322
+ maxContextBudget = 1e4,
323
+ minCohesion = 0.6,
324
+ maxFragmentation = 0.5,
325
+ focus = "all",
326
+ includeNodeModules = false,
327
+ ...scanOptions
328
+ } = options;
329
+ const files = await scanFiles({
330
+ ...scanOptions,
331
+ exclude: includeNodeModules ? scanOptions.exclude : [...scanOptions.exclude || [], "**/node_modules/**"]
332
+ });
333
+ const fileContents = await Promise.all(
334
+ files.map(async (file) => ({
335
+ file,
336
+ content: await readFileContent(file)
337
+ }))
338
+ );
339
+ const graph = buildDependencyGraph(fileContents);
340
+ const circularDeps = detectCircularDependencies(graph);
341
+ const clusters = detectModuleClusters(graph);
342
+ const fragmentationMap = /* @__PURE__ */ new Map();
343
+ for (const cluster of clusters) {
344
+ for (const file of cluster.files) {
345
+ fragmentationMap.set(file, cluster.fragmentationScore);
346
+ }
347
+ }
348
+ const results = [];
349
+ for (const { file } of fileContents) {
350
+ const node = graph.nodes.get(file);
351
+ if (!node) continue;
352
+ const importDepth = focus === "depth" || focus === "all" ? calculateImportDepth(file, graph) : 0;
353
+ const dependencyList = focus === "depth" || focus === "all" ? getTransitiveDependencies(file, graph) : [];
354
+ const contextBudget = focus === "all" ? calculateContextBudget(file, graph) : node.tokenCost;
355
+ const cohesionScore = focus === "cohesion" || focus === "all" ? calculateCohesion(node.exports) : 1;
356
+ const fragmentationScore = fragmentationMap.get(file) || 0;
357
+ const relatedFiles = [];
358
+ for (const cluster of clusters) {
359
+ if (cluster.files.includes(file)) {
360
+ relatedFiles.push(...cluster.files.filter((f) => f !== file));
361
+ break;
362
+ }
363
+ }
364
+ const { severity, issues, recommendations, potentialSavings } = analyzeIssues({
365
+ file,
366
+ importDepth,
367
+ contextBudget,
368
+ cohesionScore,
369
+ fragmentationScore,
370
+ maxDepth,
371
+ maxContextBudget,
372
+ minCohesion,
373
+ maxFragmentation,
374
+ circularDeps
375
+ });
376
+ const domains = [
377
+ ...new Set(node.exports.map((e) => e.inferredDomain || "unknown"))
378
+ ];
379
+ results.push({
380
+ file,
381
+ tokenCost: node.tokenCost,
382
+ linesOfCode: node.linesOfCode,
383
+ importDepth,
384
+ dependencyCount: dependencyList.length,
385
+ dependencyList,
386
+ circularDeps: circularDeps.filter((cycle) => cycle.includes(file)),
387
+ cohesionScore,
388
+ domains,
389
+ exportCount: node.exports.length,
390
+ contextBudget,
391
+ fragmentationScore,
392
+ relatedFiles,
393
+ severity,
394
+ issues,
395
+ recommendations,
396
+ potentialSavings
397
+ });
398
+ }
399
+ return results.sort((a, b) => {
400
+ const severityOrder = { critical: 0, major: 1, minor: 2, info: 3 };
401
+ const severityDiff = severityOrder[a.severity] - severityOrder[b.severity];
402
+ if (severityDiff !== 0) return severityDiff;
403
+ return b.contextBudget - a.contextBudget;
404
+ });
405
+ }
406
+ function generateSummary(results) {
407
+ if (results.length === 0) {
408
+ return {
409
+ totalFiles: 0,
410
+ totalTokens: 0,
411
+ avgContextBudget: 0,
412
+ maxContextBudget: 0,
413
+ avgImportDepth: 0,
414
+ maxImportDepth: 0,
415
+ deepFiles: [],
416
+ avgFragmentation: 0,
417
+ fragmentedModules: [],
418
+ avgCohesion: 0,
419
+ lowCohesionFiles: [],
420
+ criticalIssues: 0,
421
+ majorIssues: 0,
422
+ minorIssues: 0,
423
+ totalPotentialSavings: 0,
424
+ topExpensiveFiles: []
425
+ };
426
+ }
427
+ const totalFiles = results.length;
428
+ const totalTokens = results.reduce((sum, r) => sum + r.tokenCost, 0);
429
+ const totalContextBudget = results.reduce(
430
+ (sum, r) => sum + r.contextBudget,
431
+ 0
432
+ );
433
+ const avgContextBudget = totalContextBudget / totalFiles;
434
+ const maxContextBudget = Math.max(...results.map((r) => r.contextBudget));
435
+ const avgImportDepth = results.reduce((sum, r) => sum + r.importDepth, 0) / totalFiles;
436
+ const maxImportDepth = Math.max(...results.map((r) => r.importDepth));
437
+ 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);
438
+ const avgFragmentation = results.reduce((sum, r) => sum + r.fragmentationScore, 0) / totalFiles;
439
+ const moduleMap = /* @__PURE__ */ new Map();
440
+ for (const result of results) {
441
+ for (const domain of result.domains) {
442
+ if (!moduleMap.has(domain)) {
443
+ moduleMap.set(domain, []);
444
+ }
445
+ moduleMap.get(domain).push(result);
446
+ }
447
+ }
448
+ const fragmentedModules = [];
449
+ for (const [domain, files] of moduleMap.entries()) {
450
+ if (files.length < 2) continue;
451
+ const fragmentationScore = files.reduce((sum, f) => sum + f.fragmentationScore, 0) / files.length;
452
+ if (fragmentationScore < 0.3) continue;
453
+ const totalTokens2 = files.reduce((sum, f) => sum + f.tokenCost, 0);
454
+ const avgCohesion2 = files.reduce((sum, f) => sum + f.cohesionScore, 0) / files.length;
455
+ const targetFiles = Math.max(1, Math.ceil(files.length / 3));
456
+ fragmentedModules.push({
457
+ domain,
458
+ files: files.map((f) => f.file),
459
+ totalTokens: totalTokens2,
460
+ fragmentationScore,
461
+ avgCohesion: avgCohesion2,
462
+ suggestedStructure: {
463
+ targetFiles,
464
+ consolidationPlan: [
465
+ `Consolidate ${files.length} ${domain} files into ${targetFiles} cohesive file(s)`,
466
+ `Current token cost: ${totalTokens2.toLocaleString()}`,
467
+ `Estimated savings: ${Math.floor(totalTokens2 * 0.3).toLocaleString()} tokens (30%)`
468
+ ]
469
+ }
470
+ });
471
+ }
472
+ fragmentedModules.sort((a, b) => b.fragmentationScore - a.fragmentationScore);
473
+ const avgCohesion = results.reduce((sum, r) => sum + r.cohesionScore, 0) / totalFiles;
474
+ const lowCohesionFiles = results.filter((r) => r.cohesionScore < 0.6).map((r) => ({ file: r.file, score: r.cohesionScore })).sort((a, b) => a.score - b.score).slice(0, 10);
475
+ const criticalIssues = results.filter((r) => r.severity === "critical").length;
476
+ const majorIssues = results.filter((r) => r.severity === "major").length;
477
+ const minorIssues = results.filter((r) => r.severity === "minor").length;
478
+ const totalPotentialSavings = results.reduce(
479
+ (sum, r) => sum + r.potentialSavings,
480
+ 0
481
+ );
482
+ const topExpensiveFiles = results.sort((a, b) => b.contextBudget - a.contextBudget).slice(0, 10).map((r) => ({
483
+ file: r.file,
484
+ contextBudget: r.contextBudget,
485
+ severity: r.severity
486
+ }));
487
+ return {
488
+ totalFiles,
489
+ totalTokens,
490
+ avgContextBudget,
491
+ maxContextBudget,
492
+ avgImportDepth,
493
+ maxImportDepth,
494
+ deepFiles,
495
+ avgFragmentation,
496
+ fragmentedModules: fragmentedModules.slice(0, 10),
497
+ avgCohesion,
498
+ lowCohesionFiles,
499
+ criticalIssues,
500
+ majorIssues,
501
+ minorIssues,
502
+ totalPotentialSavings,
503
+ topExpensiveFiles
504
+ };
505
+ }
506
+ function analyzeIssues(params) {
507
+ const {
508
+ file,
509
+ importDepth,
510
+ contextBudget,
511
+ cohesionScore,
512
+ fragmentationScore,
513
+ maxDepth,
514
+ maxContextBudget,
515
+ minCohesion,
516
+ maxFragmentation,
517
+ circularDeps
518
+ } = params;
519
+ const issues = [];
520
+ const recommendations = [];
521
+ let severity = "info";
522
+ let potentialSavings = 0;
523
+ if (circularDeps.length > 0) {
524
+ severity = "critical";
525
+ issues.push(
526
+ `Part of ${circularDeps.length} circular dependency chain(s)`
527
+ );
528
+ recommendations.push("Break circular dependencies by extracting interfaces or using dependency injection");
529
+ potentialSavings += contextBudget * 0.2;
530
+ }
531
+ if (importDepth > maxDepth * 1.5) {
532
+ severity = severity === "critical" ? "critical" : "critical";
533
+ issues.push(`Import depth ${importDepth} exceeds limit by 50%`);
534
+ recommendations.push("Flatten dependency tree or use facade pattern");
535
+ potentialSavings += contextBudget * 0.3;
536
+ } else if (importDepth > maxDepth) {
537
+ severity = severity === "critical" ? "critical" : "major";
538
+ issues.push(`Import depth ${importDepth} exceeds recommended maximum ${maxDepth}`);
539
+ recommendations.push("Consider reducing dependency depth");
540
+ potentialSavings += contextBudget * 0.15;
541
+ }
542
+ if (contextBudget > maxContextBudget * 1.5) {
543
+ severity = severity === "critical" ? "critical" : "critical";
544
+ issues.push(`Context budget ${contextBudget.toLocaleString()} tokens is 50% over limit`);
545
+ recommendations.push("Split into smaller modules or reduce dependency tree");
546
+ potentialSavings += contextBudget * 0.4;
547
+ } else if (contextBudget > maxContextBudget) {
548
+ severity = severity === "critical" || severity === "major" ? severity : "major";
549
+ issues.push(`Context budget ${contextBudget.toLocaleString()} exceeds ${maxContextBudget.toLocaleString()}`);
550
+ recommendations.push("Reduce file size or dependencies");
551
+ potentialSavings += contextBudget * 0.2;
552
+ }
553
+ if (cohesionScore < minCohesion * 0.5) {
554
+ severity = severity === "critical" ? "critical" : "major";
555
+ issues.push(`Very low cohesion (${(cohesionScore * 100).toFixed(0)}%) - mixed concerns`);
556
+ recommendations.push("Split file by domain - separate unrelated functionality");
557
+ potentialSavings += contextBudget * 0.25;
558
+ } else if (cohesionScore < minCohesion) {
559
+ severity = severity === "critical" || severity === "major" ? severity : "minor";
560
+ issues.push(`Low cohesion (${(cohesionScore * 100).toFixed(0)}%)`);
561
+ recommendations.push("Consider grouping related exports together");
562
+ potentialSavings += contextBudget * 0.1;
563
+ }
564
+ if (fragmentationScore > maxFragmentation) {
565
+ severity = severity === "critical" || severity === "major" ? severity : "minor";
566
+ issues.push(`High fragmentation (${(fragmentationScore * 100).toFixed(0)}%) - scattered implementation`);
567
+ recommendations.push("Consolidate with related files in same domain");
568
+ potentialSavings += contextBudget * 0.3;
569
+ }
570
+ if (issues.length === 0) {
571
+ issues.push("No significant issues detected");
572
+ recommendations.push("File is well-structured for AI context usage");
573
+ }
574
+ return { severity, issues, recommendations, potentialSavings: Math.floor(potentialSavings) };
575
+ }
576
+
577
+ export {
578
+ getSmartDefaults,
579
+ analyzeContext,
580
+ generateSummary
581
+ };
package/dist/cli.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  analyzeContext,
4
4
  generateSummary
5
- } from "./chunk-T6ZCOPPI.mjs";
5
+ } from "./chunk-5N5DCJOV.mjs";
6
6
 
7
7
  // src/cli.ts
8
8
  import { Command } from "commander";
package/dist/index.d.mts CHANGED
@@ -67,6 +67,10 @@ interface ContextSummary {
67
67
  }>;
68
68
  }
69
69
 
70
+ /**
71
+ * Generate smart defaults for context analysis based on repository size
72
+ */
73
+ declare function getSmartDefaults(directory: string, userOptions: Partial<ContextAnalyzerOptions>): Promise<ContextAnalyzerOptions>;
70
74
  /**
71
75
  * Analyze AI context window cost for a codebase
72
76
  */
@@ -76,4 +80,4 @@ declare function analyzeContext(options: ContextAnalyzerOptions): Promise<Contex
76
80
  */
77
81
  declare function generateSummary(results: ContextAnalysisResult[]): ContextSummary;
78
82
 
79
- export { type ContextAnalysisResult, type ContextAnalyzerOptions, type ContextSummary, type ModuleCluster, analyzeContext, generateSummary };
83
+ export { type ContextAnalysisResult, type ContextAnalyzerOptions, type ContextSummary, type ModuleCluster, analyzeContext, generateSummary, getSmartDefaults };
package/dist/index.d.ts CHANGED
@@ -67,6 +67,10 @@ interface ContextSummary {
67
67
  }>;
68
68
  }
69
69
 
70
+ /**
71
+ * Generate smart defaults for context analysis based on repository size
72
+ */
73
+ declare function getSmartDefaults(directory: string, userOptions: Partial<ContextAnalyzerOptions>): Promise<ContextAnalyzerOptions>;
70
74
  /**
71
75
  * Analyze AI context window cost for a codebase
72
76
  */
@@ -76,4 +80,4 @@ declare function analyzeContext(options: ContextAnalyzerOptions): Promise<Contex
76
80
  */
77
81
  declare function generateSummary(results: ContextAnalysisResult[]): ContextSummary;
78
82
 
79
- export { type ContextAnalysisResult, type ContextAnalyzerOptions, type ContextSummary, type ModuleCluster, analyzeContext, generateSummary };
83
+ export { type ContextAnalysisResult, type ContextAnalyzerOptions, type ContextSummary, type ModuleCluster, analyzeContext, generateSummary, getSmartDefaults };
package/dist/index.js CHANGED
@@ -21,7 +21,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  analyzeContext: () => analyzeContext,
24
- generateSummary: () => generateSummary
24
+ generateSummary: () => generateSummary,
25
+ getSmartDefaults: () => getSmartDefaults
25
26
  });
26
27
  module.exports = __toCommonJS(index_exports);
27
28
  var import_core2 = require("@aiready/core");
@@ -299,6 +300,50 @@ function generateConsolidationPlan(domain, files, targetFiles) {
299
300
  }
300
301
 
301
302
  // src/index.ts
303
+ async function getSmartDefaults(directory, userOptions) {
304
+ const files = await (0, import_core2.scanFiles)({
305
+ rootDir: directory,
306
+ include: userOptions.include,
307
+ exclude: userOptions.exclude
308
+ });
309
+ const estimatedBlocks = files.length;
310
+ let maxDepth;
311
+ let maxContextBudget;
312
+ let minCohesion;
313
+ let maxFragmentation;
314
+ if (estimatedBlocks < 100) {
315
+ maxDepth = 3;
316
+ maxContextBudget = 5e3;
317
+ minCohesion = 0.7;
318
+ maxFragmentation = 0.3;
319
+ } else if (estimatedBlocks < 500) {
320
+ maxDepth = 4;
321
+ maxContextBudget = 8e3;
322
+ minCohesion = 0.65;
323
+ maxFragmentation = 0.4;
324
+ } else if (estimatedBlocks < 2e3) {
325
+ maxDepth = 5;
326
+ maxContextBudget = 12e3;
327
+ minCohesion = 0.6;
328
+ maxFragmentation = 0.5;
329
+ } else {
330
+ maxDepth = 6;
331
+ maxContextBudget = 2e4;
332
+ minCohesion = 0.55;
333
+ maxFragmentation = 0.6;
334
+ }
335
+ return {
336
+ maxDepth,
337
+ maxContextBudget,
338
+ minCohesion,
339
+ maxFragmentation,
340
+ focus: "all",
341
+ includeNodeModules: false,
342
+ rootDir: userOptions.rootDir || directory,
343
+ include: userOptions.include,
344
+ exclude: userOptions.exclude
345
+ };
346
+ }
302
347
  async function analyzeContext(options) {
303
348
  const {
304
349
  maxDepth = 5,
@@ -559,5 +604,6 @@ function analyzeIssues(params) {
559
604
  // Annotate the CommonJS export names for ESM import in node:
560
605
  0 && (module.exports = {
561
606
  analyzeContext,
562
- generateSummary
607
+ generateSummary,
608
+ getSmartDefaults
563
609
  });
package/dist/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  import {
2
2
  analyzeContext,
3
- generateSummary
4
- } from "./chunk-T6ZCOPPI.mjs";
3
+ generateSummary,
4
+ getSmartDefaults
5
+ } from "./chunk-5N5DCJOV.mjs";
5
6
  export {
6
7
  analyzeContext,
7
- generateSummary
8
+ generateSummary,
9
+ getSmartDefaults
8
10
  };