All files / src/signals visitor.ts

71.59% Statements 63/88
64.7% Branches 88/136
80% Functions 4/5
72.41% Lines 63/87

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                                              10x 10x             10x   10x 10x   10x 343x     343x   343x                                 343x                                                                         343x       32x         32x     32x     32x                   32x 2x                         30x   21x       2x 2x                       19x       3x 3x                             343x   343x                                           343x     17x 19x   17x 2x 2x                                 343x   343x                             343x           22x 5x 5x                             343x   343x         343x 24x 24x       343x             343x 2156x           696x 1460x 1460x 419x 224x 138x 138x     195x 195x           343x 24x         10x     10x     10x       2x 2x                           10x    
import { Severity, IssueType, SignalContext, SignalResult } from './types';
import {
  isAmbiguousName,
  isMagicNumber,
  isMagicString,
  isRedundantTypeConstant,
} from '../helpers';
import {
  CATEGORY_MAGIC_LITERAL,
  CATEGORY_REDUNDANT_TYPE_CONSTANT,
  CATEGORY_BOOLEAN_TRAP,
  CATEGORY_AMBIGUOUS_NAME,
  CATEGORY_DEEP_CALLBACK,
  CALLBACK_DEPTH_THRESHOLD,
} from './constants';
 
/**
 * Traverses the AST and detects structural signals like magic literals and boolean traps.
 */
export function detectStructuralSignals(
  ctx: SignalContext,
  ast: any
): SignalResult {
  const issues: any[] = [];
  const signals = {
    magicLiterals: 0,
    booleanTraps: 0,
    ambiguousNames: 0,
    deepCallbacks: 0,
  };
 
  const { filePath, options } = ctx;
 
  let callbackDepth = 0;
  let maxCallbackDepth = 0;
 
  const visitNode = (node: any, parent?: any, keyInParent?: string) => {
    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: 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, '');
        // Heuristic: ignore if it's likely a key in a map/dictionary (Tree-sitter)
        const isKey =
          node.parent?.type?.includes('pair') ||
          node.parent?.type === 'assignment_expression';
 
        const parentName =
          node.parent?.nameNode?.text ||
          node.parent?.childForFieldName('name')?.text ||
          '';
 
        if (!isKey && isRedundantTypeConstant(parentName, val)) {
          issues.push({
            type: IssueType.AiSignalClarity,
            category: CATEGORY_REDUNDANT_TYPE_CONSTANT,
            severity: Severity.Minor,
            message: `Redundant type constant — in modern AI-native code, use literals or centralized union types for transparency.`,
            location: {
              file: filePath,
              line: node.startPosition.row + 1,
            },
            suggestion: `Use '${val}' directly in your schema.`,
          });
        } else if (!isKey && isMagicString(val)) {
          signals.magicLiterals++;
          issues.push({
            type: IssueType.MagicLiteral,
            category: 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') {
        const isNamedConstant =
          parent?.type === 'VariableDeclarator' &&
          parent.id.type === 'Identifier' &&
          /^[A-Z0-9_]{3,}$/.test(parent.id.name);
 
        const isObjectKey =
          parent?.type === 'Property' && keyInParent === 'key';
 
        const isJSXClassName =
          parent?.type === 'JSXAttribute' && parent.name?.name === 'className';
 
        const redundantType =
          typeof node.value === 'string'
            ? isRedundantTypeConstant(
                parent?.type === 'VariableDeclarator' &&
                  parent.id.type === 'Identifier'
                  ? parent.id.name
                  : '',
                node.value
              )
            : false;
 
        if (redundantType) {
          issues.push({
            type: IssueType.AiSignalClarity,
            category: CATEGORY_REDUNDANT_TYPE_CONSTANT,
            severity: Severity.Minor,
            message: `Redundant type constant "${parent.id.name}" = '${
              node.value
            }' — in modern AI-native code, use literals or centralized union types for transparency.`,
            location: {
              file: filePath,
              line: node.loc?.start.line || 1,
            },
            suggestion: `Use '${node.value}' directly in your schema.`,
          });
        } else if (isNamedConstant || isObjectKey || isJSXClassName) {
          // Skip magic literal check for these contextually safe literals
        } else if (
          typeof node.value === 'number' &&
          isMagicNumber(node.value)
        ) {
          signals.magicLiterals++;
          issues.push({
            type: IssueType.MagicLiteral,
            category: 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: 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: 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: 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: 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: 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, node);
      }
    }
    // Recurse ESTree
    else {
      for (const key in node) {
        if (
          key === 'parent' ||
          key === 'loc' ||
          key === 'range' ||
          key === 'tokens'
        )
          continue;
        const child = node[key];
        if (child && typeof child === 'object') {
          if (Array.isArray(child)) {
            child.forEach((c) => {
              Eif (c && typeof c.type === 'string') {
                visitNode(c, node, key);
              }
            });
          E} else if (typeof child.type === 'string') {
            visitNode(child, node, key);
          }
        }
      }
    }
 
    if (isFunction) {
      callbackDepth--;
    }
  };
 
  // Start visiting
  Iif (ast.rootNode) {
    visitNode(ast.rootNode); // Tree-sitter
  } else {
    visitNode(ast); // ESTree
  }
 
  if (
    options.checkDeepCallbacks !== false &&
    maxCallbackDepth >= CALLBACK_DEPTH_THRESHOLD
  ) {
    signals.deepCallbacks = maxCallbackDepth - (CALLBACK_DEPTH_THRESHOLD - 1);
    issues.push({
      type: IssueType.AiSignalClarity,
      category: CATEGORY_DEEP_CALLBACK,
      severity: Severity.Major,
      message: `Deeply nested logic (depth ${maxCallbackDepth}) — AI loses control flow context beyond ${CALLBACK_DEPTH_THRESHOLD} levels.`,
      location: {
        file: filePath,
        line: 1,
      },
      suggestion:
        'Extract nested logic into named functions or flatten the structure.',
    });
  }
 
  return { issues, signals };
}