repopilot 0.20.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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use crate::audits::pipeline::{registered_file_audits, registered_project_audits};
use crate::findings::types::Finding;
use crate::findings::types::{FindingCategory, Severity};
use crate::rules::registry::all_rule_metadata;
use crate::scan::config::ScanConfig;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;

/// Bump whenever the on-disk shape or semantics of a cached entry changes so
/// stale caches are rejected instead of silently deserialized with
/// `#[serde(default)]` gaps.
/// v4 added `FileRoleEntry::deferred_imports`: a v3 cache lacks the field and
/// would rehydrate it as `[]`, dropping deferred (function-body) imports and
/// resurrecting the phantom cycles the deferral was meant to break.
/// v5 invalidates cached file roles because `deferred_imports` now also includes
/// TypeScript/JavaScript type-only imports and exports erased at runtime.
/// v6 invalidates cached file roles because classification now adds build-tooling
/// and managed test-support roles.
/// v7 adds explainable role-evidence records to each cached file-role entry.
/// v8 carries the remaining `FileFacts` fields needed for warm cache parity.
pub const CACHE_SCHEMA_VERSION: u32 = 8;
pub const CACHE_DIR: &str = ".repopilot/cache";
const FILE_HASHES_NAME: &str = "file_hashes.json";
const FILE_ROLES_NAME: &str = "file_roles.json";
const FINDINGS_NAME: &str = "findings.json";

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileHashEntry {
    pub path: String,
    pub hash: String,
    pub size: u64,
    pub modified_unix_seconds: u64,
    pub cache_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileRoleEvidenceEntry {
    pub role: String,
    pub source: String,
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileRoleEntry {
    pub path: String,
    pub hash: String,
    pub language: Option<String>,
    pub non_empty_lines: usize,
    #[serde(default)]
    pub branch_count: usize,
    #[serde(default)]
    pub imports: Vec<String>,
    #[serde(default)]
    pub deferred_imports: Vec<String>,
    pub roles: Vec<String>,
    #[serde(default)]
    pub role_evidence: Vec<FileRoleEvidenceEntry>,
    pub frameworks: Vec<String>,
    pub runtimes: Vec<String>,
    pub paradigms: Vec<String>,
    pub is_test: bool,
    #[serde(default)]
    pub has_inline_tests: bool,
    #[serde(default)]
    pub in_executable_package: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FindingsEntry {
    pub path: String,
    pub hash: String,
    pub config_fingerprint: String,
    pub findings: Vec<Finding>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileHashesCache {
    pub schema_version: u32,
    pub repopilot_version: String,
    pub entries: Vec<FileHashEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FileRolesCache {
    pub schema_version: u32,
    pub repopilot_version: String,
    pub entries: Vec<FileRoleEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct FindingsCache {
    pub schema_version: u32,
    pub repopilot_version: String,
    pub entries: Vec<FindingsEntry>,
}

#[derive(Debug, Default)]
pub struct ScanCache {
    pub file_hashes: BTreeMap<String, FileHashEntry>,
    pub file_roles: BTreeMap<String, FileRoleEntry>,
    pub findings: BTreeMap<String, FindingsEntry>,
}

impl ScanCache {
    pub fn load(root: &Path) -> Self {
        let cache_root = cache_dir(root);
        Self {
            file_hashes: read_cache::<FileHashesCache>(&cache_root.join(FILE_HASHES_NAME))
                .filter(valid_file_hashes_cache)
                .map(|cache| entries_by_path(cache.entries))
                .unwrap_or_default(),
            file_roles: read_cache::<FileRolesCache>(&cache_root.join(FILE_ROLES_NAME))
                .filter(valid_file_roles_cache)
                .map(|cache| entries_by_path(cache.entries))
                .unwrap_or_default(),
            findings: read_cache::<FindingsCache>(&cache_root.join(FINDINGS_NAME))
                .filter(valid_findings_cache)
                .map(|cache| entries_by_path(cache.entries))
                .unwrap_or_default(),
        }
    }

    pub fn write(&self, root: &Path) -> io::Result<()> {
        let cache_root = cache_dir(root);
        fs::create_dir_all(&cache_root)?;

        write_cache(
            &cache_root.join(FILE_HASHES_NAME),
            &FileHashesCache {
                schema_version: CACHE_SCHEMA_VERSION,
                repopilot_version: env!("CARGO_PKG_VERSION").to_string(),
                entries: self.file_hashes.values().cloned().collect(),
            },
        )?;
        write_cache(
            &cache_root.join(FILE_ROLES_NAME),
            &FileRolesCache {
                schema_version: CACHE_SCHEMA_VERSION,
                repopilot_version: env!("CARGO_PKG_VERSION").to_string(),
                entries: self.file_roles.values().cloned().collect(),
            },
        )?;
        write_cache(
            &cache_root.join(FINDINGS_NAME),
            &FindingsCache {
                schema_version: CACHE_SCHEMA_VERSION,
                repopilot_version: env!("CARGO_PKG_VERSION").to_string(),
                entries: self.findings.values().cloned().collect(),
            },
        )?;

        Ok(())
    }
}

pub fn clear_cache(root: &Path) -> io::Result<()> {
    let cache_root = cache_dir(root);
    match fs::remove_dir_all(cache_root) {
        Ok(()) => Ok(()),
        Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(error) => Err(error),
    }
}

pub fn cache_dir(root: &Path) -> PathBuf {
    root.join(CACHE_DIR)
}

pub fn file_hash_entry(root: &Path, path: &Path) -> io::Result<FileHashEntry> {
    let bytes = fs::read(path)?;
    let metadata = fs::metadata(path)?;
    let relative = relative_cache_path(root, path);
    let hash = stable_hash_hex(&bytes);
    let modified_unix_seconds = metadata
        .modified()
        .ok()
        .and_then(|modified| modified.duration_since(UNIX_EPOCH).ok())
        .map(|duration| duration.as_secs())
        .unwrap_or(0);
    let cache_key = stable_hash_hex(format!("{relative}:{hash}:{}", metadata.len()).as_bytes());

    Ok(FileHashEntry {
        path: relative,
        hash,
        size: metadata.len(),
        modified_unix_seconds,
        cache_key,
    })
}

pub fn config_fingerprint(config: &ScanConfig) -> String {
    let input = CacheFingerprintInput {
        cache_schema_version: CACHE_SCHEMA_VERSION,
        repopilot_version: env!("CARGO_PKG_VERSION"),
        scan_config: config,
        file_audits: registered_file_audits(config)
            .into_iter()
            .map(|registration| AuditFingerprint {
                audit_id: registration.metadata.audit_id,
                kind: registration.metadata.kind.label(),
                category: registration.metadata.category,
                rule_ids: registration.metadata.rule_ids.to_vec(),
            })
            .collect(),
        project_audits: registered_project_audits(config)
            .into_iter()
            .map(|registration| AuditFingerprint {
                audit_id: registration.metadata.audit_id,
                kind: registration.metadata.kind.label(),
                category: registration.metadata.category,
                rule_ids: registration.metadata.rule_ids.to_vec(),
            })
            .collect(),
        rules: all_rule_metadata()
            .map(|rule| RuleFingerprint {
                rule_id: rule.rule_id,
                title: rule.title,
                category: rule.category.clone(),
                default_severity: rule.default_severity,
                docs_url: rule.docs_url,
                description: rule.description,
                recommendation: rule.recommendation,
                required_scope: rule.requirements.scope.label(),
                required_facts: rule
                    .requirements
                    .fact_kinds
                    .iter()
                    .map(|fact| fact.label())
                    .collect(),
                requirements_lifecycle: rule.requirements.lifecycle.label(),
                cache_policy: rule.requirements.cache_policy.label(),
                produces: rule
                    .requirements
                    .produces
                    .iter()
                    .map(|output| output.label())
                    .collect(),
            })
            .collect(),
    };

    match serde_json::to_vec(&input) {
        Ok(bytes) => stable_hash_hex(&bytes),
        Err(_) => stable_hash_hex(format!("{config:?}:{}", CACHE_SCHEMA_VERSION).as_bytes()),
    }
}

pub fn stable_hash_hex(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    digest.iter().map(|byte| format!("{byte:02x}")).collect()
}

#[derive(Serialize)]
struct CacheFingerprintInput<'a> {
    cache_schema_version: u32,
    repopilot_version: &'static str,
    scan_config: &'a ScanConfig,
    file_audits: Vec<AuditFingerprint>,
    project_audits: Vec<AuditFingerprint>,
    rules: Vec<RuleFingerprint>,
}

#[derive(Serialize)]
struct AuditFingerprint {
    audit_id: &'static str,
    kind: &'static str,
    category: FindingCategory,
    rule_ids: Vec<&'static str>,
}

#[derive(Serialize)]
struct RuleFingerprint {
    rule_id: &'static str,
    title: &'static str,
    category: FindingCategory,
    default_severity: Severity,
    docs_url: Option<&'static str>,
    description: &'static str,
    recommendation: Option<&'static str>,
    required_scope: &'static str,
    required_facts: Vec<&'static str>,
    requirements_lifecycle: &'static str,
    cache_policy: &'static str,
    produces: Vec<&'static str>,
}

pub fn relative_cache_path(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/")
        .trim_start_matches("./")
        .to_string()
}

fn read_cache<T>(path: &Path) -> Option<T>
where
    T: for<'de> Deserialize<'de>,
{
    let content = fs::read_to_string(path).ok()?;
    serde_json::from_str(&content).ok()
}

fn write_cache<T>(path: &Path, value: &T) -> io::Result<()>
where
    T: Serialize,
{
    let rendered = serde_json::to_string_pretty(value).map_err(io::Error::other)?;
    fs::write(path, rendered)
}

fn entries_by_path<T>(entries: Vec<T>) -> BTreeMap<String, T>
where
    T: CachePath,
{
    entries
        .into_iter()
        .map(|entry| (entry.cache_path().to_string(), entry))
        .collect()
}

trait CachePath {
    fn cache_path(&self) -> &str;
}

impl CachePath for FileHashEntry {
    fn cache_path(&self) -> &str {
        &self.path
    }
}

impl CachePath for FileRoleEntry {
    fn cache_path(&self) -> &str {
        &self.path
    }
}

impl CachePath for FindingsEntry {
    fn cache_path(&self) -> &str {
        &self.path
    }
}

/// File-hash and file-role caches store only file metadata (path, hash, LOC,
/// language). They do not depend on which rules are active, so they only need
/// to be invalidated when the binary schema changes — not on every version
/// bump. This lets incremental rescans stay warm across patch releases.
fn valid_file_hashes_cache(cache: &FileHashesCache) -> bool {
    cache.schema_version == CACHE_SCHEMA_VERSION
}

/// See `valid_file_hashes_cache` — same rationale.
fn valid_file_roles_cache(cache: &FileRolesCache) -> bool {
    cache.schema_version == CACHE_SCHEMA_VERSION
}

/// The findings cache header is also validated by schema version only.
/// Per-entry invalidation is handled by `FindingsEntry::config_fingerprint`,
/// which is a hash of every active rule + config setting computed by
/// `config_fingerprint()` in `cache/fingerprint.rs`. When rules change,
/// the fingerprint changes and that entry is skipped; unaffected entries
/// remain valid across version bumps.
fn valid_findings_cache(cache: &FindingsCache) -> bool {
    cache.schema_version == CACHE_SCHEMA_VERSION
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CacheDiagnostics {
    pub cache_dir: PathBuf,
    pub exists: bool,
    pub schema_version: u32,
    pub repopilot_version: String,
    pub approximate_size_bytes: u64,
    pub file_hashes_count: usize,
    pub file_roles_count: usize,
    pub findings_count: usize,
    pub stale_entries_count: usize,
}

pub fn inspect_cache(root: &Path) -> CacheDiagnostics {
    let cache_root = cache_dir(root);
    let exists = cache_root.is_dir();
    let cache = ScanCache::load(root);

    CacheDiagnostics {
        cache_dir: cache_root.clone(),
        exists,
        schema_version: CACHE_SCHEMA_VERSION,
        repopilot_version: env!("CARGO_PKG_VERSION").to_string(),
        approximate_size_bytes: directory_size_bytes(&cache_root),
        file_hashes_count: cache.file_hashes.len(),
        file_roles_count: cache.file_roles.len(),
        findings_count: cache.findings.len(),
        stale_entries_count: stale_cache_entries_count(&cache),
    }
}

fn stale_cache_entries_count(cache: &ScanCache) -> usize {
    let mut count = 0;

    for key in cache.file_hashes.keys() {
        if !cache.file_roles.contains_key(key) || !cache.findings.contains_key(key) {
            count += 1;
        }
    }

    for key in cache.file_roles.keys() {
        if !cache.file_hashes.contains_key(key) {
            count += 1;
        }
    }

    for key in cache.findings.keys() {
        if !cache.file_hashes.contains_key(key) {
            count += 1;
        }
    }

    count
}

fn directory_size_bytes(path: &Path) -> u64 {
    let Ok(entries) = fs::read_dir(path) else {
        return 0;
    };

    entries
        .filter_map(Result::ok)
        .map(|entry| {
            let entry_path = entry.path();
            match entry.metadata() {
                Ok(metadata) if metadata.is_file() => metadata.len(),
                Ok(metadata) if metadata.is_dir() => directory_size_bytes(&entry_path),
                _ => 0,
            }
        })
        .sum()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn file_role_cache_round_trips_role_evidence() {
        let cache = FileRolesCache {
            schema_version: CACHE_SCHEMA_VERSION,
            repopilot_version: "test".to_string(),
            entries: vec![FileRoleEntry {
                path: "src/lib.rs".to_string(),
                hash: "hash".to_string(),
                language: Some("Rust".to_string()),
                non_empty_lines: 1,
                branch_count: 0,
                imports: Vec::new(),
                deferred_imports: Vec::new(),
                roles: vec!["domain".to_string()],
                role_evidence: vec![FileRoleEvidenceEntry {
                    role: "domain".to_string(),
                    source: "path".to_string(),
                    reason: "domain/model/entity path component matched".to_string(),
                }],
                frameworks: Vec::new(),
                runtimes: vec!["rust-library".to_string()],
                paradigms: Vec::new(),
                is_test: false,
                has_inline_tests: false,
                in_executable_package: false,
            }],
        };

        let encoded = serde_json::to_string(&cache).expect("serialize file-role cache");
        let decoded: FileRolesCache =
            serde_json::from_str(&encoded).expect("deserialize file-role cache");

        assert_eq!(decoded, cache);
        assert_eq!(decoded.entries[0].role_evidence[0].role, "domain");
    }

    #[test]
    fn previous_file_role_cache_schema_is_rejected() {
        let cache = FileRolesCache {
            schema_version: CACHE_SCHEMA_VERSION - 1,
            repopilot_version: "test".to_string(),
            entries: Vec::new(),
        };

        assert!(!valid_file_roles_cache(&cache));
    }
}