Skip to main content

lean_ctx/tools/registered/
ctx_git_read.rs

1use std::path::{Path, PathBuf};
2use std::time::Duration;
3
4use rmcp::ErrorData;
5use rmcp::model::Tool;
6use serde_json::{Map, Value, json};
7
8use crate::core::git::{clone, repo_url, run_git};
9use crate::core::protocol::append_savings;
10use crate::core::tokens::count_tokens;
11use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_int, get_str};
12use crate::tool_defs::tool_def;
13
14const DEFAULT_MAX_TOKENS: usize = 6000;
15const MAX_TREE_LINES: usize = 400;
16const MAX_GREP_LINES: usize = 200;
17/// Tool identity recorded with the admission of remote repository content.
18const TOOL: &str = "ctx_git_read";
19
20/// `ctx_git_read` — read a remote repository via a cached shallow clone instead
21/// of scraping its web page. Modes: overview / tree / read / grep.
22pub struct CtxGitReadTool;
23
24impl McpTool for CtxGitReadTool {
25    fn name(&self) -> &'static str {
26        "ctx_git_read"
27    }
28
29    fn tool_def(&self) -> Tool {
30        tool_def(
31            "ctx_git_read",
32            "Read remote git repos via cached shallow clone (not HTML scraping).\n\
33             modes: overview (tree + README) | tree (file list) | read (file content) | grep (search).\n\
34             Accepts repo URLs and GitHub/GitLab blob/tree links (ref+path auto-detected).\n\
35             https-only, SSRF-guarded. Prefer over ctx_url_read for whole-repo access.",
36            json!({
37                "type": "object",
38                "properties": {
39                    "url": { "type": "string", "description": "https repo URL (blob/tree links auto-detect ref+path)" },
40                    "mode": {
41                        "type": "string",
42                        "enum": ["overview", "tree", "read", "grep"],
43                        "description": "overview|tree|read|grep"
44                    },
45                    "path": { "type": "string", "description": "Path within repo" },
46                    "ref": { "type": "string", "description": "Branch/tag/commit (overrides URL ref)" },
47                    "query": { "type": "string", "description": "Search term for grep mode" },
48                    "max_tokens": { "type": "integer", "description": "Token budget (default: 6000)" },
49                    "timeout_secs": { "type": "integer", "description": "Timeout seconds (default: 90, max: 300)" }
50                },
51                "allOf": [
52                    {
53                        "if": { "properties": { "mode": { "const": "grep" } }, "required": ["mode"] },
54                        "then": { "required": ["mode", "query"] }
55                    }
56                ],
57                "required": ["url"]
58            }),
59        )
60    }
61
62    fn handle(
63        &self,
64        args: &Map<String, Value>,
65        _ctx: &ToolContext,
66    ) -> Result<ToolOutput, ErrorData> {
67        let url = get_str(args, "url")
68            .ok_or_else(|| ErrorData::invalid_params("url is required", None))?;
69
70        let mut repo = repo_url::parse(&url).ok_or_else(|| {
71            ErrorData::invalid_params(
72                "not a recognized https repo URL (expected https://<host>/<owner>/<repo>[/blob|tree/<ref>/<path>])",
73                None,
74            )
75        })?;
76        if let Some(r) = get_str(args, "ref") {
77            repo.git_ref = Some(r);
78        }
79
80        let path = get_str(args, "path").or_else(|| repo.subpath.clone());
81        let mode = get_str(args, "mode").unwrap_or_else(|| {
82            if path.is_some() {
83                "read".to_string()
84            } else {
85                "overview".to_string()
86            }
87        });
88        let max_tokens = get_int(args, "max_tokens")
89            .map_or(DEFAULT_MAX_TOKENS, |n| n.clamp(200, 50_000) as usize);
90        let timeout = Duration::from_secs(
91            get_int(args, "timeout_secs").map_or(clone::DEFAULT_CLONE_TIMEOUT_SECS, |n| {
92                n.clamp(5, 300) as u64
93            }),
94        );
95        let query = get_str(args, "query");
96
97        let result = tokio::task::block_in_place(|| {
98            let dir = clone::ensure_repo(&repo, timeout)?;
99            match mode.as_str() {
100                "overview" => render_overview(&dir, &repo, max_tokens),
101                "tree" => render_tree(&dir, path.as_deref()),
102                "read" => {
103                    let p = path
104                        .as_deref()
105                        .ok_or_else(|| "read mode requires 'path'".to_string())?;
106                    render_read(&dir, &repo, p, max_tokens)
107                }
108                "grep" => {
109                    let q = query
110                        .as_deref()
111                        .ok_or_else(|| "grep mode requires 'query'".to_string())?;
112                    render_grep(&dir, q, path.as_deref())
113                }
114                other => Err(format!(
115                    "invalid mode '{other}' (use: overview, tree, read, grep)"
116                )),
117            }
118        });
119
120        match result {
121            Ok(rendered) => {
122                let sent = count_tokens(&rendered.body);
123                let saved = rendered.original_tokens.saturating_sub(sent);
124                let text = append_savings(&rendered.body, rendered.original_tokens, sent);
125                Ok(ToolOutput {
126                    text,
127                    original_tokens: rendered.original_tokens,
128                    saved_tokens: saved,
129                    mode: Some(mode),
130                    path: Some(rendered.label),
131                    changed: false,
132                    shell_outcome: None,
133                    content_blocks: None,
134                })
135            }
136            Err(e) => Err(ErrorData::invalid_params(
137                format!("ctx_git_read failed: {e}"),
138                None,
139            )),
140        }
141    }
142}
143
144struct Rendered {
145    body: String,
146    original_tokens: usize,
147    label: String,
148}
149
150fn render_overview(
151    dir: &Path,
152    repo: &repo_url::RepoRef,
153    max_tokens: usize,
154) -> Result<Rendered, String> {
155    let files = list_files(dir, None)?;
156    let total = files.len();
157    let top = top_level_summary(&files);
158
159    let mut body = format!(
160        "# {} ({} files)\n\nRef: {}\n\n## Top-level\n{}\n",
161        repo.project_path(),
162        total,
163        repo.git_ref.as_deref().unwrap_or("default (HEAD)"),
164        top
165    );
166    match find_and_read_readme(dir) {
167        Some((_, Ok(readme))) if !readme.is_empty() => {
168            body.push_str("\n## README\n");
169            body.push_str(&readme);
170        }
171        Some((name, Err(reason))) => {
172            // A README that is withheld is named as such; the overview never
173            // looks as if the repository had none.
174            body.push_str("\n## README\n");
175            body.push_str(&crate::tools::admitted_sources::withheld_line(
176                name, &reason,
177            ));
178        }
179        Some((_, Ok(_))) | None => {}
180    }
181    let original_tokens = count_tokens(&body);
182    Ok(Rendered {
183        body: budget(&body, max_tokens),
184        original_tokens,
185        label: format!("{} overview", repo.project_path()),
186    })
187}
188
189fn render_tree(dir: &Path, subpath: Option<&str>) -> Result<Rendered, String> {
190    let files = list_files(dir, subpath)?;
191    let original_tokens = count_tokens(&files.join("\n"));
192    let shown: Vec<&String> = files.iter().take(MAX_TREE_LINES).collect();
193    let mut body = shown
194        .iter()
195        .map(|s| s.as_str())
196        .collect::<Vec<_>>()
197        .join("\n");
198    if files.len() > shown.len() {
199        body.push_str(&format!(
200            "\n… {} more file(s) (narrow with `path`)",
201            files.len() - shown.len()
202        ));
203    }
204    Ok(Rendered {
205        body,
206        original_tokens,
207        label: format!("tree {}", subpath.unwrap_or(".")),
208    })
209}
210
211fn render_read(
212    dir: &Path,
213    repo: &repo_url::RepoRef,
214    rel: &str,
215    max_tokens: usize,
216) -> Result<Rendered, String> {
217    let file = safe_join(dir, rel)?;
218    if file.is_dir() {
219        // A directory was requested in read mode — show its listing instead.
220        return render_tree(dir, Some(rel));
221    }
222    // Admission precedes the header, the token count and the budget cut: the
223    // whole file is judged, then only admitted text is rendered.
224    let content = admit_clone_file(dir, rel)
225        .map_err(|reason| format!("{rel}: {reason}"))?
226        .text;
227    let header = format!(
228        "// {} @ {}\n",
229        rel,
230        repo.git_ref.as_deref().unwrap_or("HEAD")
231    );
232    let body = format!("{header}{content}");
233    let original_tokens = count_tokens(&body);
234    Ok(Rendered {
235        body: budget(&body, max_tokens),
236        original_tokens,
237        label: format!("{}:{}", repo.project_path(), rel),
238    })
239}
240
241fn render_grep(dir: &Path, query: &str, subpath: Option<&str>) -> Result<Rendered, String> {
242    let mut args: Vec<&str> = vec![
243        "grep",
244        "--no-color",
245        "-n",
246        "-I",
247        "-i",
248        "--heading",
249        "-e",
250        query,
251    ];
252    if let Some(p) = subpath {
253        args.push("--");
254        args.push(p);
255    }
256    let out = run_git(&args, dir, Duration::from_secs(30), &[])?;
257    // git grep exits 1 with no matches — treat that as an empty result, not error.
258    if !out.success && !out.stdout.is_empty() {
259        return Err(out.stderr.trim().to_string());
260    }
261    // The scope is admitted whether or not git found anything: what the
262    // result says about withheld sources must not depend on the query.
263    let scope = list_files(dir, subpath)?;
264    let original_tokens = count_tokens(&out.stdout);
265    Ok(Rendered {
266        body: admitted_grep(dir, query, &out.stdout, &scope),
267        original_tokens,
268        label: format!("grep '{query}'"),
269    })
270}
271
272/// Files of one grep scope that are admitted before selection.
273const MAX_GREP_SCOPE_FILES: usize = 2000;
274/// Original bytes one grep scope may read for admission.
275const MAX_GREP_SCOPE_BYTES: u64 = 64 * 1024 * 1024;
276
277/// Rebuild `git grep --heading -n` output from sources admitted BEFORE
278/// selection (G01), the way `ctx_search` treats a project.
279///
280/// Every file of the searched scope is admitted — independently of whether it
281/// matched. git's output is then used for exactly two things: which file a
282/// group belongs to and which line numbers matched. A line is rendered only
283/// for a file the admission delivered, with its text taken from the admitted
284/// file. A file that is withheld contributes nothing, not even its name, and
285/// the note that reports withheld sources is a count over the WHOLE scope:
286/// the result is the same whether a withheld file matched the query or not,
287/// so a query cannot be used to probe its content. For a scope no rule
288/// touches the result is byte-identical to git's own output.
289fn admitted_grep(dir: &Path, query: &str, stdout: &str, scope: &[String]) -> String {
290    let matched: std::collections::HashSet<&str> = stdout
291        .lines()
292        .filter(|line| matched_line_number(line).is_none())
293        .collect();
294
295    let mut admitted: std::collections::HashMap<&str, Vec<String>> =
296        std::collections::HashMap::new();
297    let mut withheld = 0usize;
298    let mut covered = 0usize;
299    let mut bytes_left = MAX_GREP_SCOPE_BYTES;
300    for file in scope.iter().take(MAX_GREP_SCOPE_FILES) {
301        let Ok(bytes) = read_clone_text_bytes(dir, file) else {
302            // Not a text source (binary, too large, unreadable): git's `-I`
303            // skips it as well; it is neither searched nor withheld.
304            covered += 1;
305            continue;
306        };
307        if bytes.len() as u64 > bytes_left {
308            break;
309        }
310        bytes_left -= bytes.len() as u64;
311        covered += 1;
312        match crate::tools::admitted_sources::admit_remote_file(bytes, file, TOOL) {
313            Ok(source) => {
314                if matched.contains(file.as_str()) {
315                    admitted.insert(
316                        file.as_str(),
317                        source.text.lines().map(str::to_string).collect(),
318                    );
319                }
320            }
321            Err(_) => withheld += 1,
322        }
323    }
324
325    let mut rendered: Vec<String> = Vec::new();
326    // `None`: no heading seen yet, or the current file was not admitted.
327    let mut current: Option<&Vec<String>> = None;
328    for line in stdout.lines() {
329        if rendered.len() >= MAX_GREP_LINES {
330            break;
331        }
332        if let Some(number) = matched_line_number(line) {
333            // A matched line the admitted text does not have is dropped:
334            // git's raw copy of it is never used.
335            if let Some(text) = current.and_then(|lines| lines.get(number - 1)) {
336                rendered.push(format!("{number}:{text}"));
337            }
338            continue;
339        }
340        current = admitted.get(line);
341        if current.is_some() {
342            rendered.push(line.to_string());
343        }
344    }
345
346    let mut body = if rendered.is_empty() {
347        format!("No matches for '{query}'.")
348    } else {
349        rendered.join("\n")
350    };
351    if withheld > 0 {
352        // Same wording as `ctx_search`.
353        body.push_str(&format!("\n({withheld} sources withheld under policy)"));
354    }
355    if covered < scope.len() {
356        body.push_str(&format!(
357            "\n(search covered the first {covered} of {} files — narrow with `path`)",
358            scope.len()
359        ));
360    }
361    body
362}
363
364/// The 1-based line number of a `<n>:<text>` match line; `None` for a heading.
365fn matched_line_number(line: &str) -> Option<usize> {
366    let (number, _) = line.split_once(':')?;
367    number.parse::<usize>().ok().filter(|number| *number > 0)
368}
369
370/// The bytes of one text file of the clone. `Err` (content-free) for a path
371/// outside the clone, an unreadable or oversized file and a binary body —
372/// none of which is inspectable as text.
373fn read_clone_text_bytes(dir: &Path, rel: &str) -> Result<Vec<u8>, String> {
374    let file = safe_join(dir, rel)?;
375    let cap = crate::core::limits::max_read_bytes() as u64;
376    let size = std::fs::metadata(&file)
377        .map_err(|e| format!("cannot read file: {e}"))?
378        .len();
379    if size > cap {
380        return Err(format!(
381            "file too large ({size} bytes, limit {cap} bytes via LCTX_MAX_READ_BYTES)"
382        ));
383    }
384    let bytes = std::fs::read(&file).map_err(|e| format!("cannot read file: {e}"))?;
385    if crate::core::binary_detect::has_binary_extension(rel)
386        || crate::core::text_decode::looks_binary(&bytes[..bytes.len().min(8192)])
387    {
388        return Err("source format is not inspectable as text".to_owned());
389    }
390    Ok(bytes)
391}
392
393/// Read one file of the clone and admit it as a source that is not a project
394/// file, under its repository-relative path. `Err` is a content-free reason.
395fn admit_clone_file(
396    dir: &Path,
397    rel: &str,
398) -> Result<crate::core::context_admission::SourceAdmission, String> {
399    let bytes = read_clone_text_bytes(dir, rel)?;
400    crate::tools::admitted_sources::admit_remote_file(bytes, rel, TOOL)
401}
402
403// ── helpers ─────────────────────────────────────────────────────────────────
404
405/// Tracked files (gitignore-aware), optionally scoped to a subpath.
406fn list_files(dir: &Path, subpath: Option<&str>) -> Result<Vec<String>, String> {
407    let mut args = vec!["ls-files"];
408    if let Some(p) = subpath {
409        args.push("--");
410        args.push(p);
411    }
412    let out = run_git(&args, dir, Duration::from_secs(20), &[])?.ok_stdout()?;
413    Ok(out
414        .lines()
415        .filter(|l| !l.trim().is_empty())
416        .map(str::to_string)
417        .collect())
418}
419
420fn top_level_summary(files: &[String]) -> String {
421    use std::collections::BTreeMap;
422    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
423    for f in files {
424        let top = f.split('/').next().unwrap_or(f);
425        let key = if top == f.as_str() {
426            top.to_string() // a top-level file
427        } else {
428            format!("{top}/")
429        };
430        *counts.entry(key).or_insert(0) += 1;
431    }
432    counts
433        .into_iter()
434        .take(40)
435        .map(|(k, n)| {
436            if k.ends_with('/') {
437                format!("- {k} ({n})")
438            } else {
439                format!("- {k}")
440            }
441        })
442        .collect::<Vec<_>>()
443        .join("\n")
444}
445
446/// The repository's README, admitted: its name and either the delivered text
447/// or the content-free reason it is withheld for. `None`: there is none.
448fn find_and_read_readme(dir: &Path) -> Option<(&'static str, Result<String, String>)> {
449    for name in [
450        "README.md",
451        "README.MD",
452        "Readme.md",
453        "README",
454        "README.txt",
455    ] {
456        if dir.join(name).is_file() {
457            return Some((
458                name,
459                admit_clone_file(dir, name).map(|admitted| admitted.text),
460            ));
461        }
462    }
463    None
464}
465
466/// Join `rel` under `base`, rejecting any path that escapes `base`.
467fn safe_join(base: &Path, rel: &str) -> Result<PathBuf, String> {
468    let rel = rel.trim_start_matches('/');
469    if rel.split('/').any(|seg| seg == "..") {
470        return Err("path may not contain '..'".to_string());
471    }
472    let joined = base.join(rel);
473    let canon_base = std::fs::canonicalize(base).map_err(|e| e.to_string())?;
474    match std::fs::canonicalize(&joined) {
475        Ok(canon) if canon.starts_with(&canon_base) => Ok(canon),
476        Ok(_) => Err("path escapes the repository".to_string()),
477        Err(e) => Err(format!("path not found: {rel} ({e})")),
478    }
479}
480
481fn budget(content: &str, max_tokens: usize) -> String {
482    let tokens = count_tokens(content);
483    if tokens <= max_tokens {
484        return content.to_string();
485    }
486    let ratio = max_tokens as f64 / tokens as f64;
487    let keep = ((content.chars().count() as f64 * ratio) as usize).max(1);
488    let truncated: String = content.chars().take(keep).collect();
489    crate::core::recovery::with_original_pointer(
490        "ctx_git_read",
491        "budget",
492        content,
493        format!("{truncated}\n\n…[truncated to ~{max_tokens} tokens]"),
494    )
495}
496
497#[cfg(test)]
498mod tests {
499    use super::*;
500
501    #[test]
502    fn safe_join_blocks_parent_escape() {
503        let tmp = std::env::temp_dir();
504        assert!(safe_join(&tmp, "../etc/passwd").is_err());
505        assert!(safe_join(&tmp, "a/../../b").is_err());
506    }
507
508    #[test]
509    fn top_level_summary_groups_dirs_and_files() {
510        let files = vec![
511            "README.md".to_string(),
512            "src/a.rs".to_string(),
513            "src/b.rs".to_string(),
514            "tests/t.rs".to_string(),
515        ];
516        let s = top_level_summary(&files);
517        assert!(s.contains("- src/ (2)"));
518        assert!(s.contains("- tests/ (1)"));
519        assert!(s.contains("- README.md"));
520    }
521
522    const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
523
524    fn clone_file(dir: &Path, rel: &str, content: &str) {
525        let path = dir.join(rel);
526        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
527        std::fs::write(path, content).unwrap();
528    }
529
530    fn repo() -> repo_url::RepoRef {
531        repo_url::parse("https://github.com/acme/widgets").expect("repo url")
532    }
533
534    fn blocking_policy() -> crate::core::policy::ResolvedPolicy {
535        crate::core::policy::load(
536            "name = \"ctx-git-read-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
537             [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
538        )
539        .unwrap()
540    }
541
542    /// G01: a file of a remote repository is a source. The old `read` mode
543    /// returned `fs::read_to_string` of the clone verbatim — a key in the
544    /// remote file reached the model, and a file the project policy blocks
545    /// was delivered. A clean file keeps its bytes.
546    #[test]
547    fn a_remote_file_is_admitted_before_it_is_rendered() {
548        let _data = crate::core::data_dir::isolated_data_dir();
549        let clone = tempfile::tempdir().unwrap();
550        let clean = "pub fn widget() -> u8 {\n    7\n}\n";
551        clone_file(clone.path(), "src/lib.rs", clean);
552        clone_file(
553            clone.path(),
554            "deploy/settings.py",
555            &format!("AWS_ACCESS_KEY_ID = \"{AWS_KEY}\"\nREGION = \"eu-central-2\"\n"),
556        );
557        clone_file(
558            clone.path(),
559            "docs/plan.md",
560            "CONFIDENTIAL\nroadmap-marker for the launch\n",
561        );
562        {
563            let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
564            let rendered = render_read(clone.path(), &repo(), "src/lib.rs", 6000).unwrap();
565            assert_eq!(rendered.body, format!("// src/lib.rs @ HEAD\n{clean}"));
566
567            let rendered = render_read(clone.path(), &repo(), "deploy/settings.py", 6000).unwrap();
568            assert!(!rendered.body.contains(AWS_KEY), "{}", rendered.body);
569            assert!(rendered.body.contains("eu-central-2"), "{}", rendered.body);
570        }
571        let _policy =
572            crate::core::policy::runtime::TestPolicyOverride::set(Some(blocking_policy()));
573        let Err(reason) = render_read(clone.path(), &repo(), "docs/plan.md", 6000) else {
574            panic!("a blocked remote file must not be rendered");
575        };
576        assert!(reason.contains("withheld"), "{reason}");
577        assert!(!reason.contains("roadmap-marker"), "{reason}");
578    }
579
580    /// The README of the overview and every line of a grep result come from
581    /// admitted sources; a withheld file is named, never rendered and never
582    /// silently missing. git's own raw match text is not used.
583    #[test]
584    fn overview_readme_and_grep_lines_come_from_admitted_sources() {
585        let _data = crate::core::data_dir::isolated_data_dir();
586        let clone = tempfile::tempdir().unwrap();
587        clone_file(
588            clone.path(),
589            "notes.txt",
590            "alpha widget\nbeta\ngamma widget\n",
591        );
592        clone_file(
593            clone.path(),
594            "deploy/settings.py",
595            &format!("# widget deploy\nAWS_ACCESS_KEY_ID = \"{AWS_KEY}\" # widget\n"),
596        );
597        clone_file(
598            clone.path(),
599            "docs/plan.md",
600            "CONFIDENTIAL\nwidget roadmap-marker\n",
601        );
602        clone_file(clone.path(), "README.md", "CONFIDENTIAL\nreadme-marker\n");
603        // What `git grep --heading -n -i -e widget` prints for this clone.
604        let git_output = format!(
605            "deploy/settings.py\n1:# widget deploy\n2:AWS_ACCESS_KEY_ID = \"{AWS_KEY}\" # widget\n\
606             docs/plan.md\n2:widget roadmap-marker\n\
607             notes.txt\n1:alpha widget\n3:gamma widget\n"
608        );
609        // What `git ls-files` lists for this clone (the grep scope).
610        let scope: Vec<String> = [
611            "README.md",
612            "deploy/settings.py",
613            "docs/plan.md",
614            "notes.txt",
615        ]
616        .map(String::from)
617        .to_vec();
618        {
619            // Control: for a scope no rule touches the result is git's output.
620            let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
621            let clean_output = "notes.txt\n1:alpha widget\n3:gamma widget\n";
622            assert_eq!(
623                admitted_grep(clone.path(), "widget", clean_output, &scope),
624                clean_output.trim_end()
625            );
626            let body = admitted_grep(clone.path(), "widget", &git_output, &scope);
627            assert!(!body.contains(AWS_KEY), "{body}");
628            assert!(body.contains("1:# widget deploy"), "{body}");
629        }
630        let _policy =
631            crate::core::policy::runtime::TestPolicyOverride::set(Some(blocking_policy()));
632        let body = admitted_grep(clone.path(), "widget", &git_output, &scope);
633        assert!(!body.contains("roadmap-marker"), "{body}");
634        assert!(
635            !body.contains("docs/plan.md"),
636            "a withheld file is not named: {body}"
637        );
638        assert!(
639            body.contains("notes.txt\n1:alpha widget\n3:gamma widget"),
640            "{body}"
641        );
642        // README.md and docs/plan.md are blocked by the pack. deploy/settings.py
643        // is NOT withheld: a key inside otherwise admissible content is masked
644        // and the rest delivered, with a pack exactly as without one. The
645        // pack's built-in pass and the gateway spell the mask the same way, so
646        // their two orders agree (`compose_active_gateway_output`).
647        let keyed = admit_clone_file(clone.path(), "deploy/settings.py")
648            .expect("a source with a masked key is delivered under a pack");
649        assert_eq!(
650            keyed.text,
651            "# widget deploy\nAWS_ACCESS_KEY_ID = \"[REDACTED:AWS key]\" # widget\n"
652        );
653        assert!(
654            body.contains(
655                "deploy/settings.py\n1:# widget deploy\n\
656                 2:AWS_ACCESS_KEY_ID = \"[REDACTED:AWS key]\" # widget"
657            ),
658            "{body}"
659        );
660        assert!(!body.contains(AWS_KEY), "{body}");
661        // Counted over the scope.
662        assert!(
663            body.ends_with("\n(2 sources withheld under policy)"),
664            "{body}"
665        );
666
667        // No oracle: a query that matches ONLY a withheld file and a query
668        // that matches nothing produce the same result.
669        let only_withheld = admitted_grep(
670            clone.path(),
671            "q",
672            "docs/plan.md\n2:widget roadmap-marker\n",
673            &scope,
674        );
675        let nothing = admitted_grep(clone.path(), "q", "", &scope);
676        assert_eq!(only_withheld, nothing);
677        assert_eq!(
678            nothing,
679            "No matches for 'q'.\n(2 sources withheld under policy)"
680        );
681
682        let (name, readme) = find_and_read_readme(clone.path()).expect("README present");
683        assert_eq!(name, "README.md");
684        let reason = readme.expect_err("a blocked README is withheld");
685        assert!(!reason.contains("readme-marker"), "{reason}");
686    }
687
688    #[test]
689    fn budget_truncates_oversized_content() {
690        let big = "word ".repeat(4000);
691        let out = budget(&big, 50);
692        assert!(out.contains("[truncated"));
693        assert!(count_tokens(&out) < count_tokens(&big));
694    }
695}