repopilot 0.19.0

Local-first CLI for reviewing Git changes, security boundaries, and blast radius before merge.
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
//! Unified, confidence-tiered view over the review's change signals.
//!
//! Boundary, behavioral, algorithmic, and taint-lite signals converge into one
//! [`ReviewSignal`] type, grouped into three trust tiers so a reviewer's eye
//! goes to the right place first:
//!
//! - **definitely sensitive** — boundary changes and unambiguous behavior
//!   crossings (env var, migration, subprocess, removed error handling / auth /
//!   test, a network call in an auth path), plus input reaching raw SQL or exec.
//! - **maybe sensitive** — behavior in ordinary files (network call, fs write,
//!   new dependency, raw SQL), every algorithmic delta, and input reaching a
//!   filesystem write or outbound network call.
//! - **large-diff-or-noise** — a big diff with nothing flagged, surfaced once so
//!   volume is visible without pretending to understand it.
//!
//! Humble by construction: every signal carries a structural fact, never a
//! verdict. The existing `boundary_signals` view is kept untouched; this is an
//! additive, forward-looking surface.

use crate::findings::provenance::AnalysisScope;
use crate::findings::types::Confidence;
use crate::review::diff::ChangedFile;
use crate::review::paths::normalized_review_path;
use crate::review::signals::BoundarySignal;
use crate::review::signals::algorithmic::{AlgorithmicKind, AlgorithmicSignal};
use crate::review::signals::behavioral::{BehavioralKind, BehavioralSignal};
use crate::review::signals::composites;
use crate::review::signals::taint::{SinkKind, TaintSignal};
use crate::rules::{RuleLifecycle, SignalSource};
use crate::scan::cache::stable_hash_hex;
use crate::scan::types::CouplingGraph;
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

/// A big diff is only called out as "noise" once it crosses both of these and
/// nothing else was flagged.
const LARGE_DIFF_FILES: usize = 5;
const LARGE_DIFF_LINES: usize = 200;

/// How much a reviewer should trust that a signal points at something worth a look.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ConfidenceTier {
    DefinitelySensitive,
    MaybeSensitive,
    LargeDiffOrNoise,
}

/// Which detector produced a signal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SignalFamily {
    Boundary,
    Behavioral,
    Algorithmic,
    /// Untrusted input reaching a dangerous sink (taint-lite reachability).
    Taint,
    /// The single large-diff/volume note, which belongs to no detector family.
    Volume,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ReviewSignalProvenance {
    pub detector: String,
    pub lifecycle: RuleLifecycle,
    pub signal_source: SignalSource,
    pub analysis_scope: AnalysisScope,
}

/// One unified review signal, ready to render under its tier.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ReviewSignal {
    pub signal_id: String,
    pub kind: String,
    pub family: SignalFamily,
    pub tier: ConfidenceTier,
    pub confidence: Confidence,
    pub path: String,
    /// Compatibility alias retained throughout the pre-1.0 schema line.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_start: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line_end: Option<usize>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub evidence_lines: Vec<usize>,
    /// Neutral structural fact, e.g. "network call added" / "nesting 2 → 4".
    pub headline: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// How many files import the signal's file (reach), from the coupling graph.
    pub blast_radius: usize,
    pub provenance: ReviewSignalProvenance,
    pub suppressed: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub suppression_reason: Option<String>,
    pub gate_eligible: bool,
}

/// The review's signals grouped by confidence tier.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct TieredSignals {
    pub definitely: Vec<ReviewSignal>,
    pub maybe: Vec<ReviewSignal>,
    pub noise: Vec<ReviewSignal>,
}

impl TieredSignals {
    fn push(&mut self, signal: ReviewSignal) {
        match signal.tier {
            ConfidenceTier::DefinitelySensitive => self.definitely.push(signal),
            ConfidenceTier::MaybeSensitive => self.maybe.push(signal),
            ConfidenceTier::LargeDiffOrNoise => self.noise.push(signal),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.definitely.is_empty() && self.maybe.is_empty() && self.noise.is_empty()
    }

    pub fn total(&self) -> usize {
        self.definitely.len() + self.maybe.len() + self.noise.len()
    }

    fn sort(&mut self) {
        for group in [&mut self.definitely, &mut self.maybe, &mut self.noise] {
            group.sort_by(|left, right| {
                left.path
                    .cmp(&right.path)
                    .then(left.line.cmp(&right.line))
                    .then(left.headline.cmp(&right.headline))
            });
        }
    }

    pub fn gate_eligible_definitely_count(&self) -> usize {
        self.definitely
            .iter()
            .filter(|signal| signal.gate_eligible && !signal.suppressed)
            .count()
    }

    /// Whether any visible tier carries a taint-lite reachability signal. Used to
    /// surface the "a path exists, not a confirmed vulnerability" disclaimer once
    /// per report rather than repeating it on every taint row.
    pub fn has_taint_signal(&self) -> bool {
        [&self.definitely, &self.maybe, &self.noise]
            .into_iter()
            .flatten()
            .any(|signal| !signal.suppressed && signal.family == SignalFamily::Taint)
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut ReviewSignal> {
        self.definitely
            .iter_mut()
            .chain(self.maybe.iter_mut())
            .chain(self.noise.iter_mut())
    }
}

/// Fold the four signal families into one tiered view.
pub fn build_tiered(
    boundary: &[BoundarySignal],
    behavioral: &[BehavioralSignal],
    algorithmic: &[AlgorithmicSignal],
    taint: &[TaintSignal],
    changed_files: &[ChangedFile],
) -> TieredSignals {
    let mut tiered = TieredSignals::default();

    // Files that decide who-can-do-what; a network call added *there* is more
    // than maybe-sensitive.
    let access_paths: BTreeSet<&str> = boundary
        .iter()
        .filter(|signal| signal.category.is_code_boundary())
        .map(|signal| signal.path.as_str())
        .collect();

    for signal in boundary {
        tiered.push(from_boundary(signal));
    }
    for signal in behavioral {
        let in_access = access_paths.contains(signal.path.as_str());
        tiered.push(build_signal(
            behavioral_kind(signal.kind),
            SignalFamily::Behavioral,
            behavioral_tier(signal.kind, in_access, signal.is_coarse()),
            if signal.is_coarse() {
                Confidence::Low
            } else {
                Confidence::High
            },
            signal.path.clone(),
            Some(signal.line),
            behavioral_headline(signal.kind),
            Some(signal.detail.clone()),
            if signal.is_coarse() {
                SignalSource::TextHeuristic
            } else {
                SignalSource::Ast
            },
        ));
    }
    for signal in algorithmic {
        tiered.push(build_signal(
            algorithmic_kind(signal.kind),
            SignalFamily::Algorithmic,
            ConfidenceTier::MaybeSensitive,
            Confidence::Medium,
            signal.path.clone(),
            Some(signal.line),
            algorithmic_headline(signal.kind),
            Some(signal.detail.clone()),
            SignalSource::Ast,
        ));
    }
    for signal in taint {
        tiered.push(build_signal(
            taint_kind(signal.sink),
            SignalFamily::Taint,
            taint_tier(signal.sink),
            Confidence::High,
            signal.path.clone(),
            Some(signal.line),
            taint_headline(signal.sink),
            Some(signal.detail.clone()),
            SignalSource::Ast,
        ));
    }

    // Only call out raw volume when nothing else fired — otherwise the flagged
    // signals already point the eye.
    if tiered.definitely.is_empty() && tiered.maybe.is_empty() {
        let (files, lines) = diff_size(changed_files);
        if files > LARGE_DIFF_FILES && lines > LARGE_DIFF_LINES {
            tiered.push(build_signal(
                "volume.large-diff",
                SignalFamily::Volume,
                ConfidenceTier::LargeDiffOrNoise,
                Confidence::Low,
                String::new(),
                None,
                "large diff, no review signal flagged",
                Some(format!("{files} files, ~{lines} changed lines")),
                SignalSource::GitDiff,
            ));
        }
    }

    deduplicate(&mut tiered);
    tiered.sort();
    tiered
}

/// Fill each signal's reach (importer count) from the coupling graph, mirroring
/// the boundary-signal enrichment. No-op without a graph; boundary signals keep
/// the reach they were already given.
pub fn enrich_blast_radius(
    tiered: &mut TieredSignals,
    graph: Option<&CouplingGraph>,
    repo_root: &Path,
) {
    let Some(graph) = graph else {
        return;
    };
    let importers = composites::build_importers_by_target(graph, repo_root);

    for group in [&mut tiered.definitely, &mut tiered.maybe, &mut tiered.noise] {
        for signal in group.iter_mut() {
            if signal.blast_radius != 0 || signal.path.is_empty() {
                continue;
            }
            let normalized = normalized_review_path(Path::new(&signal.path), repo_root);
            signal.blast_radius = importers.get(&normalized).map_or(0, BTreeSet::len);
        }
    }
}

fn from_boundary(signal: &BoundarySignal) -> ReviewSignal {
    let mut review_signal = build_signal(
        boundary_kind(signal.category),
        SignalFamily::Boundary,
        ConfidenceTier::DefinitelySensitive,
        Confidence::High,
        signal.path.clone(),
        None,
        &format!("{} changed", signal.category.label()),
        None,
        SignalSource::GitDiff,
    );
    review_signal.blast_radius = signal.blast_radius;
    review_signal
}

#[allow(clippy::too_many_arguments)]
fn build_signal(
    kind: &str,
    family: SignalFamily,
    tier: ConfidenceTier,
    confidence: Confidence,
    path: String,
    line: Option<usize>,
    headline: &str,
    detail: Option<String>,
    signal_source: SignalSource,
) -> ReviewSignal {
    let signal_id = stable_hash_hex(format!("{kind}\0{path}").as_bytes())[..16].to_string();
    ReviewSignal {
        signal_id,
        kind: kind.to_string(),
        family,
        tier,
        confidence,
        path,
        line,
        line_start: line,
        line_end: line,
        evidence_lines: line.into_iter().collect(),
        headline: headline.to_string(),
        detail,
        blast_radius: 0,
        provenance: ReviewSignalProvenance {
            detector: kind.to_string(),
            lifecycle: RuleLifecycle::Preview,
            signal_source,
            analysis_scope: AnalysisScope::GitDiff,
        },
        suppressed: false,
        suppression_reason: None,
        gate_eligible: tier == ConfidenceTier::DefinitelySensitive,
    }
}

fn deduplicate(tiered: &mut TieredSignals) {
    let mut groups: BTreeMap<(String, String), ReviewSignal> = BTreeMap::new();
    for signal in tiered
        .definitely
        .drain(..)
        .chain(tiered.maybe.drain(..))
        .chain(tiered.noise.drain(..))
    {
        let key = (signal.kind.clone(), signal.path.clone());
        groups
            .entry(key)
            .and_modify(|existing| {
                existing.evidence_lines.extend(signal.evidence_lines.iter());
                existing.evidence_lines.sort_unstable();
                existing.evidence_lines.dedup();
                existing.line_start = existing.evidence_lines.first().copied();
                existing.line_end = existing.evidence_lines.last().copied();
                existing.line = existing.line_start;
                existing.blast_radius = existing.blast_radius.max(signal.blast_radius);
            })
            .or_insert(signal);
    }
    for signal in groups.into_values() {
        tiered.push(signal);
    }
}

fn boundary_kind(category: crate::review::signals::BoundaryCategory) -> &'static str {
    use crate::review::signals::BoundaryCategory::*;
    match category {
        AccessControl => "boundary.access-control",
        RequestTrust => "boundary.request-trust",
        DeploySurface => "boundary.deploy-surface",
        SupplyChain => "boundary.supply-chain",
        SecretConfig => "boundary.secret-config",
        Custom => "boundary.custom",
    }
}

fn behavioral_kind(kind: BehavioralKind) -> &'static str {
    use BehavioralKind::*;
    match kind {
        NetworkCallAdded => "behavioral.network-call-added",
        SubprocessAdded => "behavioral.subprocess-added",
        FsWriteAdded => "behavioral.fs-write-added",
        EnvVarIntroduced => "behavioral.env-var-introduced",
        DependencyImportAdded => "behavioral.dependency-import-added",
        MigrationAdded => "behavioral.migration-added",
        RawSqlAdded => "behavioral.raw-sql-added",
        ErrorHandlingRemoved => "behavioral.error-handling-removed",
        TestDeletedOrEmptied => "behavioral.test-deleted-or-emptied",
        AuthCheckRemoved => "behavioral.auth-check-removed",
    }
}

fn algorithmic_kind(kind: AlgorithmicKind) -> &'static str {
    use AlgorithmicKind::*;
    match kind {
        ComplexityIncreased => "algorithmic.complexity-increased",
        NestedLoopIntroduced => "algorithmic.nested-loop-introduced",
        FunctionGrew => "algorithmic.function-grew",
        RecursionIntroduced => "algorithmic.recursion-introduced",
    }
}

fn taint_kind(sink: SinkKind) -> &'static str {
    match sink {
        SinkKind::Sql => "taint.sql",
        SinkKind::Exec => "taint.exec",
        SinkKind::FsWrite => "taint.fs-write",
        SinkKind::Network => "taint.network",
    }
}

fn behavioral_tier(kind: BehavioralKind, in_access_boundary: bool, coarse: bool) -> ConfidenceTier {
    use BehavioralKind::*;
    // Coarse (non-AST) signals are best-effort hints from a file we couldn't
    // parse; keep them visible but never above the large-diff/noise tier.
    if coarse {
        return ConfidenceTier::LargeDiffOrNoise;
    }
    match kind {
        SubprocessAdded | EnvVarIntroduced | MigrationAdded | ErrorHandlingRemoved
        | TestDeletedOrEmptied | AuthCheckRemoved => ConfidenceTier::DefinitelySensitive,
        NetworkCallAdded if in_access_boundary => ConfidenceTier::DefinitelySensitive,
        NetworkCallAdded | FsWriteAdded | DependencyImportAdded | RawSqlAdded => {
            ConfidenceTier::MaybeSensitive
        }
    }
}

fn behavioral_headline(kind: BehavioralKind) -> &'static str {
    use BehavioralKind::*;
    match kind {
        NetworkCallAdded => "network call added",
        SubprocessAdded => "subprocess/exec added",
        FsWriteAdded => "filesystem write added",
        EnvVarIntroduced => "env var introduced",
        DependencyImportAdded => "dependency import added",
        MigrationAdded => "migration added",
        RawSqlAdded => "raw SQL added",
        ErrorHandlingRemoved => "error handling removed",
        TestDeletedOrEmptied => "test deleted or emptied",
        AuthCheckRemoved => "auth check removed",
    }
}

/// SQL/exec injection lands in the top tier; filesystem/network reach is real but
/// more often legitimate, so it stays *maybe sensitive*.
fn taint_tier(sink: SinkKind) -> ConfidenceTier {
    match sink {
        SinkKind::Sql | SinkKind::Exec => ConfidenceTier::DefinitelySensitive,
        SinkKind::FsWrite | SinkKind::Network => ConfidenceTier::MaybeSensitive,
    }
}

fn taint_headline(sink: SinkKind) -> &'static str {
    match sink {
        SinkKind::Sql => "untrusted input reaches raw SQL",
        SinkKind::Exec => "untrusted input reaches subprocess/exec",
        SinkKind::FsWrite => "untrusted input reaches filesystem write",
        SinkKind::Network => "untrusted input reaches network call",
    }
}

fn algorithmic_headline(kind: AlgorithmicKind) -> &'static str {
    use AlgorithmicKind::*;
    match kind {
        ComplexityIncreased => "complexity increased",
        NestedLoopIntroduced => "nested loop introduced",
        FunctionGrew => "function grew",
        RecursionIntroduced => "recursion introduced",
    }
}

fn diff_size(changed_files: &[ChangedFile]) -> (usize, usize) {
    let lines = changed_files
        .iter()
        .flat_map(|file| file.ranges.iter())
        .map(|range| range.end.saturating_sub(range.start) + 1)
        .sum();
    (changed_files.len(), lines)
}