repotoire 0.8.2

Graph-powered code analysis CLI. 110 detectors for security, architecture, bus factor, and code quality.
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
//! Findings command implementation

use anyhow::{Context, Result};
use console::style;
use std::fs;
use std::path::Path;

#[cfg(not(target_os = "windows"))]
use super::tui;
use crate::models::{Finding, Severity};

/// Run interactive TUI mode
#[cfg(not(target_os = "windows"))]
pub fn run_interactive(path: &Path) -> Result<()> {
    let findings = load_findings(path)?;
    if findings.is_empty() {
        println!("No findings! Your code looks clean.");
        return Ok(());
    }
    tui::run(findings, path.to_path_buf())
}

/// Interactive TUI is not supported on Windows — uses libc/termios/poll directly.
#[cfg(target_os = "windows")]
pub fn run_interactive(_path: &Path) -> Result<()> {
    anyhow::bail!(
        "Interactive findings browser is not yet supported on Windows. \
         Use `repotoire findings` (without -i) for paginated text output, \
         or `repotoire findings --json` for scripting."
    )
}

/// Load findings from last analysis
fn load_findings(path: &Path) -> Result<Vec<Finding>> {
    let findings_path = crate::cache::findings_cache_path(path);
    if !findings_path.exists() {
        anyhow::bail!(
            "No findings found. Run `repotoire analyze` first.\n\
             Looking for: {}",
            findings_path.display()
        );
    }

    let findings_json =
        fs::read_to_string(&findings_path).context("Failed to read findings file")?;

    let parsed: serde_json::Value =
        serde_json::from_str(&findings_json).context("Failed to parse findings file")?;
    let findings: Vec<Finding> = serde_json::from_value(
        parsed
            .get("findings")
            .cloned()
            .unwrap_or(serde_json::json!([])),
    )
    .context("Failed to parse findings array")?;

    // Semantic validation. Finding deserialization is permissive
    // (`#[serde(default)]` on every field) so `{"bogus": "x"}` parses
    // as an all-default Finding. If every entry is semantically empty
    // the cache is corrupt — bail with an actionable message rather
    // than serving garbage. See
    // docs/superpowers/specs/2026-05-11-cache-validation.md.
    if !findings.is_empty() && findings.iter().all(|f| !f.is_valid()) {
        anyhow::bail!(
            "Findings cache at {} is corrupt: every entry failed semantic validation. \
             Re-run `repotoire analyze` to regenerate it.",
            findings_path.display()
        );
    }
    let findings: Vec<Finding> = findings.into_iter().filter(|f| f.is_valid()).collect();

    Ok(findings)
}

pub struct RunArgs<'a> {
    pub path: &'a Path,
    pub index: Option<usize>,
    pub json: bool,
    pub top: Option<usize>,
    pub severity: Option<Severity>,
    pub page: usize,
    pub per_page: usize,
}

pub fn run(args: RunArgs<'_>) -> Result<()> {
    let RunArgs {
        path,
        index,
        json,
        top,
        severity,
        page,
        per_page,
    } = args;
    let mut findings = load_findings(path)?;

    // Filter by severity if specified
    if let Some(min) = severity {
        findings.retain(|f| f.severity >= min);
    }

    // Sort by severity (critical first)
    findings.sort_by_key(|f| std::cmp::Reverse(f.severity));

    // Apply top N limit
    if let Some(n) = top {
        findings.truncate(n);
    }

    if findings.is_empty() {
        println!("{}", style("No findings! Your code looks clean.").green());
        return Ok(());
    }

    // If JSON output requested
    if json {
        println!("{}", serde_json::to_string_pretty(&findings)?);
        return Ok(());
    }

    // If specific index requested
    if let Some(idx) = index {
        if idx == 0 || idx > findings.len() {
            anyhow::bail!(
                "Invalid finding index: {}. Valid range: 1-{}",
                idx,
                findings.len()
            );
        }
        let finding = &findings[idx - 1];
        print_finding_detail(finding, idx);
        return Ok(());
    }

    // Print summary of all findings
    println!("{}", style("🔍 Code Findings").bold());
    println!();

    // Group by severity
    let critical: Vec<_> = findings
        .iter()
        .filter(|f| f.severity == Severity::Critical)
        .collect();
    let high: Vec<_> = findings
        .iter()
        .filter(|f| f.severity == Severity::High)
        .collect();
    let medium: Vec<_> = findings
        .iter()
        .filter(|f| f.severity == Severity::Medium)
        .collect();
    let low: Vec<_> = findings
        .iter()
        .filter(|f| f.severity == Severity::Low)
        .collect();

    println!(
        "   {} {} critical",
        style(critical.len()).red().bold(),
        if critical.len() == 1 {
            "finding"
        } else {
            "findings"
        }
    );
    println!(
        "   {} {} high",
        style(high.len()).yellow().bold(),
        if high.len() == 1 {
            "finding"
        } else {
            "findings"
        }
    );
    println!(
        "   {} {} medium",
        style(medium.len()).cyan(),
        if medium.len() == 1 {
            "finding"
        } else {
            "findings"
        }
    );
    println!(
        "   {} {} low",
        style(low.len()).dim(),
        if low.len() == 1 {
            "finding"
        } else {
            "findings"
        }
    );
    println!();

    // Apply pagination (per_page = 0 means all)
    let total_findings = findings.len();
    let (start_idx, end_idx, current_page, total_pages) = if per_page > 0 {
        let total_pages = total_findings.div_ceil(per_page);
        let current_page = page.max(1).min(total_pages.max(1));
        let start = (current_page - 1) * per_page;
        let end = (start + per_page).min(total_findings);
        (start, end, current_page, total_pages)
    } else {
        (0, total_findings, 1, 1)
    };

    for (i, finding) in findings
        .iter()
        .enumerate()
        .skip(start_idx)
        .take(end_idx - start_idx)
    {
        let idx = i + 1; // 1-indexed for user display
        let severity_icon = match finding.severity {
            Severity::Critical => style("🔴").red(),
            Severity::High => style("🟠").yellow(),
            Severity::Medium => style("🟡").cyan(),
            Severity::Low => style("").dim(),
            Severity::Info => style("ℹ️").dim(),
        };

        let file = finding
            .affected_files
            .first()
            .map(|p| p.display().to_string())
            // Empty `PathBuf::from("")` deserves the same treatment as a
            // missing entry — otherwise we'd render a bare `└─ ` with no
            // path (qa-audit-2026-05-07/03-functional.md #2).
            .filter(|s| !s.is_empty());

        let line = finding
            .line_start
            .map(|l| format!(":{}", l))
            .unwrap_or_default();

        println!(
            "{:>3}. {} {}",
            style(idx).dim(),
            severity_icon,
            style(&finding.title).bold()
        );
        // Suppress the `└─` location line entirely when the finding is
        // repo-level (no specific file).
        if let Some(file) = file {
            println!(
                "     {} {}{}",
                style("└─").dim(),
                style(&file).dim(),
                style(&line).dim()
            );
        }
    }

    // Show pagination info
    if per_page > 0 && total_pages > 1 {
        println!();
        println!(
            "{}Showing page {} of {} ({} per page, {} total)",
            style("📑 ").bold(),
            style(current_page).cyan(),
            style(total_pages).cyan(),
            style(per_page).dim(),
            style(total_findings).cyan(),
        );
        if current_page < total_pages {
            println!(
                "   Use {} to see more",
                style(format!("--page {}", current_page + 1)).yellow()
            );
        }
    }

    println!();
    println!("{}", style("💡 Tips").bold());
    println!(
        "   • Run {} for details on a specific finding",
        style("repotoire findings <n>").cyan()
    );
    println!(
        "   • Run {} for AI-assisted fixes",
        style("repotoire fix <n>").cyan()
    );
    println!(
        "   • Run {} for JSON output",
        style("repotoire findings --json").cyan()
    );

    Ok(())
}

/// Accept one or all findings into the baseline.
///
/// - `index = Some(n)` → accept finding #n from the last analysis
/// - `index = None` → accept all current findings
pub fn accept_findings(path: &Path, index: Option<usize>, reason: Option<String>) -> Result<()> {
    use crate::baseline::{Baseline, BaselineEntry};

    let findings = load_findings(path)?;
    if findings.is_empty() {
        println!("{}", style("No findings to accept.").green());
        return Ok(());
    }

    // Resolve repo root (baseline lives next to repotoire.toml / .git)
    let repo_root = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    let mut baseline = Baseline::load(&repo_root)?;

    let to_accept: Vec<(usize, &Finding)> = if let Some(idx) = index {
        if idx == 0 || idx > findings.len() {
            anyhow::bail!(
                "Invalid finding index: {}. Valid range: 1-{}",
                idx,
                findings.len()
            );
        }
        vec![(idx, &findings[idx - 1])]
    } else {
        findings
            .iter()
            .enumerate()
            .map(|(i, f)| (i + 1, f))
            .collect()
    };

    let mut added = 0;
    for (_idx, finding) in &to_accept {
        let fingerprint = crate::baseline::fingerprint::file_fingerprint(
            &finding.detector,
            &finding
                .affected_files
                .first()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or_default(),
            finding.description.lines().next().unwrap_or(""),
        );
        if baseline.add(BaselineEntry {
            detector: finding.detector.clone(),
            fingerprint,
            qualified_name: None,
            file: finding
                .affected_files
                .first()
                .map(|p| p.to_string_lossy().to_string()),
            first_line_content: finding.description.lines().next().map(|s| s.to_string()),
            accepted_by: None,
            reason: reason.clone(),
        }) {
            added += 1;
        }
    }

    let path = baseline.save(&repo_root)?;

    if let Some(idx) = index {
        let finding = &to_accept[0].1;
        if added > 0 {
            println!(
                "Accepted finding #{} ({}: {}) into baseline",
                idx, finding.detector, finding.title
            );
        } else {
            println!("Finding #{} already in baseline", idx);
        }
    } else {
        println!(
            "Accepted {} new findings into baseline ({} total)",
            added,
            baseline.findings.len()
        );
    }
    println!("Baseline: {}", style(path.display()).dim());

    Ok(())
}

fn print_finding_detail(finding: &Finding, index: usize) {
    let severity_str = match finding.severity {
        Severity::Critical => style("CRITICAL").red().bold(),
        Severity::High => style("HIGH").yellow().bold(),
        Severity::Medium => style("MEDIUM").cyan(),
        Severity::Low => style("LOW").dim(),
        Severity::Info => style("INFO").dim(),
    };

    println!();
    println!("{} Finding #{}", style("📋").bold(), index);
    println!();
    println!("   {} {}", style("Title:").bold(), finding.title);
    println!("   {} {}", style("Severity:").bold(), severity_str);
    println!("   {} {}", style("Detector:").bold(), finding.detector);

    if let Some(cat) = &finding.category {
        println!("   {} {}", style("Category:").bold(), cat);
    }

    if let Some(cwe) = &finding.cwe_id {
        println!("   {} {}", style("CWE:").bold(), cwe);
    }

    println!();
    println!("{}", style("📁 Affected Files").bold());
    for file in &finding.affected_files {
        let line_info = match (finding.line_start, finding.line_end) {
            (Some(start), Some(end)) if start != end => format!(" (lines {}-{})", start, end),
            (Some(start), _) => format!(" (line {})", start),
            _ => String::new(),
        };
        println!("{}{}", file.display(), style(&line_info).dim());
    }

    println!();
    println!("{}", style("📝 Description").bold());
    for line in finding.description.lines() {
        println!("   {}", line);
    }

    if let Some(fix) = &finding.suggested_fix {
        println!();
        println!("{}", style("🔧 Suggested Fix").bold());
        for line in fix.lines() {
            println!("   {}", line);
        }
    }

    if let Some(why) = &finding.why_it_matters {
        println!();
        println!("{}", style("❓ Why It Matters").bold());
        for line in why.lines() {
            println!("   {}", line);
        }
    }

    if let Some(effort) = &finding.estimated_effort {
        println!();
        println!("   {} {}", style("⏱️  Estimated Effort:").bold(), effort);
    }

    println!();
    println!("{}", style("💡 Next Steps").bold());
    println!(
        "   • Run {} for AI-assisted fix",
        style(format!("repotoire fix {}", index)).cyan()
    );
}