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    let mut file = fs::File::open(path).await?;
505    let probe = BinaryProbe::read_from(&mut file).await?;
506    if probe.is_binary() {
507        return Ok(()); // Skip binary files silently
508    }
509
510    // Read the rest of the file from the same handle, continuing after the probe
511    let mut remaining = Vec::new();
512    file.read_to_end(&mut remaining).await?;
513
514    // Combine sample + remaining into full content
515    let mut full_content = Vec::with_capacity(probe.bytes().len() + remaining.len());
516    full_content.extend_from_slice(probe.bytes());
517    full_content.extend_from_slice(&remaining);
518
519    // Convert to string and search
520    let content = String::from_utf8_lossy(&full_content);
521    let relative = path.strip_prefix(work_dir).unwrap_or(path);
522    for (idx, line) in content.lines().enumerate() {
523        if regex.is_match(line) {
524            results.push(format!("{}:{}:{}", relative.display(), idx + 1, line));
525            if results.len() >= 100 {
526                break;
527            }
528        }
529    }
530    Ok(())
531}
532
533fn glob_to_regex(pattern: &str) -> Result<Regex> {
534    let mut escaped = String::new();
535    for ch in pattern.chars() {
536        match ch {
537            '.' => escaped.push_str("\\."),
538            '*' => escaped.push_str(".*"),
539            '?' => escaped.push('.'),
540            other => escaped.push(other),
541        }
542    }
543    Regex::new(&format!("^{}$", escaped))
544        .map_err(|e| eyre::eyre!("invalid file_glob {pattern:?}: {e}"))
545}
546
547/// One read of up to 8 KiB from the handle's current position; a NUL byte in the sample marks
548/// the file binary. The sample is kept so a caller that goes on reading the same handle can
549/// splice it back instead of re-opening (`search_file` does exactly that).
550struct BinaryProbe {
551    sample: [u8; 8192],
552    len: usize,
553}
554
555impl BinaryProbe {
556    async fn read_from(file: &mut fs::File) -> std::io::Result<Self> {
557        use tokio::io::AsyncReadExt;
558        let mut sample = [0u8; 8192];
559        let len = file.read(&mut sample).await?;
560        Ok(Self { sample, len })
561    }
562
563    fn is_binary(&self) -> bool {
564        self.sample[..self.len].contains(&0)
565    }
566
567    fn bytes(&self) -> &[u8] {
568        &self.sample[..self.len]
569    }
570}
571
572/// Check if a file is binary by reading the first 8 KiB and checking for null bytes.
573/// Returns `true` if binary, `false` if text, or an error if the file cannot be read.
574pub async fn is_binary_file(path: &Path) -> std::io::Result<bool> {
575    let mut file = fs::File::open(path).await?;
576    Ok(BinaryProbe::read_from(&mut file).await?.is_binary())
577}
578
579pub struct GitTool;
580
581impl Tool for GitTool {
582    fn name(&self) -> String {
583        "git".to_string()
584    }
585
586    fn definition(&self) -> ToolDefinition {
587        ToolDefinition {
588            name: "git".to_string(),
589            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."
590                .to_string(),
591            parameters: json!({
592                "type": "object",
593                "properties": {
594                    "command": {
595                        "type": "string",
596                        "description": "Read-only git command to run, for example 'diff --stat HEAD~1' or 'log --oneline -n 20'."
597                    }
598                },
599                "required": ["command"],
600                "additionalProperties": false
601            }),
602        }
603    }
604
605    fn call(
606        &self,
607        args: Value,
608        work_dir: PathBuf,
609    ) -> Pin<Box<dyn std::future::Future<Output = Result<String>> + Send>> {
610        Box::pin(async move {
611            let command = args
612                .get("command")
613                .and_then(|value| value.as_str())
614                .ok_or_else(|| eyre::eyre!("missing command"))?;
615            let tokens = command.split_whitespace().collect::<Vec<_>>();
616            let Some((subcommand, rest)) = tokens.split_first() else {
617                return Ok("Error: empty git command".to_string());
618            };
619            if !ALLOWED_GIT_SUBCOMMANDS.contains(subcommand) {
620                return Ok(format!("Error: git subcommand '{subcommand}' not allowed"));
621            }
622            if let Err(msg) = ensure_readonly_git(subcommand, rest) {
623                return Ok(msg);
624            }
625            // GIT_OPTIONAL_LOCKS=0 keeps even nominally-read commands side-effect-free: it stops
626            // e.g. `git status` from refreshing/rewriting `.git/index` stat caches and avoids
627            // index.lock contention when running against the user's repo in `pr` in-place mode.
628            let output = tokio::process::Command::new("git")
629                .args(tokens)
630                .env("GIT_OPTIONAL_LOCKS", "0")
631                .current_dir(&work_dir)
632                .output()
633                .await?;
634            let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();
635            if stdout.len() > 50_000 {
636                let original_len = stdout.len();
637                let boundary = floor_char_boundary(&stdout, 50_000);
638                stdout.truncate(boundary);
639                stdout.push_str(&format!(
640                    "\n... truncated after 50,000 chars; {} chars omitted",
641                    original_len.saturating_sub(boundary)
642                ));
643            }
644            if !output.status.success() {
645                let stderr = String::from_utf8_lossy(&output.stderr);
646                return Ok(format!("Error: {stderr}"));
647            }
648            Ok(stdout)
649        })
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use super::{
656        ALLOWED_GIT_SUBCOMMANDS, GitTool, GlobTool, GrepTool, ReadFileTool, Tool,
657        ensure_readonly_git, floor_char_boundary, is_binary_file, search_file, tool_definitions,
658    };
659    use regex::Regex;
660    use serde_json::json;
661    use std::collections::HashMap;
662    use std::sync::Arc;
663
664    /// Two maps holding the same tools must serialize identically however they were built. Asserts
665    /// the sorted postcondition, since two default-seeded maps can coincide by chance.
666    #[test]
667    fn tool_definitions_order_is_independent_of_map_construction() {
668        let tools: Vec<Arc<dyn Tool>> = vec![
669            Arc::new(ReadFileTool),
670            Arc::new(GlobTool),
671            Arc::new(GrepTool),
672            Arc::new(GitTool),
673        ];
674        let names = |map: &HashMap<String, Arc<dyn Tool>>| {
675            tool_definitions(map)
676                .into_iter()
677                .map(|definition| definition.name)
678                .collect::<Vec<_>>()
679        };
680
681        let forward: HashMap<String, Arc<dyn Tool>> = tools
682            .iter()
683            .map(|tool| (tool.name(), Arc::clone(tool)))
684            .collect();
685        let reversed: HashMap<String, Arc<dyn Tool>> = tools
686            .iter()
687            .rev()
688            .map(|tool| (tool.name(), Arc::clone(tool)))
689            .collect();
690
691        let ordered = names(&forward);
692        assert_eq!(ordered, names(&reversed));
693
694        // pins the ordering key: the map's (unique) keys, not the map's iteration order
695        let mut expected: Vec<String> = forward.keys().cloned().collect();
696        expected.sort();
697        assert_eq!(ordered, expected);
698    }
699
700    #[test]
701    fn floor_char_boundary_handles_end_and_past_end() {
702        // pos beyond the end must not panic and clamps to len (the end is a valid boundary).
703        assert_eq!(floor_char_boundary("héllo", 100), "héllo".len());
704        assert_eq!(floor_char_boundary("abc", 3), 3);
705        assert_eq!(floor_char_boundary("", 5), 0);
706        // 'é' occupies bytes 1..=2; pos 2 is mid-character and floors back to its start (1).
707        assert_eq!(floor_char_boundary("héllo", 2), 1);
708        assert_eq!(floor_char_boundary("héllo", 1), 1);
709    }
710
711    /// Mirror the two gates GitTool applies: subcommand allowlist, then read-only argument check.
712    fn check(cmd: &str) -> Result<(), String> {
713        let tokens: Vec<&str> = cmd.split_whitespace().collect();
714        let (sub, rest) = tokens.split_first().expect("non-empty command");
715        if !ALLOWED_GIT_SUBCOMMANDS.contains(sub) {
716            return Err(format!("subcommand '{sub}' not allowed"));
717        }
718        ensure_readonly_git(sub, rest)
719    }
720
721    #[test]
722    fn rejects_output_file_write() {
723        // --output / -o turn a read-only command into a write-anywhere primitive
724        assert!(check("diff HEAD~1 --output=/tmp/evil").is_err());
725        assert!(check("diff --output ../escape.txt HEAD~1").is_err());
726        assert!(check("log --oneline -o /tmp/x").is_err());
727        assert!(check("show -o/tmp/glued HEAD").is_err());
728        assert!(check("diff --out=/tmp/abbrev HEAD~1").is_err()); // long-option abbreviation
729    }
730
731    #[test]
732    fn allows_plain_read_commands() {
733        assert!(check("diff HEAD~1").is_ok());
734        assert!(check("log --oneline -n 5").is_ok());
735        assert!(check("show HEAD").is_ok());
736        assert!(check("status --porcelain").is_ok());
737        // --oneline must not be mistaken for the -o output flag
738        assert!(check("log --oneline").is_ok());
739        // -o is a write flag only on diff/log/show; on ls-files it means --others (read-only)
740        assert!(check("ls-files -o --exclude-standard").is_ok());
741        assert!(check("ls-files --others").is_ok());
742        // refs, ranges, and in-repo pathspecs must survive the path-escape guard
743        assert!(check("diff --stat HEAD~1 -- src/foo.rs").is_ok());
744        assert!(check("log origin/main..HEAD").is_ok());
745        assert!(check("blame -- src/foo.rs").is_ok());
746        assert!(check("blame --ignore-rev HEAD -- src/foo.rs").is_ok());
747        assert!(check("blame --ignore-rev=HEAD -- src/foo.rs").is_ok());
748        assert!(check("show HEAD:src/foo.rs").is_ok());
749        assert!(check("show v:src/foo.rs").is_ok());
750        assert!(check("diff HEAD -- ./src").is_ok());
751        assert!(check(r"diff HEAD -- src\foo.rs").is_ok());
752    }
753
754    #[test]
755    fn rejects_arbitrary_file_read() {
756        // diff --no-index / blame --contents read straight from the filesystem, bypassing the
757        // canonicalize sandbox that read_file/grep/glob enforce.
758        assert!(check("diff --no-index /etc/passwd /dev/null").is_err());
759        assert!(check("diff --no-i /etc/passwd /dev/null").is_err()); // abbreviation
760        assert!(check("diff --no-index a b").is_err()); // flag denied even with relative paths
761        assert!(check("blame --contents /etc/passwd -- a.txt").is_err());
762        assert!(check("blame --contents=/etc/passwd -- a.txt").is_err());
763        assert!(check("blame --contents secret.txt -- a.txt").is_err());
764        // absolute paths and `..` traversal are rejected on any subcommand
765        assert!(check("diff /etc/passwd").is_err());
766        assert!(check("log -- ../../../etc/passwd").is_err());
767        assert!(check("show ../outside").is_err());
768        assert!(check("diff HEAD -- a/../../../etc/passwd").is_err());
769    }
770
771    #[test]
772    fn rejects_windows_style_path_escapes() {
773        assert!(check(r"diff C:\Users\victim\secret").is_err());
774        assert!(check(r"diff C:/Users/victim\secret").is_err());
775        assert!(check(r"diff \\server\share\secret").is_err());
776        assert!(check(r"log -- ..\secret").is_err());
777        assert!(check(r"show a\..\secret").is_err());
778    }
779
780    #[test]
781    fn rejects_blame_revision_file_reads() {
782        assert!(check("blame --ignore-revs-file README.md -- src/tools.rs").is_err());
783        assert!(check("blame --ignore-revs-file=README.md -- src/tools.rs").is_err());
784        assert!(check("blame --ignore-revs README.md -- src/tools.rs").is_err());
785        assert!(check("blame --ignore-revs-f=README.md -- src/tools.rs").is_err());
786    }
787
788    #[tokio::test]
789    async fn read_file_invalid_utf8_reports_text_only_feedback() {
790        let dir = tempfile::tempdir().unwrap();
791        std::fs::write(dir.path().join("bin.dat"), [0xff, 0xfe]).unwrap();
792        let work_dir = dir.path().canonicalize().unwrap();
793
794        let err = ReadFileTool
795            .call(json!({ "path": "bin.dat" }), work_dir)
796            .await
797            .unwrap_err()
798            .to_string();
799
800        assert_eq!(
801            err,
802            "file is not valid UTF-8; read_file only supports text files"
803        );
804    }
805
806    #[tokio::test]
807    async fn binary_probe_checks_only_the_first_8_kib() {
808        let dir = tempfile::tempdir().unwrap();
809
810        let nul_early = dir.path().join("early.bin");
811        std::fs::write(&nul_early, b"head\0tail").unwrap();
812        assert!(is_binary_file(&nul_early).await.unwrap());
813
814        let text = dir.path().join("text.txt");
815        std::fs::write(&text, "plain text").unwrap();
816        assert!(!is_binary_file(&text).await.unwrap());
817
818        // the probe window is the first 8 KiB only; a NUL past it does not flag the file
819        let nul_late = dir.path().join("late.txt");
820        let mut bytes = vec![b'x'; 8192];
821        bytes.push(0);
822        std::fs::write(&nul_late, &bytes).unwrap();
823        assert!(!is_binary_file(&nul_late).await.unwrap());
824    }
825
826    /// grep probes the first 8 KiB from the same handle it then keeps reading, splicing the
827    /// sample back in front of the remainder. Losing the sample breaks a match that straddles
828    /// the boundary; duplicating it doubles a line inside the window; not continuing past the
829    /// probe loses later matches.
830    #[tokio::test]
831    async fn grep_reassembles_the_probe_sample_without_loss_or_duplication() {
832        let dir = tempfile::tempdir().unwrap();
833        let work_dir = dir.path().canonicalize().unwrap();
834
835        let mut content = String::from("EARLY marker line\n");
836        content.push_str(&"a".repeat(8188 - content.len()));
837        content.push_str("STRADDLE"); // bytes 8188..8196 span the 8192 probe boundary
838        content.push_str("\nBEYOND the probe window\n");
839        let path = work_dir.join("big.txt");
840        std::fs::write(&path, &content).unwrap();
841
842        for (pattern, why) in [
843            ("EARLY", "a duplicated sample would match this line twice"),
844            (
845                "STRADDLE",
846                "a lost sample would break the boundary-straddling match",
847            ),
848            ("BEYOND", "the same handle must keep reading past the probe"),
849        ] {
850            let regex = Regex::new(pattern).unwrap();
851            let mut results = Vec::new();
852            search_file(&path, &regex, &work_dir, &mut results)
853                .await
854                .unwrap();
855            assert_eq!(results.len(), 1, "{pattern}: {why}");
856        }
857    }
858
859    #[tokio::test]
860    async fn grep_skips_binary_files_silently() {
861        let dir = tempfile::tempdir().unwrap();
862        let work_dir = dir.path().canonicalize().unwrap();
863        let path = work_dir.join("bin.dat");
864        std::fs::write(&path, b"match\0me").unwrap();
865
866        let regex = Regex::new("match").unwrap();
867        let mut results = Vec::new();
868        search_file(&path, &regex, &work_dir, &mut results)
869            .await
870            .unwrap();
871        assert!(results.is_empty());
872    }
873
874    #[test]
875    fn rejects_branch_and_tag_porcelain() {
876        // branch/tag conflate read and write and are not on the allowlist at all; ref listing must
877        // go through the for-each-ref/show-ref plumbing instead.
878        assert!(check("branch -D some-branch").is_err());
879        assert!(check("branch new-branch").is_err());
880        assert!(check("branch --set-upstream-to=origin/main").is_err());
881        assert!(check("branch -- newbranch").is_err());
882        assert!(check("tag v9.9.9").is_err());
883        assert!(check("tag -d v1").is_err());
884        // even pure listing forms are rejected — the model is steered to for-each-ref
885        assert!(check("branch --list").is_err());
886    }
887
888    #[test]
889    fn reflect_tools_is_all_tools_minus_git() {
890        use std::collections::HashSet;
891        let all: HashSet<String> = super::all_tools().into_keys().collect();
892        let reflect: HashSet<String> = super::reflect_tools().into_keys().collect();
893        assert!(all.contains("git"));
894        // Exact set equality pins the derivation: any tool added to all_tools() that isn't git must
895        // also appear in reflect_tools(), or this fails.
896        let expected: HashSet<String> = all.iter().filter(|k| *k != "git").cloned().collect();
897        assert_eq!(reflect, expected);
898    }
899
900    #[test]
901    fn allows_readonly_ref_plumbing() {
902        // for-each-ref / show-ref have no ref-creating mode, so any arg shape is safe.
903        assert!(check("for-each-ref refs/heads/").is_ok());
904        assert!(check("for-each-ref --contains HEAD refs/heads/").is_ok());
905        assert!(check("for-each-ref --format=%(refname) --sort=-creatordate").is_ok());
906        assert!(check("show-ref --tags").is_ok());
907        assert!(check("show-ref --heads").is_ok());
908        // for-each-ref/show-ref have no --output flag, so git itself rejects a write attempt; our
909        // layer doesn't need to gate them (the --output block is scoped to diff/log/show).
910    }
911}