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 | 21x 21x 21x 21x 21x 21x 21x 21x 21x 17x 4x 4x 4x 17x 7x 7x 3x 7x 7x 17x 2x 2x 2x 2x 21x 7x 7x 25x 25x 7x 7x 7x 21x 21x 21x 147x 21x 7x 7x 7x 7x 7x 7x 4x 7x 6x 6x 7x 3x 7x | import {
scanFiles,
calculateTestabilityIndex,
Severity,
IssueType,
runBatchAnalysis,
getParser,
isTestFile,
detectTestFramework,
} from '@aiready/core';
import { readFileSync } from 'fs';
import type {
TestabilityOptions,
TestabilityIssue,
TestabilityReport,
} from './types';
// ---------------------------------------------------------------------------
// Per-file analysis
// ---------------------------------------------------------------------------
interface FileAnalysis {
pureFunctions: number;
totalFunctions: number;
injectionPatterns: number;
totalClasses: number;
bloatedInterfaces: number;
totalInterfaces: number;
externalStateMutations: number;
}
async function analyzeFileTestability(filePath: string): Promise<FileAnalysis> {
const result: FileAnalysis = {
pureFunctions: 0,
totalFunctions: 0,
injectionPatterns: 0,
totalClasses: 0,
bloatedInterfaces: 0,
totalInterfaces: 0,
externalStateMutations: 0,
};
const parser = await getParser(filePath);
Iif (!parser) return result;
let code: string;
try {
code = readFileSync(filePath, 'utf-8');
} catch {
return result;
}
try {
await parser.initialize();
const parseResult = parser.parse(code, filePath);
for (const exp of parseResult.exports) {
if (exp.type === 'function') {
result.totalFunctions++;
Eif (exp.isPure) result.pureFunctions++;
Iif (exp.hasSideEffects) result.externalStateMutations++;
}
if (exp.type === 'class') {
result.totalClasses++;
// Generalized DI heuristic: constructor/initializer with parameters
if (exp.parameters && exp.parameters.length > 0) {
result.injectionPatterns++;
}
// Heuristic: bloated classes
const total = (exp.methodCount || 0) + (exp.propertyCount || 0);
Iif (total > 10) {
result.bloatedInterfaces++;
}
}
if (exp.type === 'interface') {
result.totalInterfaces++;
// Heuristic: interfaces with many methods/props are considered bloated
const total = (exp.methodCount || 0) + (exp.propertyCount || 0);
Eif (total > 10) {
result.bloatedInterfaces++;
}
}
}
} catch (error) {
console.warn(`Testability: Failed to parse ${filePath}: ${error}`);
}
return result;
}
// Main analyzer
// ---------------------------------------------------------------------------
export async function analyzeTestability(
options: TestabilityOptions
): Promise<TestabilityReport> {
// Use core scanFiles which respects .gitignore recursively
const allFiles = await scanFiles({
...options,
include: options.include || ['**/*.{ts,tsx,js,jsx,py,java,cs,go}'],
includeTests: true,
});
const sourceFiles = allFiles.filter(
(f) => !isTestFile(f, options.testPatterns)
);
const testFiles = allFiles.filter((f) => isTestFile(f, options.testPatterns));
const aggregated: FileAnalysis = {
pureFunctions: 0,
totalFunctions: 0,
injectionPatterns: 0,
totalClasses: 0,
bloatedInterfaces: 0,
totalInterfaces: 0,
externalStateMutations: 0,
};
// Collect file-level details for smarter scoring
const fileDetails: Array<{
filePath: string;
pureFunctions: number;
totalFunctions: number;
}> = [];
await runBatchAnalysis(
sourceFiles,
'analyzing files',
'testability',
options.onProgress,
async (f: string) => ({
filePath: f,
analysis: await analyzeFileTestability(f),
}),
(result: { filePath: string; analysis: FileAnalysis }) => {
const a = result.analysis;
for (const key of Object.keys(aggregated) as Array<keyof FileAnalysis>) {
aggregated[key] += a[key];
}
// Collect file-level data
fileDetails.push({
filePath: result.filePath,
pureFunctions: a.pureFunctions,
totalFunctions: a.totalFunctions,
});
}
);
const hasTestFramework = detectTestFramework(options.rootDir);
const indexResult = calculateTestabilityIndex({
testFiles: testFiles.length,
sourceFiles: sourceFiles.length,
pureFunctions: aggregated.pureFunctions,
totalFunctions: Math.max(1, aggregated.totalFunctions),
injectionPatterns: aggregated.injectionPatterns,
totalClasses: Math.max(1, aggregated.totalClasses),
bloatedInterfaces: aggregated.bloatedInterfaces,
totalInterfaces: Math.max(1, aggregated.totalInterfaces),
externalStateMutations: aggregated.externalStateMutations,
hasTestFramework,
fileDetails,
});
// Build issues
const issues: TestabilityIssue[] = [];
const minCoverage = options.minCoverageRatio ?? 0.3;
const actualRatio =
sourceFiles.length > 0 ? testFiles.length / sourceFiles.length : 0;
if (!hasTestFramework) {
issues.push({
type: IssueType.LowTestability,
dimension: 'framework',
severity: Severity.Critical,
message:
'No major testing framework detected — AI changes cannot be safely verified.',
location: { file: options.rootDir, line: 0 },
suggestion:
'Add a testing framework (e.g., Jest, Pytest, JUnit) to enable automated verification.',
});
}
if (actualRatio < minCoverage) {
const needed =
Math.ceil(sourceFiles.length * minCoverage) - testFiles.length;
issues.push({
type: IssueType.LowTestability,
dimension: 'test-coverage',
severity: actualRatio === 0 ? Severity.Critical : Severity.Major,
message: `Test ratio is ${Math.round(actualRatio * 100)}% (${testFiles.length} test files for ${sourceFiles.length} source files). Need at least ${Math.round(minCoverage * 100)}%.`,
location: { file: options.rootDir, line: 0 },
suggestion: `Add ~${needed} test file(s) to reach the ${Math.round(minCoverage * 100)}% minimum for safe AI assistance.`,
});
}
if (indexResult.dimensions.purityScore < 50) {
issues.push({
type: IssueType.LowTestability,
dimension: 'purity',
severity: Severity.Major,
message: `Only ${indexResult.dimensions.purityScore}% of functions appear pure — side-effectful code is harder for AI to verify safely.`,
location: { file: options.rootDir, line: 0 },
suggestion:
'Refactor complex side-effectful logic into pure functions where possible.',
});
}
return {
summary: {
sourceFiles: sourceFiles.length,
testFiles: testFiles.length,
coverageRatio: Math.round(actualRatio * 100) / 100,
score: indexResult.score,
rating: indexResult.rating,
aiChangeSafetyRating: indexResult.aiChangeSafetyRating,
dimensions: indexResult.dimensions,
},
issues,
rawData: {
sourceFiles: sourceFiles.length,
testFiles: testFiles.length,
...aggregated,
hasTestFramework,
},
recommendations: indexResult.recommendations,
};
}
|