All files cli.ts

90.72% Statements 88/97
82.14% Branches 23/28
100% Functions 5/5
92.04% Lines 81/88

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                  37x 37x       4x 4x       20x 18x     226x   10x           18x       3x 3x 5x 5x   2x 2x 2x 2x 2x 2x   3x     3x               3x 4x 4x 3x 5x 3x 2x 2x 2x 2x 2x 2x 2x       3x                                                     3x           3x   6x         6x 6x     2x 2x     2x 2x     12x 4x                 71x 71x   71x 111x       33x 33x         37x   37x 37x         4x   4x 4x         14x 14x         2x 2x         3x 3x 3x 3x 3x         13x 13x 13x         5x 5x 5x       71x     1x 1x     410x       17x 436x 10x       71x                                                                                                                                                                    
import path from 'node:path';
 
import { ALL_CATEGORIES, DEFAULT_OPTS, PILLAR_CATEGORIES } from './types.js';
 
import type { AnalysisOptions } from './types.js';
 
// ─── Helpers ─────────────────────────────────────────────────────────────────
 
function parseNumeric(raw: string | undefined, fallback: number): number {
  const n = parseInt(raw ?? '', 10);
  return Number.isNaN(n) ? fallback : n;
}
 
function parseDecimal(raw: string | undefined, fallback: number): number {
  const n = parseFloat(raw ?? '');
  return Number.isNaN(n) ? fallback : n;
}
 
function resolveCategories(val: string, flagName: string): Set<string> {
  const tokens = val.split(',').map((s) => s.trim()).filter(Boolean);
  const resolved = new Set<string>();
  for (const token of tokens) {
    if (PILLAR_CATEGORIES[token]) {
      for (const cat of PILLAR_CATEGORIES[token]) resolved.add(cat);
    } else if (ALL_CATEGORIES.has(token)) {
      resolved.add(token);
    } else {
      console.error(`Unknown ${flagName}: "${token}". Use pillar names (${Object.keys(PILLAR_CATEGORIES).join(', ')}) or category names.`);
      process.exit(1);
    }
  }
  return resolved;
}
 
function parseScope(val: string, root: string): { paths: string[]; symbols: Map<string, string[]> } {
  const paths: string[] = [];
  const symbols = new Map<string, string[]>();
  for (const token of val.split(',').map((s) => s.trim()).filter(Boolean)) {
    const colonIdx = token.lastIndexOf(':');
    if (colonIdx > 0 && !token.substring(0, colonIdx).includes(':')) {
      const filePart = token.substring(0, colonIdx);
      const symbolPart = token.substring(colonIdx + 1);
      const absFile = path.resolve(root, filePart);
      paths.push(absFile);
      Eif (!symbols.has(absFile)) symbols.set(absFile, []);
      symbols.get(absFile)!.push(symbolPart);
    } else {
      paths.push(path.resolve(root, token));
    }
  }
  return { paths, symbols };
}
 
// ─── Flag dispatch tables ────────────────────────────────────────────────────
 
type FlagHandler = (opts: AnalysisOptions, argv: string[], i: number) => number;
 
/** Boolean flags — no argument consumed */
const BOOL_FLAGS: Record<string, (opts: AnalysisOptions, value: boolean) => void> = {
  '--json':          (o) => { o.json = true; },
  '--include-tests': (o) => { o.includeTests = true; },
  '--emit-tree':     (o) => { o.emitTree = true; },
  '--no-tree':       (o) => { o.emitTree = false; },
  '--graph':         (o) => { o.graph = true; },
  '--semantic':      (o) => { o.semantic = true; },
  '--no-diversify':  (o) => { o.noDiversify = true; },
  '--no-cache':      (o) => { o.noCache = true; },
  '--clear-cache':   (o) => { o.clearCache = true; },
  '--graph-advanced': (o) => { o.graphAdvanced = true; },
  '--flow':          (o) => { o.flow = true; },
  '--all':           (o) => { o.includeTests = true; o.semantic = true; },
};
 
/** Numeric (int) flags — consume next arg */
const INT_FLAGS: Record<string, keyof AnalysisOptions> = {
  '--findings-limit':              'findingsLimit',
  '--min-function-statements':     'minFunctionStatements',
  '--min-flow-statements':         'minFlowStatements',
  '--critical-complexity-threshold': 'criticalComplexityThreshold',
  '--deep-link-topn':              'deepLinkTopN',
  '--tree-depth':                  'treeDepth',
  '--coupling-threshold':          'couplingThreshold',
  '--fan-in-threshold':            'fanInThreshold',
  '--fan-out-threshold':           'fanOutThreshold',
  '--god-module-statements':       'godModuleStatements',
  '--god-module-exports':          'godModuleExports',
  '--god-function-statements':     'godFunctionStatements',
  '--cognitive-complexity-threshold': 'cognitiveComplexityThreshold',
  '--barrel-symbol-threshold':     'barrelSymbolThreshold',
  '--parameter-threshold':         'parameterThreshold',
  '--halstead-effort-threshold':   'halsteadEffortThreshold',
  '--maintainability-index-threshold': 'maintainabilityIndexThreshold',
  '--any-threshold':               'anyThreshold',
  '--flow-dup-threshold':          'flowDupThreshold',
  '--max-recs-per-category':       'maxRecsPerCategory',
  '--override-chain-threshold':    'overrideChainThreshold',
  '--secret-min-length':           'secretMinLength',
  '--mock-threshold':              'mockThreshold',
};
 
/** Decimal (float) flags — consume next arg */
const FLOAT_FLAGS: Record<string, keyof AnalysisOptions> = {
  '--secret-entropy-threshold':     'secretEntropyThreshold',
  '--similarity-threshold':         'similarityThreshold',
};
 
/** Special flags that need custom handling */
const SPECIAL_FLAGS: Record<string, FlagHandler> = {
  '--parser': (opts, argv, i) => {
    const next = argv[i + 1];
    if (!['auto', 'typescript', 'tree-sitter'].includes(next)) {
      console.error(`Unsupported parser: ${next}. Use auto|typescript|tree-sitter`);
      process.exit(1);
    }
    opts.parser = next as AnalysisOptions['parser'];
    return i + 1;
  },
  '--root': (opts, argv, i) => {
    opts.root = path.resolve(argv[i + 1]);
    return i + 1;
  },
  '--out': (opts, argv, i) => {
    opts.out = argv[i + 1];
    return i + 1;
  },
  '--layer-order': (opts, argv, i) => {
    opts.layerOrder = argv[i + 1].split(',').map((s) => s.trim());
    return i + 1;
  },
  '--help': () => { printHelp(); return process.exit(0) as never; },
  '-h': () => { printHelp(); return process.exit(0) as never; },
};
 
// ─── Main parser ─────────────────────────────────────────────────────────────
 
export function parseArgs(argv: string[]): AnalysisOptions {
  const opts: AnalysisOptions = { ...DEFAULT_OPTS };
  let excludeSet: Set<string> | null = null;
 
  for (let i = 0; i < argv.length; i++) {
    const arg = argv[i];
 
    // Boolean flags
    if (BOOL_FLAGS[arg]) {
      BOOL_FLAGS[arg](opts, true);
      continue;
    }
 
    // Integer flags
    if (INT_FLAGS[arg]) {
      const key = INT_FLAGS[arg];
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (opts as any)[key] = parseNumeric(argv[++i], (DEFAULT_OPTS as any)[key]);
      continue;
    }
 
    // Float flags
    if (FLOAT_FLAGS[arg]) {
      const key = FLOAT_FLAGS[arg];
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (opts as any)[key] = parseDecimal(argv[++i], (DEFAULT_OPTS as any)[key]);
      continue;
    }
 
    // Special flags
    if (SPECIAL_FLAGS[arg]) {
      i = SPECIAL_FLAGS[arg](opts, argv, i);
      continue;
    }
 
    // --out=value form
    if (arg.startsWith('--out=')) {
      opts.out = arg.slice('--out='.length);
      continue;
    }
 
    // --scope / --scope=
    if (arg === '--scope' || arg.startsWith('--scope=')) {
      const val = arg.includes('=') ? arg.split('=')[1] : argv[++i];
      const { paths, symbols } = parseScope(val, opts.root);
      opts.scope = paths;
      if (symbols.size > 0) opts.scopeSymbols = symbols;
      continue;
    }
 
    // --features / --features=
    if (arg === '--features' || arg.startsWith('--features=')) {
      const val = arg.startsWith('--features=') ? arg.slice('--features='.length) : argv[++i];
      opts.features = resolveCategories(val, 'feature');
      continue;
    }
 
    // --exclude / --exclude=
    if (arg === '--exclude' || arg.startsWith('--exclude=')) {
      const val = arg.startsWith('--exclude=') ? arg.slice('--exclude='.length) : argv[++i];
      excludeSet = resolveCategories(val, 'exclude');
      continue;
    }
  }
 
  opts.packageRoot = path.join(opts.root, 'packages');
 
  if (opts.features !== null && excludeSet !== null) {
    console.error('--features and --exclude are mutually exclusive. Use one or the other.');
    process.exit(1);
  }
  if (excludeSet !== null) {
    opts.features = new Set([...ALL_CATEGORIES].filter((c) => !excludeSet!.has(c)));
  }
 
  if (opts.features !== null) {
    const testQualityCats = new Set(PILLAR_CATEGORIES['test-quality']);
    if ([...opts.features].some((f) => testQualityCats.has(f))) {
      opts.includeTests = true;
    }
  }
 
  return opts;
}
 
export function printHelp(): void {
  console.log(`
Usage:
  node scripts/index.js [options]
 
Options:
  --root <path>                 Analyze a different repo root (default: cwd)
  --out <path>                  Output directory for split report files (timestamped dir by default).
                                If path ends with .json, writes single monolithic file (legacy mode).
  --json                        Print report JSON to stdout
  --include-tests               Include *.test* and *.spec* files
  --parser <auto|typescript|tree-sitter>
                                Parser engine for extra AST metadata (default: auto)
  --no-tree                     Do not write AST trees to report
  --emit-tree                   Force include tree blocks
  --graph                       Emit Mermaid dependency graph to .md file alongside JSON
  --graph-advanced              Enable advanced graph overlays and additional architecture findings
  --flow                        Enable lightweight flow enrichment for evidence traces and cfgFlags
  --min-function-statements N    Minimum function body statement count for duplicate matching (default 6)
  --min-flow-statements N        Minimum control-flow statement count for duplicate matching (default 6)
  --critical-complexity-threshold N
                                Complexity threshold for HIGH complexity findings and critical path weighting.
  --findings-limit N            Cap findings in the report (default: no limit)
  --deep-link-topn N            Max number of critical dependency paths to report (default 12)
  --tree-depth N                AST tree depth when tree snapshots are emitted (default 4)
  --coupling-threshold N        Ca+Ce threshold for high-coupling findings (default 15)
  --fan-in-threshold N          Fan-in threshold for god-module-coupling (default 20)
  --fan-out-threshold N         Fan-out threshold for god-module-coupling (default 15)
  --god-module-statements N     Statement threshold for god-module findings (default 500)
  --god-module-exports N        Export threshold for god-module findings (default 20)
  --god-function-statements N   Statement threshold for god-function findings (default 100)
  --cognitive-complexity-threshold N
                                Cognitive complexity threshold for findings (default 15)
  --barrel-symbol-threshold N   Re-export count threshold for barrel-explosion (default 30)
  --layer-order <layers>        Comma-separated layer names for violation detection (e.g. ui,service,repository)
  --parameter-threshold N       Max function parameters before flagging (default 5)
  --halstead-effort-threshold N Halstead effort threshold for findings (default 500000)
  --maintainability-index-threshold N
                                MI below this triggers a finding (default 20, scale 0-100)
  --any-threshold N             Max \`any\` type usages per file before flagging (default 5)
  --flow-dup-threshold N        Min occurrences for a repeated flow to become a finding (default 3)
  --max-recs-per-category N     Max findings per category in top recommendations (default 2)
  --scope=X,Y,Z                 Limit scan to specific paths, files, or functions. Comma-separated.
                                Supports file:functionName to drill into a specific function.
                                Examples: --scope=packages/octocode-mcp
                                          --scope=packages/octocode-mcp/src/tools
                                          --scope=packages/octocode-mcp/src/session.ts
                                          --scope=packages/octocode-mcp/src/session.ts:initSession
                                          --scope=packages/foo,packages/bar
  --features=X,Y,Z              Run only selected features. Accepts pillar names (architecture,
                                code-quality, dead-code, security, test-quality) or individual
                                category names. Comma-separated.
                                Examples: --features=architecture
                                          --features=dead-code,cognitive-complexity
                                          --features=dependency-cycle,dead-export
  --exclude=X,Y,Z               Run everything EXCEPT the given pillars or categories. Mutually
                                exclusive with --features. Same pillar/category names as --features.
                                Examples: --exclude=architecture
                                          --exclude=dead-export,unsafe-any
  --semantic                    Enable semantic analysis phase (TypeChecker + LanguageService).
                                Adds 14 categories: over-abstraction, concrete-dependency,
                                circular-type-dependency, unused-parameter,
                                deep-override-chain, interface-compliance, unused-import,
                                orphan-implementation, shotgun-surgery, move-to-caller,
                                narrowable-type, semantic-dead-export.
  --override-chain-threshold N  Max method override depth before flagging (default 3, requires --semantic)
  --secret-entropy-threshold N  Shannon entropy threshold for secret detection (default 4.5)
  --secret-min-length N         Min string length for entropy-based secret detection (default 20)
  --similarity-threshold N      Jaccard similarity threshold for near-clone detection (default 0.85)
  --mock-threshold N            Max mock/spy calls per test file (default 10)
  --no-diversify                Disable category-aware diversification when truncating findings.
                                By default, --findings-limit interleaves categories so the
                                truncated list is diverse. Use this to get pure severity ordering.
  --no-cache                    Disable incremental cache; re-parse all files
  --clear-cache                 Delete the analysis cache and exit (no scan)
  --all                         Enable all features: --include-tests --semantic
  --help                        Show this message
`);
}