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/// Shell operators a model glues onto a git command out of habit. Tokens go to git's argv with no
68/// shell, so `|`, `&&`, or `>` reach git as literal arguments: usually a loud failure, sometimes a
69/// silently wrong result that the agent then works around by dumping whole files. Exact-token
70/// matching keeps `--format=%h|%an` legal.
71const SHELL_OPERATOR_TOKENS: &[&str] = &[
72    "&&", "||", "|", ";", "&", ">", ">>", "<", "1>", "2>", "&>", "2>&1",
73];
74
75fn reject_shell_syntax(tokens: &[&str]) -> std::result::Result<(), String> {
76    match tokens.iter().find(|token| {
77        SHELL_OPERATOR_TOKENS.contains(token) || token.starts_with("$(") || token.starts_with('`')
78    }) {
79        None => Ok(()),
80        Some(token) => Err(format!(
81            "the git tool runs one git invocation with whitespace-split arguments and no \
82             shell, so `{token}` is not interpreted. To read part of a file at a revision use \
83             `blame -L <start>,<end> <rev> -- <path>`; for the working-tree version use read_file \
84             with a line range."
85        )),
86    }
87}
88
89/// Reject git invocations that aren't genuinely read-only or that escape the repository. The
90/// subcommand allowlist alone is not enough — `read_file`/`grep`/`glob` confine reads to `work_dir`
91/// via canonicalize, but several git flags read straight from the filesystem and would bypass that
92/// sandbox. Three layers: (1) no argument may reference a path outside the repo (absolute or `..`,
93/// including Windows-style paths), (2) filesystem-reading flags are denied outright, and (3) the
94/// write-to-file `--output`/`-o` on `diff`/`log`/`show`. Returns `Err(message)` when rejected.
95fn ensure_readonly_git(subcommand: &str, rest: &[&str]) -> std::result::Result<(), String> {
96    // Layer 1 (all subcommands): an argument value may not reference a path outside the repo. The
97    // value is the token itself, or the part after `=` for a `--flag=value`; a bare `--flag` whose
98    // path is the *next* token is caught when that token is examined on its own. Refs (`HEAD~1`,
99    // `origin/main..HEAD`), ranges, and `--format=%H` have no leading `/` and no `..` component.
100    for token in rest {
101        let value = match token.starts_with('-') {
102            true => token.split_once('=').map(|(_, v)| v).unwrap_or(""),
103            false => token,
104        };
105        if looks_like_external_path(value) {
106            return Err(format!(
107                "git argument '{token}' references a path outside the repository"
108            ));
109        }
110    }
111    // Layer 2: flags that read a file by path, bypassing the object database entirely. They have no
112    // role in reviewing repo history, so deny them by name (incl. unambiguous abbreviations and the
113    // `=`-glued form) — this also closes a relative-but-symlinked path that would slip past layer 1.
114    let fs_reading_flags: &[&str] = match subcommand {
115        "diff" => &["no-index"],
116        "blame" => &["contents", "ignore-revs-file"],
117        _ => &[],
118    };
119    for flag in fs_reading_flags {
120        if rest
121            .iter()
122            .any(|token| blocked_fs_reading_flag_matches(token, flag))
123        {
124            return Err(format!(
125                "git --{flag} reads files outside the repository and is not allowed"
126            ));
127        }
128    }
129    // Layer 3: `--output`/`-o` is a write-to-file flag only on `diff`/`log`/`show` (which share
130    // diff's output machinery). On other subcommands `-o` means something else and is read-only —
131    // notably `ls-files -o` (= `--others`) — so gate only these three to avoid blocking legit reads.
132    if matches!(subcommand, "diff" | "log" | "show") {
133        for token in rest {
134            if long_flag_matches(token, "output")
135                || *token == "-o"
136                || (token.starts_with("-o") && !token.starts_with("--") && token.len() > 2)
137            {
138                return Err("writing git output to a file (--output/-o) is not allowed".into());
139            }
140        }
141    }
142    Ok(())
143}
144
145fn looks_like_external_path(value: &str) -> bool {
146    if value.is_empty() {
147        return false;
148    }
149    Path::new(value).is_absolute()
150        || value.starts_with('\\')
151        || has_windows_drive_prefix(value)
152        || value.split(['/', '\\']).any(|component| component == "..")
153}
154
155fn has_windows_drive_prefix(value: &str) -> bool {
156    let bytes = value.as_bytes();
157    bytes.len() >= 3
158        && bytes[0].is_ascii_alphabetic()
159        && bytes[1] == b':'
160        && matches!(bytes.get(2).copied(), Some(b'/' | b'\\'))
161}
162
163pub trait Tool: Send + Sync {
164    fn name(&self) -> String;
165    fn definition(&self) -> ToolDefinition;
166    fn call(
167        &self,
168        args: Value,
169        work_dir: PathBuf,
170    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>>;
171}
172
173pub fn all_tools() -> HashMap<String, Arc<dyn Tool>> {
174    let tools: Vec<Arc<dyn Tool>> = vec![
175        Arc::new(ReadFileTool),
176        Arc::new(GlobTool),
177        Arc::new(GrepTool),
178        Arc::new(GitTool),
179    ];
180    tools.into_iter().map(|tool| (tool.name(), tool)).collect()
181}
182
183pub fn reflect_tools() -> HashMap<String, Arc<dyn Tool>> {
184    // Reflection has no repo checkout to run git against, so it gets every tool except git.
185    let mut tools = all_tools();
186    tools.remove("git");
187    tools
188}
189
190/// Definitions in a stable order, sorted by map key (unique, unlike definition names).
191///
192/// Load-bearing for cost: the schemas open every request, so reordering them re-prefills the whole
193/// conversation on a prefix-caching provider — and `HashMap` order varies per map instance.
194pub fn tool_definitions(tools: &HashMap<String, Arc<dyn Tool>>) -> Vec<ToolDefinition> {
195    let mut entries: Vec<(&String, &Arc<dyn Tool>)> = tools.iter().collect();
196    entries.sort_unstable_by_key(|(key, _)| key.as_str());
197    entries
198        .into_iter()
199        .map(|(_, tool)| tool.definition())
200        .collect()
201}
202
203pub struct ReadFileTool;
204
205impl Tool for ReadFileTool {
206    fn name(&self) -> String {
207        "read_file".to_string()
208    }
209
210    fn definition(&self) -> ToolDefinition {
211        ToolDefinition {
212            name: "read_file".to_string(),
213            description:
214                "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."
215                    .to_string(),
216            parameters: json!({
217                "type": "object",
218                "properties": {
219                    "path": {
220                        "type": "string",
221                        "description": "Workspace-relative file path to read."
222                    },
223                    "start_line": {
224                        "type": "integer",
225                        "minimum": 1,
226                        "description": "First line to include. Omit to start at line 1."
227                    },
228                    "end_line": {
229                        "type": "integer",
230                        "minimum": 1,
231                        "description": "Last line to include. Omit to read to the end of the file."
232                    }
233                },
234                "required": ["path"],
235                "additionalProperties": false
236            }),
237        }
238    }
239
240    fn call(
241        &self,
242        args: Value,
243        work_dir: PathBuf,
244    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
245        Box::pin(async move {
246            let path = args
247                .get("path")
248                .and_then(|value| value.as_str())
249                .ok_or_else(|| eyre::eyre!("missing path"))?;
250            let start_line = args
251                .get("start_line")
252                .and_then(|value| value.as_u64())
253                .unwrap_or(1) as usize;
254            let end_line = args
255                .get("end_line")
256                .and_then(|value| value.as_u64())
257                .map(|value| value as usize);
258            let full_path = work_dir.join(path);
259            let full_path = full_path.canonicalize().map_err(|e| {
260                eyre::eyre!(
261                    "cannot resolve path {path:?}: {e}. Only files within {} are accessible.",
262                    work_dir.display()
263                )
264            })?;
265            if !full_path.starts_with(&work_dir) {
266                eyre::bail!(
267                    "access denied: {path:?} is outside the allowed workspace ({}). Only project files are accessible.",
268                    work_dir.display()
269                );
270            }
271            let content = match fs::read_to_string(&full_path).await {
272                Ok(content) => content,
273                Err(err) if err.kind() == std::io::ErrorKind::InvalidData => {
274                    eyre::bail!("file is not valid UTF-8; read_file only supports text files")
275                }
276                Err(err) => return Err(err.into()),
277            };
278            let (start_line, end_line, swapped) = match end_line {
279                Some(end) if end < start_line => (end, Some(start_line), true),
280                _ => (start_line, end_line, false),
281            };
282            let lines = content.lines().collect::<Vec<_>>();
283            let total = lines.len();
284            let start = start_line.max(1).min(total.max(1));
285            let end = end_line.unwrap_or(total).max(start).min(total);
286            let relative = full_path
287                .strip_prefix(&work_dir)
288                .unwrap_or(&full_path)
289                .display()
290                .to_string();
291            let mut output = format!("File: {relative}\nLines: {start}-{end} of {total}\n");
292            if swapped {
293                output.push_str("Note: start_line and end_line were given in reverse order and swapped\n");
294            }
295            output.push('\n');
296            for (idx, line) in lines.iter().enumerate() {
297                let line_num = idx + 1;
298                if line_num < start || line_num > end {
299                    continue;
300                }
301                output.push_str(&format!("{line_num:>4} {line}\n"));
302            }
303            Ok(output)
304        })
305    }
306}
307
308pub struct GlobTool;
309
310impl Tool for GlobTool {
311    fn name(&self) -> String {
312        "glob".to_string()
313    }
314
315    fn definition(&self) -> ToolDefinition {
316        ToolDefinition {
317            name: "glob".to_string(),
318            description:
319                "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."
320                    .to_string(),
321            parameters: json!({
322                "type": "object",
323                "properties": {
324                    "pattern": {
325                        "type": "string",
326                        "description": "Workspace-relative glob such as 'src/**/*.rs' or '**/*.toml'."
327                    }
328                },
329                "required": ["pattern"],
330                "additionalProperties": false
331            }),
332        }
333    }
334
335    fn call(
336        &self,
337        args: Value,
338        work_dir: PathBuf,
339    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
340        Box::pin(async move {
341            let pattern = args
342                .get("pattern")
343                .and_then(|value| value.as_str())
344                .ok_or_else(|| eyre::eyre!("missing pattern"))?;
345            let pattern_path = Path::new(pattern);
346            if pattern_path.is_absolute()
347                || pattern_path
348                    .components()
349                    .any(|c| c == std::path::Component::ParentDir)
350            {
351                eyre::bail!(
352                    "access denied: glob pattern {pattern:?} must be relative to the workspace ({}). Absolute paths and parent-directory traversal are not allowed.",
353                    work_dir.display()
354                );
355            }
356            let mut results = Vec::new();
357            let full_pattern = work_dir.join(pattern);
358            let full_pattern = full_pattern.to_string_lossy();
359            for entry in glob(&full_pattern)? {
360                if let Ok(path) = entry {
361                    if let Ok(relative) = path.strip_prefix(&work_dir) {
362                        results.push(relative.display().to_string());
363                    }
364                }
365                if results.len() >= 200 {
366                    break;
367                }
368            }
369            if results.is_empty() {
370                return Ok(format!("No files matched pattern: {pattern}"));
371            }
372            Ok(results.join("\n"))
373        })
374    }
375}
376
377pub struct GrepTool;
378
379impl Tool for GrepTool {
380    fn name(&self) -> String {
381        "grep".to_string()
382    }
383
384    fn definition(&self) -> ToolDefinition {
385        ToolDefinition {
386            name: "grep".to_string(),
387            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."
388                .to_string(),
389            parameters: json!({
390                "type": "object",
391                "properties": {
392                    "pattern": {
393                        "type": "string",
394                        "description": "Regular expression to search for in file contents."
395                    },
396                    "path": {
397                        "type": "string",
398                        "description": "Optional workspace-relative file or directory to search within."
399                    },
400                    "file_glob": {
401                        "type": "string",
402                        "description": "Optional filename filter such as '*.rs'; matched against file names, not full paths."
403                    }
404                },
405                "required": ["pattern"],
406                "additionalProperties": false
407            }),
408        }
409    }
410
411    fn call(
412        &self,
413        args: Value,
414        work_dir: PathBuf,
415    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
416        Box::pin(async move {
417            let pattern = args
418                .get("pattern")
419                .and_then(|value| value.as_str())
420                .ok_or_else(|| eyre::eyre!("missing pattern"))?;
421            let base_path = args
422                .get("path")
423                .and_then(|value| value.as_str())
424                .map(|value| {
425                    let p = work_dir.join(value);
426                    // canonicalize to resolve symlinks and `..` before the workspace check
427                    p.canonicalize()
428                        .map_err(|e| eyre::eyre!("cannot resolve path {value:?}: {e}. Only files within {} are accessible.", work_dir.display()))
429                })
430                .transpose()?
431                .unwrap_or_else(|| work_dir.clone());
432            if !base_path.starts_with(&work_dir) {
433                let path_arg = args.get("path").and_then(|v| v.as_str()).unwrap_or("?");
434                eyre::bail!(
435                    "access denied: {path_arg:?} is outside the allowed workspace ({}). Only project files are accessible.",
436                    work_dir.display()
437                );
438            }
439            let file_glob = args
440                .get("file_glob")
441                .and_then(|value| value.as_str())
442                .map(glob_to_regex)
443                .transpose()?;
444            let regex =
445                Regex::new(pattern).map_err(|e| eyre::eyre!("invalid regex {pattern:?}: {e}"))?;
446            let mut results = Vec::new();
447            let mut skipped_files = 0usize;
448            if base_path.is_file() {
449                if let Err(e) = search_file(&base_path, &regex, &work_dir, &mut results).await {
450                    debug!("skipping file {}: {e}", base_path.display());
451                    skipped_files += 1;
452                }
453            } else {
454                let mut stack = vec![base_path];
455                while let Some(path) = stack.pop() {
456                    let entries = match fs::read_dir(&path).await {
457                        Ok(entries) => entries,
458                        Err(e) => {
459                            debug!("skipping unreadable dir {}: {e}", path.display());
460                            continue;
461                        }
462                    };
463                    let mut entries = entries;
464                    while let Ok(Some(entry)) = entries.next_entry().await {
465                        let entry_path = entry.path();
466                        let file_type = match entry.file_type().await {
467                            Ok(file_type) => file_type,
468                            Err(e) => {
469                                debug!("skipping {}: {e}", entry_path.display());
470                                continue;
471                            }
472                        };
473                        let name = entry.file_name();
474                        let name = name.to_string_lossy();
475                        if file_type.is_dir() {
476                            if name.starts_with('.') || name == "target" || name == "node_modules" {
477                                continue;
478                            }
479                            stack.push(entry_path);
480                        } else if file_type.is_file() {
481                            if let Some(filter) = &file_glob {
482                                if !filter.is_match(&name) {
483                                    continue;
484                                }
485                            }
486                            match search_file(&entry_path, &regex, &work_dir, &mut results).await {
487                                Ok(_) => {}
488                                Err(e) => {
489                                    debug!("skipping file {}: {e}", entry_path.display());
490                                    skipped_files += 1;
491                                }
492                            }
493                            if results.len() >= 100 {
494                                break;
495                            }
496                        }
497                        if results.len() >= 100 {
498                            break;
499                        }
500                    }
501                    if results.len() >= 100 {
502                        break;
503                    }
504                }
505            }
506            if results.is_empty() {
507                let mut output = format!("No matches for regex: {pattern}");
508                if skipped_files > 0 {
509                    output.push_str(&format!("\nSkipped unreadable files: {skipped_files}"));
510                }
511                return Ok(output);
512            }
513            let mut output = format!("Matches: {}\n", results.len());
514            if skipped_files > 0 {
515                output.push_str(&format!("Skipped unreadable files: {skipped_files}\n"));
516            }
517            output.push('\n');
518            output.push_str(&results.join("\n"));
519            Ok(output)
520        })
521    }
522}
523
524async fn search_file(
525    path: &PathBuf,
526    regex: &Regex,
527    work_dir: &Path,
528    results: &mut Vec<String>,
529) -> Result<()> {
530    use tokio::io::AsyncReadExt;
531
532    let mut file = fs::File::open(path).await?;
533    let probe = BinaryProbe::read_from(&mut file).await?;
534    if probe.is_binary() {
535        return Ok(()); // Skip binary files silently
536    }
537
538    // Read the rest of the file from the same handle, continuing after the probe
539    let mut remaining = Vec::new();
540    file.read_to_end(&mut remaining).await?;
541
542    // Combine sample + remaining into full content
543    let mut full_content = Vec::with_capacity(probe.bytes().len() + remaining.len());
544    full_content.extend_from_slice(probe.bytes());
545    full_content.extend_from_slice(&remaining);
546
547    // Convert to string and search
548    let content = String::from_utf8_lossy(&full_content);
549    let relative = path.strip_prefix(work_dir).unwrap_or(path);
550    for (idx, line) in content.lines().enumerate() {
551        if regex.is_match(line) {
552            results.push(format!("{}:{}:{}", relative.display(), idx + 1, line));
553            if results.len() >= 100 {
554                break;
555            }
556        }
557    }
558    Ok(())
559}
560
561fn glob_to_regex(pattern: &str) -> Result<Regex> {
562    let mut escaped = String::new();
563    for ch in pattern.chars() {
564        match ch {
565            '.' => escaped.push_str("\\."),
566            '*' => escaped.push_str(".*"),
567            '?' => escaped.push('.'),
568            other => escaped.push(other),
569        }
570    }
571    Regex::new(&format!("^{}$", escaped))
572        .map_err(|e| eyre::eyre!("invalid file_glob {pattern:?}: {e}"))
573}
574
575/// One read of up to 8 KiB from the handle's current position; a NUL byte in the sample marks
576/// the file binary. The sample is kept so a caller that goes on reading the same handle can
577/// splice it back instead of re-opening (`search_file` does exactly that).
578struct BinaryProbe {
579    sample: [u8; 8192],
580    len: usize,
581}
582
583impl BinaryProbe {
584    async fn read_from(file: &mut fs::File) -> std::io::Result<Self> {
585        use tokio::io::AsyncReadExt;
586        let mut sample = [0u8; 8192];
587        let len = file.read(&mut sample).await?;
588        Ok(Self { sample, len })
589    }
590
591    fn is_binary(&self) -> bool {
592        self.sample[..self.len].contains(&0)
593    }
594
595    fn bytes(&self) -> &[u8] {
596        &self.sample[..self.len]
597    }
598}
599
600/// Check if a file is binary by reading the first 8 KiB and checking for null bytes.
601/// Returns `true` if binary, `false` if text, or an error if the file cannot be read.
602pub async fn is_binary_file(path: &Path) -> std::io::Result<bool> {
603    let mut file = fs::File::open(path).await?;
604    Ok(BinaryProbe::read_from(&mut file).await?.is_binary())
605}
606
607pub struct GitTool;
608
609impl Tool for GitTool {
610    fn name(&self) -> String {
611        "git".to_string()
612    }
613
614    fn definition(&self) -> ToolDefinition {
615        ToolDefinition {
616            name: "git".to_string(),
617            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. Arguments are split on whitespace and passed straight to git: there is no shell, so pipes, redirects, `&&`, and command substitution do not work."
618                .to_string(),
619            parameters: json!({
620                "type": "object",
621                "properties": {
622                    "command": {
623                        "type": "string",
624                        "description": "One read-only git command without the leading 'git' and without shell operators, for example 'diff --stat HEAD~1' or 'log --oneline -n 20'."
625                    }
626                },
627                "required": ["command"],
628                "additionalProperties": false
629            }),
630        }
631    }
632
633    fn call(
634        &self,
635        args: Value,
636        work_dir: PathBuf,
637    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
638        Box::pin(async move {
639            let command = args
640                .get("command")
641                .and_then(|value| value.as_str())
642                .ok_or_else(|| eyre::eyre!("missing command"))?;
643            let tokens = command.split_whitespace().collect::<Vec<_>>();
644            // Failures are `Err`: the agent feeds them back to the model as `Error: …` text and
645            // records the call with error status, so the classification never depends on stdout.
646            if let Err(msg) = reject_shell_syntax(&tokens) {
647                eyre::bail!(msg);
648            }
649            let Some((subcommand, rest)) = tokens.split_first() else {
650                eyre::bail!("empty git command");
651            };
652            if !ALLOWED_GIT_SUBCOMMANDS.contains(subcommand) {
653                eyre::bail!("git subcommand '{subcommand}' not allowed");
654            }
655            if let Err(msg) = ensure_readonly_git(subcommand, rest) {
656                eyre::bail!(msg);
657            }
658            // GIT_OPTIONAL_LOCKS=0 keeps even nominally-read commands side-effect-free: it stops
659            // e.g. `git status` from refreshing/rewriting `.git/index` stat caches and avoids
660            // index.lock contention when running against the user's repo in `pr` in-place mode.
661            let output = tokio::process::Command::new("git")
662                .args(tokens)
663                .env("GIT_OPTIONAL_LOCKS", "0")
664                .current_dir(&work_dir)
665                .output()
666                .await?;
667            let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
668            if stdout.len() > 50_000 {
669                let original_len = stdout.len();
670                let boundary = floor_char_boundary(&stdout, 50_000);
671                stdout.truncate(boundary);
672                stdout.push_str(&format!(
673                    "\n... truncated after 50,000 chars; {} chars omitted",
674                    original_len.saturating_sub(boundary)
675                ));
676            }
677            if !output.status.success() {
678                let stderr = String::from_utf8_lossy(&output.stderr);
679                eyre::bail!("{}", stderr.trim_end());
680            }
681            Ok(stdout)
682        })
683    }
684}
685
686#[cfg(test)]
687mod tests {
688    use super::{
689        ALLOWED_GIT_SUBCOMMANDS, GitTool, GlobTool, GrepTool, ReadFileTool, Tool,
690        ensure_readonly_git, floor_char_boundary, is_binary_file, reject_shell_syntax, search_file,
691        tool_definitions,
692    };
693    use regex::Regex;
694    use serde_json::json;
695    use std::collections::HashMap;
696    use std::sync::Arc;
697
698    /// Two maps holding the same tools must serialize identically however they were built. Asserts
699    /// the sorted postcondition, since two default-seeded maps can coincide by chance.
700    #[test]
701    fn tool_definitions_order_is_independent_of_map_construction() {
702        let tools: Vec<Arc<dyn Tool>> = vec![
703            Arc::new(ReadFileTool),
704            Arc::new(GlobTool),
705            Arc::new(GrepTool),
706            Arc::new(GitTool),
707        ];
708        let names = |map: &HashMap<String, Arc<dyn Tool>>| {
709            tool_definitions(map)
710                .into_iter()
711                .map(|definition| definition.name)
712                .collect::<Vec<_>>()
713        };
714
715        let forward: HashMap<String, Arc<dyn Tool>> = tools
716            .iter()
717            .map(|tool| (tool.name(), Arc::clone(tool)))
718            .collect();
719        let reversed: HashMap<String, Arc<dyn Tool>> = tools
720            .iter()
721            .rev()
722            .map(|tool| (tool.name(), Arc::clone(tool)))
723            .collect();
724
725        let ordered = names(&forward);
726        assert_eq!(ordered, names(&reversed));
727
728        // pins the ordering key: the map's (unique) keys, not the map's iteration order
729        let mut expected: Vec<String> = forward.keys().cloned().collect();
730        expected.sort();
731        assert_eq!(ordered, expected);
732    }
733
734    #[test]
735    fn floor_char_boundary_handles_end_and_past_end() {
736        // pos beyond the end must not panic and clamps to len (the end is a valid boundary).
737        assert_eq!(floor_char_boundary("héllo", 100), "héllo".len());
738        assert_eq!(floor_char_boundary("abc", 3), 3);
739        assert_eq!(floor_char_boundary("", 5), 0);
740        // 'é' occupies bytes 1..=2; pos 2 is mid-character and floors back to its start (1).
741        assert_eq!(floor_char_boundary("héllo", 2), 1);
742        assert_eq!(floor_char_boundary("héllo", 1), 1);
743    }
744
745    /// Mirror the two gates GitTool applies: subcommand allowlist, then read-only argument check.
746    fn check(cmd: &str) -> Result<(), String> {
747        let tokens: Vec<&str> = cmd.split_whitespace().collect();
748        let (sub, rest) = tokens.split_first().expect("non-empty command");
749        if !ALLOWED_GIT_SUBCOMMANDS.contains(sub) {
750            return Err(format!("subcommand '{sub}' not allowed"));
751        }
752        ensure_readonly_git(sub, rest)
753    }
754
755    #[test]
756    fn rejects_output_file_write() {
757        // --output / -o turn a read-only command into a write-anywhere primitive
758        assert!(check("diff HEAD~1 --output=/tmp/evil").is_err());
759        assert!(check("diff --output ../escape.txt HEAD~1").is_err());
760        assert!(check("log --oneline -o /tmp/x").is_err());
761        assert!(check("show -o/tmp/glued HEAD").is_err());
762        assert!(check("diff --out=/tmp/abbrev HEAD~1").is_err()); // long-option abbreviation
763    }
764
765    #[test]
766    fn allows_plain_read_commands() {
767        assert!(check("diff HEAD~1").is_ok());
768        assert!(check("log --oneline -n 5").is_ok());
769        assert!(check("show HEAD").is_ok());
770        assert!(check("status --porcelain").is_ok());
771        // --oneline must not be mistaken for the -o output flag
772        assert!(check("log --oneline").is_ok());
773        // -o is a write flag only on diff/log/show; on ls-files it means --others (read-only)
774        assert!(check("ls-files -o --exclude-standard").is_ok());
775        assert!(check("ls-files --others").is_ok());
776        // refs, ranges, and in-repo pathspecs must survive the path-escape guard
777        assert!(check("diff --stat HEAD~1 -- src/foo.rs").is_ok());
778        assert!(check("log origin/main..HEAD").is_ok());
779        assert!(check("blame -- src/foo.rs").is_ok());
780        assert!(check("blame --ignore-rev HEAD -- src/foo.rs").is_ok());
781        assert!(check("blame --ignore-rev=HEAD -- src/foo.rs").is_ok());
782        assert!(check("show HEAD:src/foo.rs").is_ok());
783        assert!(check("show v:src/foo.rs").is_ok());
784        assert!(check("diff HEAD -- ./src").is_ok());
785        assert!(check(r"diff HEAD -- src\foo.rs").is_ok());
786    }
787
788    #[test]
789    fn rejects_arbitrary_file_read() {
790        // diff --no-index / blame --contents read straight from the filesystem, bypassing the
791        // canonicalize sandbox that read_file/grep/glob enforce.
792        assert!(check("diff --no-index /etc/passwd /dev/null").is_err());
793        assert!(check("diff --no-i /etc/passwd /dev/null").is_err()); // abbreviation
794        assert!(check("diff --no-index a b").is_err()); // flag denied even with relative paths
795        assert!(check("blame --contents /etc/passwd -- a.txt").is_err());
796        assert!(check("blame --contents=/etc/passwd -- a.txt").is_err());
797        assert!(check("blame --contents secret.txt -- a.txt").is_err());
798        // absolute paths and `..` traversal are rejected on any subcommand
799        assert!(check("diff /etc/passwd").is_err());
800        assert!(check("log -- ../../../etc/passwd").is_err());
801        assert!(check("show ../outside").is_err());
802        assert!(check("diff HEAD -- a/../../../etc/passwd").is_err());
803    }
804
805    #[test]
806    fn rejects_windows_style_path_escapes() {
807        assert!(check(r"diff C:\Users\victim\secret").is_err());
808        assert!(check(r"diff C:/Users/victim\secret").is_err());
809        assert!(check(r"diff \\server\share\secret").is_err());
810        assert!(check(r"log -- ..\secret").is_err());
811        assert!(check(r"show a\..\secret").is_err());
812    }
813
814    #[test]
815    fn rejects_blame_revision_file_reads() {
816        assert!(check("blame --ignore-revs-file README.md -- src/tools.rs").is_err());
817        assert!(check("blame --ignore-revs-file=README.md -- src/tools.rs").is_err());
818        assert!(check("blame --ignore-revs README.md -- src/tools.rs").is_err());
819        assert!(check("blame --ignore-revs-f=README.md -- src/tools.rs").is_err());
820    }
821
822    #[test]
823    fn rejects_shell_operators_but_not_glued_format_pipes() {
824        assert!(reject_shell_syntax(&["log", "--oneline", "|", "head", "-n", "3"]).is_err());
825        assert!(reject_shell_syntax(&["show", "HEAD:src/a.rs", "&&", "git", "log"]).is_err());
826        assert!(reject_shell_syntax(&["diff", "HEAD~1", ">", "out.txt"]).is_err());
827        assert!(reject_shell_syntax(&["log", "2>&1"]).is_err());
828        assert!(reject_shell_syntax(&["show", "$(cat", "x)"]).is_err());
829        assert!(reject_shell_syntax(&["log", "--format=%h|%an", "-n", "5"]).is_ok());
830        assert!(reject_shell_syntax(&["diff", "HEAD~1", "--", "a|b.txt"]).is_ok());
831    }
832
833    #[tokio::test]
834    async fn git_tool_fails_on_shell_syntax_without_running_git() {
835        // not a git repo: a real invocation would fail differently, so the message proves the
836        // operator check fired first
837        let dir = tempfile::tempdir().unwrap();
838        let err = GitTool
839            .call(
840                json!({ "command": "log --oneline | head -n 3" }),
841                dir.path().to_path_buf(),
842            )
843            .await
844            .unwrap_err()
845            .to_string();
846        assert!(err.contains("`|`"));
847    }
848
849    #[tokio::test]
850    async fn read_file_swaps_inverted_range() {
851        let dir = tempfile::tempdir().unwrap();
852        std::fs::write(dir.path().join("a.txt"), "1\n2\n3\n4\n").unwrap();
853        let work_dir = dir.path().canonicalize().unwrap();
854
855        let output = ReadFileTool
856            .call(
857                json!({ "path": "a.txt", "start_line": 3, "end_line": 2 }),
858                work_dir,
859            )
860            .await
861            .unwrap();
862
863        assert_eq!(
864            output,
865            "File: a.txt\nLines: 2-3 of 4\nNote: start_line and end_line were given in reverse order and swapped\n\n   2 2\n   3 3\n"
866        );
867    }
868
869    #[tokio::test]
870    async fn read_file_invalid_utf8_reports_text_only_feedback() {
871        let dir = tempfile::tempdir().unwrap();
872        std::fs::write(dir.path().join("bin.dat"), [0xff, 0xfe]).unwrap();
873        let work_dir = dir.path().canonicalize().unwrap();
874
875        let err = ReadFileTool
876            .call(json!({ "path": "bin.dat" }), work_dir)
877            .await
878            .unwrap_err()
879            .to_string();
880
881        assert_eq!(
882            err,
883            "file is not valid UTF-8; read_file only supports text files"
884        );
885    }
886
887    #[tokio::test]
888    async fn binary_probe_checks_only_the_first_8_kib() {
889        let dir = tempfile::tempdir().unwrap();
890
891        let nul_early = dir.path().join("early.bin");
892        std::fs::write(&nul_early, b"head\0tail").unwrap();
893        assert!(is_binary_file(&nul_early).await.unwrap());
894
895        let text = dir.path().join("text.txt");
896        std::fs::write(&text, "plain text").unwrap();
897        assert!(!is_binary_file(&text).await.unwrap());
898
899        // the probe window is the first 8 KiB only; a NUL past it does not flag the file
900        let nul_late = dir.path().join("late.txt");
901        let mut bytes = vec![b'x'; 8192];
902        bytes.push(0);
903        std::fs::write(&nul_late, &bytes).unwrap();
904        assert!(!is_binary_file(&nul_late).await.unwrap());
905    }
906
907    /// grep probes the first 8 KiB from the same handle it then keeps reading, splicing the
908    /// sample back in front of the remainder. Losing the sample breaks a match that straddles
909    /// the boundary; duplicating it doubles a line inside the window; not continuing past the
910    /// probe loses later matches.
911    #[tokio::test]
912    async fn grep_reassembles_the_probe_sample_without_loss_or_duplication() {
913        let dir = tempfile::tempdir().unwrap();
914        let work_dir = dir.path().canonicalize().unwrap();
915
916        let mut content = String::from("EARLY marker line\n");
917        content.push_str(&"a".repeat(8188 - content.len()));
918        content.push_str("STRADDLE"); // bytes 8188..8196 span the 8192 probe boundary
919        content.push_str("\nBEYOND the probe window\n");
920        let path = work_dir.join("big.txt");
921        std::fs::write(&path, &content).unwrap();
922
923        for (pattern, why) in [
924            ("EARLY", "a duplicated sample would match this line twice"),
925            (
926                "STRADDLE",
927                "a lost sample would break the boundary-straddling match",
928            ),
929            ("BEYOND", "the same handle must keep reading past the probe"),
930        ] {
931            let regex = Regex::new(pattern).unwrap();
932            let mut results = Vec::new();
933            search_file(&path, &regex, &work_dir, &mut results)
934                .await
935                .unwrap();
936            assert_eq!(results.len(), 1, "{pattern}: {why}");
937        }
938    }
939
940    #[tokio::test]
941    async fn grep_skips_binary_files_silently() {
942        let dir = tempfile::tempdir().unwrap();
943        let work_dir = dir.path().canonicalize().unwrap();
944        let path = work_dir.join("bin.dat");
945        std::fs::write(&path, b"match\0me").unwrap();
946
947        let regex = Regex::new("match").unwrap();
948        let mut results = Vec::new();
949        search_file(&path, &regex, &work_dir, &mut results)
950            .await
951            .unwrap();
952        assert!(results.is_empty());
953    }
954
955    #[test]
956    fn rejects_branch_and_tag_porcelain() {
957        // branch/tag conflate read and write and are not on the allowlist at all; ref listing must
958        // go through the for-each-ref/show-ref plumbing instead.
959        assert!(check("branch -D some-branch").is_err());
960        assert!(check("branch new-branch").is_err());
961        assert!(check("branch --set-upstream-to=origin/main").is_err());
962        assert!(check("branch -- newbranch").is_err());
963        assert!(check("tag v9.9.9").is_err());
964        assert!(check("tag -d v1").is_err());
965        // even pure listing forms are rejected — the model is steered to for-each-ref
966        assert!(check("branch --list").is_err());
967    }
968
969    #[test]
970    fn reflect_tools_is_all_tools_minus_git() {
971        use std::collections::HashSet;
972        let all: HashSet<String> = super::all_tools().into_keys().collect();
973        let reflect: HashSet<String> = super::reflect_tools().into_keys().collect();
974        assert!(all.contains("git"));
975        // Exact set equality pins the derivation: any tool added to all_tools() that isn't git must
976        // also appear in reflect_tools(), or this fails.
977        let expected: HashSet<String> = all.iter().filter(|k| *k != "git").cloned().collect();
978        assert_eq!(reflect, expected);
979    }
980
981    #[test]
982    fn allows_readonly_ref_plumbing() {
983        // for-each-ref / show-ref have no ref-creating mode, so any arg shape is safe.
984        assert!(check("for-each-ref refs/heads/").is_ok());
985        assert!(check("for-each-ref --contains HEAD refs/heads/").is_ok());
986        assert!(check("for-each-ref --format=%(refname) --sort=-creatordate").is_ok());
987        assert!(check("show-ref --tags").is_ok());
988        assert!(check("show-ref --heads").is_ok());
989        // for-each-ref/show-ref have no --output flag, so git itself rejects a write attempt; our
990        // layer doesn't need to gate them (the --output block is scoped to diff/log/show).
991    }
992}