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
//! 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 clap::{Parser, Subcommand};
use cmd::{analyze::AnalyzeArgs, config::ConfigAction, diff::DiffArgs};
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>,
/// 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)]
per_function_touches: bool,
/// Disable per-function touch metrics, use file-level batching instead.
/// Overrides config and --per-function-touches. Useful for large repos
/// where the cold-start per-function git log -L calls dominate CPU time.
#[arg(long, conflicts_with = "per_function_touches")]
no_per_function_touches: bool,
/// Skip all touch metrics entirely (no git log calls for churn/recency).
/// Overrides --per-function-touches and --no-per-function-touches.
/// Use for benchmarking pure analysis + call graph performance.
#[arg(long, conflicts_with = "per_function_touches")]
skip_touch_metrics: bool,
/// Output all functions as a flat array (only valid with --mode snapshot --format json)
#[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,
/// Hybrid touch mode: run file-level touch first, then per-function only for
/// files with touch_count_30d >= N. Balances accuracy and performance for
/// large repos. Conflicts with --per-function-touches and --no-per-function-touches.
#[arg(long, value_name = "N", conflicts_with_all = ["per_function_touches", "no_per_function_touches"])]
hybrid_touches: Option<usize>,
},
/// 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,
},
}
#[derive(Clone, Copy, clap::ValueEnum)]
pub(crate) enum OutputFormat {
Text,
Json,
Html,
Jsonl,
Sarif,
}
#[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();
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,
skip_gate,
} => 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,
skip_gate,
})?,
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,
})?,
}
Ok(())
}