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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Hotspots CLI - multi-language static analysis tool
#![deny(warnings)]
// Global invariants enforced:
// - Deterministic output ordering
// - Identical input yields byte-for-byte identical output
mod cmd;
mod output;
mod util;
use anyhow::Context;
use clap::{Parser, Subcommand};
use cmd::{analyze::AnalyzeArgs, config::ConfigAction, diff::DiffArgs, estimate::EstimateArgs};
use std::io::Read;
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "hotspots")]
#[command(
about = "Multi-language static analysis tool (TypeScript, JavaScript, Go, Java, Python, Rust)"
)]
#[command(version = env!("HOTSPOTS_VERSION"))]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Analyze source files (TypeScript, JavaScript, Go, Java, Python, Rust)
Analyze {
/// Path to source file or directory
path: PathBuf,
/// Output format
#[arg(long, default_value = "text")]
format: OutputFormat,
/// Output mode (snapshot, delta, or models)
#[arg(long)]
mode: Option<OutputMode>,
/// Evaluate policies (only valid with --mode delta)
#[arg(long)]
policy: bool,
/// Show only top N results (overrides config file)
#[arg(long)]
top: Option<usize>,
/// Minimum LRS threshold (overrides config file)
#[arg(long)]
min_lrs: Option<f64>,
/// Path to config file (default: auto-discover)
#[arg(long)]
config: Option<PathBuf>,
/// Output file path (for HTML format, default: .hotspots/report.html)
#[arg(long)]
output: Option<PathBuf>,
/// Show human-readable risk explanations (only valid with --mode snapshot)
#[arg(long)]
explain: bool,
/// Overwrite existing snapshot if it already exists
#[arg(short = 'f', long)]
force: bool,
/// Skip writing snapshot to disk (only valid with --mode snapshot or --mode delta)
#[arg(long)]
no_persist: bool,
/// Output level for text format: file shows a ranked file risk table
#[arg(long, value_name = "LEVEL")]
level: Option<OutputLevel>,
/// Touch metrics mode: `auto` (default — config or hybrid:5), `per-function`
/// (accurate, O(functions) git calls, cached in .hotspots/touch-cache.json.zst),
/// `file` (fast file-level batching), `hybrid[:N]` (file-level first,
/// per-function only for files with touch_count_30d >= N, default N=5), or
/// `none` (skip touch metrics, directed coupling, and burst_score entirely —
/// no git log calls; for benchmarking pure analysis + call graph performance).
#[arg(long, value_parser = cmd::analyze::parse_touch_mode_arg, conflicts_with_all = ["per_function_touches", "no_per_function_touches", "skip_touch_metrics", "hybrid_touches"])]
touch_mode: Option<cmd::analyze::TouchModeArg>,
/// Deprecated: use `--touch-mode per-function`. Use per-function git log -L
/// for touch metrics (more accurate than file-level batching). Results are
/// cached in .hotspots/touch-cache.json.zst — the first run on a new commit
/// is slow (~9 ms per uncached function); subsequent runs are fast. A warning
/// is printed when 50+ functions need to be fetched.
#[arg(long, conflicts_with = "touch_mode")]
per_function_touches: bool,
/// Deprecated: use `--touch-mode file`. Disable per-function touch metrics,
/// use file-level batching instead. Overrides config and --per-function-touches.
#[arg(long, conflicts_with = "touch_mode")]
no_per_function_touches: bool,
/// Deprecated: use `--touch-mode none`. Skip all touch metrics entirely (no
/// git log calls for churn/recency), skip directed coupling (also a git log
/// walk), and skip burst_score (also a full-history git log walk).
#[arg(long, conflicts_with = "touch_mode")]
skip_touch_metrics: bool,
/// Output all functions as a flat array (only valid with --mode snapshot --format json).
/// Note: `quadrant`, `driver`, `driver_detail`, and `percentile` are population-relative
/// and can change run-to-run even when a function's own `lrs`/`activity_risk`/`band`
/// don't; see docs/REFERENCE.md "Field stability" before keying CI gates on them.
#[arg(long)]
all_functions: bool,
/// Include model risk map data in snapshot JSON/HTML reports.
#[arg(long)]
include_models: bool,
/// Populate and emit pattern details for --explain-patterns
#[arg(long)]
explain_patterns: bool,
/// URL of the written analysis post to link from the HTML report (HTML format only)
#[arg(long, value_name = "URL")]
source_url: Option<String>,
/// Number of parallel worker threads (default: number of logical CPUs)
#[arg(long, short = 'j', value_name = "N")]
jobs: Option<usize>,
/// Skip all call graph algorithms when the repo exceeds N functions.
/// Omits PageRank, betweenness, fan-in/fan-out, SCC, and dependency depth.
/// Useful for very large repos where graph computation dominates CPU time.
#[arg(long, value_name = "N")]
callgraph_skip_above: Option<usize>,
/// Skip the suppression gate check (the P@10 calibration that warns when
/// the activity ranker may be producing misleading rankings).
#[arg(long)]
skip_gate: bool,
/// Deprecated: use `--touch-mode hybrid:N`. Hybrid touch mode: run file-level
/// touch first, then per-function only for files with touch_count_30d >= N.
#[arg(long, value_name = "N", conflicts_with = "touch_mode")]
hybrid_touches: Option<usize>,
/// Rank using a Gini-gated cold-start strategy (formula / IsolationForest
/// anomaly / uniform prior) instead of a trained ranker. For repos with no
/// fix-commit label history yet. Reads no label data. Explicit opt-in only —
/// not an automatic fallback when `hotspots train` fails its label threshold.
#[arg(long)]
cold_start: bool,
/// Print three independent ranked sections — Risk, Coupling, Ownership —
/// instead of a single merged list. Files may appear in more than one
/// section; overlap is not deduplicated. Use --top to control section size.
#[arg(long)]
axes: bool,
},
/// Prune unreachable snapshots
Prune {
/// Prune unreachable snapshots (must be explicitly specified)
#[arg(long)]
unreachable: bool,
/// Only prune commits older than this many days
#[arg(long)]
older_than: Option<u64>,
/// Dry-run mode (report what would be pruned without actually deleting)
#[arg(long)]
dry_run: bool,
},
/// Compact history to reduce storage
Compact {
/// Compaction level (0 = full snapshots, 1 = deltas only, 2 = band transitions only)
#[arg(long)]
level: u32,
/// Report what would be done without modifying any files
#[arg(long)]
dry_run: bool,
},
/// Analyze trends from snapshot history
Trends {
/// Path to repository root
path: PathBuf,
/// Output format
#[arg(long, default_value = "json")]
format: OutputFormat,
/// Window size (number of snapshots to analyze)
#[arg(long, default_value = "10")]
window: usize,
/// Top K functions for hotspot analysis
#[arg(long, default_value = "5")]
top: usize,
},
/// Validate a configuration file
#[command(name = "config")]
Config {
#[command(subcommand)]
action: ConfigAction,
},
/// Print hook templates for CI/CD integration
Init {
/// Print pre-commit framework and raw shell hook templates to stdout
#[arg(long)]
hooks: bool,
/// Write a GitHub Actions workflow to .github/workflows/hotspots.yml
#[arg(long)]
ci: bool,
},
/// Compare analysis snapshots between two git refs
Diff {
/// Base git ref (branch, tag, SHA, or HEAD~N)
base: String,
/// Head git ref (branch, tag, SHA, or HEAD~N)
head: String,
/// Output format
#[arg(long, default_value = "text")]
format: OutputFormat,
/// Write output to file instead of stdout (HTML default: .hotspots/delta-report.html)
#[arg(long)]
output: Option<PathBuf>,
/// Evaluate policy rules; exit 1 on blocking failures
#[arg(long)]
policy: bool,
/// Limit output to top N changed functions (by |ΔLRS|)
#[arg(long)]
top: Option<usize>,
/// Path to config file (default: auto-discover)
#[arg(long)]
config: Option<PathBuf>,
/// Analyze missing refs automatically using git worktrees
#[arg(long)]
auto_analyze: bool,
},
/// Train a local RandomForest ranker from fix-commit history
Train {
/// Path to repository root
#[arg(default_value = ".")]
path: PathBuf,
/// Output path for the trained model (JSON)
#[arg(long, default_value = ".hotspots/ranker.json")]
output: PathBuf,
/// Days of git history to scan for fix-commit labels
#[arg(long, default_value = "365")]
label_window: u32,
/// Upper bound for the label window (ISO date, e.g. "2025-01-01").
/// When set, only fix commits before this date are used as training labels.
/// Useful for matching a specific benchmark label window exactly.
#[arg(long)]
label_before: Option<String>,
/// Number of trees in the RandomForest
#[arg(long, default_value = "200")]
n_estimators: usize,
/// Maximum tree depth
#[arg(long, default_value = "6")]
max_depth: usize,
/// Use blame-based function-level labelling instead of file-level labelling.
/// More precise labels (only the function that owned the changed lines is
/// marked positive) but slower on repos with many fix commits.
#[arg(long, default_value = "false")]
blame: bool,
/// After training, evaluate the model with P@K on the same label window.
/// Prints a table of Precision@K for K in [10, 20, 50, 100, 200] alongside
/// the fix-label base rate so you can judge whether the ranker beats random.
#[arg(long, default_value = "false")]
eval: bool,
/// Run a pre-flight data-quality check before training. Aborts with SKIP_FT
/// when mean hotspots score is too flat; warns on AMBIGUOUS. Saves wasted
/// training runs on repos unlikely to produce a useful model.
#[arg(long, default_value = "false")]
screen: bool,
/// Skip the confirmation prompt before training (non-interactive / CI use).
#[arg(long, short = 'y', default_value = "false")]
yes: bool,
/// Suppress per-tree progress lines. Estimate and completion line are still shown.
#[arg(long, short = 'q', default_value = "false")]
quiet: bool,
},
/// Analyze coupling and ownership risk for a set of files before starting work
Coordinate {
/// Comma-separated list of file paths to analyze
#[arg(long)]
files: Option<String>,
/// Derive the file set from a unified diff read on stdin
#[arg(long)]
diff: bool,
/// Derive the file set from `git diff --cached --name-only`
#[arg(long)]
staged: bool,
/// Path to repository root
#[arg(default_value = ".")]
path: PathBuf,
},
/// Check whether a newer version of hotspots is available
Upgrade,
/// Project `analyze --touch-mode per-function`'s wall-clock cost before running it
Estimate {
/// Path to source file or directory
path: PathBuf,
/// Output format
#[arg(long, default_value = "text")]
format: OutputFormat,
/// Path to config file (default: auto-discover)
#[arg(long)]
config: Option<PathBuf>,
/// If given, recommend a touch mode against this wall-clock budget (seconds)
#[arg(long, value_name = "SECONDS")]
budget_seconds: Option<u64>,
/// How long to let the Tier 1 structural pass run before giving up on it
#[arg(long, value_name = "SECONDS", default_value = "30")]
tier1_timeout_seconds: u64,
},
}
#[derive(Clone, Copy, clap::ValueEnum)]
pub(crate) enum OutputFormat {
Text,
Json,
Html,
Jsonl,
Sarif,
Csv,
Xlsx,
}
#[derive(Clone, Copy, PartialEq, clap::ValueEnum)]
pub(crate) enum OutputMode {
Snapshot,
Delta,
Models,
}
#[derive(Clone, Copy, PartialEq, clap::ValueEnum)]
pub(crate) enum OutputLevel {
File,
Module,
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
if !matches!(cli.command, Commands::Upgrade) {
cmd::upgrade::maybe_print_update_notice();
}
match cli.command {
Commands::Analyze {
path,
format,
mode,
policy,
top,
min_lrs,
config: config_path,
output,
explain,
force,
no_persist,
level,
per_function_touches,
no_per_function_touches,
skip_touch_metrics,
all_functions,
include_models,
explain_patterns,
source_url,
jobs,
callgraph_skip_above,
hybrid_touches,
touch_mode,
skip_gate,
cold_start,
axes,
} => cmd::analyze::handle_analyze(AnalyzeArgs {
path,
format,
mode,
policy,
top,
min_lrs,
config_path,
output,
explain,
force,
no_persist,
level,
per_function_touches,
no_per_function_touches,
skip_touch_metrics,
all_functions,
include_models,
explain_patterns,
source_url,
jobs,
callgraph_skip_above,
hybrid_touches,
touch_mode,
skip_gate,
cold_start,
axes,
})?,
Commands::Prune {
unreachable,
older_than,
dry_run,
} => cmd::prune::handle_prune(unreachable, older_than, dry_run)?,
Commands::Compact { level, dry_run } => cmd::compact::handle_compact(level, dry_run)?,
Commands::Config { action } => cmd::config::handle_config(action)?,
Commands::Trends {
path,
format,
window,
top,
} => cmd::trends::handle_trends(path, format, window, top)?,
Commands::Init { hooks, ci } => cmd::init::handle_init(hooks, ci)?,
Commands::Diff {
base,
head,
format,
output,
policy,
top,
config,
auto_analyze,
} => cmd::diff::handle_diff(DiffArgs {
base,
head,
format,
output,
policy,
top,
config_path: config,
auto_analyze,
})?,
Commands::Train {
path,
output,
label_window,
label_before,
n_estimators,
max_depth,
blame,
eval,
screen,
yes,
quiet,
} => cmd::train::handle_train(cmd::train::TrainArgs {
path,
output,
label_window_days: label_window,
label_before,
n_estimators,
max_depth,
blame_labels: blame,
eval,
screen,
yes,
quiet,
})?,
Commands::Coordinate {
files,
diff,
staged,
path,
} => {
let diff_text = if diff {
let mut buf = String::new();
std::io::stdin()
.read_to_string(&mut buf)
.context("read diff from stdin")?;
Some(buf)
} else {
None
};
cmd::coordinate::handle_coordinate(cmd::coordinate::CoordinateArgs {
files,
diff: diff_text,
staged,
path,
})?
}
Commands::Upgrade => cmd::upgrade::handle_upgrade()?,
Commands::Estimate {
path,
format,
config,
budget_seconds,
tier1_timeout_seconds,
} => cmd::estimate::handle_estimate(EstimateArgs {
path,
format,
config_path: config,
budget_seconds,
tier1_timeout_seconds,
})?,
}
Ok(())
}