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