perspica 0.1.1

Review code changes by what they do: semantic diff, noise hiding, reading order, and what you asked your coding agent for
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
mod git;
mod render_tty;
mod render_json;
mod intel;
mod llm;
mod web;
mod deep;
mod sessions;
mod saved;

use clap::Parser;
use perspica_core::cross_file::{BrokenReferenceEntry, CallSite, CrossFileManifest, FileChange};
use perspica_core::manifest::{Location, Side};
use perspica_core::{DiffResult, Language};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Parser, Debug)]
#[command(
    name = "perspica",
    about = "Review code changes by what they do",
    version,
    after_help = "Examples:\n  perspica                      review the current branch (run inside a repo)\n  perspica old.ts new.ts\n  perspica --staged --web\n  perspica --git main...feature -s\n  perspica --pr 123 --web"
)]
struct Cli {
    /// Old file path
    old_file: Option<PathBuf>,

    /// New file path
    new_file: Option<PathBuf>,

    /// Override language detection
    #[arg(short, long)]
    language: Option<String>,

    /// Output format: tty (default), json, web
    #[arg(short, long, default_value = "tty")]
    format: String,

    /// Shorthand for --format json
    #[arg(long)]
    json: bool,

    /// Open results in browser
    #[arg(long)]
    web: bool,

    /// Port for web viewer (the next free port is used if taken)
    #[arg(long, default_value = "7890")]
    port: u16,

    /// Don't open a browser tab (web mode)
    #[arg(long)]
    no_open: bool,

    /// Disable colored output
    #[arg(long)]
    no_color: bool,

    /// Show mechanical hunks (formatting, renames, moves) in full in the terminal
    #[arg(long)]
    show_noise: bool,

    // -- Git integration --
    /// Diff staged changes
    #[arg(long)]
    staged: bool,

    /// Diff working tree against HEAD, or specify a commit range (a..b, a...b, or a ref)
    #[arg(long, num_args = 0..=1, default_missing_value = "HEAD")]
    git: Option<String>,

    /// Review a GitHub pull request by number (uses the `gh` CLI)
    #[arg(long)]
    pr: Option<u64>,

    /// Review the current branch against its merge-base with <BASE> (default: origin/HEAD,
    /// main or master). What `perspica` does with no arguments
    #[arg(long, num_args = 0..=1, default_missing_value = "", value_name = "BASE")]
    branch: Option<String>,

    // -- LLM analysis --
    /// Group changes by intent, with risk and a summary, using an LLM. Sends the change
    /// list and changed code, never whole files
    #[arg(short, long)]
    summarize: bool,

    /// Thorough analysis: the LLM may first read definitions and small files from the
    /// changed files. Slower. Implies -s
    #[arg(short, long)]
    deep: bool,

    /// LLM API key (better: set it in the environment, see the README)
    #[arg(long)]
    api_key: Option<String>,

    /// With --api-key: anthropic (default) or openai. `ollama` needs no key and uses a local model
    #[arg(long)]
    provider: Option<String>,

    /// Model to use instead of the provider's default
    #[arg(long)]
    model: Option<String>,

    /// Don't read the Claude Code or Codex sessions behind your change (your prompts are
    /// shown, and sent with -s). Never read for other people's changes
    #[arg(long)]
    no_sessions: bool,

    /// Run the LLM analysis again even if a saved one matches this diff
    #[arg(long)]
    fresh: bool,
}

/// Multi-file analysis output.
#[derive(Debug, Serialize, Deserialize)]
pub struct MultiFileResult {
    pub version: String,
    pub source: SourceInfo,
    pub files: Vec<FileEntry>,
    pub results: Vec<DiffResult>,
    pub cross_file: CrossFileManifest,
    pub intent_groups: Option<Vec<intel::IntentGroup>>,
    pub summary: Option<String>,
    #[serde(default)]
    pub concerns: Vec<String>,
    /// Name of the LLM provider used, if any.
    #[serde(default)]
    pub llm_provider: Option<String>,
    /// Model the intent groups came from.
    #[serde(default)]
    pub llm_model: Option<String>,
    /// When the intent groups were loaded from a saved analysis: when it was made (unix seconds).
    #[serde(default)]
    pub llm_saved_at: Option<u64>,
    /// Why the LLM analysis did not run or failed.
    #[serde(default)]
    pub llm_error: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceInfo {
    /// e.g. "main..feature", "staged changes", "PR #12"
    pub label: String,
    /// The label in full (commit ids, refs, PR URL), for a tooltip.
    #[serde(default)]
    pub detail: Option<String>,
    /// Which repository this is: `owner/name` (or the folder name), and its web URL.
    #[serde(default)]
    pub repo: Option<String>,
    #[serde(default)]
    pub repo_url: Option<String>,
    #[serde(default)]
    pub pr_title: Option<String>,
    #[serde(default)]
    pub pr_url: Option<String>,
    /// PR description or commit messages, used as author context for the LLM.
    #[serde(default, skip_serializing)]
    pub author_context: Option<String>,
    /// Coding-agent sessions that made the change, and the user's prompts in them.
    #[serde(default)]
    pub sessions: sessions::SessionContext,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct FileEntry {
    pub old_path: String,
    pub new_path: String,
    pub language: String,
    pub old_source: String,
    pub new_source: String,
    /// A, M, D, R, C, T
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub binary: bool,
}

impl MultiFileResult {
    pub fn file_sources(&self) -> Vec<(String, String, String)> {
        self.files.iter().map(|f| (f.new_path.clone(), f.old_source.clone(), f.new_source.clone())).collect()
    }
}

fn parse_language(lang_str: &str) -> Language {
    match lang_str.to_lowercase().as_str() {
        "typescript" | "ts" | "javascript" | "js" => Language::TypeScript,
        "tsx" | "jsx" => Language::Tsx,
        "python" | "py" => Language::Python,
        "rust" | "rs" => Language::Rust,
        "go" => Language::Go,
        "java" => Language::Java,
        "c" => Language::C,
        "scala" => Language::Scala,
        _ => Language::Unknown,
    }
}

fn fail(msg: impl std::fmt::Display) -> ! {
    eprintln!("perspica: {msg}");
    std::process::exit(1);
}

fn main() {
    // Exit quietly when the reader goes away (`perspica | head`) instead of panicking.
    #[cfg(unix)]
    unsafe {
        libc::signal(libc::SIGPIPE, libc::SIG_DFL);
    }
    let cli = Cli::parse();
    let format = if cli.json { "json" } else if cli.web { "web" } else { cli.format.as_str() };

    // Gather inputs
    let file_mode = cli.old_file.is_some() || cli.new_file.is_some();
    let branch_base = match &cli.branch {
        Some(b) => Some(b.as_str()),
        None if !file_mode && !cli.staged && cli.git.is_none() && cli.pr.is_none() && git::repo_root().is_some() => Some(""),
        None => None,
    };
    if !file_mode {
        // git reports root-relative paths; run everything from the root.
        if let Some(root) = git::repo_root() {
            let _ = std::env::set_current_dir(root);
        }
    }
    let mut source = SourceInfo { label: String::new(), pr_title: None, pr_url: None, author_context: None, sessions: Default::default(), detail: None, repo: None, repo_url: None };
    let mut target: Option<git::Target> = None;
    let diffs: Vec<git::GitFileDiff> = if let Some(pr) = cli.pr {
        let (t, info) = git::pr_target(pr).unwrap_or_else(|e| fail(e));
        source.label = format!("PR #{}", info.number);
        source.detail = Some(format!("PR #{}: {}\n{}\n{}", info.number, info.title, info.url, t.detail()));
        source.author_context = Some(format!("{}\n\n{}", info.title, info.body));
        source.pr_title = Some(info.title);
        source.pr_url = Some(info.url);
        let d = git::collect(&t).unwrap_or_else(|e| fail(e));
        target = Some(t);
        d
    } else if let Some(base) = branch_base {
        let t = git::Target::branch(Some(base).filter(|b| !b.is_empty())).unwrap_or_else(|e| fail(e));
        source.label = t.label();
        source.detail = Some(t.detail());
        source.author_context = git::commit_messages(&t);
        let d = git::collect(&t).unwrap_or_else(|e| fail(e));
        target = Some(t);
        d
    } else if cli.staged || cli.git.is_some() {
        let t = if cli.staged { git::Target::Staged } else { git::Target::from_spec(cli.git.as_deref()).unwrap_or_else(|e| fail(e)) };
        source.label = t.label();
        source.detail = Some(t.detail());
        source.author_context = git::commit_messages(&t);
        let d = git::collect(&t).unwrap_or_else(|e| fail(e));
        target = Some(t);
        d
    } else {
        file_pair_input(&cli)
    };

    // Agent sessions describe the local user's own work only.
    if let (Some(t), false) = (&target, cli.no_sessions || target.as_ref().is_some_and(|t| !git::is_own_change(t))) {
        if let (Some(root), Some(since)) = (git::repo_root(), git::base_time(t)) {
            let changed: Vec<String> = diffs.iter().map(|d| d.new_path.clone()).collect();
            // A little slack: the commit is made just after the last prompt's work.
            let until = git::head_time(t).map(|h| h + 120);
            source.sessions = sessions::find(&root, &changed, since, until);
            // Reading transcripts should never be silent.
            let ctx = &source.sessions;
            if !ctx.is_empty() {
                let mut agents: Vec<&str> = ctx.sessions.iter().map(|s| if s.agent == "codex" { "Codex" } else { "Claude Code" }).collect();
                agents.dedup();
                let n = ctx.sessions.len();
                eprintln!("Using your prompts from {n} {} session{} that edited these files (--no-sessions to skip).",
                    agents.join(" and "), if n == 1 { "" } else { "s" });
            }
        }
    }

    if target.is_some() {
        if let Some((name, url)) = git::repo_identity() {
            source.repo = Some(name);
            source.repo_url = url;
        }
    }

    if diffs.is_empty() {
        eprintln!("No changes found{}.", if source.label.is_empty() { String::new() } else { format!(" ({})", source.label) });
        std::process::exit(0);
    }

    // Analyze
    let changes: Vec<FileChange> = diffs.iter().map(|d| {
        let hunks = git::parse_unified_diff(&d.raw_unified_diff);
        FileChange {
            old_path: d.old_path.clone(),
            new_path: d.new_path.clone(),
            old_source: d.old_content.clone(),
            new_source: d.new_content.clone(),
            language: d.language,
            display_hunks: if hunks.is_empty() && !d.binary { None } else { Some(hunks) },
            role: d.role,
        }
    }).collect();
    let analysis = perspica_core::analyze_multi(&changes).unwrap_or_else(|e| fail(format!("analysis failed: {e}")));
    drop(changes);

    let files: Vec<FileEntry> = diffs.into_iter().map(|d| FileEntry {
        old_path: d.old_path,
        new_path: d.new_path,
        language: format!("{:?}", d.language),
        old_source: d.old_content,
        new_source: d.new_content,
        status: d.status.to_string(),
        binary: d.binary,
    }).collect();

    let mut multi = MultiFileResult {
        version: env!("CARGO_PKG_VERSION").to_string(),
        source,
        files,
        results: analysis.file_results.into_iter().map(|(_, r)| r).collect(),
        cross_file: analysis.cross_file,
        intent_groups: None,
        summary: None,
        concerns: vec![],
        llm_provider: None,
        llm_model: None,
        llm_saved_at: None,
        llm_error: None,
    };

    if let Some(t) = &target {
        enrich_with_repo_references(&mut multi, t);
    }

    // Optional LLM analysis
    let rt = tokio::runtime::Runtime::new().unwrap_or_else(|e| fail(e));
    let wants_llm = cli.summarize || cli.deep;
    let detect = llm::Detect { api_key: cli.api_key.clone(), provider: cli.provider.clone(), model: cli.model.clone() };
    let provider = if wants_llm || format == "web" {
        rt.block_on(detect.run())
    } else {
        None
    };
    multi.llm_provider = provider.as_ref().map(|p| p.name().to_string());

    // A saved analysis of this exact diff: shown in the viewer, and reused by -s
    // when it came from the same model and depth (unless --fresh).
    let key = saved::key(&multi);
    let mut reused = false;
    if let Some(s) = saved::load(&key).filter(|_| !cli.fresh) {
        let matches = cli.model.as_deref().is_none_or(|m| m == s.model) && (!cli.deep || s.depth == "thorough");
        if wants_llm && matches {
            eprintln!("Using the saved analysis of this diff by {} from {}; --fresh to run it again.", s.model, ago(s.saved_at));
            saved::apply(&mut multi, s);
            reused = true;
        } else if !wants_llm && format == "web" {
            saved::apply(&mut multi, s);
        }
    }
    let wants_llm = wants_llm && !reused;

    if wants_llm {
        match &provider {
            Some(p) => rt.block_on(run_llm(&mut multi, &**p, cli.deep)),
            // The viewer explains the setup when Analyze is clicked.
            None if format == "web" => {}
            None => eprintln!("{}\nShowing the analysis without it.\n", rt.block_on(llm::setup()).hint()),
        }
    }

    // Render
    if wants_llm && multi.llm_error.is_none() {
        if let (Some(groups), Some(p)) = (&multi.intent_groups, &provider) {
            saved::save(&key, &saved::SavedAnalysis {
                provider: p.name().to_string(),
                model: p.model().to_string(),
                depth: if cli.deep { "thorough" } else { "standard" }.into(),
                saved_at: saved::now(),
                groups: groups.clone(),
                summary: multi.summary.clone().unwrap_or_default(),
                concerns: multi.concerns.clone(),
            });
        }
    }

    match format {
        "json" => render_json::render_multi(&multi),
        "web" => rt.block_on(web::serve(multi, cli.port, provider, detect, !cli.no_open, key)),
        _ => render_tty::render_multi(&multi, !cli.no_color, cli.show_noise),
    }
}

/// Two files on disk (or one missing, for added/deleted).
fn file_pair_input(cli: &Cli) -> Vec<git::GitFileDiff> {
    let (Some(old_path), Some(new_path)) = (&cli.old_file, &cli.new_file) else {
        eprintln!("Usage: perspica <old_file> <new_file>");
        eprintln!("       perspica [--branch [<base>]] | --staged | --git [<range>] | --pr <number>");
        eprintln!("Run `perspica --help` for all options.");
        std::process::exit(1);
    };
    let read = |p: &PathBuf| std::fs::read(p).unwrap_or_else(|e| fail(format!("reading {}: {e}", p.display())));
    let (old_bytes, new_bytes) = (read(old_path), read(new_path));
    let binary = old_bytes.contains(&0) || new_bytes.contains(&0);
    let language = match &cli.language {
        Some(l) => parse_language(l),
        None => Language::from_path(&new_path.display().to_string()),
    };
    let raw = git::no_index_diff(&old_path.display().to_string(), &new_path.display().to_string()).unwrap_or_default();
    if old_bytes == new_bytes {
        return vec![];
    }
    vec![git::GitFileDiff {
        old_path: old_path.display().to_string(),
        new_path: new_path.display().to_string(),
        old_content: if binary { String::new() } else { String::from_utf8_lossy(&old_bytes).into_owned() },
        new_content: if binary { String::new() } else { String::from_utf8_lossy(&new_bytes).into_owned() },
        language: if binary { Language::Unknown } else { language },
        raw_unified_diff: raw,
        status: 'M',
        binary,
        // Comparing two files directly means reviewing them as code, wherever they live.
        role: Some(perspica_core::roles::FileRole::Source),
    }]
}

/// Search the whole repository (not just changed files) for references to
/// names that vanished and for calls to functions whose signature changed.
fn enrich_with_repo_references(multi: &mut MultiFileResult, target: &git::Target) {
    // Plenty of lines to scan (the per-symbol cap below limits what is reported).
    const MAX_HITS: usize = 3000;
    const MAX_PER_SYMBOL: usize = 10;
    let in_diff: std::collections::HashSet<&str> = multi.files.iter().map(|f| f.new_path.as_str()).collect();
    let vanished: Vec<perspica_core::cross_file::Vanished> = multi.cross_file.vanished.iter()
        .map(|v| (v.name.clone(), v.renamed_to.clone(), v.origin.clone(), v.owner.clone()))
        .collect();
    let sig_names: Vec<String> = multi.cross_file.signature_impacts.iter()
        .filter(|s| s.exported)
        .map(|s| perspica_core::parser::bare_name(&s.name).to_string())
        .filter(|n| n.len() >= 3)
        .collect();
    let mut names: Vec<&str> = vanished.iter().map(|v| v.0.as_str()).chain(sig_names.iter().map(String::as_str)).collect();
    names.sort_unstable();
    names.dedup();
    if names.is_empty() {
        return;
    }
    let hits = git::grep_words(target, &names, MAX_HITS);
    // A vanished name that some other code still defines (another type's method
    // of the same name, say) can't be told apart from it by name: drop it.
    let ambiguous: std::collections::HashSet<&str> = hits.iter()
        .filter(|(name, path, _, text)| !in_diff.contains(path.as_str()) && vanished.iter().any(|v| &v.0 == name)
            && Language::from_path(path) != Language::Unknown && perspica_core::cross_file::looks_like_definition(text, name))
        .map(|(name, ..)| name.as_str())
        .collect();
    multi.cross_file.broken_references.retain(|b| !ambiguous.contains(b.symbol_name.as_str()));
    multi.cross_file.vanished.retain(|v| !ambiguous.contains(v.name.as_str()));
    let mut next_id = max_id(multi) + 1;
    let mut per_symbol: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
    for (name, path, line, text) in &hits {
        if in_diff.contains(path.as_str()) || ambiguous.contains(name.as_str()) {
            continue; // already scanned precisely by the core, or not a stale name after all
        }
        // Mentions in docs, config or other non-code files aren't references.
        if Language::from_path(path) == Language::Unknown || perspica_core::roles::is_docs_path(path) {
            continue;
        }
        let count = per_symbol.entry(name.as_str()).or_default();
        if *count >= MAX_PER_SYMBOL {
            continue;
        }
        *count += 1;
        if let Some((_, renamed_to, origin, owner)) = vanished.iter().find(|v| &v.0 == name) {
            // Same rule as the core: a method's name only counts on its own type.
            if perspica_core::cross_file::scan_references(text, name, owner.as_deref()).is_empty() {
                continue;
            }
            multi.cross_file.broken_references.push(BrokenReferenceEntry {
                id: next_id,
                symbol_name: name.clone(),
                renamed_from: renamed_to.clone(),
                reference_file: path.clone(),
                reference_location: Location { file: Some(path.clone()), line_start: *line, line_end: *line, side: Side::New },
                reason: perspica_core::cross_file::broken_reason(name, renamed_to.as_deref(), origin),
                line_text: text.clone(),
                in_diff: false,
            });
            next_id += 1;
        }
        for impact in multi.cross_file.signature_impacts.iter_mut().filter(|s| s.exported) {
            let def = impact.definition.file.clone().unwrap_or_default();
            let accept = |q: Option<&str>| perspica_core::cross_file::call_qualifier_ok(q, &def, &impact.name);
            if perspica_core::parser::bare_name(&impact.name) == name
                && !perspica_core::cross_file::scan_calls(text, name, &accept).is_empty()
            {
                impact.call_sites.push(CallSite { file: path.clone(), line: *line, text: text.clone(), updated: false, in_diff: false });
            }
        }
    }
}

/// "3 minutes ago", "2 days ago".
fn ago(unix: u64) -> String {
    let secs = saved::now().saturating_sub(unix);
    let (n, unit) = match secs {
        0..=89 => return "just now".into(),
        90..=5399 => (secs / 60, "minute"),
        5400..=129_599 => (secs / 3600, "hour"),
        _ => (secs / 86_400, "day"),
    };
    format!("{n} {unit}{} ago", if n == 1 { "" } else { "s" })
}

fn max_id(multi: &MultiFileResult) -> u32 {
    let cf = &multi.cross_file;
    multi.results.iter().flat_map(|r| r.manifest.ids())
        .chain(cf.moves.iter().map(|m| m.id))
        .chain(cf.broken_references.iter().map(|b| b.id))
        .chain(cf.signature_impacts.iter().map(|s| s.id))
        .max()
        .unwrap_or(0)
}

async fn run_llm(multi: &mut MultiFileResult, provider: &dyn llm::LlmProvider, deep: bool) {
    use std::io::IsTerminal;
    let label = format!("Analyzing with {}{}", provider.name(), if deep { " (thorough)" } else { "" });
    let tty = std::io::stderr().is_terminal();
    eprint!("{label}…{}", if tty { " [0s]" } else { "\n" });
    let start = std::time::Instant::now();
    let timer_label = label.clone();
    let timer = tokio::spawn(async move {
        loop {
            tokio::time::sleep(std::time::Duration::from_secs(1)).await;
            if tty {
                eprint!("\r{timer_label}… [{}s]", start.elapsed().as_secs());
            }
        }
    });

    let sources = multi.file_sources();
    let input = intel::IntelInput {
        results: &multi.results,
        sources: &sources,
        cross_file: &multi.cross_file,
        author_context: multi.source.author_context.as_deref(),
        requirements: &multi.source.sessions.requirements,
    };
    let result = if deep {
        match deep::deep_analyze(&input, provider).await {
            Ok(d) => {
                eprint!("\r{label}: {} tool calls, {} iterations", d.tool_calls_made, d.iterations);
                Ok(intel::IntelResult { groups: d.groups, summary: d.summary, concerns: d.concerns })
            }
            Err(e) => {
                eprintln!("\rDeep analysis failed: {e}. Falling back to standard.");
                intel::run_analysis(&input, provider).await
            }
        }
    } else {
        intel::run_analysis(&input, provider).await
    };
    timer.abort();
    let secs = start.elapsed().as_secs();
    match result {
        Ok(r) => {
            eprintln!("\r{label} [{secs}s] ✓        ");
            multi.intent_groups = Some(r.groups);
            multi.summary = Some(r.summary).filter(|s| !s.trim().is_empty());
            multi.concerns = r.concerns;
            multi.llm_model = Some(provider.model().to_string());
            multi.llm_saved_at = None;
        }
        Err(e) => {
            eprintln!("\r{label} [{secs}s] ✗        ");
            eprintln!("Analysis failed: {e}");
            eprintln!("Showing the results without it.");
            multi.llm_error = Some(e);
        }
    }
}