codescout 0.15.0

High-performance coding agent toolkit MCP server
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
//! Preflight check for `index(action='build')`: scope guard against pathologically broad
//! roots (home dir, system paths) and oversized source trees. Triggers an MCP
//! elicitation in the caller when confirmation is required.

use std::path::{Path, PathBuf};

/// Why a path is considered broad enough to warrant confirmation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SuspiciousReason {
    /// Root exactly matches the user's home directory.
    HomeDirectory,
    /// Root is the parent of the user's home directory (e.g. `/home`).
    HomeParent,
    /// Root is a known system path (`/`, `/usr`, `/etc`, ...).
    SystemPath(PathBuf),
}

/// Summary produced by the preflight scan — used to build the elicitation message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreflightInfo {
    pub root: PathBuf,
    pub file_count: usize,
    pub approx_bytes: u64,
    pub suspicious_reason: Option<SuspiciousReason>,
    pub size_exceeds_threshold: bool,
}

/// Verdict returned by [`check_index_scope`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreflightVerdict {
    /// Proceed to `build_index` — no confirmation needed.
    Clear,
    /// Caller must elicit confirmation from the user before proceeding.
    RequiresConfirmation(PreflightInfo),
}

/// Human-readable byte size. Always 1 decimal place, KB/MB/GB.
#[allow(dead_code)] // used in Task 4 (check_index_scope walker)
pub(crate) fn format_bytes(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = 1024 * 1024;
    const GB: u64 = 1024 * 1024 * 1024;
    if bytes >= GB {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{bytes} B")
    }
}

const SYSTEM_PATHS: &[&str] = &[
    "/", "/usr", "/etc", "/var", "/tmp", "/root", "/opt", "/proc", "/sys", "/home",
];

/// Classify a root path against the known-broad list.
/// Returns `None` for ordinary project directories.
pub(crate) fn classify_path(root: &Path) -> Option<SuspiciousReason> {
    let canon = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());

    if let Some(home) = crate::platform::home_dir() {
        let home_canon = std::fs::canonicalize(&home).unwrap_or(home.clone());
        if canon == home_canon {
            return Some(SuspiciousReason::HomeDirectory);
        }
        if let Some(parent) = home_canon.parent() {
            if canon == parent && canon != Path::new("/") {
                return Some(SuspiciousReason::HomeParent);
            }
        }
    }

    for sys in SYSTEM_PATHS {
        let sys_path = Path::new(sys);
        let sys_canon = std::fs::canonicalize(sys_path).unwrap_or_else(|_| sys_path.to_path_buf());
        if canon == sys_canon {
            return Some(SuspiciousReason::SystemPath(canon.clone()));
        }
    }

    None
}

/// Preflight scan: walk `root` exactly as `RetrievalClient::sync_project`
/// does — `hidden(false)` (tracked dotfiles included), `.gitignore` respected,
/// counting only files whose extension the indexer embeds
/// (`crate::embed::lang_for_ext`). Accumulates an eligible-file count and an
/// approximate source-byte total, then compares against `max_bytes` and
/// classifies the root.
///
/// Returns `PreflightVerdict::Clear` if neither trigger fires — caller proceeds
/// to index. Otherwise returns `RequiresConfirmation(PreflightInfo)`; caller
/// must elicit user confirmation.
///
/// The walker and extension allowlist are kept identical to `sync_project`'s
/// (via the shared `lang_for_ext`) so the guard's estimate matches what is
/// actually indexed. They previously diverged — the guard used `hidden(true)`,
/// applied an `ignored_paths` filter the indexer never honoured, and counted
/// every file regardless of extension; see
/// `docs/issues/2026-06-02-preflight-sync-walker-divergence.md`.
///
/// Per-file `metadata()` errors are silently skipped (matching `WalkBuilder::flatten`).
/// Only failure to read the root itself propagates as an error.
pub fn check_index_scope(root: &Path, max_bytes: u64) -> anyhow::Result<PreflightVerdict> {
    if !root.exists() {
        anyhow::bail!("project root does not exist: {}", root.display());
    }

    // Walk exactly as `RetrievalClient::sync_project` does: `hidden(false)` so
    // tracked dotfiles are visited, `.gitignore` respected, and only files
    // whose extension the indexer actually embeds (`crate::embed::lang_for_ext`)
    // are counted. This keeps the estimate faithful to what `sync_project`
    // will index — `.git/` internals and binary blobs are skipped because no
    // indexable extension matches them, without any bespoke ignore list.
    let walker = ignore::WalkBuilder::new(root)
        .hidden(false)
        .git_ignore(true)
        .build();

    let mut file_count: usize = 0;
    let mut approx_bytes: u64 = 0;

    for entry in walker.flatten() {
        let Some(ftype) = entry.file_type() else {
            continue;
        };
        if !ftype.is_file() {
            continue;
        }
        let ext = entry
            .path()
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("");
        if crate::embed::lang_for_ext(ext).is_none() {
            continue;
        }
        let Ok(meta) = entry.metadata() else { continue };
        file_count += 1;
        approx_bytes = approx_bytes.saturating_add(meta.len());
    }

    let suspicious_reason = classify_path(root);
    let size_exceeds_threshold = approx_bytes > max_bytes;

    if suspicious_reason.is_none() && !size_exceeds_threshold {
        return Ok(PreflightVerdict::Clear);
    }

    let canonical_root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());

    Ok(PreflightVerdict::RequiresConfirmation(PreflightInfo {
        root: canonical_root,
        file_count,
        approx_bytes,
        suspicious_reason,
        size_exceeds_threshold,
    }))
}

impl PreflightInfo {
    /// Build the human-readable confirmation message shown in the elicitation
    /// dialog. Lines that don't apply (no suspicious reason, etc.) are omitted.
    pub fn elicitation_message(&self) -> String {
        let mut lines: Vec<String> = Vec::new();

        let header = if self.size_exceeds_threshold && self.suspicious_reason.is_some() {
            "⚠ Index scope confirmation required (broad root + large size)"
        } else if self.size_exceeds_threshold {
            "⚠ Large index scope detected"
        } else {
            "⚠ Broad index scope detected"
        };
        lines.push(header.to_string());
        lines.push(String::new());

        let root_line = match &self.suspicious_reason {
            Some(SuspiciousReason::HomeDirectory) => {
                format!("Root: {}  (home directory)", self.root.display())
            }
            Some(SuspiciousReason::HomeParent) => {
                format!("Root: {}  (parent of home directory)", self.root.display())
            }
            Some(SuspiciousReason::SystemPath(p)) => {
                format!(
                    "Root: {}  (system directory: {})",
                    self.root.display(),
                    p.display()
                )
            }
            None => format!("Root: {}", self.root.display()),
        };
        lines.push(root_line);

        lines.push(format!(
            "Eligible files: ~{}",
            format_count(self.file_count)
        ));
        lines.push(format!(
            "Approx source content: ~{}",
            format_bytes(self.approx_bytes)
        ));

        // Rough estimate: indexer chunk_size ≈ 4000 chars. Integer math, no decimals.
        let est_chunks = usize::try_from(self.approx_bytes / 4000).unwrap_or(usize::MAX);
        lines.push(format!("Estimated chunks: ~{}", format_count(est_chunks)));

        lines.push(String::new());
        lines.push("This will use significant RAM and CPU time.".to_string());
        lines.push("Confirm indexing this directory?".to_string());

        lines.join("\n")
    }
}

/// Format an integer with thousand separators (e.g. `3,200`).
fn format_count(n: usize) -> String {
    let s = n.to_string();
    let bytes = s.as_bytes();
    let mut out = String::with_capacity(s.len() + s.len() / 3);
    for (i, &b) in bytes.iter().enumerate() {
        if i > 0 && (bytes.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(b as char);
    }
    out
}

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

    #[test]
    fn format_bytes_rounds_to_one_decimal() {
        assert_eq!(format_bytes(0), "0 B");
        assert_eq!(format_bytes(1023), "1023 B");
        assert_eq!(format_bytes(1024), "1.0 KB");
        assert_eq!(format_bytes(1536), "1.5 KB");
        assert_eq!(format_bytes(2 * 1024 * 1024), "2.0 MB");
        assert_eq!(
            format_bytes((2 * 1024 * 1024 * 1024) + (500 * 1024 * 1024)),
            "2.5 GB"
        );
    }

    use std::path::Path;

    #[test]
    fn classify_path_detects_home_directory() {
        let _guard = crate::config::global::lock_env_for_tests();
        let Some(home) = crate::platform::home_dir() else {
            return;
        };
        assert_eq!(classify_path(&home), Some(SuspiciousReason::HomeDirectory),);
    }

    #[test]
    fn classify_path_detects_home_parent() {
        let _guard = crate::config::global::lock_env_for_tests();
        let Some(home) = crate::platform::home_dir() else {
            return;
        };
        let Some(parent) = home.parent() else { return };
        // Skip when home's parent is '/' — that hits SystemPath, not HomeParent.
        if parent == Path::new("/") {
            return;
        }
        assert_eq!(classify_path(parent), Some(SuspiciousReason::HomeParent),);
    }

    #[test]
    fn classify_path_detects_root_system_path() {
        // '/' is a system path. It also tests canonicalization doesn't break it.
        let v = classify_path(Path::new("/"));
        assert!(matches!(v, Some(SuspiciousReason::SystemPath(_))));
    }

    #[test]
    fn classify_path_detects_usr_etc_var() {
        let _guard = crate::config::global::lock_env_for_tests();
        for p in ["/usr", "/etc", "/var", "/tmp", "/opt"] {
            if !Path::new(p).exists() {
                continue;
            }
            let v = classify_path(Path::new(p));
            assert!(
                matches!(v, Some(SuspiciousReason::SystemPath(_))),
                "{p} should classify as SystemPath, got {v:?}",
            );
        }
    }

    #[test]
    fn classify_path_allows_normal_project_dirs() {
        let tmp = tempfile::tempdir().unwrap();
        assert_eq!(classify_path(tmp.path()), None);
    }

    use std::io::Write;

    fn make_tempdir_with_bytes(total: u64) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        // Single file with the requested byte count.
        let mut f = std::fs::File::create(dir.path().join("big.rs")).unwrap();
        f.write_all(&vec![b'x'; total as usize]).unwrap();
        dir
    }

    #[test]
    fn check_index_scope_returns_clear_for_small_dir() {
        let dir = make_tempdir_with_bytes(1024); // 1 KB
        let v = check_index_scope(dir.path(), 500 * 1024 * 1024).unwrap();
        assert!(matches!(v, PreflightVerdict::Clear), "got {v:?}");
    }

    #[test]
    fn check_index_scope_flags_oversized_dir() {
        let dir = make_tempdir_with_bytes(2048);
        let v = check_index_scope(dir.path(), 1024).unwrap();
        match v {
            PreflightVerdict::RequiresConfirmation(info) => {
                assert!(info.size_exceeds_threshold);
                assert_eq!(info.suspicious_reason, None);
                assert_eq!(info.file_count, 1);
                assert!(info.approx_bytes >= 2048);
            }
            other => panic!("expected RequiresConfirmation, got {other:?}"),
        }
    }

    #[test]
    fn check_index_scope_respects_gitignore() {
        let dir = tempfile::tempdir().unwrap();
        // Initialise a real git repo so WalkBuilder (require_git=true default)
        // actually applies .gitignore rules — matching sync_project's walker.
        std::process::Command::new("git")
            .args(["init", "-q"])
            .current_dir(dir.path())
            .status()
            .unwrap();
        // Big *indexable* file (.rs) that is gitignored — so only the gitignore
        // rule (not the extension filter) can exclude it. If gitignore were not
        // honoured, its 2 KB would trip the 1 KB threshold.
        let mut gi = std::fs::File::create(dir.path().join(".gitignore")).unwrap();
        gi.write_all(b"ignored_big.rs\n").unwrap();
        let mut f = std::fs::File::create(dir.path().join("ignored_big.rs")).unwrap();
        f.write_all(&vec![b'x'; 2048]).unwrap();
        // Small real source file that should be counted.
        let mut s = std::fs::File::create(dir.path().join("small.rs")).unwrap();
        s.write_all(b"fn main() {}\n").unwrap();

        let v = check_index_scope(dir.path(), 1024).unwrap();
        // ignored_big.rs should be gitignored → under threshold → Clear.
        assert!(matches!(v, PreflightVerdict::Clear), "got {v:?}");
    }

    #[test]
    fn check_index_scope_counts_only_indexable_extensions() {
        // The guard estimates *indexed* size, so non-indexed extensions
        // (.bin, .png, .git internals) must not count — matching the
        // `lang_for_ext` allowlist that `sync_project` applies.
        let dir = tempfile::tempdir().unwrap();
        // Large non-indexable blob.
        let mut blob = std::fs::File::create(dir.path().join("data.bin")).unwrap();
        blob.write_all(&vec![b'x'; 8192]).unwrap();
        // Small indexable source file.
        let mut src = std::fs::File::create(dir.path().join("lib.rs")).unwrap();
        src.write_all(b"fn main() {}\n").unwrap();

        let v = check_index_scope(dir.path(), 1024).unwrap();
        // Only lib.rs (~13 B) is counted; data.bin (8 KB) is excluded → Clear.
        assert!(matches!(v, PreflightVerdict::Clear), "got {v:?}");
    }

    #[test]
    fn check_index_scope_counts_hidden_non_gitignored_files() {
        // `sync_project` walks with `hidden(false)`; the guard must match so it
        // does not under-count tracked dotfiles. A hidden, non-gitignored,
        // indexable file must be counted.
        let dir = tempfile::tempdir().unwrap();
        // Write via `fs::write` so the file handle is closed before the walk.
        // On Windows a still-open write handle makes the walker's per-entry
        // `metadata()` call fail, so the dotfile gets silently skipped and the
        // count comes back 0 (the original Windows-only failure). `fs::write`
        // opens-writes-closes atomically; Unix never saw this because it has no
        // mandatory file locking.
        std::fs::write(dir.path().join(".config.toml"), vec![b'x'; 2048]).unwrap();

        let v = check_index_scope(dir.path(), 1024).unwrap();
        match v {
            PreflightVerdict::RequiresConfirmation(info) => {
                assert!(info.size_exceeds_threshold);
                assert_eq!(info.file_count, 1, "hidden .config.toml must be counted");
            }
            other => panic!("expected RequiresConfirmation (hidden file counted), got {other:?}"),
        }
    }

    #[test]
    fn elicitation_message_includes_home_reason() {
        let info = PreflightInfo {
            root: PathBuf::from("/home/alice"),
            file_count: 3200,
            approx_bytes: 2 * 1024 * 1024 * 1024 + 400 * 1024 * 1024, // 2.4 GB
            suspicious_reason: Some(SuspiciousReason::HomeDirectory),
            size_exceeds_threshold: true,
        };
        let msg = info.elicitation_message();
        assert!(msg.contains("home directory"), "msg={msg}");
        assert!(msg.contains("/home/alice"), "msg={msg}");
        assert!(msg.contains("2.4 GB"), "msg={msg}");
        assert!(msg.contains("3,200") || msg.contains("3200"), "msg={msg}");
        assert!(msg.contains("Confirm"), "msg={msg}");
    }

    #[test]
    fn elicitation_message_size_only_omits_suspicious_line() {
        let info = PreflightInfo {
            root: PathBuf::from("/workspace/big"),
            file_count: 10_000,
            approx_bytes: 700 * 1024 * 1024,
            suspicious_reason: None,
            size_exceeds_threshold: true,
        };
        let msg = info.elicitation_message();
        assert!(!msg.to_lowercase().contains("home directory"), "msg={msg}");
        assert!(
            !msg.to_lowercase().contains("system directory"),
            "msg={msg}"
        );
        assert!(msg.contains("700.0 MB"), "msg={msg}");
    }

    #[test]
    fn elicitation_message_system_path_labelled() {
        let info = PreflightInfo {
            root: PathBuf::from("/usr"),
            file_count: 100_000,
            approx_bytes: 8 * 1024 * 1024 * 1024,
            suspicious_reason: Some(SuspiciousReason::SystemPath(PathBuf::from("/usr"))),
            size_exceeds_threshold: true,
        };
        let msg = info.elicitation_message();
        assert!(msg.to_lowercase().contains("system directory"), "msg={msg}");
        assert!(msg.contains("/usr"), "msg={msg}");
    }
}