cargo-judge 0.7.0

Deterministic post-refactoring analysis for Rust workspaces
Documentation
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
531
532
533
534
535
536
537
538
539
540
541
542
//! Lightweight workspace projections: inspection, refactoring map, and impact.

use crate::*;
use std::collections::{BTreeMap, BTreeSet};

/// Loads the workspace and runs the shared complexity/duplication pass,
/// respecting `--include-tests`. Shared by `complexity` and `map`, whose
/// data-loading preamble is otherwise byte-identical; neither command needs
/// the `Workspace` itself afterwards, only the derived `RefactorMap`.
fn load_complexity_map(include_tests: bool) -> Result<judge::refactor_map::RefactorMap, CliError> {
    let workspace = judge::ingest::load(None)?;
    Ok(judge::refactor_map::analyze(&workspace, include_tests))
}

/// Builds the `sarif`/`markdown` rejection every command in this module
/// returns from its final match arm — only the command name differs, the
/// supported-format list (`tty, json`) is identical across all of them.
fn unsupported_workspace_format(command_name: &str, format: OutputFormat) -> CliError {
    unsupported_format(command_name, format, "tty, json")
}

/// Prints "analysis errors: N" when `errors` is non-empty. Shared by
/// `complexity` and `refactor`, which report only the count (unlike
/// `structure`/`map`, which also list each error's text).
fn print_analysis_error_count_tty(out: &mut dyn Write, errors: &[String]) -> std::io::Result<()> {
    if !errors.is_empty() {
        writeln!(out, "analysis errors: {}", errors.len())?;
    }
    Ok(())
}

/// Renders up to `limit` files ranked by measured complexity. Shared by
/// `complexity` (top 20) and `map` (top 15) — the limit is the only
/// difference between the two callers.
fn print_top_complexity_files_tty(
    out: &mut dyn Write,
    map: &judge::refactor_map::RefactorMap,
    limit: usize,
) -> std::io::Result<()> {
    for file in map
        .files
        .iter()
        .filter(|file| file.complexity_rank.is_some())
        .take(limit)
    {
        let metrics = file.complexity_in_scope(map.includes_tests);
        writeln!(
            out,
            "  #{:<2} {:>4} total, {:>3} max, {:>3} functions  {}",
            file.complexity_rank.unwrap(),
            metrics.total_cyclomatic,
            metrics.max_cyclomatic,
            metrics.functions,
            file.file.display()
        )?;
    }
    Ok(())
}

/// Current-state workspace architecture, deliberately independent of Git.
pub(crate) fn run_structure(
    options: StructureOptions,
    out: &mut dyn Write,
) -> Result<CommandOutcome, CliError> {
    let workspace = judge::ingest::load(None)?;
    let map = judge::refactor_map::analyze(&workspace, false);
    let graph =
        judge::rules::boundaries::build_crate_graph(Some(&workspace.root.join("Cargo.toml")))?;

    match options.format {
        OutputFormat::Json => write_json(
            out,
            &serde_json::json!({
                "schema_version": 1,
                "workspace_root": workspace.root,
                "crates": workspace.crates.iter().map(|krate| serde_json::json!({
                    "name": krate.name,
                    "version": krate.version,
                    "manifest": krate.manifest_path,
                    "source_files": krate.source_files.len(),
                    "entry_points": krate.entry_points.iter().map(|entry| serde_json::json!({
                        "kind": entry.kind.label(),
                        "name": entry.name,
                        "path": entry.path,
                    })).collect::<Vec<_>>(),
                })).collect::<Vec<_>>(),
                "internal_dependency_edges": graph.edges,
                "complexity": map.crates,
                "files": map.files,
                "duplication": map.duplication,
                "analysis_errors": map.analysis_errors,
            }),
        )?,
        OutputFormat::Tty => {
            writeln!(
                out,
                "workspace structure: {} crates",
                workspace.crates.len()
            )?;
            for krate in &workspace.crates {
                writeln!(
                    out,
                    "  {} {} — {} source files",
                    krate.name,
                    krate.version,
                    krate.source_files.len()
                )?;
                for entry in &krate.entry_points {
                    writeln!(
                        out,
                        "    [{}] {}  {}",
                        entry.kind.label(),
                        entry.name,
                        entry.path.display()
                    )?;
                }
            }
            writeln!(out, "\ninternal dependency edges:")?;
            let mut names: Vec<_> = graph.edges.keys().collect();
            names.sort();
            for name in names {
                let dependencies = &graph.edges[name];
                if dependencies.is_empty() {
                    writeln!(out, "  {name} -> none")?;
                } else {
                    writeln!(out, "  {name} -> {}", dependencies.join(", "))?;
                }
            }
            writeln!(out, "\ncomplexity concentration (production code):")?;
            for krate in &map.crates {
                writeln!(
                    out,
                    "  {}  {} functions, {} total cyclomatic, {} max",
                    krate.name,
                    krate.production.functions,
                    krate.production.total_cyclomatic,
                    krate.production.max_cyclomatic
                )?;
            }
            if !map.analysis_errors.is_empty() {
                writeln!(out, "\nanalysis errors:")?;
                for error in map.analysis_errors {
                    writeln!(out, "  {error}")?;
                }
            }
        }
        OutputFormat::Sarif | OutputFormat::Markdown => {
            return Err(unsupported_workspace_format("`structure`", options.format));
        }
    }
    Ok(CommandOutcome::Clean)
}

/// A focused projection of the measured complexity data already used by map.
pub(crate) fn run_complexity(
    options: ComplexityOptions,
    out: &mut dyn Write,
) -> Result<CommandOutcome, CliError> {
    let map = load_complexity_map(options.include_tests)?;
    match options.format {
        OutputFormat::Json => write_json(
            out,
            &serde_json::json!({
                "schema_version": 1,
                "includes_tests": map.includes_tests,
                "crates": map.crates,
                "files": map.files,
                "analysis_errors": map.analysis_errors,
            }),
        )?,
        OutputFormat::Tty => {
            writeln!(
                out,
                "complexity: {}",
                if map.includes_tests {
                    "production + tests"
                } else {
                    "production"
                }
            )?;
            print_top_complexity_files_tty(out, &map, 20)?;
            print_analysis_error_count_tty(out, &map.analysis_errors)?;
        }
        OutputFormat::Sarif | OutputFormat::Markdown => {
            return Err(unsupported_workspace_format("`complexity`", options.format));
        }
    }
    Ok(CommandOutcome::Clean)
}

#[derive(Serialize)]
struct RefactorCandidate {
    file: PathBuf,
    severity: judge::finding::Severity,
    rules: Vec<String>,
    finding_ids: Vec<String>,
    items: Vec<String>,
    reason_count: usize,
}

/// How many of the highest-ranked candidates surface as curated
/// `next_actions` — a small, bounded summary layered on top of the full
/// `candidates` queue, not a replacement for it.
const NEXT_ACTIONS_LIMIT: usize = 10;

/// A ranked, evidence-linked inspection step derived from an already-sorted
/// `RefactorCandidate`. Every field is copied from the candidate it
/// summarizes; nothing here is a separate analysis pass or an invented fix.
#[derive(Serialize)]
struct NextAction {
    rank: usize,
    action: String,
    file: PathBuf,
    severity: judge::finding::Severity,
    reason_count: usize,
    rules: Vec<String>,
    finding_ids: Vec<String>,
}

/// Derives the curated `next_actions` list from `candidates`, which is
/// already sorted deterministically by severity, then reason count, then
/// file. Ranking here just takes the top `NEXT_ACTIONS_LIMIT` — it never
/// recomputes or re-sorts.
fn build_next_actions(candidates: &[RefactorCandidate]) -> Vec<NextAction> {
    candidates
        .iter()
        .take(NEXT_ACTIONS_LIMIT)
        .enumerate()
        .map(|(index, candidate)| NextAction {
            rank: index + 1,
            action: format!(
                "Inspect {}: {} finding{} across [{}], highest severity {}",
                candidate.file.display(),
                candidate.reason_count,
                if candidate.reason_count == 1 { "" } else { "s" },
                candidate.rules.join(", "),
                severity_label(candidate.severity)
            ),
            file: candidate.file.clone(),
            severity: candidate.severity,
            reason_count: candidate.reason_count,
            rules: candidate.rules.clone(),
            finding_ids: candidate.finding_ids.clone(),
        })
        .collect()
}

/// Aggregates existing Fast-Tier findings into an inspection queue. It does
/// not invent a fix: every reason is a stable finding id supplied in output.
pub(crate) fn run_refactor(
    options: RefactorOptions,
    out: &mut dyn Write,
) -> Result<CommandOutcome, CliError> {
    let workspace = judge::ingest::load(None)?;
    let mut collected = super::combined_analysis::collect_findings(&workspace)?;
    judge::finding::sort_by_severity_desc(&mut collected.findings);
    judge::finding::relativize_paths(&mut collected.findings, &workspace.root);

    let target = options.target.as_ref().map(|path| {
        path.strip_prefix(&workspace.root)
            .unwrap_or(path)
            .to_path_buf()
    });
    let mut grouped: BTreeMap<PathBuf, Vec<&Finding>> = BTreeMap::new();
    for finding in &collected.findings {
        if target
            .as_ref()
            .is_some_and(|target| &finding.location.file != target)
        {
            continue;
        }
        grouped
            .entry(finding.location.file.clone())
            .or_default()
            .push(finding);
    }
    let mut candidates = grouped
        .into_iter()
        .map(|(file, findings)| {
            let severity = findings
                .iter()
                .map(|finding| finding.severity)
                .max()
                .expect("a candidate contains at least one finding");
            let rules = findings
                .iter()
                .map(|finding| finding.rule.to_string())
                .collect::<BTreeSet<_>>()
                .into_iter()
                .collect();
            let items = findings
                .iter()
                .map(|finding| finding.location.item_path.clone())
                .collect::<BTreeSet<_>>()
                .into_iter()
                .collect();
            RefactorCandidate {
                file,
                severity,
                rules,
                finding_ids: findings
                    .iter()
                    .map(|finding| finding.id.to_string())
                    .collect::<BTreeSet<_>>()
                    .into_iter()
                    .collect(),
                items,
                reason_count: findings.len(),
            }
        })
        .collect::<Vec<_>>();
    candidates.sort_by_key(|candidate| {
        (
            std::cmp::Reverse(candidate.severity),
            std::cmp::Reverse(candidate.reason_count),
            candidate.file.clone(),
        )
    });
    let context_findings = collected
        .findings
        .iter()
        .filter(|finding| {
            target
                .as_ref()
                .is_none_or(|target| &finding.location.file == target)
        })
        .cloned()
        .collect::<Vec<_>>();
    let next_actions = build_next_actions(&candidates);

    match options.format {
        OutputFormat::Json => write_json(
            out,
            &serde_json::json!({
                "schema_version": 1,
                "scope": { "tier": "fast", "target": target },
                "analysis_errors": collected.analysis_errors,
                "candidates": candidates,
                "next_actions": next_actions,
                "findings": context_findings,
                "contract": "Each candidate aggregates only the included findings. finding_ids resolve within this artifact to locations, evidence, limitations, and causal links; no candidate is an automatic refactoring instruction."
            }),
        )?,
        OutputFormat::Tty => {
            writeln!(out, "refactoring candidates: {}", candidates.len())?;
            for (index, candidate) in candidates.iter().enumerate() {
                writeln!(
                    out,
                    "  {}. [{}] {} — {} reasons: {}",
                    index + 1,
                    severity_label(candidate.severity),
                    candidate.file.display(),
                    candidate.reason_count,
                    candidate.rules.join(", ")
                )?;
            }
            if !next_actions.is_empty() {
                writeln!(out, "next actions:")?;
                for next_action in &next_actions {
                    writeln!(out, "  {}. {}", next_action.rank, next_action.action)?;
                }
            }
            print_analysis_error_count_tty(out, &collected.analysis_errors)?;
        }
        OutputFormat::Sarif | OutputFormat::Markdown => {
            return Err(unsupported_workspace_format("`refactor`", options.format));
        }
    }
    Ok(CommandOutcome::Clean)
}

pub(crate) fn run_inspect(out: &mut dyn Write) -> Result<CommandOutcome, CliError> {
    let workspace = judge::ingest::load(None)?;

    writeln!(out, "workspace root: {}", workspace.root.display())?;
    writeln!(out, "crates: {}", workspace.crates.len())?;
    for krate in &workspace.crates {
        writeln!(out)?;
        writeln!(out, "  {} {}", krate.name, krate.version)?;
        writeln!(out, "    manifest: {}", krate.manifest_path.display())?;
        writeln!(out, "    source files: {}", krate.source_files.len())?;
        if krate.entry_points.is_empty() {
            writeln!(out, "    entry points: none")?;
        } else {
            writeln!(out, "    entry points:")?;
            for entry in &krate.entry_points {
                writeln!(
                    out,
                    "      [{}] {} — {}",
                    entry.kind.label(),
                    entry.name,
                    entry.path.display()
                )?;
            }
        }
    }

    writeln!(out)?;
    writeln!(out, "tiers:")?;
    writeln!(out, "  fast: available")?;
    writeln!(
        out,
        "  deep: {}",
        if AnalysisTier::Deep.is_available() {
            "available"
        } else {
            "not available (build with --features deep)"
        }
    )?;
    writeln!(out)?;
    writeln!(out, "cache: not implemented yet")?;
    Ok(CommandOutcome::Clean)
}

/// `cargo judge map`: concise workspace facts ordered by measured aggregate
/// cyclomatic complexity. This is a planning aid, not a verdict or an
/// automatic refactoring recommendation.
pub(crate) fn run_map(
    options: MapOptions,
    out: &mut dyn Write,
) -> Result<CommandOutcome, CliError> {
    let map = load_complexity_map(options.include_tests)?;

    match options.format {
        OutputFormat::Json => write_json(out, &map)?,
        OutputFormat::Tty => {
            let authored_files = map
                .files
                .iter()
                .filter(|file| file.source_kind == "authored")
                .count();
            writeln!(
                out,
                "workspace map: {} crates, {authored_files} authored files",
                map.crates.len()
            )?;
            if !map.analysis_errors.is_empty() {
                writeln!(out, "analysis errors: {}", map.analysis_errors.len())?;
                for error in &map.analysis_errors {
                    writeln!(out, "  {error}")?;
                }
            }
            writeln!(out)?;
            writeln!(
                out,
                "complexity attention ({}, measured total cyclomatic, not a verdict):",
                if map.includes_tests {
                    "production + test code"
                } else {
                    "production code"
                }
            )?;
            print_top_complexity_files_tty(out, &map, 15)?;
            writeln!(out)?;
            writeln!(
                out,
                "duplication attention (repeated tokens, not an automatic merge recommendation):"
            )?;
            if map.duplication.top_families.is_empty() {
                writeln!(out, "  none at the configured threshold")?;
            }
            for family in &map.duplication.top_families {
                writeln!(
                    out,
                    "  #{}  {} members × {} tokens across {} files  {}",
                    family.rank,
                    family.members,
                    family.tokens_per_member,
                    family.files.len(),
                    family.representative_items.join(", ")
                )?;
            }
        }
        OutputFormat::Sarif | OutputFormat::Markdown => {
            return Err(unsupported_workspace_format("`map`", options.format));
        }
    }
    Ok(CommandOutcome::Clean)
}

/// `cargo judge impact <PATH>`: metadata-backed context for planning a change
/// to one source file. It identifies direct analysis inputs; it intentionally
/// does not guess which individual findings will result from an edit.
pub(crate) fn run_impact(
    options: ImpactOptions,
    out: &mut dyn Write,
) -> Result<CommandOutcome, CliError> {
    let workspace = judge::ingest::load(None)?;
    let impact = judge::impact::analyze(&workspace, &options.target)
        .map_err(|err| CliError::Config(err.to_string()))?;

    match options.format {
        OutputFormat::Json => write_json(out, &impact)?,
        OutputFormat::Tty => {
            writeln!(out, "impact: {}", impact.target.display())?;
            writeln!(out, "crate: {}", impact.crate_name)?;
            writeln!(
                out,
                "source: {} ({})",
                impact.source_kind, impact.source_domain
            )?;
            writeln!(out)?;
            writeln!(
                out,
                "Cargo targets in this crate (shared crate, not reachability proof):"
            )?;
            for target in &impact.crate_targets {
                writeln!(
                    out,
                    "  {}:{}  {}{}",
                    target.kind,
                    target.name,
                    target.source.display(),
                    if target.is_target_root {
                        " (this file)"
                    } else {
                        ""
                    }
                )?;
            }
            writeln!(out)?;
            writeln!(out, "direct analysis inputs (not a finding prediction):")?;
            for effect in &impact.direct_analysis {
                if effect.included_by_default {
                    writeln!(out, "  included  {:<30} {}", effect.command, effect.input)?;
                } else {
                    writeln!(
                        out,
                        "  excluded  {:<30} {} ({})",
                        effect.command,
                        effect.input,
                        effect.required_opt_in.unwrap_or("opt-in required")
                    )?;
                }
            }
        }
        OutputFormat::Sarif | OutputFormat::Markdown => {
            return Err(unsupported_workspace_format("`impact`", options.format));
        }
    }
    Ok(CommandOutcome::Clean)
}