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 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | 3x 3x 3x 60x 9x 5x 5x 5x 9x 9x 2x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 8x 8x 8x 7x 7x 8x 8x 1x 1x 1x 1x 1x 8x 7x 7x 6x 1x 1x 7x 7x 7x 7x 267x 267x 267x 267x 267x 23x 5x 5x 18x 5x 5x 267x 267x 267x 17x 19x 17x 2x 2x 267x 267x 267x 14x 5x 5x 267x 267x 267x 23x 23x 267x 267x 1680x 1146x 1146x 330x 179x 109x 151x 151x 267x 23x 7x 7x 7x 2x 2x 7x 2x | /**
* Language-agnostic scanner for AI signal clarity signals.
*
* Detects code patterns that empirically cause AI models to generate
* incorrect code across all supported languages (TS, Python, Java, C#, Go).
*/
import { readFileSync } from 'fs';
import { getParser, Severity, IssueType, Language } from '@aiready/core';
import type {
AiSignalClarityIssue,
FileAiSignalClarityResult,
AiSignalClarityOptions,
} from './types';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const AMBIGUOUS_NAME_PATTERNS = [
/^[a-z]$/, // single letter: a, b, x, y
/^(tmp|temp|data|obj|val|res|ret|result|item|elem|thing|stuff|info|misc|util|helper|handler|cb|fn|func)$/i,
/^[a-z]\d+$/, // x1, x2, n3
];
const MAGIC_LITERAL_IGNORE = new Set([0, 1, -1, 2, 10, 100, 1000, 1024]);
const MAGIC_STRING_IGNORE = new Set([
'',
' ',
'\n',
'\t',
'utf8',
'utf-8',
'hex',
'base64',
'true',
'false',
'null',
]);
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function isAmbiguousName(name: string): boolean {
return AMBIGUOUS_NAME_PATTERNS.some((p) => p.test(name));
}
function isMagicNumber(value: number): boolean {
return !MAGIC_LITERAL_IGNORE.has(value);
}
function isMagicString(value: string): boolean {
Iif (value.length === 0) return false;
Iif (MAGIC_STRING_IGNORE.has(value)) return false;
// Allow URL-like strings, CSS values — focus on short opaque strings
return value.length <= 20 && !/[/.]/.test(value) && !/^\s+$/.test(value);
}
// ---------------------------------------------------------------------------
// Main scanner
// ---------------------------------------------------------------------------
export async function scanFile(
filePath: string,
options: AiSignalClarityOptions = { rootDir: '.' }
): Promise<FileAiSignalClarityResult> {
let code: string;
try {
code = readFileSync(filePath, 'utf-8');
} catch {
return emptyResult(filePath);
}
const parser = getParser(filePath);
Iif (!parser) return emptyResult(filePath);
try {
await parser.initialize();
const result = parser.parse(code, filePath);
const ast = await parser.getAST(code, filePath);
const issues: AiSignalClarityIssue[] = [];
const signals = {
magicLiterals: 0,
booleanTraps: 0,
ambiguousNames: 0,
undocumentedExports: 0,
implicitSideEffects: 0,
deepCallbacks: 0,
overloadedSymbols: 0,
totalSymbols: result.exports.length + result.imports.length,
totalExports: result.exports.length,
};
// Symbol tracking for overloading detection
const symbolCounts = new Map<string, number>();
// 1. Check Metadata-based signals (Side Effects, Docs, Overloads)
for (const exp of result.exports) {
// Overload tracking
symbolCounts.set(exp.name, (symbolCounts.get(exp.name) || 0) + 1);
// Undocumented Exports
Eif (options.checkUndocumentedExports !== false) {
if (!exp.documentation || !exp.documentation.content) {
signals.undocumentedExports++;
issues.push({
type: IssueType.AiSignalClarity,
category: 'undocumented-export',
severity: Severity.Minor,
message: `Public export "${exp.name}" has no documentation — AI fabricates behavior from the name alone.`,
location: {
file: filePath,
line: exp.loc?.start.line || 1,
column: exp.loc?.start.column,
},
suggestion:
'Add a docstring or comment describing parameters, return value, and side effects.',
});
}
}
// Implicit Side Effects
Eif (options.checkImplicitSideEffects !== false) {
if (exp.hasSideEffects && !exp.isPure && exp.type === 'function') {
const lowerName = exp.name.toLowerCase();
const looksPure =
!/(set|update|save|delete|create|write|send|post|sync)/.test(
lowerName
);
Eif (looksPure) {
signals.implicitSideEffects++;
issues.push({
type: IssueType.AiSignalClarity,
category: 'implicit-side-effect',
severity: Severity.Major,
message: `Function "${exp.name}" mutates external state but name doesn't reflect it — AI misses this contract.`,
location: {
file: filePath,
line: exp.loc?.start.line || 1,
},
suggestion:
'Make side-effects explicit in function name (e.g., updateX) or return a result.',
});
}
}
}
// Ambiguous Names for Exports
Iif (options.checkAmbiguousNames !== false && isAmbiguousName(exp.name)) {
signals.ambiguousNames++;
issues.push({
type: IssueType.AmbiguousApi,
category: 'ambiguous-name',
severity: Severity.Info,
message: `Ambiguous public export "${exp.name}" — AI cannot infer intent and will guess incorrectly.`,
location: {
file: filePath,
line: exp.loc?.start.line || 1,
},
suggestion: 'Use a domain-descriptive name instead.',
});
}
}
// Report Overloads
Eif (options.checkOverloadedSymbols !== false) {
for (const [name, count] of symbolCounts.entries()) {
if (count > 1 && name !== 'default' && name !== 'anonymous') {
signals.overloadedSymbols++;
issues.push({
type: IssueType.AiSignalClarity,
category: 'overloaded-symbol',
severity: Severity.Critical,
message: `Symbol "${name}" has ${count} overloaded signatures — AI often picks the wrong one or gets confused by conflicting contracts.`,
location: {
file: filePath,
line: 1,
},
suggestion: `Rename overloads to unique, descriptive names if possible.`,
});
}
}
}
// 2. Check AST-based signals (Structural: Magic Literals, Boolean Traps, Callbacks)
Eif (ast) {
let callbackDepth = 0;
let maxCallbackDepth = 0;
const visitNode = (node: any) => {
Iif (!node) return;
// --- Magic Literals ---
Eif (options.checkMagicLiterals !== false) {
// Tree-sitter (Python, Java, etc.)
Iif (node.type === 'number') {
const val = parseFloat(node.text);
if (!isNaN(val) && isMagicNumber(val)) {
signals.magicLiterals++;
issues.push({
type: IssueType.MagicLiteral,
category: 'magic-literal',
severity: Severity.Minor,
message: `Magic number ${node.text} — AI will invent wrong semantics. Extract to a named constant.`,
location: {
file: filePath,
line: node.startPosition.row + 1,
column: node.startPosition.column,
},
suggestion: `const MEANINGFUL_NAME = ${node.text};`,
});
}
I} else if (node.type === 'string' || node.type === 'string_literal') {
const val = node.text.replace(/['"]/g, '');
if (isMagicString(val)) {
signals.magicLiterals++;
issues.push({
type: IssueType.MagicLiteral,
category: 'magic-literal',
severity: Severity.Info,
message: `Magic string "${val}" — intent is ambiguous to AI. Consider a named constant.`,
location: {
file: filePath,
line: node.startPosition.row + 1,
},
});
}
}
// ESTree (TypeScript, JavaScript)
else if (node.type === 'Literal') {
if (typeof node.value === 'number' && isMagicNumber(node.value)) {
signals.magicLiterals++;
issues.push({
type: IssueType.MagicLiteral,
category: 'magic-literal',
severity: Severity.Minor,
message: `Magic number ${node.value} — AI will invent wrong semantics. Extract to a named constant.`,
location: {
file: filePath,
line: node.loc?.start.line || 1,
column: node.loc?.start.column,
},
suggestion: `const MEANINGFUL_NAME = ${node.value};`,
});
} else if (
typeof node.value === 'string' &&
isMagicString(node.value)
) {
signals.magicLiterals++;
issues.push({
type: IssueType.MagicLiteral,
category: 'magic-literal',
severity: Severity.Info,
message: `Magic string "${node.value}" — intent is ambiguous to AI. Consider a named constant.`,
location: {
file: filePath,
line: node.loc?.start.line || 1,
},
});
}
}
}
// --- Boolean Traps ---
Eif (options.checkBooleanTraps !== false) {
// Tree-sitter
Iif (node.type === 'argument_list') {
const hasBool = node.namedChildren?.some(
(c: any) =>
c.type === 'true' ||
c.type === 'false' ||
(c.type === 'boolean' &&
(c.text === 'true' || c.text === 'false'))
);
if (hasBool) {
signals.booleanTraps++;
issues.push({
type: IssueType.BooleanTrap,
category: 'boolean-trap',
severity: Severity.Major,
message: `Boolean trap: positional boolean argument at call site. AI inverts intent ~30% of the time.`,
location: {
file: filePath,
line: (node.startPosition?.row || 0) + 1,
},
suggestion:
'Replace boolean arg with a named options object or separate functions.',
});
}
}
// ESTree
else if (node.type === 'CallExpression') {
const hasBool = node.arguments.some(
(arg: any) =>
arg.type === 'Literal' && typeof arg.value === 'boolean'
);
if (hasBool) {
signals.booleanTraps++;
issues.push({
type: IssueType.BooleanTrap,
category: 'boolean-trap',
severity: Severity.Major,
message: `Boolean trap: positional boolean argument at call site. AI inverts intent ~30% of the time.`,
location: {
file: filePath,
line: node.loc?.start.line || 1,
},
suggestion:
'Replace boolean arg with a named options object or separate functions.',
});
}
}
}
// --- Ambiguous Names ---
Eif (options.checkAmbiguousNames !== false) {
// Tree-sitter
Iif (node.type === 'variable_declarator') {
const nameNode = node.childForFieldName('name');
if (nameNode && isAmbiguousName(nameNode.text)) {
signals.ambiguousNames++;
issues.push({
type: IssueType.AmbiguousApi,
category: 'ambiguous-name',
severity: Severity.Info,
message: `Ambiguous variable name "${nameNode.text}" — AI intent is unclear.`,
location: {
file: filePath,
line: node.startPosition.row + 1,
},
});
}
}
// ESTree
else if (
node.type === 'VariableDeclarator' &&
node.id.type === 'Identifier'
) {
if (isAmbiguousName(node.id.name)) {
signals.ambiguousNames++;
issues.push({
type: IssueType.AmbiguousApi,
category: 'ambiguous-name',
severity: Severity.Info,
message: `Ambiguous variable name "${node.id.name}" — AI intent is unclear.`,
location: {
file: filePath,
line: node.loc?.start.line || 1,
},
});
}
}
}
// --- Callback Depth ---
const nodeType = (node.type || '').toLowerCase();
const isFunction =
nodeType.includes('function') ||
nodeType.includes('arrow') ||
nodeType.includes('lambda') ||
nodeType === 'method_declaration';
if (isFunction) {
callbackDepth++;
maxCallbackDepth = Math.max(maxCallbackDepth, callbackDepth);
}
// Recurse Tree-sitter
Iif (node.namedChildren) {
for (const child of node.namedChildren) {
visitNode(child);
}
}
// Recurse ESTree
else {
for (const key in node) {
if (key === 'parent' || key === 'loc' || key === 'range') continue;
const child = node[key];
if (child && typeof child === 'object') {
if (Array.isArray(child)) {
child.forEach(
(c) => c && typeof c.type === 'string' && visitNode(c)
);
E} else if (typeof child.type === 'string') {
visitNode(child);
}
}
}
}
if (isFunction) {
callbackDepth--;
}
};
// Start visiting
Iif ((ast as any).rootNode) {
visitNode((ast as any).rootNode); // Tree-sitter
} else {
visitNode(ast); // ESTree
}
if (options.checkDeepCallbacks !== false && maxCallbackDepth >= 3) {
signals.deepCallbacks = maxCallbackDepth - 2;
issues.push({
type: IssueType.AiSignalClarity,
category: 'deep-callback',
severity: Severity.Major,
message: `Deeply nested logic (depth ${maxCallbackDepth}) — AI loses control flow context beyond 3 levels.`,
location: {
file: filePath,
line: 1,
},
suggestion:
'Extract nested logic into named functions or flatten the structure.',
});
}
}
return {
filePath,
issues,
signals,
fileName: filePath,
metrics: {
totalSymbols: signals.totalSymbols,
totalExports: signals.totalExports,
},
};
} catch (error) {
console.error(`AI Signal Clarity: Failed to scan ${filePath}: ${error}`);
return emptyResult(filePath);
}
}
function emptyResult(filePath: string): FileAiSignalClarityResult {
return {
filePath,
issues: [],
signals: {
magicLiterals: 0,
booleanTraps: 0,
ambiguousNames: 0,
undocumentedExports: 0,
implicitSideEffects: 0,
deepCallbacks: 0,
overloadedSymbols: 0,
totalSymbols: 0,
totalExports: 0,
},
fileName: filePath,
metrics: {
totalSymbols: 0,
totalExports: 0,
},
};
}
|