All files / dist index.mjs

18.75% Statements 21/112
0% Branches 0/75
0% Functions 0/12
19.62% Lines 21/107

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438                                                                                                                                                      1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                                                                                                                                                       1x                                                                                                                                                                                                                                             1x                                                                                                                          
import {
  BARREL_EXPORT_MIN_EXPORTS,
  BARREL_EXPORT_TOKEN_LIMIT,
  CONFIG_NAME_PATTERNS,
  Classification,
  EMAIL_NAME_PATTERNS,
  HANDLER_NAME_PATTERNS,
  NEXTJS_METADATA_EXPORTS,
  PARSER_NAME_PATTERNS,
  SERVICE_NAME_PATTERNS,
  SESSION_NAME_PATTERNS,
  adjustCohesionForClassification,
  adjustFragmentationForClassification,
  analyzeContext,
  buildCoUsageMatrix,
  buildDependencyGraph,
  buildTypeGraph,
  calculateCohesion,
  calculateContextBudget,
  calculateDirectoryDistance,
  calculateDomainConfidence,
  calculateEnhancedCohesion,
  calculateFragmentation,
  calculateImportDepth,
  calculatePathEntropy,
  calculateStructuralCohesionFromCoUsage,
  classifyFile,
  detectCircularDependencies,
  detectModuleClusters,
  displayConsoleReport,
  extractDomainKeywordsFromPaths,
  extractExports,
  findSemanticClusters,
  generateHTMLReport,
  generateSummary,
  getClassificationRecommendations,
  getCoUsageData,
  getGeneralRecommendations,
  getTransitiveDependencies,
  inferDomain,
  inferDomainFromSemantics,
  isBarrelExport,
  isBoilerplateBarrel,
  isConfigFile,
  isEmailTemplate,
  isHubAndSpokeFile,
  isLambdaHandler,
  isNextJsPage,
  isParserFile,
  isServiceFile,
  isSessionFile,
  isTypeDefinition,
  isUtilityModule,
  runInteractiveSetup
} from "./chunk-J3MUOWHC.mjs";
import "./chunk-64U3PNO3.mjs";
 
// src/index.ts
import { ToolRegistry } from "@aiready/core";
 
// src/provider.ts
import {
  ToolName as ToolName2,
  IssueType,
  SpokeOutputSchema
} from "@aiready/core";
 
// src/scoring.ts
import {
  calculateMonthlyCost,
  calculateProductivityImpact,
  DEFAULT_COST_CONFIG,
  ToolName,
  getRatingSlug
} from "@aiready/core";
var BUDGET_EXCELLENT_THRESHOLD = 8e3;
var BUDGET_PENALTY_RATE = 200;
var DEPTH_EXCELLENT_THRESHOLD = 8;
var DEPTH_PENALTY_WEIGHT = 5;
var FRAGMENTATION_EXCELLENT_THRESHOLD = 0.5;
var FRAGMENTATION_PENALTY_WEIGHT = 100;
var MAX_CRITICAL_PENALTY = 20;
var CRITICAL_ISSUE_WEIGHT = 3;
var MAX_MAJOR_PENALTY = 15;
var MAJOR_ISSUE_WEIGHT = 1;
var EXTREME_FILE_THRESHOLD = 15e3;
var MAX_EXTREME_PENALTY = 20;
var EXTREME_PENALTY_DIVISOR = 500;
var FRAGMENTATION_BONUS_THRESHOLD = 0.2;
var ORGANIZATION_BONUS = 5;
var MAX_TOTAL_PENALTY = 30;
var WEIGHT_BUDGET = 0.35;
var WEIGHT_DEPTH = 0.25;
var WEIGHT_FRAGMENTATION = 0.25;
function calculateContextScore(summary, costConfig) {
  const {
    avgContextBudget,
    maxContextBudget,
    avgImportDepth,
    maxImportDepth,
    avgFragmentation,
    criticalIssues,
    majorIssues,
    totalFiles
  } = summary;
  const budgetScore = avgContextBudget < BUDGET_EXCELLENT_THRESHOLD ? 100 : Math.max(
    0,
    100 - (avgContextBudget - BUDGET_EXCELLENT_THRESHOLD) / BUDGET_PENALTY_RATE
  );
  const depthScore = avgImportDepth < DEPTH_EXCELLENT_THRESHOLD ? 100 : Math.max(
    0,
    100 - (avgImportDepth - DEPTH_EXCELLENT_THRESHOLD) * DEPTH_PENALTY_WEIGHT
  );
  const fragmentationScore = avgFragmentation < FRAGMENTATION_EXCELLENT_THRESHOLD ? 100 : Math.max(
    0,
    100 - (avgFragmentation - FRAGMENTATION_EXCELLENT_THRESHOLD) * FRAGMENTATION_PENALTY_WEIGHT
  );
  const criticalPenalty = Math.min(
    MAX_CRITICAL_PENALTY,
    criticalIssues * CRITICAL_ISSUE_WEIGHT
  );
  const majorPenalty = Math.min(
    MAX_MAJOR_PENALTY,
    majorIssues * MAJOR_ISSUE_WEIGHT
  );
  const maxBudgetPenalty = maxContextBudget > EXTREME_FILE_THRESHOLD ? Math.min(
    MAX_EXTREME_PENALTY,
    (maxContextBudget - EXTREME_FILE_THRESHOLD) / EXTREME_PENALTY_DIVISOR
  ) : 0;
  let bonus = 0;
  if (criticalIssues === 0 && majorIssues === 0 && avgFragmentation < FRAGMENTATION_BONUS_THRESHOLD) {
    bonus = ORGANIZATION_BONUS;
  }
  const rawScore = budgetScore * WEIGHT_BUDGET + depthScore * WEIGHT_DEPTH + fragmentationScore * WEIGHT_FRAGMENTATION + bonus;
  const finalScore = rawScore - Math.min(MAX_TOTAL_PENALTY, criticalPenalty + majorPenalty) - maxBudgetPenalty;
  const score = Math.max(0, Math.min(100, Math.round(finalScore)));
  const factors = [
    {
      name: "Context Budget",
      impact: Math.round(budgetScore * WEIGHT_BUDGET - WEIGHT_BUDGET * 100),
      description: `Avg ${Math.round(avgContextBudget)} tokens per file ${avgContextBudget < BUDGET_EXCELLENT_THRESHOLD ? "(excellent)" : avgContextBudget < 12e3 ? "(acceptable)" : "(high)"}`
    },
    {
      name: "Import Depth",
      impact: Math.round(depthScore * WEIGHT_DEPTH - WEIGHT_DEPTH * 100),
      description: `Avg ${avgImportDepth.toFixed(1)} levels ${avgImportDepth < DEPTH_EXCELLENT_THRESHOLD ? "(excellent)" : avgImportDepth < 12 ? "(acceptable)" : "(deep)"}`
    },
    {
      name: "Fragmentation",
      impact: Math.round(
        fragmentationScore * WEIGHT_FRAGMENTATION - WEIGHT_FRAGMENTATION * 100
      ),
      description: `${(avgFragmentation * 100).toFixed(0)}% fragmentation ${avgFragmentation < 0.3 ? "(well-organized)" : avgFragmentation < 0.5 ? "(moderate)" : "(high)"}`
    }
  ];
  if (bonus > 0) {
    factors.push({
      name: "Well-Organized Codebase",
      impact: bonus,
      description: "No critical/major issues and low fragmentation"
    });
  }
  if (criticalIssues > 0) {
    factors.push({
      name: "Critical Issues",
      impact: -criticalPenalty,
      description: `${criticalIssues} critical context issue${criticalIssues > 1 ? "s" : ""}`
    });
  }
  if (majorIssues > 0) {
    factors.push({
      name: "Major Issues",
      impact: -majorPenalty,
      description: `${majorIssues} major context issue${majorIssues > 1 ? "s" : ""}`
    });
  }
  if (maxBudgetPenalty > 0) {
    factors.push({
      name: "Extreme File Detected",
      impact: -Math.round(maxBudgetPenalty),
      description: `One file requires ${Math.round(maxContextBudget)} tokens (very high)`
    });
  }
  const recommendations = [];
  if (avgContextBudget > 12e3) {
    const estimatedImpact = Math.min(
      15,
      Math.round((avgContextBudget - 12e3) / 1e3)
    );
    recommendations.push({
      action: "Reduce file dependencies to lower context requirements",
      estimatedImpact,
      priority: "high"
    });
  }
  if (avgImportDepth > 10) {
    const estimatedImpact = Math.min(
      10,
      Math.round((avgImportDepth - 10) * 1.5)
    );
    recommendations.push({
      action: "Flatten import chains to reduce depth",
      estimatedImpact,
      priority: avgImportDepth > 15 ? "high" : "medium"
    });
  }
  if (avgFragmentation > 0.5) {
    const estimatedImpact = Math.min(
      12,
      Math.round((avgFragmentation - 0.5) * 40)
    );
    recommendations.push({
      action: "Consolidate related code into cohesive modules",
      estimatedImpact,
      priority: "medium"
    });
  }
  if (maxContextBudget > 2e4) {
    recommendations.push({
      action: `Split large file (${Math.round(maxContextBudget)} tokens) into smaller modules`,
      estimatedImpact: 8,
      priority: "high"
    });
  }
  const cfg = { ...DEFAULT_COST_CONFIG, ...costConfig };
  const estimatedMonthlyCost = calculateMonthlyCost(
    avgContextBudget * (totalFiles || 1),
    cfg
  );
  const issues = [
    ...Array(criticalIssues).fill({ severity: "critical" }),
    ...Array(majorIssues).fill({ severity: "major" })
  ];
  const productivityImpact = calculateProductivityImpact(issues);
  return {
    toolName: ToolName.ContextAnalyzer,
    score,
    rawMetrics: {
      avgContextBudget: Math.round(avgContextBudget),
      maxContextBudget: Math.round(maxContextBudget),
      avgImportDepth: Math.round(avgImportDepth * 10) / 10,
      maxImportDepth,
      avgFragmentation: Math.round(avgFragmentation * 100) / 100,
      criticalIssues,
      majorIssues,
      estimatedMonthlyCost,
      estimatedDeveloperHours: productivityImpact.totalHours
    },
    factors,
    recommendations
  };
}
function mapScoreToRating(score) {
  return getRatingSlug(score).replace("-", " ");
}
 
// src/provider.ts
var ContextAnalyzerProvider = {
  id: ToolName2.ContextAnalyzer,
  alias: ["context", "fragmentation", "budget"],
  async analyze(options) {
    const results = await analyzeContext(options);
    const summary = generateSummary(results, options);
    const normalizedResults = results.map(
      (r) => ({
        fileName: r.file,
        issues: r.issues.map((msg) => ({
          type: IssueType.ContextFragmentation,
          severity: r.severity,
          message: msg,
          location: { file: r.file, line: 1 },
          suggestion: r.recommendations[0]
        })),
        metrics: {
          tokenCost: r.tokenCost,
          complexityScore: r.importDepth
          // Map other context-specific metrics if needed
        }
      })
    );
    return SpokeOutputSchema.parse({
      results: normalizedResults,
      summary: {
        ...summary
      },
      metadata: {
        toolName: ToolName2.ContextAnalyzer,
        version: "0.17.5",
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      }
    });
  },
  score(output, options) {
    const summary = output.summary;
    return calculateContextScore(summary, options.costConfig);
  },
  defaultWeight: 19
};
 
// src/defaults.ts
import { scanFiles } from "@aiready/core";
async function getSmartDefaults(directory, userOptions) {
  const files = await scanFiles({
    rootDir: directory,
    include: userOptions.include,
    exclude: userOptions.exclude
  });
  const estimatedBlocks = files.length;
  let maxDepth;
  let maxContextBudget;
  let minCohesion;
  let maxFragmentation;
  if (estimatedBlocks < 100) {
    maxDepth = 5;
    maxContextBudget = 8e3;
    minCohesion = 0.5;
    maxFragmentation = 0.5;
  } else if (estimatedBlocks < 500) {
    maxDepth = 6;
    maxContextBudget = 15e3;
    minCohesion = 0.45;
    maxFragmentation = 0.6;
  } else if (estimatedBlocks < 2e3) {
    maxDepth = 8;
    maxContextBudget = 25e3;
    minCohesion = 0.4;
    maxFragmentation = 0.7;
  } else {
    maxDepth = 12;
    maxContextBudget = 4e4;
    minCohesion = 0.35;
    maxFragmentation = 0.8;
  }
  return {
    maxDepth,
    maxContextBudget,
    minCohesion,
    maxFragmentation,
    focus: "all",
    includeNodeModules: false,
    rootDir: userOptions.rootDir || directory,
    include: userOptions.include,
    exclude: userOptions.exclude
  };
}
 
// src/semantic/consolidation.ts
function findConsolidationCandidates(graph, coUsageMatrix, typeGraph, minCoUsage = 5, minSharedTypes = 2) {
  const candidates = [];
  for (const [fileA, coUsages] of coUsageMatrix) {
    const nodeA = graph.nodes.get(fileA);
    if (!nodeA) continue;
    for (const [fileB, count] of coUsages) {
      if (fileB <= fileA || count < minCoUsage) continue;
      const nodeB = graph.nodes.get(fileB);
      if (!nodeB) continue;
      const typesA = new Set(
        nodeA.exports.flatMap((e) => e.typeReferences || [])
      );
      const typesB = new Set(
        nodeB.exports.flatMap((e) => e.typeReferences || [])
      );
      const sharedTypes = Array.from(typesA).filter((t) => typesB.has(t));
      if (sharedTypes.length >= minSharedTypes || count >= minCoUsage * 2) {
        candidates.push({
          files: [fileA, fileB],
          reason: `High co-usage (${count}x)`,
          strength: count / 10
        });
      }
    }
  }
  return candidates.sort((a, b) => b.strength - a.strength);
}
 
// src/index.ts
ToolRegistry.register(ContextAnalyzerProvider);
export {
  BARREL_EXPORT_MIN_EXPORTS,
  BARREL_EXPORT_TOKEN_LIMIT,
  CONFIG_NAME_PATTERNS,
  Classification,
  ContextAnalyzerProvider,
  EMAIL_NAME_PATTERNS,
  HANDLER_NAME_PATTERNS,
  NEXTJS_METADATA_EXPORTS,
  PARSER_NAME_PATTERNS,
  SERVICE_NAME_PATTERNS,
  SESSION_NAME_PATTERNS,
  adjustCohesionForClassification,
  adjustFragmentationForClassification,
  analyzeContext,
  buildCoUsageMatrix,
  buildDependencyGraph,
  buildTypeGraph,
  calculateCohesion,
  calculateContextBudget,
  calculateContextScore,
  calculateDirectoryDistance,
  calculateDomainConfidence,
  calculateEnhancedCohesion,
  calculateFragmentation,
  calculateImportDepth,
  calculatePathEntropy,
  calculateStructuralCohesionFromCoUsage,
  classifyFile,
  detectCircularDependencies,
  detectModuleClusters,
  displayConsoleReport,
  extractDomainKeywordsFromPaths,
  extractExports,
  findConsolidationCandidates,
  findSemanticClusters,
  generateHTMLReport,
  generateSummary,
  getClassificationRecommendations,
  getCoUsageData,
  getGeneralRecommendations,
  getSmartDefaults,
  getTransitiveDependencies,
  inferDomain,
  inferDomainFromSemantics,
  isBarrelExport,
  isBoilerplateBarrel,
  isConfigFile,
  isEmailTemplate,
  isHubAndSpokeFile,
  isLambdaHandler,
  isNextJsPage,
  isParserFile,
  isServiceFile,
  isSessionFile,
  isTypeDefinition,
  isUtilityModule,
  mapScoreToRating,
  runInteractiveSetup
};