Skip to main content

nitpicker_agent/
tools.rs

1use eyre::Result;
2use glob::glob;
3use regex::Regex;
4use rig_core::completion::ToolDefinition;
5use serde_json::{Value, json};
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::pin::Pin;
9use std::sync::Arc;
10use tokio::fs;
11use tracing::debug;
12
13/// Find a valid UTF-8 character boundary at or before the given position.
14/// This is a polyfill for `str::floor_char_boundary` which requires Rust 1.91.
15pub fn floor_char_boundary(s: &str, pos: usize) -> usize {
16    let pos = pos.min(s.len());
17    // UTF-8 continuation bytes start with 10xxxxxx (0x80-0xBF)
18    // We need to find a byte that is NOT a continuation byte
19    let bytes = s.as_bytes();
20    for i in (0..=pos).rev() {
21        // `i == s.len()` is the end-of-string boundary (matches std's `str::floor_char_boundary`)
22        // and must be checked before indexing, since `bytes[s.len()]` is out of bounds.
23        if i == s.len() || i == 0 || (bytes[i] & 0xC0) != 0x80 {
24            return i;
25        }
26    }
27    0
28}
29
30/// Allowlisted read-only git subcommands. Ref listing is served by the `for-each-ref`/`show-ref`
31/// plumbing (no ref-creating/deleting mode → safe by construction for any args), deliberately not
32/// the `branch`/`tag` porcelain whose read and write modes are indistinguishable by arguments.
33const ALLOWED_GIT_SUBCOMMANDS: &[&str] = &[
34    "diff",
35    "log",
36    "show",
37    "blame",
38    "status",
39    "rev-parse",
40    "shortlog",
41    "ls-files",
42    "for-each-ref",
43    "show-ref",
44];
45
46/// True if `token` is a long option `--<stem>` (optionally `--<stem>=value`) whose stem is a
47/// non-empty prefix of `name`. git accepts unambiguous long-option abbreviations, so `--out`
48/// matches `output` and `--no-i` matches `no-index`.
49fn long_flag_matches(token: &str, name: &str) -> bool {
50    long_flag_stem(token).is_some_and(|stem| name.starts_with(stem))
51}
52
53fn long_flag_stem(token: &str) -> Option<&str> {
54    token
55        .strip_prefix("--")
56        .map(|long| long.split('=').next().unwrap_or(long))
57        .filter(|stem| !stem.is_empty())
58}
59
60fn blocked_fs_reading_flag_matches(token: &str, name: &str) -> bool {
61    if name == "ignore-revs-file" && long_flag_stem(token) == Some("ignore-rev") {
62        return false;
63    }
64    long_flag_matches(token, name)
65}
66
67/// Reject git invocations that aren't genuinely read-only or that escape the repository. The
68/// subcommand allowlist alone is not enough — `read_file`/`grep`/`glob` confine reads to `work_dir`
69/// via canonicalize, but several git flags read straight from the filesystem and would bypass that
70/// sandbox. Three layers: (1) no argument may reference a path outside the repo (absolute or `..`,
71/// including Windows-style paths), (2) filesystem-reading flags are denied outright, and (3) the
72/// write-to-file `--output`/`-o` on `diff`/`log`/`show`. Returns `Err(message)` when rejected.
73fn ensure_readonly_git(subcommand: &str, rest: &[&str]) -> std::result::Result<(), String> {
74    // Layer 1 (all subcommands): an argument value may not reference a path outside the repo. The
75    // value is the token itself, or the part after `=` for a `--flag=value`; a bare `--flag` whose
76    // path is the *next* token is caught when that token is examined on its own. Refs (`HEAD~1`,
77    // `origin/main..HEAD`), ranges, and `--format=%H` have no leading `/` and no `..` component.
78    for token in rest {
79        let value = match token.starts_with('-') {
80            true => token.split_once('=').map(|(_, v)| v).unwrap_or(""),
81            false => token,
82        };
83        if looks_like_external_path(value) {
84            return Err(format!(
85                "Error: git argument '{token}' references a path outside the repository"
86            ));
87        }
88    }
89    // Layer 2: flags that read a file by path, bypassing the object database entirely. They have no
90    // role in reviewing repo history, so deny them by name (incl. unambiguous abbreviations and the
91    // `=`-glued form) — this also closes a relative-but-symlinked path that would slip past layer 1.
92    let fs_reading_flags: &[&str] = match subcommand {
93        "diff" => &["no-index"],
94        "blame" => &["contents", "ignore-revs-file"],
95        _ => &[],
96    };
97    for flag in fs_reading_flags {
98        if rest
99            .iter()
100            .any(|token| blocked_fs_reading_flag_matches(token, flag))
101        {
102            return Err(format!(
103                "Error: git --{flag} reads files outside the repository and is not allowed"
104            ));
105        }
106    }
107    // Layer 3: `--output`/`-o` is a write-to-file flag only on `diff`/`log`/`show` (which share
108    // diff's output machinery). On other subcommands `-o` means something else and is read-only —
109    // notably `ls-files -o` (= `--others`) — so gate only these three to avoid blocking legit reads.
110    if matches!(subcommand, "diff" | "log" | "show") {
111        for token in rest {
112            if long_flag_matches(token, "output")
113                || *token == "-o"
114                || (token.starts_with("-o") && !token.starts_with("--") && token.len() > 2)
115            {
116                return Err(
117                    "Error: writing git output to a file (--output/-o) is not allowed".into(),
118                );
119            }
120        }
121    }
122    Ok(())
123}
124
125fn looks_like_external_path(value: &str) -> bool {
126    if value.is_empty() {
127        return false;
128    }
129    Path::new(value).is_absolute()
130        || value.starts_with('\\')
131        || has_windows_drive_prefix(value)
132        || value.split(['/', '\\']).any(|component| component == "..")
133}
134
135fn has_windows_drive_prefix(value: &str) -> bool {
136    let bytes = value.as_bytes();
137    bytes.len() >= 3
138        && bytes[0].is_ascii_alphabetic()
139        && bytes[1] == b':'
140        && matches!(bytes.get(2).copied(), Some(b'/' | b'\\'))
141}
142
143pub trait Tool: Send + Sync {
144    fn name(&self) -> String;
145    fn definition(&self) -> ToolDefinition;
146    fn call(
147        &self,
148        args: Value,
149        work_dir: PathBuf,
150    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>>;
151}
152
153pub fn all_tools() -> HashMap<String, Arc<dyn Tool>> {
154    let tools: Vec<Arc<dyn Tool>> = vec![
155        Arc::new(ReadFileTool),
156        Arc::new(GlobTool),
157        Arc::new(GrepTool),
158        Arc::new(GitTool),
159    ];
160    tools.into_iter().map(|tool| (tool.name(), tool)).collect()
161}
162
163pub fn reflect_tools() -> HashMap<String, Arc<dyn Tool>> {
164    // Reflection has no repo checkout to run git against, so it gets every tool except git.
165    let mut tools = all_tools();
166    tools.remove("git");
167    tools
168}
169
170pub fn tool_definitions(tools: &HashMap<String, Arc<dyn Tool>>) -> Vec<ToolDefinition> {
171    tools.values().map(|tool| tool.definition()).collect()
172}
173
174pub struct ReadFileTool;
175
176impl Tool for ReadFileTool {
177    fn name(&self) -> String {
178        "read_file".to_string()
179    }
180
181    fn definition(&self) -> ToolDefinition {
182        ToolDefinition {
183            name: "read_file".to_string(),
184            description:
185                "Read a text file inside the workspace and return numbered lines. Use this after glob or grep to inspect specific files; prefer start_line/end_line for focused reads."
186                    .to_string(),
187            parameters: json!({
188                "type": "object",
189                "properties": {
190                    "path": {
191                        "type": "string",
192                        "description": "Workspace-relative file path to read."
193                    },
194                    "start_line": {
195                        "type": "integer",
196                        "minimum": 1,
197                        "description": "First line to include. Omit to start at line 1."
198                    },
199                    "end_line": {
200                        "type": "integer",
201                        "minimum": 1,
202                        "description": "Last line to include. Omit to read to the end of the file."
203                    }
204                },
205                "required": ["path"],
206                "additionalProperties": false
207            }),
208        }
209    }
210
211    fn call(
212        &self,
213        args: Value,
214        work_dir: PathBuf,
215    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
216        Box::pin(async move {
217            let path = args
218                .get("path")
219                .and_then(|value| value.as_str())
220                .ok_or_else(|| eyre::eyre!("missing path"))?;
221            let start_line = args
222                .get("start_line")
223                .and_then(|value| value.as_u64())
224                .unwrap_or(1) as usize;
225            let end_line = args
226                .get("end_line")
227                .and_then(|value| value.as_u64())
228                .map(|value| value as usize);
229            let full_path = work_dir.join(path);
230            let full_path = full_path.canonicalize().map_err(|e| {
231                eyre::eyre!(
232                    "cannot resolve path {path:?}: {e}. Only files within {} are accessible.",
233                    work_dir.display()
234                )
235            })?;
236            if !full_path.starts_with(&work_dir) {
237                eyre::bail!(
238                    "access denied: {path:?} is outside the allowed workspace ({}). Only project files are accessible.",
239                    work_dir.display()
240                );
241            }
242            let content = match fs::read_to_string(&full_path).await {
243                Ok(content) => content,
244                Err(err) if err.kind() == std::io::ErrorKind::InvalidData => {
245                    eyre::bail!("file is not valid UTF-8; read_file only supports text files")
246                }
247                Err(err) => return Err(err.into()),
248            };
249            let lines = content.lines().collect::<Vec<_>>();
250            let total = lines.len();
251            let start = start_line.max(1).min(total.max(1));
252            let end = end_line.unwrap_or(total).max(start).min(total);
253            let relative = full_path
254                .strip_prefix(&work_dir)
255                .unwrap_or(&full_path)
256                .display()
257                .to_string();
258            let mut output = format!("File: {relative}\nLines: {start}-{end} of {total}\n\n");
259            for (idx, line) in lines.iter().enumerate() {
260                let line_num = idx + 1;
261                if line_num < start || line_num > end {
262                    continue;
263                }
264                output.push_str(&format!("{line_num:>4} {line}\n"));
265            }
266            Ok(output)
267        })
268    }
269}
270
271pub struct GlobTool;
272
273impl Tool for GlobTool {
274    fn name(&self) -> String {
275        "glob".to_string()
276    }
277
278    fn definition(&self) -> ToolDefinition {
279        ToolDefinition {
280            name: "glob".to_string(),
281            description:
282                "Find workspace-relative file paths by glob pattern. Use this when you know the file name or extension pattern but not the exact path; returns at most 200 matches."
283                    .to_string(),
284            parameters: json!({
285                "type": "object",
286                "properties": {
287                    "pattern": {
288                        "type": "string",
289                        "description": "Workspace-relative glob such as 'src/**/*.rs' or '**/*.toml'."
290                    }
291                },
292                "required": ["pattern"],
293                "additionalProperties": false
294            }),
295        }
296    }
297
298    fn call(
299        &self,
300        args: Value,
301        work_dir: PathBuf,
302    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
303        Box::pin(async move {
304            let pattern = args
305                .get("pattern")
306                .and_then(|value| value.as_str())
307                .ok_or_else(|| eyre::eyre!("missing pattern"))?;
308            let pattern_path = Path::new(pattern);
309            if pattern_path.is_absolute()
310                || pattern_path
311                    .components()
312                    .any(|c| c == std::path::Component::ParentDir)
313            {
314                eyre::bail!(
315                    "access denied: glob pattern {pattern:?} must be relative to the workspace ({}). Absolute paths and parent-directory traversal are not allowed.",
316                    work_dir.display()
317                );
318            }
319            let mut results = Vec::new();
320            let full_pattern = work_dir.join(pattern);
321            let full_pattern = full_pattern.to_string_lossy();
322            for entry in glob(&full_pattern)? {
323                if let Ok(path) = entry {
324                    if let Ok(relative) = path.strip_prefix(&work_dir) {
325                        results.push(relative.display().to_string());
326                    }
327                }
328                if results.len() >= 200 {
329                    break;
330                }
331            }
332            if results.is_empty() {
333                return Ok(format!("No files matched pattern: {pattern}"));
334            }
335            Ok(results.join("\n"))
336        })
337    }
338}
339
340pub struct GrepTool;
341
342impl Tool for GrepTool {
343    fn name(&self) -> String {
344        "grep".to_string()
345    }
346
347    fn definition(&self) -> ToolDefinition {
348        ToolDefinition {
349            name: "grep".to_string(),
350            description: "Search text files for a regex and return path:line:content matches. Use this to locate relevant code before calling read_file; optionally limit by path or file_glob, and expect at most 100 matches."
351                .to_string(),
352            parameters: json!({
353                "type": "object",
354                "properties": {
355                    "pattern": {
356                        "type": "string",
357                        "description": "Regular expression to search for in file contents."
358                    },
359                    "path": {
360                        "type": "string",
361                        "description": "Optional workspace-relative file or directory to search within."
362                    },
363                    "file_glob": {
364                        "type": "string",
365                        "description": "Optional filename filter such as '*.rs'; matched against file names, not full paths."
366                    }
367                },
368                "required": ["pattern"],
369                "additionalProperties": false
370            }),
371        }
372    }
373
374    fn call(
375        &self,
376        args: Value,
377        work_dir: PathBuf,
378    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
379        Box::pin(async move {
380            let pattern = args
381                .get("pattern")
382                .and_then(|value| value.as_str())
383                .ok_or_else(|| eyre::eyre!("missing pattern"))?;
384            let base_path = args
385                .get("path")
386                .and_then(|value| value.as_str())
387                .map(|value| {
388                    let p = work_dir.join(value);
389                    // canonicalize to resolve symlinks and `..` before the workspace check
390                    p.canonicalize()
391                        .map_err(|e| eyre::eyre!("cannot resolve path {value:?}: {e}. Only files within {} are accessible.", work_dir.display()))
392                })
393                .transpose()?
394                .unwrap_or_else(|| work_dir.clone());
395            if !base_path.starts_with(&work_dir) {
396                let path_arg = args.get("path").and_then(|v| v.as_str()).unwrap_or("?");
397                eyre::bail!(
398                    "access denied: {path_arg:?} is outside the allowed workspace ({}). Only project files are accessible.",
399                    work_dir.display()
400                );
401            }
402            let file_glob = args
403                .get("file_glob")
404                .and_then(|value| value.as_str())
405                .map(glob_to_regex)
406                .transpose()?;
407            let regex =
408                Regex::new(pattern).map_err(|e| eyre::eyre!("invalid regex {pattern:?}: {e}"))?;
409            let mut results = Vec::new();
410            let mut skipped_files = 0usize;
411            if base_path.is_file() {
412                if let Err(e) = search_file(&base_path, &regex, &work_dir, &mut results).await {
413                    debug!("skipping file {}: {e}", base_path.display());
414                    skipped_files += 1;
415                }
416            } else {
417                let mut stack = vec![base_path];
418                while let Some(path) = stack.pop() {
419                    let entries = match fs::read_dir(&path).await {
420                        Ok(entries) => entries,
421                        Err(e) => {
422                            debug!("skipping unreadable dir {}: {e}", path.display());
423                            continue;
424                        }
425                    };
426                    let mut entries = entries;
427                    while let Ok(Some(entry)) = entries.next_entry().await {
428                        let entry_path = entry.path();
429                        let file_type = match entry.file_type().await {
430                            Ok(file_type) => file_type,
431                            Err(e) => {
432                                debug!("skipping {}: {e}", entry_path.display());
433                                continue;
434                            }
435                        };
436                        let name = entry.file_name();
437                        let name = name.to_string_lossy();
438                        if file_type.is_dir() {
439                            if name.starts_with('.') || name == "target" || name == "node_modules" {
440                                continue;
441                            }
442                            stack.push(entry_path);
443                        } else if file_type.is_file() {
444                            if let Some(filter) = &file_glob {
445                                if !filter.is_match(&name) {
446                                    continue;
447                                }
448                            }
449                            match search_file(&entry_path, &regex, &work_dir, &mut results).await {
450                                Ok(_) => {}
451                                Err(e) => {
452                                    debug!("skipping file {}: {e}", entry_path.display());
453                                    skipped_files += 1;
454                                }
455                            }
456                            if results.len() >= 100 {
457                                break;
458                            }
459                        }
460                        if results.len() >= 100 {
461                            break;
462                        }
463                    }
464                    if results.len() >= 100 {
465                        break;
466                    }
467                }
468            }
469            if results.is_empty() {
470                let mut output = format!("No matches for regex: {pattern}");
471                if skipped_files > 0 {
472                    output.push_str(&format!("\nSkipped unreadable files: {skipped_files}"));
473                }
474                return Ok(output);
475            }
476            let mut output = format!("Matches: {}\n", results.len());
477            if skipped_files > 0 {
478                output.push_str(&format!("Skipped unreadable files: {skipped_files}\n"));
479            }
480            output.push('\n');
481            output.push_str(&results.join("\n"));
482            Ok(output)
483        })
484    }
485}
486
487async fn search_file(
488    path: &PathBuf,
489    regex: &Regex,
490    work_dir: &Path,
491    results: &mut Vec<String>,
492) -> Result<()> {
493    use tokio::io::AsyncReadExt;
494
495    // Open file and check first 8KB for binary content before reading full file
496    let mut file = fs::File::open(path).await?;
497    let mut buffer = [0u8; 8192];
498    let bytes_read = file.read(&mut buffer).await?;
499
500    // Check for null bytes in the sample (binary file indicator)
501    if buffer[..bytes_read].contains(&0) {
502        return Ok(()); // Skip binary files silently
503    }
504
505    // Read the rest of the file
506    let mut remaining = Vec::new();
507    file.read_to_end(&mut remaining).await?;
508
509    // Combine sample + remaining into full content
510    let mut full_content = Vec::with_capacity(bytes_read + remaining.len());
511    full_content.extend_from_slice(&buffer[..bytes_read]);
512    full_content.extend_from_slice(&remaining);
513
514    // Convert to string and search
515    let content = String::from_utf8_lossy(&full_content);
516    let relative = path.strip_prefix(work_dir).unwrap_or(path);
517    for (idx, line) in content.lines().enumerate() {
518        if regex.is_match(line) {
519            results.push(format!("{}:{}:{}", relative.display(), idx + 1, line));
520            if results.len() >= 100 {
521                break;
522            }
523        }
524    }
525    Ok(())
526}
527
528fn glob_to_regex(pattern: &str) -> Result<Regex> {
529    let mut escaped = String::new();
530    for ch in pattern.chars() {
531        match ch {
532            '.' => escaped.push_str("\\."),
533            '*' => escaped.push_str(".*"),
534            '?' => escaped.push('.'),
535            other => escaped.push(other),
536        }
537    }
538    Regex::new(&format!("^{}$", escaped))
539        .map_err(|e| eyre::eyre!("invalid file_glob {pattern:?}: {e}"))
540}
541
542/// Check if a file is binary by reading the first 8 KiB and checking for null bytes.
543/// Returns `true` if binary, `false` if text, or an error if the file cannot be read.
544pub async fn is_binary_file(path: &Path) -> std::io::Result<bool> {
545    use tokio::io::AsyncReadExt;
546    let mut file = fs::File::open(path).await?;
547    let mut buffer = [0u8; 8192];
548    let bytes_read = file.read(&mut buffer).await?;
549    Ok(buffer[..bytes_read].contains(&0)) // null byte = binary
550}
551
552pub struct GitTool;
553
554impl Tool for GitTool {
555    fn name(&self) -> String {
556        "git".to_string()
557    }
558
559    fn definition(&self) -> ToolDefinition {
560        ToolDefinition {
561            name: "git".to_string(),
562            description: "Run an allowlisted read-only git command for review context: diff, log, show, blame, status, rev-parse, shortlog, ls-files, for-each-ref, show-ref. To list or query branches/tags use for-each-ref (e.g. `for-each-ref --contains <sha> refs/heads/`), not branch/tag. Use this for repository history or patch context, not for general file search."
563                .to_string(),
564            parameters: json!({
565                "type": "object",
566                "properties": {
567                    "command": {
568                        "type": "string",
569                        "description": "Read-only git command to run, for example 'diff --stat HEAD~1' or 'log --oneline -n 20'."
570                    }
571                },
572                "required": ["command"],
573                "additionalProperties": false
574            }),
575        }
576    }
577
578    fn call(
579        &self,
580        args: Value,
581        work_dir: PathBuf,
582    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
583        Box::pin(async move {
584            let command = args
585                .get("command")
586                .and_then(|value| value.as_str())
587                .ok_or_else(|| eyre::eyre!("missing command"))?;
588            let tokens = command.split_whitespace().collect::<Vec<_>>();
589            let Some((subcommand, rest)) = tokens.split_first() else {
590                return Ok("Error: empty git command".to_string());
591            };
592            if !ALLOWED_GIT_SUBCOMMANDS.contains(subcommand) {
593                return Ok(format!("Error: git subcommand '{subcommand}' not allowed"));
594            }
595            if let Err(msg) = ensure_readonly_git(subcommand, rest) {
596                return Ok(msg);
597            }
598            // GIT_OPTIONAL_LOCKS=0 keeps even nominally-read commands side-effect-free: it stops
599            // e.g. `git status` from refreshing/rewriting `.git/index` stat caches and avoids
600            // index.lock contention when running against the user's repo in `pr` in-place mode.
601            let output = tokio::process::Command::new("git")
602                .args(tokens)
603                .env("GIT_OPTIONAL_LOCKS", "0")
604                .current_dir(&work_dir)
605                .output()
606                .await?;
607            let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
608            if stdout.len() > 50_000 {
609                let original_len = stdout.len();
610                let boundary = floor_char_boundary(&stdout, 50_000);
611                stdout.truncate(boundary);
612                stdout.push_str(&format!(
613                    "\n... truncated after 50,000 chars; {} chars omitted",
614                    original_len.saturating_sub(boundary)
615                ));
616            }
617            if !output.status.success() {
618                let stderr = String::from_utf8_lossy(&output.stderr);
619                return Ok(format!("Error: {stderr}"));
620            }
621            Ok(stdout)
622        })
623    }
624}
625
626#[cfg(test)]
627mod tests {
628    use super::{ALLOWED_GIT_SUBCOMMANDS, ReadFileTool, Tool, ensure_readonly_git, floor_char_boundary};
629    use serde_json::json;
630
631    #[test]
632    fn floor_char_boundary_handles_end_and_past_end() {
633        // pos beyond the end must not panic and clamps to len (the end is a valid boundary).
634        assert_eq!(floor_char_boundary("héllo", 100), "héllo".len());
635        assert_eq!(floor_char_boundary("abc", 3), 3);
636        assert_eq!(floor_char_boundary("", 5), 0);
637        // 'é' occupies bytes 1..=2; pos 2 is mid-character and floors back to its start (1).
638        assert_eq!(floor_char_boundary("héllo", 2), 1);
639        assert_eq!(floor_char_boundary("héllo", 1), 1);
640    }
641
642    /// Mirror the two gates GitTool applies: subcommand allowlist, then read-only argument check.
643    fn check(cmd: &str) -> Result<(), String> {
644        let tokens: Vec<&str> = cmd.split_whitespace().collect();
645        let (sub, rest) = tokens.split_first().expect("non-empty command");
646        if !ALLOWED_GIT_SUBCOMMANDS.contains(sub) {
647            return Err(format!("subcommand '{sub}' not allowed"));
648        }
649        ensure_readonly_git(sub, rest)
650    }
651
652    #[test]
653    fn rejects_output_file_write() {
654        // --output / -o turn a read-only command into a write-anywhere primitive
655        assert!(check("diff HEAD~1 --output=/tmp/evil").is_err());
656        assert!(check("diff --output ../escape.txt HEAD~1").is_err());
657        assert!(check("log --oneline -o /tmp/x").is_err());
658        assert!(check("show -o/tmp/glued HEAD").is_err());
659        assert!(check("diff --out=/tmp/abbrev HEAD~1").is_err()); // long-option abbreviation
660    }
661
662    #[test]
663    fn allows_plain_read_commands() {
664        assert!(check("diff HEAD~1").is_ok());
665        assert!(check("log --oneline -n 5").is_ok());
666        assert!(check("show HEAD").is_ok());
667        assert!(check("status --porcelain").is_ok());
668        // --oneline must not be mistaken for the -o output flag
669        assert!(check("log --oneline").is_ok());
670        // -o is a write flag only on diff/log/show; on ls-files it means --others (read-only)
671        assert!(check("ls-files -o --exclude-standard").is_ok());
672        assert!(check("ls-files --others").is_ok());
673        // refs, ranges, and in-repo pathspecs must survive the path-escape guard
674        assert!(check("diff --stat HEAD~1 -- src/foo.rs").is_ok());
675        assert!(check("log origin/main..HEAD").is_ok());
676        assert!(check("blame -- src/foo.rs").is_ok());
677        assert!(check("blame --ignore-rev HEAD -- src/foo.rs").is_ok());
678        assert!(check("blame --ignore-rev=HEAD -- src/foo.rs").is_ok());
679        assert!(check("show HEAD:src/foo.rs").is_ok());
680        assert!(check("show v:src/foo.rs").is_ok());
681        assert!(check("diff HEAD -- ./src").is_ok());
682        assert!(check(r"diff HEAD -- src\foo.rs").is_ok());
683    }
684
685    #[test]
686    fn rejects_arbitrary_file_read() {
687        // diff --no-index / blame --contents read straight from the filesystem, bypassing the
688        // canonicalize sandbox that read_file/grep/glob enforce.
689        assert!(check("diff --no-index /etc/passwd /dev/null").is_err());
690        assert!(check("diff --no-i /etc/passwd /dev/null").is_err()); // abbreviation
691        assert!(check("diff --no-index a b").is_err()); // flag denied even with relative paths
692        assert!(check("blame --contents /etc/passwd -- a.txt").is_err());
693        assert!(check("blame --contents=/etc/passwd -- a.txt").is_err());
694        assert!(check("blame --contents secret.txt -- a.txt").is_err());
695        // absolute paths and `..` traversal are rejected on any subcommand
696        assert!(check("diff /etc/passwd").is_err());
697        assert!(check("log -- ../../../etc/passwd").is_err());
698        assert!(check("show ../outside").is_err());
699        assert!(check("diff HEAD -- a/../../../etc/passwd").is_err());
700    }
701
702    #[test]
703    fn rejects_windows_style_path_escapes() {
704        assert!(check(r"diff C:\Users\victim\secret").is_err());
705        assert!(check(r"diff C:/Users/victim\secret").is_err());
706        assert!(check(r"diff \\server\share\secret").is_err());
707        assert!(check(r"log -- ..\secret").is_err());
708        assert!(check(r"show a\..\secret").is_err());
709    }
710
711    #[test]
712    fn rejects_blame_revision_file_reads() {
713        assert!(check("blame --ignore-revs-file README.md -- src/tools.rs").is_err());
714        assert!(check("blame --ignore-revs-file=README.md -- src/tools.rs").is_err());
715        assert!(check("blame --ignore-revs README.md -- src/tools.rs").is_err());
716        assert!(check("blame --ignore-revs-f=README.md -- src/tools.rs").is_err());
717    }
718
719    #[tokio::test]
720    async fn read_file_invalid_utf8_reports_text_only_feedback() {
721        let dir = tempfile::tempdir().unwrap();
722        std::fs::write(dir.path().join("bin.dat"), [0xff, 0xfe]).unwrap();
723        let work_dir = dir.path().canonicalize().unwrap();
724
725        let err = ReadFileTool
726            .call(json!({ "path": "bin.dat" }), work_dir)
727            .await
728            .unwrap_err()
729            .to_string();
730
731        assert_eq!(
732            err,
733            "file is not valid UTF-8; read_file only supports text files"
734        );
735    }
736
737    #[test]
738    fn rejects_branch_and_tag_porcelain() {
739        // branch/tag conflate read and write and are not on the allowlist at all; ref listing must
740        // go through the for-each-ref/show-ref plumbing instead.
741        assert!(check("branch -D some-branch").is_err());
742        assert!(check("branch new-branch").is_err());
743        assert!(check("branch --set-upstream-to=origin/main").is_err());
744        assert!(check("branch -- newbranch").is_err());
745        assert!(check("tag v9.9.9").is_err());
746        assert!(check("tag -d v1").is_err());
747        // even pure listing forms are rejected — the model is steered to for-each-ref
748        assert!(check("branch --list").is_err());
749    }
750
751    #[test]
752    fn reflect_tools_is_all_tools_minus_git() {
753        use std::collections::HashSet;
754        let all: HashSet<String> = super::all_tools().into_keys().collect();
755        let reflect: HashSet<String> = super::reflect_tools().into_keys().collect();
756        assert!(all.contains("git"));
757        // Exact set equality pins the derivation: any tool added to all_tools() that isn't git must
758        // also appear in reflect_tools(), or this fails.
759        let expected: HashSet<String> = all.iter().filter(|k| *k != "git").cloned().collect();
760        assert_eq!(reflect, expected);
761    }
762
763    #[test]
764    fn allows_readonly_ref_plumbing() {
765        // for-each-ref / show-ref have no ref-creating mode, so any arg shape is safe.
766        assert!(check("for-each-ref refs/heads/").is_ok());
767        assert!(check("for-each-ref --contains HEAD refs/heads/").is_ok());
768        assert!(check("for-each-ref --format=%(refname) --sort=-creatordate").is_ok());
769        assert!(check("show-ref --tags").is_ok());
770        assert!(check("show-ref --heads").is_ok());
771        // for-each-ref/show-ref have no --output flag, so git itself rejects a write attempt; our
772        // layer doesn't need to gate them (the --output block is scoped to diff/log/show).
773    }
774}