rdar 0.6.7

radar - the repository cartographer for AI agents: compiles a repo into tiny committed MAP.md routers, with measured token benchmarks
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
//! Deterministic review-impact analysis over the cached file graph.
//!
//! This is deliberately a file-level, conservative report. A reference to a
//! public name fans out to every public definer of that name, so ambiguity is
//! visible instead of silently choosing one target. The report is useful for
//! review triage and test selection; source remains authoritative for semantic
//! proof.

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use serde::Serialize;

use crate::cache::ScanCache;
use crate::extract::{RefKind, SymKind, Vis};

/// One path reached from a changed file, with the shortest graph distance.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ImpactPath {
    pub path: String,
    pub distance: usize,
}

/// One extracted definition involved in review impact.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct ImpactDefinition {
    pub path: String,
    pub symbol: String,
    pub line: u32,
    pub end_line: u32,
    pub kind: SymKind,
    pub visibility: Vis,
}

/// One direct call/import edge incident to a changed file.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
pub struct ImpactEdge {
    pub from: String,
    pub from_symbol: Option<String>,
    pub to: String,
    pub to_symbol: String,
    pub reference_line: u32,
    pub kind: RefKind,
}

/// Historical co-change evidence attached by an explicit history request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct HistoricalImpact {
    pub commits_scanned: usize,
    pub seed_commits: usize,
    pub candidates: Vec<crate::gitfacts::HistoryCoChange>,
    pub omitted: usize,
    pub bulk_commits_skipped: usize,
}

/// Review-impact report for a Git change set.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct ImpactReport {
    /// The Git revision used as the comparison base.
    pub base: String,
    /// Maximum number of graph hops followed in each direction.
    pub depth: usize,
    /// All paths Git reported as changed, including non-source paths.
    pub changed: Vec<String>,
    /// Current extracted definitions in changed source files.
    pub changed_definitions: Vec<ImpactDefinition>,
    /// Direct call/import edges entering or leaving changed files.
    pub direct_edges: Vec<ImpactEdge>,
    /// Files that call or import changed public symbols, nearest first.
    pub callers: Vec<ImpactPath>,
    /// Files referenced by changed files, nearest first.
    pub dependencies: Vec<ImpactPath>,
    /// Changed or caller paths matching the stable test/spec naming heuristic.
    pub tests: Vec<String>,
    /// References from changed source files with no public definer.
    pub unresolved_refs: usize,
    /// Changed-file references whose public name has multiple definers.
    pub ambiguous_refs: usize,
    /// Optional historical evidence; absent unless explicitly requested.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub history: Option<HistoricalImpact>,
}

/// Build a deterministic impact report from one canonical scan cache.
pub fn analyze(
    cache: &ScanCache,
    base: impl Into<String>,
    changed: impl IntoIterator<Item = String>,
    depth: usize,
) -> ImpactReport {
    let changed: BTreeSet<String> = changed.into_iter().collect();
    let mut definitions_by_path: BTreeMap<String, Vec<ImpactDefinition>> = BTreeMap::new();
    let mut definers: BTreeMap<String, Vec<ImpactDefinition>> = BTreeMap::new();

    for (path, entry) in &cache.files {
        let Some(lang) = entry.lang else { continue };
        let Some(extraction) = cache.parses.get(&(lang, entry.hash)) else {
            continue;
        };
        for definition in &extraction.defs {
            let definition = ImpactDefinition {
                path: path.clone(),
                symbol: definition.name.clone(),
                line: definition.line,
                end_line: definition.end_line,
                kind: definition.kind,
                visibility: definition.vis,
            };
            definitions_by_path
                .entry(path.clone())
                .or_default()
                .push(definition.clone());
            if definition.visibility == Vis::Pub {
                definers
                    .entry(definition.symbol.clone())
                    .or_default()
                    .push(definition);
            }
        }
    }

    let mut dependencies: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut callers: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut direct_edges = Vec::new();
    let mut unresolved_refs = 0usize;
    let mut ambiguous_refs = 0usize;

    for (path, entry) in &cache.files {
        let Some(lang) = entry.lang else { continue };
        let Some(extraction) = cache.parses.get(&(lang, entry.hash)) else {
            continue;
        };
        for reference in &extraction.refs {
            let Some(targets) = definers.get(&reference.name) else {
                if changed.contains(path) {
                    unresolved_refs += 1;
                }
                continue;
            };
            let targets: Vec<&ImpactDefinition> = targets
                .iter()
                .filter(|target| target.path != *path)
                .collect();
            let target_paths: BTreeSet<&str> =
                targets.iter().map(|target| target.path.as_str()).collect();
            if changed.contains(path) && target_paths.len() > 1 {
                ambiguous_refs += 1;
            }
            for target in targets {
                dependencies
                    .entry(path.clone())
                    .or_default()
                    .insert(target.path.clone());
                callers
                    .entry(target.path.clone())
                    .or_default()
                    .insert(path.clone());
                if changed.contains(path) || changed.contains(&target.path) {
                    direct_edges.push(ImpactEdge {
                        from: path.clone(),
                        from_symbol: definitions_by_path
                            .get(path)
                            .and_then(|defs| enclosing_definition(defs, reference.line))
                            .map(|definition| definition.symbol.clone()),
                        to: target.path.clone(),
                        to_symbol: target.symbol.clone(),
                        reference_line: reference.line,
                        kind: reference.kind,
                    });
                }
            }
        }
    }

    let mut changed_definitions: Vec<ImpactDefinition> = changed
        .iter()
        .flat_map(|path| definitions_by_path.get(path).into_iter().flatten().cloned())
        .collect();
    changed_definitions.sort();
    direct_edges.sort();
    direct_edges.dedup();

    let caller_paths = reachable(&callers, &changed, depth);
    let dependency_paths = reachable(&dependencies, &changed, depth);
    let mut tests: BTreeSet<String> = changed
        .iter()
        .filter(|path| is_test_path(path))
        .cloned()
        .collect();
    tests.extend(
        caller_paths
            .iter()
            .filter(|entry| is_test_path(&entry.path))
            .map(|entry| entry.path.clone()),
    );

    ImpactReport {
        base: base.into(),
        depth,
        changed: changed.into_iter().collect(),
        changed_definitions,
        direct_edges,
        callers: caller_paths,
        dependencies: dependency_paths,
        tests: tests.into_iter().collect(),
        unresolved_refs,
        ambiguous_refs,
        history: None,
    }
}

/// Attach bounded Git co-change facts to an otherwise source-derived report.
pub fn attach_history(report: &mut ImpactReport, facts: crate::gitfacts::HistoryFacts) {
    report.history = Some(HistoricalImpact {
        commits_scanned: facts.commits_scanned,
        seed_commits: facts.seed_commits,
        candidates: facts.candidates,
        omitted: facts.omitted,
        bulk_commits_skipped: facts.bulk_commits_skipped,
    });
}

fn enclosing_definition(definitions: &[ImpactDefinition], line: u32) -> Option<&ImpactDefinition> {
    definitions
        .iter()
        .filter(|definition| definition.line <= line && line <= definition.end_line)
        .min_by_key(|definition| {
            (
                definition.end_line.saturating_sub(definition.line),
                definition.line,
                definition.symbol.as_str(),
            )
        })
}

fn reachable(
    graph: &BTreeMap<String, BTreeSet<String>>,
    starts: &BTreeSet<String>,
    depth: usize,
) -> Vec<ImpactPath> {
    if depth == 0 {
        return Vec::new();
    }
    let mut distances: BTreeMap<String, usize> = BTreeMap::new();
    let mut queue = VecDeque::new();
    for start in starts {
        distances.insert(start.clone(), 0);
        queue.push_back(start.clone());
    }
    while let Some(current) = queue.pop_front() {
        let Some(&distance) = distances.get(&current) else {
            continue;
        };
        if distance >= depth {
            continue;
        }
        let Some(next_paths) = graph.get(&current) else {
            continue;
        };
        for next in next_paths {
            let next_distance = distance + 1;
            let is_shorter = distances
                .get(next)
                .is_none_or(|known| next_distance < *known);
            if is_shorter {
                distances.insert(next.clone(), next_distance);
                queue.push_back(next.clone());
            }
        }
    }
    let mut out: Vec<ImpactPath> = distances
        .into_iter()
        .filter(|(path, distance)| !starts.contains(path) && *distance <= depth)
        .map(|(path, distance)| ImpactPath { path, distance })
        .collect();
    out.sort_by(|left, right| {
        left.distance
            .cmp(&right.distance)
            .then_with(|| left.path.cmp(&right.path))
    });
    out
}

fn is_test_path(path: &str) -> bool {
    let basename = path.rsplit('/').next().unwrap_or(path).to_ascii_lowercase();
    if basename.starts_with("test")
        || basename.contains("_test")
        || basename.contains(".test")
        || basename.contains("_spec")
        || basename.contains(".spec")
    {
        return true;
    }
    path.split('/').any(|part| {
        matches!(
            part.to_ascii_lowercase().as_str(),
            "test" | "tests" | "spec" | "specs"
        )
    })
}

/// Render the report for a human review loop.
pub fn render(report: &ImpactReport) -> String {
    let mut out = format!(
        "radar impact - base {} (depth {})\n",
        report.base, report.depth
    );
    section(
        &mut out,
        "changed",
        report.changed.iter().map(String::as_str),
    );
    section(
        &mut out,
        "changed definitions",
        report.changed_definitions.iter().map(|definition| {
            format!(
                "{}#{}:{}",
                definition.path, definition.symbol, definition.line
            )
        }),
    );
    section(
        &mut out,
        "direct edges",
        report.direct_edges.iter().map(|edge| {
            let from = edge.from_symbol.as_deref().map_or_else(
                || edge.from.clone(),
                |symbol| format!("{}#{}", edge.from, symbol),
            );
            format!(
                "{} -{:?} line {}-> {}#{}",
                from, edge.kind, edge.reference_line, edge.to, edge.to_symbol
            )
        }),
    );
    section(
        &mut out,
        "callers / affected",
        report
            .callers
            .iter()
            .map(|entry| format!("{} (distance {})", entry.path, entry.distance)),
    );
    section(
        &mut out,
        "dependencies",
        report
            .dependencies
            .iter()
            .map(|entry| format!("{} (distance {})", entry.path, entry.distance)),
    );
    section(&mut out, "tests", report.tests.iter().map(String::as_str));
    if let Some(history) = &report.history {
        section(
            &mut out,
            "historical co-change candidates",
            history.candidates.iter().map(|candidate| {
                let commit = candidate.latest_commit.chars().take(8).collect::<String>();
                format!(
                    "{} ({} commit(s), latest {})",
                    candidate.path, candidate.commits, commit
                )
            }),
        );
        out.push_str(&format!(
            "history commits scanned: {}   seed commits: {}   bulk commits skipped: {}   omitted: {}\n",
            history.commits_scanned,
            history.seed_commits,
            history.bulk_commits_skipped,
            history.omitted
        ));
    }
    out.push_str(&format!(
        "unresolved references: {}\nambiguous references: {}\n",
        report.unresolved_refs, report.ambiguous_refs
    ));
    out
}

fn section<'a, I, T>(out: &mut String, name: &str, entries: I)
where
    I: IntoIterator<Item = T>,
    T: std::fmt::Display + 'a,
{
    let entries: Vec<T> = entries.into_iter().collect();
    out.push_str(&format!("{name} ({}):\n", entries.len()));
    if entries.is_empty() {
        out.push_str("  none\n");
    } else {
        for entry in entries {
            out.push_str(&format!("  {entry}\n"));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cache::FileEntry;
    use crate::extract::{Extraction, RefKind, RefName, SymKind, Symbol};
    use crate::lang::Lang;

    fn file(cache: &mut ScanCache, path: &str, defs: &[&str], refs: &[&str]) {
        let hash = *blake3::hash(path.as_bytes()).as_bytes();
        cache.files.insert(
            path.to_string(),
            FileEntry {
                mtime: (1, 0),
                size: 1,
                ino: 0,
                hash,
                lang: Some(Lang::Python),
            },
        );
        cache.parses.insert(
            (Lang::Python, hash),
            Extraction {
                defs: defs
                    .iter()
                    .enumerate()
                    .map(|(line, name)| Symbol {
                        line: line as u32 + 1,
                        end_line: line as u32 + 2,
                        name: (*name).to_string(),
                        kind: SymKind::Fn,
                        vis: Vis::Pub,
                        sig: format!("def {name}()"),
                        terms: Vec::new(),
                    })
                    .collect(),
                refs: refs
                    .iter()
                    .enumerate()
                    .map(|(line, name)| RefName {
                        line: line as u32 + 10,
                        name: (*name).to_string(),
                        kind: RefKind::Call,
                    })
                    .collect(),
            },
        );
    }

    #[test]
    fn walks_callers_dependencies_and_tests_deterministically() {
        let mut cache = ScanCache::default();
        file(&mut cache, "core.py", &["changed"], &["helper"]);
        file(&mut cache, "util.py", &["helper"], &[]);
        file(&mut cache, "api.py", &["api"], &["changed"]);
        file(&mut cache, "tests/test_api.py", &[], &["api"]);

        let report = analyze(&cache, "HEAD", ["core.py".to_string()], 2);
        assert_eq!(report.changed, ["core.py"]);
        assert_eq!(report.changed_definitions[0].symbol, "changed");
        assert_eq!(report.direct_edges.len(), 2);
        assert_eq!(report.direct_edges[0].from, "api.py");
        assert_eq!(report.direct_edges[0].to_symbol, "changed");
        assert_eq!(report.dependencies[0].path, "util.py");
        assert_eq!(report.callers[0].path, "api.py");
        assert_eq!(report.callers[0].distance, 1);
        assert_eq!(report.tests, ["tests/test_api.py"]);
        assert_eq!(report.unresolved_refs, 0);
        assert!(render(&report).contains("callers / affected (2):"));
    }

    #[test]
    fn ambiguity_is_reported_and_name_resolution_fans_out() {
        let mut cache = ScanCache::default();
        file(&mut cache, "changed.py", &["run"], &["shared"]);
        file(&mut cache, "one.py", &["shared"], &[]);
        file(&mut cache, "two.py", &["shared"], &[]);

        let report = analyze(&cache, "HEAD", ["changed.py".to_string()], 1);
        assert_eq!(report.ambiguous_refs, 1);
        assert_eq!(
            report
                .dependencies
                .iter()
                .map(|entry| entry.path.as_str())
                .collect::<Vec<_>>(),
            ["one.py", "two.py"]
        );
    }
}