# All files / src/analyzers python-context.ts

75.58% Statements 65/86
38.46% Branches 10/26
88.88% Functions 8/9
75% Lines 60/80

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

    5x
    5x

    5x
    1x
    1x

    6x

    4x
    4x

    4x

    4x
    4x
    4x
    4x

    6x

    6x

    4x
    4x

    4x

    4x
    4x

    4x

    3x

    4x

    4x
    4x

    4x

    4x
    4x
    4x
    4x

    4x

    4x
    6x
    6x

    4x

    4x

    12x

    12x
    6x
    6x
    6x
    6x
    6x

    6x
    6x

    6x
    6x

    6x
    12x

    6x
    6x

    6x
    12x

    12x

    1x
    1x

    1x
    1x

    1x

    1x

     /**
     * Python Context Analyzer
     *
     * Analyzes Python code for:
     * - Import chain depth
     * - Context budget (tokens needed)
     * - Module cohesion
     * - Import fragmentation
     */

    import { getParser, estimateTokens } from '@aiready/core';
    import { resolve, relative, dirname, join } from 'path';
    import fs from 'fs';
    import {
      calculateImportDepthFromEdges,
      detectGraphCyclesFromFile,
    } from '../utils/dependency-graph-utils';

    export interface PythonContextMetrics {
      file: string;
      importDepth: number;
      contextBudget: number; // Total tokens needed (file + dependencies)
      cohesion: number; // 0-1, higher is better
      imports: PythonImportInfo[];
      exports: PythonExportInfo[];
      metrics: {
        linesOfCode: number;
        importCount: number;
        exportCount: number;
        circularDependencies: string[];
      };
    }

    export interface PythonImportInfo {
      source: string;
      specifiers: string[];
      isRelative: boolean;
      resolvedPath?: string;
    }

    export interface PythonExportInfo {
      name: string;
      type: string;
    }

    /**
     * Analyze Python files for context metrics
     */
    export async function analyzePythonContext(
      files: string[],
      rootDir: string
    ): Promise<PythonContextMetrics[]> {
      const results: PythonContextMetrics[] = [];
      const parser = await getParser('dummy.py');

      if (!parser) {
        console.warn('Python parser not available');
        return results;
      }

      const pythonFiles = files.filter((f) => f.toLowerCase().endsWith('.py'));

      // Some path helpers are imported for future use; reference them to avoid lint warnings
      void relative;
      void join;

      // Build dependency graph first
      const dependencyGraph = await buildPythonDependencyGraph(
        pythonFiles,
        rootDir
      );

      for (const file of pythonFiles) {
        try {
          const code = await fs.promises.readFile(file, 'utf-8');
          const result = parser.parse(code, file);

          const imports: PythonImportInfo[] = result.imports.map((imp) => ({
            source: imp.source,
            specifiers: imp.specifiers,
            isRelative: imp.source.startsWith('.'),
            resolvedPath: resolvePythonImport(file, imp.source, rootDir),
          }));

          const exports: PythonExportInfo[] = result.exports.map((exp) => ({
            name: exp.name,
            type: exp.type,
          }));

          // Calculate metrics
          const linesOfCode = code.split('\n').length;
          const importDepth = calculateImportDepthFromEdges(
            file,
            dependencyGraph,
            new Set()
          );
          const contextBudget = estimateContextBudget(
            code,
            imports,
            dependencyGraph
          );
          const cohesion = calculatePythonCohesion(exports, imports);
          const circularDependencies = detectGraphCyclesFromFile(
            file,
            dependencyGraph
          ).map((cycle) => cycle.join(' -> '));

          results.push({
            file,
            importDepth,
            contextBudget,
            cohesion,
            imports,
            exports,
            metrics: {
              linesOfCode,
              importCount: imports.length,
              exportCount: exports.length,
              circularDependencies,
            },
          });
        } catch (error) {
          console.warn(`Failed to analyze ${file}:`, error);
        }
      }

      return results;
    }

    /**
     * Build dependency graph for Python files
     */
    async function buildPythonDependencyGraph(
      files: string[],
      rootDir: string
    ): Promise<Map<string, Set<string>>> {
      const graph = new Map<string, Set<string>>();
      const parser = await getParser('dummy.py');

      Iif (!parser) return graph;

      for (const file of files) {
        try {
          const code = await fs.promises.readFile(file, 'utf-8');
          const result = parser.parse(code, file);

          const dependencies = new Set<string>();

          for (const imp of result.imports) {
            const resolved = resolvePythonImport(file, imp.source, rootDir);
            Iif (resolved && files.includes(resolved)) {
              dependencies.add(resolved);
            }
          }

          graph.set(file, dependencies);
        } catch (error) {
          void error;
          // Skip files with errors
        }
      }

      return graph;
    }

    /**
     * Resolve Python import to file path
     */
    function resolvePythonImport(
      fromFile: string,
      importPath: string,
      rootDir: string
    ): string | undefined {
      const dir = dirname(fromFile);

      // Handle relative imports
      if (importPath.startsWith('.')) {
        const parts = importPath.split('.');
        let upCount = 0;
        while (parts[0] === '') {
          upCount++;
          parts.shift();
        }

        let targetDir = dir;
        for (let i = 0; i < upCount - 1; i++) {
          targetDir = dirname(targetDir);
        }

        const modulePath = parts.join('/');
        const possiblePaths = [
          resolve(targetDir, `${modulePath}.py`),
          resolve(targetDir, modulePath, '__init__.py'),
        ];

        for (const path of possiblePaths) {
          Iif (fs.existsSync(path)) {
            return path;
          }
        }
      } else {
        // Handle absolute imports (from project root)
        const modulePath = importPath.replace(/\./g, '/');
        const possiblePaths = [
          resolve(rootDir, `${modulePath}.py`),
          resolve(rootDir, modulePath, '__init__.py'),
        ];

        for (const path of possiblePaths) {
          Iif (fs.existsSync(path)) {
            return path;
          }
        }
      }

      return undefined;
    }

    /**
     * Estimate context budget (tokens needed for file + direct deps)
     */
    function estimateContextBudget(
      code: string,
      imports: PythonImportInfo[],
      dependencyGraph: Map<string, Set<string>>
    ): number {
      // File tokens
      void dependencyGraph;
      let budget = estimateTokens(code);

      // Add tokens for direct dependencies (simplified)
      // In a full implementation, we'd load each dependency file
      const avgTokensPerDep = 500; // Conservative estimate
      budget += imports.length * avgTokensPerDep;

      return budget;
    }

    /**
     * Calculate cohesion for a Python module
     *
     * Cohesion = How related are the exports to each other?
     * Higher cohesion = better (single responsibility)
     */
    function calculatePythonCohesion(
      exports: PythonExportInfo[],
      imports: PythonImportInfo[]
    ): number {
      Eif (exports.length === 0) return 1;

      // Simple heuristic: files with many exports but few imports are less cohesive
      const exportCount = exports.length;
      const importCount = imports.length;

      // Ideal: 1-5 exports per module
      let cohesion = 1;

      if (exportCount > 10) {
        cohesion *= 0.6; // Too many exports = God module
      } else if (exportCount > 5) {
        cohesion *= 0.8;
      }

      // High import-to-export ratio suggests focused module
      if (exportCount > 0) {
        const ratio = importCount / exportCount;
        if (ratio > 2) {
          cohesion *= 1.1; // Good: imports more than it exports
        } else if (ratio < 0.5) {
          cohesion *= 0.9; // Bad: exports more than it imports
        }
      }

      return Math.min(1, Math.max(0, cohesion));
    }