Skip to content

Usage Guide ​

Basic Analysis ​

bash
hotspots analyze src/ --format json                  # JSON output, all functions
hotspots analyze src/ --format json --top 20         # top 20 by LRS
hotspots analyze src/ --format json --min-lrs 5       # only LRS ≥ 5.0
hotspots analyze src/ --explain --top 10              # human-readable, with risk breakdown
hotspots analyze src/ --format json | jq '.functions[] | select(.band=="critical")'

Text format needs --explain or --level file (plain text output without either is an error — see Troubleshooting); --format json/html/sarif need neither.

Snapshots ​

Every analyze run captures a full analysis tied to the current git commit and, by default, writes it to disk. This enables:

  • Diff comparisons (hotspots diff)
  • HTML trend charts
  • Trained ranker scoring
bash
# Capture current state (persisted by default)
hotspots analyze .

# With detailed per-function explanation
hotspots analyze . --format text --explain --top 10

# Without saving to disk
hotspots analyze . --no-persist --format json

# Regenerate an existing snapshot (e.g. after config change)
hotspots analyze . --force

Snapshots are stored as .hotspots/snapshots/<commit-sha>.json.zst and are immutable by default.

Higher-level views ​

bash
# File-level risk table (ranked by composite file_risk_score)
hotspots analyze . --format text --level file

File risk score = max_cc×0.4 + avg_cc×0.3 + log2(fn_count+1)×0.2.

Cold-Start Ranking ​

hotspots train needs at least 50 functions and enough confirmed fix-commit labels (≥ 5 positive / ≥ 10 negative) to fit a ranker — a repo that's brand new to hotspots, or one with too little confirmed-fix history, doesn't clear that bar. --cold-start gives those repos a ranking anyway, with no trained model required:

bash
hotspots analyze . --cold-start
hotspots analyze . --cold-start --top 20

It skips the trained-ranker/snapshot pipeline entirely (mutually exclusive with --axes and every other absorbed-subcommand flag) and picks one of three strategies per-repo, printed as the route before the ranked list:

  • formula — commit activity is concentrated in a few files; the existing activity_risk/lrs score is already a good day-one ranking.
  • anomaly — commit activity is spread out, or the repo has fix history but too few confirmed fixes to trust a supervised model; ranks by a label-free anomaly score over history signals (commit count, author entropy, burst score, isolation rate, age, etc.) instead.
  • uniform-prior — no file stands out by commit count at all; prints a note instead of a manufactured ranking.

See docs/REFERENCE.md for the exact routing thresholds.

hotspots diff ​

Reviewing a PR? Run it with no args — base auto-detects the merge-base against your default branch and head defaults to HEAD:

bash
hotspots diff --auto-analyze --policy   # the "review my PR" entry point

Or compare snapshots between any two git refs explicitly (not just parent → HEAD):

bash
hotspots diff main HEAD               # compare branch vs main
hotspots diff v1.0.0 v2.0.0          # compare releases
hotspots diff main HEAD --top 10 --policy
hotspots diff main HEAD --format json

Both refs must have existing snapshots. If one is missing:

bash
git checkout main && hotspots analyze .
git checkout my-branch && hotspots analyze .
hotspots diff main HEAD

--top N applies after policy evaluation, so violations outside the top N are still detected. It ranks and limits only new/modified entries; deleted functions are excluded from the top-N cutoff entirely rather than ranked by their pre-deletion complexity — a deleted function's complexity isn't signal for "what should I review," and research found including it diluted recall of real regressions in the truncated view.

Exit codes: 0 = success, 1 = policy failure, 2 = auto-analysis failed, 3 = snapshot missing.

What the PR summary shows ​

Every diff collapses all function-level changes into one PR-wide summary: the number of new, modified and deleted functions, the highest risk band reached by any new or modified function, and fn_changed_lines, the diff-changed lines that fall inside a touched function. Text output prints it under the summary line; JSON exposes it at delta.aggregates.pr_summary; the HTML report shows it as summary cards.

Why fn_changed_lines and not a combined risk score. In our evaluation, tested directly against the real compiled binary, fn_changed_lines was the strongest predictor of which PRs later need a defect fix, and every LRS-based PR score we tried was weaker. So the summary reports the line count for "is this PR risky" and the band for "what is the worst code in this diff", and does not add up LRS into a single PR score.

3 modified, 1 new, 0 deleted
Changed lines in touched functions: 84 (strongest tested predictor of defect risk in our evaluation) · highest band: critical
====================================================================================================

Which changed file deserves the closest look ​

Each changed file is also ranked by file_risk_score against only the other files changed in this same diff — not repo-wide. Files at or above the 90th percentile of that diff-local ranking are marked [top 10%] in --format text, next to the file name in the per-function table; JSON exposes the full ranking as file_risk_score/file_risk_diff_percentile/ file_risk_top_decile on each entry in delta.aggregates.files. A file with no file_risk_score (deleted, or an unscoreable type) is left out of the ranking rather than shown with a misleading low score, and a diff with only one scoreable file gets no flag at all. See Reference for the full field list.

hotspots analyze — ownership risk ​

Before starting work on a set of files — your own, or a set an AI coding agent is about to touch — check whether they're entangled with other in-flight work. This used to be the standalone hotspots coordinate command; it's a set of flags on analyze now:

bash
hotspots analyze . --files src/api.ts,src/db.ts
hotspots analyze . --staged                    # from `git diff --cached --name-only`
hotspots analyze . --ownership                 # same as --staged, with no file list to type
git diff main | hotspots analyze . --diff      # derive the file set from a unified diff on stdin

Output (JSON only today):

json
{
  "schema_version": 6,
  "coordinate": {
    "input_files": ["src/api.ts", "src/db.ts"],
    "ownership": [
      { "file": "src/api.ts", "author_count": 2, "author_entropy": 0.61, "newcomer_rate": 0.43, "knowledge_mode": null, "ownership_risk": 0.61, "ownership_risk_band": "low" }
    ]
  }
}
  • ownership — author_count, author_entropy (0 = one owner, higher = more diffuse), newcomer_rate, and knowledge_mode ("concentrated" when ownership is narrow enough that a single-owner handoff is more likely than a real conflict; null otherwise — there is no "diffuse" value today), ownership_risk (normalized entropy, higher = more diffuse) and ownership_risk_band (low/medium/high). Rank a set of files by ownership_risk to decide which ones need coordination first.

Earlier versions also reported raw co-change coupling facts (within_set, hidden_dependencies) as descriptive data with no recommendation attached. Hotspots 2.0 removed them too, once the bar for shipping a field became "proven to work, not just not-yet-refuted": our evaluation actively tested them and found coupling_ratio predicts less coordination friction, not more, and adds nothing once ownership is controlled for — the opposite of the evidence ownership has. Use knowledge_mode and your own judgment instead.

Policy Engine ​

The policy engine runs via hotspots diff ... --policy.

Blocking by default (exit code 1) — severity configurable, see below:

  • critical-introduction — new or existing function crosses LRS ≥ 9.0
  • excessive-risk-regression — LRS increases by ≥ 1.0 on a modified function. This is a flat absolute threshold, not size-relative — our analysis found this mechanically favors flagging large functions over small ones, but couldn't gather enough evidence to say whether that miscalibration matters in practice (see the doc comment on REGRESSION_THRESHOLD in hotspots-core/src/policy.rs).

Warnings (exit code 0, informational): none by default. A policy you downgrade to "warn" (below) reports as a warning instead of failing.

Downgrading a blocking policy for your repo ​

critical-introduction fires the same way whether a function is brand-new or an existing function that regressed — a Critical function needs review either way. But some repos have a legitimately different baseline: a research repo shipping dense, one-shot experiment scripts will routinely introduce Critical-scoring functions on day one, and blocking CI on every one of them is noise, not signal.

If that's your repo, downgrade the policy in .hotspotsrc.json instead of annotating every function with // hotspots-ignore or excluding files forever (which also loses future regression detection on them):

json
{
  "policy": {
    "critical_introduction": "warn",
    "critical_introduction_reason": "eval/ scripts are one-shot research code reviewed case-by-case, not shipped services — approved by @yourhandle 2026-07-06"
  }
}

Each policy accepts "block" (default), "warn" (report, exit 0), or "off" (skip entirely). Downgrading below "block" requires a <name>_reason string — hotspots analyze --validate-config rejects a missing or blank one. This mirrors the // hotspots-ignore: <reason> convention: the point isn't to make the gate unbypassable (anyone with commit access to .hotspotsrc.json can weaken it, same as anyone with access to a CI workflow file can remove a required check) — it's to make sure the change can't be silent. A reviewer of the config diff sees why the gate was weakened, in the same place they see that it was.

The same "block"/"warn"/"off" + _reason pattern applies to excessive_risk_regression via policy.excessive_risk_regression / policy.excessive_risk_regression_reason. Full field reference: Configuration → policy.

CI/CD Setup ​

yaml
name: Hotspots
on:
  pull_request:
  push:
    branches: [main]

jobs:
  analyze:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0        # required for git history
      - uses: Stephen-Collins-tech/hotspots-action@v1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}

The action posts PR comments, generates HTML reports, and fails on blocking policy violations.

Action inputs:

InputDefaultDescription
github-token—Required for PR comments
path.Path to analyze
policycritical-introductioncritical-introduction (enabled), off (disabled)
fail-onerrorerror, warn, never
configauto-discoverPath to config file
versionlatestPin a specific version
post-commenttruePost PR comment

Action outputs: violations (JSON), passed (bool), summary (markdown), report-path, json-output.

Monorepo:

yaml
jobs:
  frontend:
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: Stephen-Collins-tech/hotspots-action@v1
        with:
          path: packages/frontend
          github-token: ${{ secrets.GITHUB_TOKEN }}
  backend:
    steps:
      - uses: actions/checkout@v4
        with: { fetch-depth: 0 }
      - uses: Stephen-Collins-tech/hotspots-action@v1
        with:
          path: packages/backend
          github-token: ${{ secrets.GITHUB_TOKEN }}

Upload HTML report as artifact:

yaml
- uses: Stephen-Collins-tech/hotspots-action@v1
  id: hotspots
  with:
    github-token: ${{ secrets.GITHUB_TOKEN }}
- uses: actions/upload-artifact@v4
  if: always()
  with:
    name: hotspots-report-${{ github.sha }}
    path: ${{ steps.hotspots.outputs.report-path }}
    retention-days: 30

Manual CI (GitLab, CircleCI, Jenkins, etc.) ​

bash
# Fail CI on blocking violations
hotspots diff --auto-analyze --policy

For GitLab CI:

yaml
hotspots:
  stage: analyze
  image: rust:latest
  before_script:
    - cargo install hotspots-cli
  script:
    - hotspots diff --auto-analyze --policy
  artifacts:
    paths: [.hotspots/report.html]
    expire_in: 1 week
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'

Troubleshooting:

  • "failed to extract git context" — use fetch-depth: 0 in checkout
  • "merge-base not found" — fetch the base branch explicitly: git fetch origin $BASE_BRANCH
  • PR comments not posting — ensure pull-requests: write permission and github-token is set

Output Formats ​

Text ​

bash
hotspots analyze . --format text --explain  # with per-function detail
hotspots analyze . --format text --level file

Color-coded by risk band (critical=red, high=yellow, moderate=blue, low=green). Disable: NO_COLOR=1 hotspots analyze ....

The --explain view adds per-function risk breakdown. When a trained ranker is active (run hotspots train first), it also emits a ✦ phrase line for each CRITICAL/HIGH function derived from which signals are in the top 20th percentile for the repo — e.g.:

  0.56  hotspots-core/src/aggregates.rs:694  compute_module_instability_from_edges
         ✦ Tightly coupled to other hotspots, depended on by many callers, and high cyclomatic complexity.
           Worth prioritising before next release.

No ✦ lines appear without a trained ranker.

JSON ​

bash
hotspots analyze src/ --format json
hotspots analyze . --format json --all-functions  # full functions array

Every JSON output is the unified master-schema envelope (schema_version: 6, same version across analyze, diff, the ownership-risk flags, and --axes). Default JSON omits the flat functions array in favor of the triage-first structure (active/quiet groups); use --all-functions to get the flat functions array instead. Always check schema_version in tooling.

Useful jq patterns:

bash
# Critical functions only
jq '.functions[] | select(.band == "critical")' output.json

# Count by band
jq '.aggregates.by_band' output.json

# Top 10 by LRS
jq '.functions | sort_by(.lrs) | reverse | .[0:10]' output.json

HTML ​

Interactive self-contained report with sortable table, risk landscape scatter plot, and trend charts (requires ≥ 2 snapshots):

bash
hotspots analyze . --format html
open .hotspots/report.html   # macOS

Need JSON and the report for the same commit? One run writes both, so the second analysis (about as expensive as the first on large repos) is avoided:

bash
hotspots analyze . --format json --html-output report.html > snapshot.json

SARIF (GitHub Code Scanning) ​

bash
hotspots analyze . --format sarif --output .hotspots/results.sarif

Maps bands to SARIF levels: critical→error, high→warning, moderate→note. Integrate with GitHub code scanning:

yaml
- name: Run Hotspots
  run: hotspots analyze . --format sarif --output .hotspots/results.sarif
- uses: github/codeql-action/upload-sarif@v3
  with:
    sarif_file: .hotspots/results.sarif

Suppression Comments ​

Suppress CI policy failures while keeping the function visible in reports:

typescript
// hotspots-ignore: legacy payment processor, rewrite scheduled Q2 2026
function legacyBillingLogic() { ... }
python
# hotspots-ignore: legacy payment processor, rewrite scheduled Q2 2026
def legacy_billing_logic(): ...

Rules:

  • Comment must be on the line immediately before the function (no blank line between)
  • Format: // hotspots-ignore: <reason> — use # instead of // for Python; every other supported language (Go, Java, C#, PHP, Rust, C/C++, TypeScript/JavaScript, Vue, Astro) uses //
  • Reason is required (missing reason triggers a warning, not a hard failure)
  • Suppressed functions still appear in all reports with a suppression_reason field
  • Suppressed functions still count toward net repo regression

Good reasons: complex algorithm with test coverage, generated code, migration pending with date. Bad reasons: "TODO fix this later", no reason at all.

Touch Metrics ​

Touch metrics measure how often a file has changed in the last 365 days and how long ago it last changed. They feed activity_risk and are computed from one batched git log per file.

bash
# Default: touch, churn and recency are computed
hotspots analyze .

# Skip all git I/O (benchmarking, or very large repos) — an env var now, not a flag
HOTSPOTS_SKIP_TOUCH_METRICS=1 hotspots analyze .

Snapshot Management ​

This used to be the standalone hotspots prune command; it's the --prune flag on analyze now:

bash
# Prune snapshots for deleted/force-pushed branches
hotspots analyze --prune --unreachable --dry-run
hotspots analyze --prune --unreachable --older-than 30

# Compact snapshot storage (1 = deltas between snapshots, 2 = keep only band changes)
hotspots analyze --prune --compact 1 --dry-run
hotspots analyze --prune --compact 1

Training a Repo-Specific Ranker ​

By default, hotspots ranks by LRS. Training fits a model from your repo's bug-fix history to re-rank based on which structural features actually predict bugs in your codebase.

bash
# File-level labels (fast); always runs a pre-flight screen and a post-training P@K eval
hotspots train .

# Blame-based function-level labels (more precise, slower)
hotspots train . --blame

There is no --eval flag — the P@K report always prints after a successful training run:

P@K evaluation (365-day fix-label window):
  K      P@K      base_rate
  10     0.400    0.084
  20     0.300    0.084

If P@K is well above base_rate, apply the model. If P@K ≈ base_rate, skip it — the default LRS ranking is just as good.

Once .hotspots/ranker.json exists, every hotspots analyze loads it automatically, and prints which model class is in effect:

hotspots: using trained ranker (model class: Ridge)

Training requires: ≥ 50 functions in snapshot, ≥ 5 positive and ≥ 10 negative labels from fix commits. Fix keywords: fix:, bug, patch, hotfix, regression, defect.

Training is most valuable on repos with 1+ year of history, recognizable fix-commit conventions, and bug clusters in specific files. There is no --screen flag to check suitability separately — every train run screens the repo first and aborts with SKIP_FT before fitting anything if the signal is too flat.

Ridge vs. RandomForest: automatic model class selection ​

hotspots train doesn't always fit a RandomForest. Before training, it runs a quick pre-flight comparison — the regime screener — to check whether a plain linear model (Ridge regression) already predicts which functions were touched by fix commits (the same fix-commit labels described above) as well as a forest does. If so, it fits Ridge instead and skips RandomForest training entirely.

Why this matters: on repos where the relationship between features (churn, coupling, LRS, etc.) and bug-proneness is essentially linear, a RandomForest adds complexity (harder to reason about, slower to train, more prone to overfitting on ties) without improving ranking quality. The screener catches this automatically so you don't have to guess.

You'll see the verdict printed during training:

Model class: Ridge (regime=LINEAR, Δρ=+0.03) — RandomForest training skipped

or, when trees add real lift:

Model class: RandomForest (regime=STRONG, Δρ=+0.14)

Verdicts:

VerdictMeaningModel used
LINEARΔρ < 0.03 — Ridge matches RandomForestRidge
WEAK0.03 ≤ Δρ ≤ 0.10 — modest tree advantageRandomForest
STRONGΔρ > 0.10 — trees clearly helpRandomForest
UNRELIABLEToo few positive labels to trust the comparisonRandomForest (safe default)

This selection is fully automatic — there's no flag to control it. The chosen model class is saved in ranker.json and reused every time hotspots analyze scores your repo, so you always know which kind of model produced your rankings.

AI Integration ​

bash
# Agent-optimized snapshot JSON (triage buckets + action text)
hotspots analyze . --format json

# Flat array for tooling that expects a complete function list
hotspots analyze . --format json --all-functions

# Diff for PR review context
hotspots diff --auto-analyze --format json

# Pipe critical functions to Claude/Cursor/Copilot
hotspots analyze src/ --format json | jq '.functions[] | select(.lrs > 9)'

# Print the dense, machine-readable agent contract (flags, JSON shape, exit codes)
hotspots analyze --help-agent

Hooks and CI templates ​

Policy checks run via diff --auto-analyze --policy, which compares against the auto-detected merge-base. Seed a baseline first, otherwise --auto-analyze has to build it on the fly:

bash
hotspots analyze .

Pre-push hook, with the pre-commit framework (.pre-commit-config.yaml):

yaml
repos:
  - repo: local
    hooks:
      - id: hotspots
        name: hotspots risk check
        language: system
        entry: hotspots diff --auto-analyze --policy --format text
        pass_filenames: false
        stages: [pre-push]

Pre-push hook, plain shell (save as .git/hooks/pre-push, then chmod +x):

sh
#!/usr/bin/env sh
set -e
hotspots diff --auto-analyze --policy --format text

GitHub Actions (.github/workflows/hotspots.yml). A push to the main branch builds and caches the baseline snapshot; a pull request restores the base commit's snapshot and gates on the delta. The first PR has no baseline yet and skips policy; gating starts once a main-branch snapshot is cached.

yaml
name: Hotspots

on:
  pull_request:
  push:
    branches:
      - main
      - master

permissions:
  contents: read

jobs:
  hotspots:
    name: Analyze code hotspots
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Hotspots CLI
        run: |
          curl -fsSL https://raw.githubusercontent.com/Stephen-Collins-tech/hotspots/main/install.sh | sh
          echo "$HOME/.local/bin" >> "$GITHUB_PATH"

      # On push-to-main we save the snapshot under hotspots-{sha}.
      # On a PR we restore the snapshot for the base-branch commit so that
      # `diff` has a baseline to compare against.
      - name: Restore snapshot cache
        uses: actions/cache@v4
        with:
          path: .hotspots/
          key: hotspots-${{ github.sha }}
          restore-keys: |
            hotspots-${{ github.event.pull_request.base.sha }}
            hotspots-

      - name: Analyze (snapshot on main, diff on PR)
        run: |
          if [ "${{ github.event_name }}" = "pull_request" ]; then
            hotspots diff --auto-analyze --policy
          else
            # text format requires --explain (or --level) when not --format
            # json/html/sarif; the snapshot is persisted to .hotspots/ either way.
            hotspots analyze . --format json > /dev/null
          fi

Troubleshooting ​

"snapshot already exists and differs" — regenerate with --force.

"no snapshot found for ref ..." from diff — run hotspots analyze . on that ref first, or pass --auto-analyze to generate it on the fly.

"failed to extract git context" — must be run inside a git repository.

Text format without --explain is not supported — --format text needs --explain or --level file; use --format json if you don't want either.

--no-persist and --force are mutually exclusive — pick one.

--level and --explain are mutually exclusive — pick one.

Released under the MIT License. · hotspots.dev