sinter-io 0.45.0

sinter command-line interface
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
//! `sinter impact <rev-range>`: changed symbols -> blast radius -> affected
//! tests. Line hunks come from `git diff -U0`; spans are matched against the
//! graph built from the working tree, so build before asking.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::process::{Command, Output};

use anyhow::{Context, Result, bail};
use serde::Serialize;
use sinter_core::{Node, SymbolKind};
use sinter_resolve::qualified_of;
use sinter_store::EdgeFilter;

use crate::lookup::{open_current, open_store};

#[derive(Serialize)]
pub struct ImpactReport {
    pub rev_range: String,
    /// Whether every file in the requested diff could be projected onto
    /// the current graph snapshot. `partial_reasons` explains every reason
    /// this is `partial`; agents must not treat a partial blast radius as a
    /// complete test-selection proof.
    pub analysis_status: AnalysisStatus,
    pub partial_reasons: Vec<&'static str>,
    /// Hunks come from the rev range but spans match the working-tree
    /// graph; uncommitted edits shift spans, so totals may include drift.
    pub working_tree_dirty: bool,
    /// Authoritative path-level ledger from `git diff --name-status`.
    /// Unlike `changed_symbols`, this never drops configuration, binary,
    /// deleted, renamed, or otherwise unindexed paths.
    pub changed_files: Vec<ChangedFile>,
    /// Entries from `git status --porcelain`, including untracked paths
    /// which Git does not include in a normal `git diff <rev>`.
    pub working_tree_changes: Vec<WorkingTreeChange>,
    /// Changed paths that could not be represented completely by the
    /// working-tree graph. A file can have mapped symbols and still appear
    /// here when deleted content has no current-tree symbol.
    pub unmapped_files: Vec<UnmappedFile>,
    pub changed_symbols: Vec<SymbolRef>,
    pub blast_radius: Vec<SymbolRef>,
    pub affected_tests: Vec<SymbolRef>,
}

#[derive(Serialize, Clone, Copy, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AnalysisStatus {
    Complete,
    Partial,
}

#[derive(Serialize, Clone, Copy, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum FileChangeKind {
    Added,
    Copied,
    Deleted,
    Modified,
    Renamed,
    TypeChanged,
    Unmerged,
    Unknown,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq)]
pub struct ChangedFile {
    /// New/current path for additions, copies, and renames; the removed
    /// path for deletions.
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_path: Option<String>,
    /// Exact Git status (`M`, `D`, `R100`, ...), retained alongside the
    /// normalized kind so agents do not lose rename/copy similarity data.
    pub git_status: String,
    pub kind: FileChangeKind,
    pub mapped_symbols: usize,
}

#[derive(Serialize, Clone, Copy, Debug, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum UnmappedReason {
    Deleted,
    NotIndexed,
    Unreadable,
    NoContentHunks,
    NoSymbolOverlap,
    DeletedContentNotInCurrentGraph,
    UnknownGitStatus,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq)]
pub struct UnmappedFile {
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_path: Option<String>,
    pub git_status: String,
    pub reason: UnmappedReason,
}

#[derive(Serialize, Clone, Debug, Eq, PartialEq)]
pub struct WorkingTreeChange {
    /// Current path; for a rename or copy, `old_path` is the source path.
    pub path: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub old_path: Option<String>,
    /// Git porcelain's index (`X`) and worktree (`Y`) states, normalized
    /// into stable names instead of exposing whitespace-sensitive bytes.
    pub index_status: &'static str,
    pub worktree_status: &'static str,
    pub conflicted: bool,
}

#[derive(Clone, Copy, Debug)]
struct Hunk {
    new_start: usize,
    new_count: usize,
    deleted_only: bool,
}

#[derive(Serialize, Clone)]
pub struct SymbolRef {
    pub qualified: String,
    pub kind: &'static str,
    pub file: String,
}

fn symbol_ref(node: &Node) -> SymbolRef {
    SymbolRef {
        qualified: qualified_of(node.id.as_str()).to_string(),
        kind: node.kind.as_str(),
        file: node.file.clone(),
    }
}

fn git_diff(repo: &Path, rev_range: &str, args: &[&str]) -> Result<Output> {
    if rev_range.trim().is_empty() || rev_range.starts_with('-') {
        bail!("rev range must be a non-empty revision expression, not a Git option");
    }
    let output = Command::new("git")
        .args(["-c", "diff.noprefix=false", "diff", "--no-ext-diff"])
        .args(args)
        .arg(rev_range)
        .arg("--")
        .current_dir(repo)
        .output()
        .context("run git diff")?;
    if output.status.success() {
        return Ok(output);
    }
    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.to_lowercase().contains("not a git repository") {
        bail!("not a git repository — impact needs git history");
    }
    // Full git stderr can run to pages; the first line names the problem.
    bail!(
        "git diff {rev_range} failed: {}",
        stderr.lines().next().unwrap_or("").trim()
    );
}

fn file_change_kind(status: &str) -> FileChangeKind {
    match status.as_bytes().first().copied() {
        Some(b'A') => FileChangeKind::Added,
        Some(b'C') => FileChangeKind::Copied,
        Some(b'D') => FileChangeKind::Deleted,
        Some(b'M') => FileChangeKind::Modified,
        Some(b'R') => FileChangeKind::Renamed,
        Some(b'T') => FileChangeKind::TypeChanged,
        Some(b'U') => FileChangeKind::Unmerged,
        _ => FileChangeKind::Unknown,
    }
}

fn path_string(raw: &[u8]) -> String {
    String::from_utf8_lossy(raw).into_owned()
}

fn parse_changed_files(raw: &[u8]) -> Result<Vec<ChangedFile>> {
    let fields: Vec<&[u8]> = raw
        .split(|byte| *byte == 0)
        .filter(|field| !field.is_empty())
        .collect();
    let mut cursor = 0usize;
    let mut files = Vec::new();
    while cursor < fields.len() {
        let git_status = path_string(fields[cursor]);
        cursor += 1;
        let kind = file_change_kind(&git_status);
        let (old_path, path) = if matches!(kind, FileChangeKind::Copied | FileChangeKind::Renamed) {
            let old = fields
                .get(cursor)
                .context("git diff emitted a rename/copy without its old path")?;
            let new = fields
                .get(cursor + 1)
                .context("git diff emitted a rename/copy without its new path")?;
            cursor += 2;
            (Some(path_string(old)), path_string(new))
        } else {
            let path = fields
                .get(cursor)
                .context("git diff emitted a status without a path")?;
            cursor += 1;
            (None, path_string(path))
        };
        files.push(ChangedFile {
            path,
            old_path,
            git_status,
            kind,
            mapped_symbols: 0,
        });
    }
    files.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then_with(|| a.old_path.cmp(&b.old_path))
    });
    Ok(files)
}

fn changed_files(repo: &Path, rev_range: &str) -> Result<Vec<ChangedFile>> {
    let output = git_diff(repo, rev_range, &["--name-status", "-z", "--find-renames"])?;
    parse_changed_files(&output.stdout)
}

fn status_name(status: u8) -> &'static str {
    match status {
        b' ' => "unmodified",
        b'M' => "modified",
        b'T' => "type_changed",
        b'A' => "added",
        b'D' => "deleted",
        b'R' => "renamed",
        b'C' => "copied",
        b'U' => "unmerged",
        b'?' => "untracked",
        b'!' => "ignored",
        _ => "unknown",
    }
}

fn is_conflict_status(index: u8, worktree: u8) -> bool {
    matches!(
        (index, worktree),
        (b'D', b'D')
            | (b'A', b'U')
            | (b'U', b'D')
            | (b'U', b'A')
            | (b'D', b'U')
            | (b'A', b'A')
            | (b'U', b'U')
    )
}

fn parse_working_tree_changes(raw: &[u8]) -> Result<Vec<WorkingTreeChange>> {
    let fields: Vec<&[u8]> = raw
        .split(|byte| *byte == 0)
        .filter(|field| !field.is_empty())
        .collect();
    let mut cursor = 0usize;
    let mut changes = Vec::new();
    while cursor < fields.len() {
        let entry = fields[cursor];
        cursor += 1;
        if entry.len() < 4 || entry[2] != b' ' {
            bail!("git status emitted a malformed porcelain record");
        }
        let index = entry[0];
        let worktree = entry[1];
        let path = path_string(&entry[3..]);
        let old_path = if matches!(index, b'R' | b'C') || matches!(worktree, b'R' | b'C') {
            let old = fields
                .get(cursor)
                .context("git status emitted a rename/copy without its old path")?;
            cursor += 1;
            Some(path_string(old))
        } else {
            None
        };
        changes.push(WorkingTreeChange {
            path,
            old_path,
            index_status: status_name(index),
            worktree_status: status_name(worktree),
            conflicted: is_conflict_status(index, worktree),
        });
    }
    changes.sort_by(|a, b| {
        a.path
            .cmp(&b.path)
            .then_with(|| a.old_path.cmp(&b.old_path))
    });
    Ok(changes)
}

fn working_tree_changes(repo: &Path) -> Result<Vec<WorkingTreeChange>> {
    let output = Command::new("git")
        .args(["status", "--porcelain=v1", "-z", "--untracked-files=all"])
        .current_dir(repo)
        .output()
        .context("run git status")?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!(
            "git status failed: {}",
            stderr.lines().next().unwrap_or("").trim()
        );
    }
    parse_working_tree_changes(&output.stdout)
}

fn parse_range(token: &str, prefix: char) -> Option<(usize, usize)> {
    let range = token.strip_prefix(prefix)?;
    let mut parts = range.splitn(2, ',');
    let start = parts.next()?.parse().ok()?;
    let count = parts.next().map_or(Some(1), |value| value.parse().ok())?;
    Some((start, count))
}

fn parse_hunks(raw: &[u8]) -> BTreeMap<String, Vec<Hunk>> {
    let mut hunks: BTreeMap<String, Vec<Hunk>> = BTreeMap::new();
    let mut current: Option<String> = None;
    for line in String::from_utf8_lossy(raw).lines() {
        if let Some(rest) = line.strip_prefix("+++ ") {
            // Deletions ("+++ /dev/null") and quoted/unexpected paths must
            // clear the current file, never inherit the previous one.
            current = rest.strip_prefix("b/").map(str::to_string);
        } else if let (Some(file), Some(rest)) = (&current, line.strip_prefix("@@ ")) {
            let mut ranges = rest.split_whitespace();
            let old = ranges.next().and_then(|part| parse_range(part, '-'));
            let new = ranges.next().and_then(|part| parse_range(part, '+'));
            if let (Some((_, old_count)), Some((new_start, new_count))) = (old, new) {
                hunks.entry(file.clone()).or_default().push(Hunk {
                    new_start,
                    new_count,
                    deleted_only: old_count > 0 && new_count == 0,
                });
            }
        }
    }
    hunks
}

fn unmapped(change: &ChangedFile, reason: UnmappedReason) -> UnmappedFile {
    UnmappedFile {
        path: change.path.clone(),
        old_path: change.old_path.clone(),
        git_status: change.git_status.clone(),
        reason,
    }
}

/// Test detection heuristic: conventional test files and names.
pub fn is_test(node: &Node) -> bool {
    let f = &node.file;
    f.ends_with("_test.go")
        || f.ends_with("_test.py")
        || f.ends_with("Tests.cs")
        || f.contains(".test.")
        || f.contains(".spec.")
        || f.starts_with("tests/")
        || f.contains("/tests/")
        || f.contains("/test/")
        || node.name.starts_with("test_")
        || node.name.starts_with("Test")
        // Rust `#[cfg(test)] mod tests` inline modules.
        || qualified_of(node.id.as_str()).split("::").any(|s| s == "tests")
}

pub fn compute(repo: &Path, rev_range: &str) -> Result<ImpactReport> {
    compute_filtered(repo, rev_range, &EdgeFilter::default())
}

pub fn compute_filtered(repo: &Path, rev_range: &str, filter: &EdgeFilter) -> Result<ImpactReport> {
    let repo = repo.canonicalize()?;
    let store = open_store(&repo)?;
    compute_with_store(&repo, rev_range, filter, &store)
}

pub(crate) fn compute_current(repo: &Path, rev_range: &str) -> Result<ImpactReport> {
    let repo = repo.canonicalize()?;
    let store = open_current(&repo)?;
    compute_with_store(&repo, rev_range, &EdgeFilter::default(), &store)
}

pub(crate) fn compute_with_store(
    repo: &Path,
    rev_range: &str,
    filter: &EdgeFilter,
    store: &sinter_store::Store,
) -> Result<ImpactReport> {
    let working_tree_changes = working_tree_changes(repo)?;
    let working_tree_dirty = !working_tree_changes.is_empty();
    let mut changed_files = changed_files(repo, rev_range)?;
    // New-side hunks per file from Git. Name/status is deliberately a
    // separate command: patch text cannot represent config-only, binary,
    // deleted, pure-rename, or mode-only changes reliably.
    let patch = git_diff(repo, rev_range, &["-U0", "--no-color", "--find-renames"])?;
    let hunks = parse_hunks(&patch.stdout);

    // Changed symbols: nodes whose byte span overlaps a changed line range.
    // The BTreeMap de-duplicates nodes while preserving deterministic output.
    let mut changed_by_id: BTreeMap<String, Node> = BTreeMap::new();
    let mut unmapped_files = Vec::new();
    for change in &mut changed_files {
        let reason = if change.kind == FileChangeKind::Deleted {
            Some(UnmappedReason::Deleted)
        } else if change.kind == FileChangeKind::Unknown {
            Some(UnmappedReason::UnknownGitStatus)
        } else {
            let Some(facts) = store.facts(&change.path)? else {
                unmapped_files.push(unmapped(change, UnmappedReason::NotIndexed));
                continue;
            };
            let Ok(source) = std::fs::read_to_string(repo.join(&change.path)) else {
                unmapped_files.push(unmapped(change, UnmappedReason::Unreadable));
                continue;
            };
            let ranges = hunks.get(&change.path).map(Vec::as_slice).unwrap_or(&[]);
            let mut mapped_ids = BTreeSet::new();

            if ranges.is_empty()
                && matches!(
                    change.kind,
                    FileChangeKind::Copied | FileChangeKind::Renamed
                )
            {
                // A pure rename/copy has no patch hunks but changes the
                // identity of every symbol in the file. Include the file
                // node too so import dependents remain visible.
                for node in &facts.nodes {
                    mapped_ids.insert(node.id.as_str().to_string());
                    changed_by_id.insert(node.id.as_str().to_string(), node.clone());
                }
            } else if ranges.is_empty() {
                change.mapped_symbols = 0;
                unmapped_files.push(unmapped(change, UnmappedReason::NoContentHunks));
                continue;
            } else {
                let mut line_starts = vec![0u64];
                for (i, byte) in source.bytes().enumerate() {
                    if byte == b'\n' {
                        line_starts.push(i as u64 + 1);
                    }
                }
                let byte_range = |line: usize, count: usize| -> Option<(u64, u64)> {
                    if line == 0 || count == 0 {
                        return None;
                    }
                    let start = line_starts
                        .get(line - 1)
                        .copied()
                        .unwrap_or(source.len() as u64);
                    let end = line_starts
                        .get(line - 1 + count)
                        .copied()
                        .unwrap_or(source.len() as u64);
                    Some((start, end))
                };
                for node in &facts.nodes {
                    if node.kind == SymbolKind::File {
                        continue;
                    }
                    let touched = ranges.iter().any(|hunk| {
                        byte_range(hunk.new_start, hunk.new_count).is_some_and(|(start, end)| {
                            node.span.start < end && start < node.span.end
                        })
                    });
                    if touched {
                        mapped_ids.insert(node.id.as_str().to_string());
                        changed_by_id.insert(node.id.as_str().to_string(), node.clone());
                    }
                }
                if mapped_ids.is_empty() {
                    // Imports and other file-level changes live outside a
                    // definition span. The file node is the graph's honest
                    // fallback and carries import dependents.
                    if let Some(node) = facts
                        .nodes
                        .iter()
                        .find(|node| node.kind == SymbolKind::File)
                    {
                        mapped_ids.insert(node.id.as_str().to_string());
                        changed_by_id.insert(node.id.as_str().to_string(), node.clone());
                    }
                }
            }
            change.mapped_symbols = mapped_ids.len();
            if ranges.iter().any(|hunk| hunk.deleted_only) {
                Some(UnmappedReason::DeletedContentNotInCurrentGraph)
            } else if mapped_ids.is_empty() {
                Some(UnmappedReason::NoSymbolOverlap)
            } else {
                None
            }
        };
        if let Some(reason) = reason {
            unmapped_files.push(unmapped(change, reason));
        }
    }
    let changed: Vec<Node> = changed_by_id.into_values().collect();

    // Blast radius: union of dependents of every changed symbol.
    let mut radius: BTreeMap<String, Node> = BTreeMap::new();
    for node in &changed {
        for reached in store.dependents(&node.id, filter, 25)? {
            radius.insert(reached.node.id.as_str().to_string(), reached.node);
        }
    }
    for node in &changed {
        radius.remove(node.id.as_str());
    }

    let affected_tests: Vec<SymbolRef> = radius
        .values()
        .chain(changed.iter())
        .filter(|n| is_test(n))
        .map(symbol_ref)
        .collect();

    let mut partial_reasons = Vec::new();
    if !unmapped_files.is_empty() {
        partial_reasons.push("one_or_more_changed_files_are_not_fully_mapped");
    }
    if rev_range.contains("..") && working_tree_dirty {
        partial_reasons.push("historical_diff_uses_a_dirty_working_tree_graph");
    }
    if working_tree_changes
        .iter()
        .any(|change| change.index_status == "untracked" || change.worktree_status == "untracked")
    {
        partial_reasons.push("untracked_files_are_not_included_in_git_diff");
    }
    if working_tree_changes.iter().any(|change| change.conflicted) {
        partial_reasons.push("working_tree_has_unmerged_paths");
    }
    let analysis_status = if partial_reasons.is_empty() {
        AnalysisStatus::Complete
    } else {
        AnalysisStatus::Partial
    };

    Ok(ImpactReport {
        rev_range: rev_range.to_string(),
        analysis_status,
        partial_reasons,
        working_tree_dirty,
        changed_files,
        working_tree_changes,
        unmapped_files,
        changed_symbols: changed.iter().map(symbol_ref).collect(),
        blast_radius: radius.values().map(symbol_ref).collect(),
        affected_tests,
    })
}

pub fn run(
    repo: &Path,
    rev_range: &str,
    manifest: Option<&Path>,
    evidence: &[String],
    certain: bool,
    json: bool,
) -> Result<()> {
    let filter = crate::lookup::edge_filter(evidence, certain)?;
    let mut report = compute_filtered(repo, rev_range, &filter)?;
    // Workspace mode: follow boundary links out of the changed member and
    // continue the blast radius inside the other members.
    if let Some(manifest) = manifest {
        let ws = crate::workspace::load(manifest)?;
        let repo_canon = repo.canonicalize()?;
        let member = ws
            .members
            .iter()
            .find(|(_, path)| **path == repo_canon)
            .map(|(name, _)| name.clone())
            .ok_or_else(|| anyhow::anyhow!("--repo is not a member of this workspace"))?;
        // Resolve changed symbols to node ids first, then drop the handle:
        // workspace traversal opens every member store itself, and redb
        // forbids a second open of the same file in-process.
        let changed_ids: Vec<sinter_core::NodeId> = {
            let store = open_store(&repo_canon)?;
            report
                .changed_symbols
                .iter()
                .filter_map(|c| {
                    crate::lookup::unique_symbol(&store, &c.qualified)
                        .ok()
                        .map(|n| n.id)
                })
                .collect()
        };
        let mut cross: std::collections::BTreeMap<String, SymbolRef> =
            std::collections::BTreeMap::new();
        for node_id in &changed_ids {
            for reached in crate::workspace::dependents(&ws, &member, node_id, &filter, 25)? {
                if reached.member == member {
                    continue; // local radius already counted
                }
                let key = format!("{}:{}", reached.member, reached.node.id.as_str());
                let mut sym = symbol_ref(&reached.node);
                sym.file = format!("{}:{}", reached.member, sym.file);
                if is_test(&reached.node) {
                    report.affected_tests.push(sym.clone());
                }
                cross.insert(key, sym);
            }
        }
        report.blast_radius.extend(cross.into_values());
    }
    if json {
        crate::agent_protocol::write_json(&to_json(&report))?;
        return Ok(());
    }
    let status = match report.analysis_status {
        AnalysisStatus::Complete => "complete",
        AnalysisStatus::Partial => "partial",
    };
    println!(
        "impact {}: {status}; {} changed files, {} changed symbols, {} in blast radius, {} tests affected",
        report.rev_range,
        report.changed_files.len(),
        report.changed_symbols.len(),
        report.blast_radius.len(),
        report.affected_tests.len()
    );
    for reason in &report.partial_reasons {
        println!("  partial: {reason}");
    }
    if report.working_tree_dirty {
        println!(
            "  note: working tree has {} uncommitted path(s); see working_tree_changes in --json output",
            report.working_tree_changes.len()
        );
    }
    println!("changed files:");
    for file in &report.changed_files {
        if let Some(old) = &file.old_path {
            println!(
                "  {}  {} -> {}  ({} graph symbols)",
                file.git_status, old, file.path, file.mapped_symbols
            );
        } else {
            println!(
                "  {}  {}  ({} graph symbols)",
                file.git_status, file.path, file.mapped_symbols
            );
        }
    }
    if !report.unmapped_files.is_empty() {
        println!("unmapped files:");
        for file in &report.unmapped_files {
            println!("  {:?}  {}", file.reason, file.path);
        }
    }
    println!("changed:");
    for s in &report.changed_symbols {
        println!("  {} {}  {}", s.kind, s.qualified, s.file);
    }
    println!("blast radius:");
    for s in &report.blast_radius {
        println!("  {} {}  {}", s.kind, s.qualified, s.file);
    }
    println!("affected tests:");
    for s in &report.affected_tests {
        println!("  {} {}  {}", s.kind, s.qualified, s.file);
    }
    Ok(())
}

/// Also usable by the MCP server.
pub fn to_json(report: &ImpactReport) -> serde_json::Value {
    serde_json::to_value(report).expect("impact report serializes")
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::Path;
    use std::process::Command;

    use super::{
        AnalysisStatus, FileChangeKind, UnmappedReason, changed_files, compute, is_test,
        working_tree_changes,
    };
    use sinter_core::{Node, NodeId, Span, SymbolKind};
    use tempfile::TempDir;

    fn node(id: &str, name: &str, file: &str) -> Node {
        Node {
            id: NodeId::new(id),
            kind: SymbolKind::Function,
            name: name.to_string(),
            file: file.to_string(),
            span: Span { start: 0, end: 1 },
            signature: String::new(),
            doc: None,
        }
    }

    fn git(repo: &Path, args: &[&str]) {
        let output = Command::new("git")
            .args(args)
            .current_dir(repo)
            .output()
            .expect("run git");
        assert!(
            output.status.success(),
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn write(repo: &Path, path: &str, contents: &str) {
        let path = repo.join(path);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("create parent directory");
        }
        fs::write(path, contents).expect("write fixture");
    }

    fn repository() -> TempDir {
        let repo = TempDir::new().expect("temp repo");
        git(repo.path(), &["init", "-q"]);
        git(
            repo.path(),
            &["config", "user.email", "impact@example.test"],
        );
        git(repo.path(), &["config", "user.name", "Impact Test"]);
        write(repo.path(), ".gitignore", ".sinter/\n");
        write(
            repo.path(),
            "Cargo.toml",
            "[package]\nname = \"impact-fixture\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        );
        write(repo.path(), "src/lib.rs", "pub fn value() -> u32 { 1 }\n");
        write(repo.path(), "deleted.rs", "pub fn removed() {}\n");
        write(repo.path(), "old.rs", "pub fn renamed() {}\n");
        git(repo.path(), &["add", "."]);
        git(repo.path(), &["commit", "-qm", "base"]);
        repo
    }

    #[test]
    fn detects_conventional_test_files_and_names() {
        // One case per convention.
        for (id, name, file) in [
            ("a_test.go#f", "f", "a_test.go"),                  // Go
            ("a_test.py#f", "f", "a_test.py"),                  // Python file
            ("FooTests.cs#F", "F", "FooTests.cs"),              // C#
            ("app.test.ts#f", "f", "app.test.ts"),              // JS/TS .test.
            ("app.spec.js#f", "f", "app.spec.js"),              // JS/TS .spec.
            ("tests/x.rs#f", "f", "tests/x.rs"),                // tests/ dir
            ("crate/tests/x.rs#f", "f", "crate/tests/x.rs"),    // nested tests/
            ("pkg/test/x.py#f", "f", "pkg/test/x.py"),          // test/ dir
            ("m.py#test_f", "test_f", "m.py"),                  // test_ prefix
            ("M.go#TestF", "TestF", "M.go"),                    // Test prefix
            ("src/lib.rs#tests::works", "works", "src/lib.rs"), // #[cfg(test)] mod
        ] {
            assert!(is_test(&node(id, name, file)), "{file} {name}");
        }
    }

    #[test]
    fn plain_symbols_are_not_tests() {
        for (id, name, file) in [
            ("src/lib.rs#build", "build", "src/lib.rs"),
            ("src/attest.rs#attest", "attest", "src/attest.rs"),
            ("contest.py#run", "run", "contest.py"),
        ] {
            assert!(!is_test(&node(id, name, file)), "{file} {name}");
        }
    }

    #[test]
    fn impact_reports_commit_range_paths_including_config_deletion_and_rename() {
        let repo = repository();
        write(
            repo.path(),
            "Cargo.toml",
            "[package]\nname = \"impact-fixture\"\nversion = \"0.2.0\"\nedition = \"2024\"\n",
        );
        write(repo.path(), "src/lib.rs", "pub fn value() -> u32 { 2 }\n");
        fs::remove_file(repo.path().join("deleted.rs")).expect("delete fixture");
        git(repo.path(), &["mv", "old.rs", "renamed.rs"]);
        git(repo.path(), &["add", "-A"]);
        git(repo.path(), &["commit", "-qm", "mixed changes"]);

        let files = changed_files(repo.path(), "HEAD~1..HEAD").expect("collect changed paths");
        assert!(
            files
                .iter()
                .any(|file| { file.path == "Cargo.toml" && file.kind == FileChangeKind::Modified })
        );
        assert!(
            files
                .iter()
                .any(|file| file.path == "deleted.rs" && file.kind == FileChangeKind::Deleted)
        );
        assert!(files.iter().any(|file| {
            file.path == "renamed.rs"
                && file.old_path.as_deref() == Some("old.rs")
                && file.kind == FileChangeKind::Renamed
        }));

        crate::pipeline::build(repo.path(), None).expect("build fixture graph");
        let report = compute(repo.path(), "HEAD~1..HEAD").expect("compute impact");
        assert_eq!(report.analysis_status, AnalysisStatus::Partial);
        assert_eq!(report.changed_files.len(), 4);
        assert!(report.unmapped_files.iter().any(|file| {
            file.path == "Cargo.toml" && file.reason == UnmappedReason::NotIndexed
        }));
        assert!(
            report.unmapped_files.iter().any(|file| {
                file.path == "deleted.rs" && file.reason == UnmappedReason::Deleted
            })
        );
        assert!(
            report
                .changed_files
                .iter()
                .any(|file| { file.path == "renamed.rs" && file.mapped_symbols > 0 })
        );
        assert!(
            report
                .changed_symbols
                .iter()
                .any(|symbol| symbol.file == "src/lib.rs")
        );
    }

    #[test]
    fn impact_reports_staged_unstaged_renamed_deleted_and_untracked_states() {
        let repo = repository();
        write(repo.path(), "src/lib.rs", "pub fn value() -> u32 { 2 }\n");
        git(repo.path(), &["add", "src/lib.rs"]);
        write(repo.path(), "src/lib.rs", "pub fn value() -> u32 { 3 }\n");
        fs::remove_file(repo.path().join("deleted.rs")).expect("delete fixture");
        git(repo.path(), &["mv", "old.rs", "renamed.rs"]);
        write(repo.path(), "untracked.rs", "pub fn untracked() {}\n");

        let changes = working_tree_changes(repo.path()).expect("collect working tree state");
        let modified = changes
            .iter()
            .find(|change| change.path == "src/lib.rs")
            .expect("modified path");
        assert_eq!(modified.index_status, "modified");
        assert_eq!(modified.worktree_status, "modified");
        let deleted = changes
            .iter()
            .find(|change| change.path == "deleted.rs")
            .expect("deleted path");
        assert_eq!(deleted.index_status, "unmodified");
        assert_eq!(deleted.worktree_status, "deleted");
        let renamed = changes
            .iter()
            .find(|change| change.path == "renamed.rs")
            .expect("renamed path");
        assert_eq!(renamed.old_path.as_deref(), Some("old.rs"));
        assert_eq!(renamed.index_status, "renamed");
        let untracked = changes
            .iter()
            .find(|change| change.path == "untracked.rs")
            .expect("untracked path");
        assert_eq!(untracked.index_status, "untracked");
        assert_eq!(untracked.worktree_status, "untracked");
    }
}