Skip to main content

nitpicker_agent/
tools.rs

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