Skip to main content

nitpicker_agent/
tools.rs

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