Skip to main content

tinyharness_lib/tools/
mod.rs

1pub mod auto_compact;
2pub mod edit;
3pub mod glob;
4pub mod grep;
5pub mod invoke_skill;
6pub mod ls;
7pub mod question;
8pub mod read;
9pub mod run;
10pub mod switch_mode;
11pub mod tool;
12pub mod write;
13
14use crate::mode::AgentMode;
15use crate::provider::ToolDefinition;
16use crate::sandbox::Sandbox;
17use crate::tools::tool::{Tool, ToolCategory};
18
19/// Events emitted by signal-category tools that the caller must interpret.
20/// These tools return a result string, but the caller should parse these
21/// into structured events for proper handling (e.g., prompting the user,
22/// switching mode, triggering compaction).
23#[derive(Debug, Clone)]
24pub enum SignalEvent {
25    /// The model requests a mode switch.
26    SwitchMode { mode: AgentMode },
27    /// The model asks the user a question with options.
28    Question {
29        question: String,
30        answers: Vec<String>,
31    },
32    /// The model requests conversation compaction.
33    AutoCompact { focus: String },
34    /// The model requests invocation of a skill by name.
35    InvokeSkill { skill_name: String },
36}
37
38/// Controls which optional tools are advertised to the model.
39///
40/// Tools disabled here are filtered out of [`ToolManager::tools_for_mode`],
41/// so the model never sees them and cannot call them. All flags default to
42/// `true` — opt out explicitly.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub struct ToolAvailability {
45    /// Whether the model may request conversation compaction (`auto_compact`).
46    pub auto_compact: bool,
47    /// Whether the model may ask the user multiple-choice questions (`question`).
48    pub question: bool,
49}
50
51impl Default for ToolAvailability {
52    fn default() -> Self {
53        Self::all()
54    }
55}
56
57impl ToolAvailability {
58    /// Every optional tool available (the default).
59    pub fn all() -> Self {
60        ToolAvailability {
61            auto_compact: true,
62            question: true,
63        }
64    }
65
66    /// Whether the named tool is available under this configuration.
67    /// Tools not listed here are always available.
68    pub fn allows(&self, tool_name: &str) -> bool {
69        match tool_name {
70            "auto_compact" => self.auto_compact,
71            "question" => self.question,
72            _ => true,
73        }
74    }
75}
76
77#[derive(Default)]
78pub struct ToolManager {
79    tools: Vec<Tool>,
80    /// Confines the built-in file tools to the workspace (see
81    /// [`PathGuard`]). Always set by the binary; `None` means no containment,
82    /// which is only sensible in tests.
83    path_guard: Option<crate::path_guard::PathGuard>,
84    /// OS-level sandbox for shell-executing tools. Cloned into each shell
85    /// tool's handler at registration time.
86    sandbox: Option<Sandbox>,
87}
88
89impl ToolManager {
90    pub fn new() -> Self {
91        Self::default()
92    }
93
94    /// Confine the built-in file tools (`ls`, `read`, `write`, `edit`,
95    /// `grep`, `glob`) to the paths the guard allows.
96    ///
97    /// **Must be called before** [`ToolManager::register_defaults`]: the
98    /// guard is checked in [`ToolManager::execute_tool_call`] *and* cloned
99    /// into the `ls`/`read`/`write`/`edit` handlers, which verify the opened
100    /// file descriptor against it (closing the check-then-open race).
101    pub fn set_path_guard(&mut self, guard: crate::path_guard::PathGuard) {
102        self.path_guard = Some(guard);
103    }
104
105    /// The active path guard, if any.
106    pub fn path_guard(&self) -> Option<&crate::path_guard::PathGuard> {
107        self.path_guard.as_ref()
108    }
109
110    /// Enable the OS-level sandbox for `run` and custom tools.
111    ///
112    /// **Must be called before** [`register_defaults`] and
113    /// [`register_custom_tools`]: tool handlers are opaque closures, so the
114    /// sandbox is cloned into them at construction. Setting it afterwards
115    /// leaves the already-registered tools unsandboxed.
116    ///
117    /// [`register_defaults`]: ToolManager::register_defaults
118    /// [`register_custom_tools`]: ToolManager::register_custom_tools
119    pub fn set_sandbox(&mut self, sandbox: Sandbox) {
120        self.sandbox = Some(sandbox);
121    }
122
123    /// The active process sandbox, if any.
124    pub fn sandbox(&self) -> Option<&Sandbox> {
125        self.sandbox.as_ref()
126    }
127
128    /// Validate a tool call's path arguments against the guard and return
129    /// arguments with every path **replaced by its resolved absolute form**.
130    ///
131    /// Substitution is the point: a handler that received the raw string would
132    /// resolve a relative path against the *process* cwd, while the guard
133    /// resolved it against the *workspace root*. Those coincide only when the
134    /// harness happens to be started in the workspace, so checking one and
135    /// opening the other leaves the containment purely incidental.
136    ///
137    /// Returns `Err(violation_message)` when the guard rejects a path, or the
138    /// arguments unchanged when no guard is active.
139    pub fn guard_arguments(
140        &self,
141        tool_name: &str,
142        arguments: &serde_json::Value,
143    ) -> Result<serde_json::Value, String> {
144        match self.path_guard.as_ref() {
145            Some(guard) => resolve_tool_args_guarded(guard, tool_name, arguments),
146            None => Ok(arguments.clone()),
147        }
148    }
149
150    /// Confine a `glob` result to the guard's roots, line by line.
151    ///
152    /// Validating the pattern's static prefix is not sufficient: the `glob`
153    /// crate descends into symlinked directories, so `**/*.env` lists
154    /// `<root>/link/canary.env` — and thus whatever is really under
155    /// `/outside` — even though every argument was in bounds. Filtering the
156    /// *results* through the guard is what confines the tool.
157    ///
158    /// Non-path lines (the "no files found" and truncation notices) resolve
159    /// under the workspace root and so survive; only paths a symlink carried
160    /// the walker out to are dropped.
161    fn filter_glob_output(&self, result: String) -> String {
162        let Some(guard) = self.path_guard.as_ref() else {
163            return result;
164        };
165        let kept: Vec<&str> = result
166            .lines()
167            .filter(|line| guard.resolve_contained(line).is_ok())
168            .collect();
169        if kept.len() == result.lines().count() {
170            return result;
171        }
172        if kept.is_empty() {
173            return "No files found matching pattern (all matches resolved outside the workspace)"
174                .to_string();
175        }
176        kept.join("\n")
177    }
178
179    /// Register all built-in tools.
180    pub fn register_defaults(&mut self) {
181        let sandbox = self.sandbox.clone();
182        // The file tools get the guard cloned in so they can verify the
183        // *opened* descriptor, not just the argument (see
184        // `PathGuard::open_read_contained`). Set the guard before this call.
185        let guard = self.path_guard.clone();
186        self.register_tool(crate::tools::auto_compact::auto_compact_tool_entry());
187        self.register_tool(crate::tools::ls::ls_tool_entry(guard.clone()));
188        self.register_tool(crate::tools::read::read_tool_entry(guard.clone()));
189        self.register_tool(crate::tools::write::write_tool_entry(guard.clone()));
190        self.register_tool(crate::tools::edit::edit_tool_entry(guard));
191        self.register_tool(crate::tools::grep::grep_tool_entry());
192        self.register_tool(crate::tools::run::run_tool_entry(sandbox));
193        self.register_tool(crate::tools::glob::glob_tool_entry());
194        self.register_tool(crate::tools::switch_mode::switch_mode_tool_entry());
195        self.register_tool(crate::tools::question::question_tool_entry());
196        self.register_tool(crate::tools::invoke_skill::invoke_skill_tool_entry());
197    }
198
199    pub fn register_tool(&mut self, tool: Tool) {
200        self.tools.push(tool);
201    }
202
203    /// Register custom tools from [`crate::custom_tools::CustomToolManager`].
204    /// Tools whose names collide with built-in tools are silently skipped.
205    pub fn register_custom_tools(&mut self, tools: &[crate::custom_tools::CustomToolDefinition]) {
206        let existing: std::collections::HashSet<String> =
207            self.tools.iter().map(|t| t.name.clone()).collect();
208        let sandbox = self.sandbox.clone();
209        for def in tools {
210            if existing.contains(&def.name) {
211                tracing::warn!(
212                    "Custom tool '{}' collides with an existing tool — skipping",
213                    def.name
214                );
215                continue;
216            }
217            match def.build_tool_with_sandbox(sandbox.clone()) {
218                Ok(tool) => self.register_tool(tool),
219                Err(e) => tracing::warn!("Failed to register custom tool '{}': {}", def.name, e),
220            }
221        }
222    }
223
224    /// Returns the tool definitions for all registered tools.
225    pub fn get_all_tool_definitions(&self) -> Vec<ToolDefinition> {
226        self.tools.iter().map(|t| t.to_definition()).collect()
227    }
228
229    /// Returns the tool definitions appropriate for the given agent mode.
230    ///
231    /// Tools disabled in `availability` (e.g. `auto_compact`, `question`) are
232    /// excluded, so the model never sees them.
233    pub fn tools_for_mode(
234        &self,
235        mode: AgentMode,
236        availability: ToolAvailability,
237    ) -> Vec<ToolDefinition> {
238        let is_available = |t: &&Tool| availability.allows(&t.name);
239        match mode {
240            AgentMode::Agent => self
241                .tools
242                .iter()
243                .filter(is_available)
244                .map(|t| t.to_definition())
245                .collect(),
246            // Casual mode is pure chat — no tools are advertised.
247            AgentMode::Casual => Vec::new(),
248            // Planning mode: read-only + signal tools only.
249            AgentMode::Planning => self
250                .tools
251                .iter()
252                .filter(|t| {
253                    is_available(t)
254                        && (t.category == ToolCategory::ReadOnly
255                            || t.category == ToolCategory::Signal)
256                })
257                .map(|t| t.to_definition())
258                .collect(),
259        }
260    }
261
262    /// Returns the category of a tool by name, or `None` if not found.
263    pub fn category_of(&self, tool_name: &str) -> Option<ToolCategory> {
264        self.tools
265            .iter()
266            .find(|t| t.name == tool_name)
267            .map(|t| t.category)
268    }
269
270    /// Returns `true` if the tool requires user approval before execution.
271    /// Destructive tools (write, edit, run) and signal tools (switch_mode,
272    /// question, auto_compact) require approval.
273    pub fn needs_approval(&self, tool_name: &str) -> bool {
274        self.category_of(tool_name)
275            .map(|c| c == ToolCategory::Destructive || c == ToolCategory::Signal)
276            .unwrap_or(false)
277    }
278
279    /// Returns `true` if the tool is a signal tool (switch_mode, question, auto_compact).
280    /// Signal tools are handled specially by the agent loop rather than executed generically.
281    pub fn is_signal_tool(&self, tool_name: &str) -> bool {
282        self.category_of(tool_name) == Some(ToolCategory::Signal)
283    }
284
285    /// Parse a signal tool's result string into a structured `SignalEvent`.
286    ///
287    /// Signal tools return plain strings, but the agent loop needs structured
288    /// data to dispatch them correctly. This method interprets the tool call
289    /// arguments (not the result string) to produce the appropriate event.
290    ///
291    /// Returns `None` if the tool is not a signal tool or the arguments are invalid.
292    pub fn parse_signal_event(
293        &self,
294        tool_name: &str,
295        arguments: &serde_json::Value,
296    ) -> Option<SignalEvent> {
297        match tool_name {
298            "switch_mode" => {
299                let mode_str = arguments.get("mode").and_then(|v| v.as_str()).unwrap_or("");
300                mode_str
301                    .parse::<AgentMode>()
302                    .ok()
303                    .map(|mode| SignalEvent::SwitchMode { mode })
304            }
305            "question" => {
306                let question = arguments
307                    .get("question")
308                    .and_then(|v| v.as_str())
309                    .unwrap_or("")
310                    .to_string();
311                let answers: Vec<String> = arguments
312                    .get("answers")
313                    .and_then(|v| v.as_array())
314                    .map(|arr| {
315                        arr.iter()
316                            .filter_map(|item| item.as_str().map(|s| s.to_string()))
317                            .collect()
318                    })
319                    .unwrap_or_default();
320                Some(SignalEvent::Question { question, answers })
321            }
322            "auto_compact" => {
323                let focus = arguments
324                    .get("focus")
325                    .and_then(|v| v.as_str())
326                    .unwrap_or("")
327                    .to_string();
328                Some(SignalEvent::AutoCompact { focus })
329            }
330            "invoke_skill" => {
331                let skill_name = arguments
332                    .get("skill_name")
333                    .and_then(|v| v.as_str())
334                    .unwrap_or("")
335                    .to_string();
336                if skill_name.is_empty() {
337                    None
338                } else {
339                    Some(SignalEvent::InvokeSkill { skill_name })
340                }
341            }
342            _ => None,
343        }
344    }
345
346    pub async fn execute_tool_call(
347        &self,
348        tool_name: &str,
349        arguments: &serde_json::Value,
350    ) -> String {
351        // Path containment: reject any tool call that would touch a path
352        // outside the allowed roots, and hand the handler the *resolved*
353        // paths. This happens before the tool handler runs, so it applies
354        // regardless of auto-accept mode.
355        let arguments = match self.guard_arguments(tool_name, arguments) {
356            Ok(args) => args,
357            Err(error) => return error,
358        };
359
360        let Some(tool) = self.tools.iter().find(|t| t.name == tool_name) else {
361            return format!("Error: Tool '{}' not found", tool_name);
362        };
363
364        let result = tool::execute_tool_call(tool, &arguments).await;
365        if tool_name == "glob" {
366            self.filter_glob_output(result)
367        } else {
368            result
369        }
370    }
371}
372
373/// Resolve a tool call's path arguments against the guard.
374///
375/// Path-bearing tools (`ls`, `read`, `write`, `edit`, `grep`, `glob`) have
376/// their path/pattern arguments resolved, and the resolved absolute form is
377/// **substituted into the arguments** the handler receives. The `run` tool's
378/// explicit `cwd` is resolved too — not because a sandboxed shell could
379/// escape (it couldn't; the directory simply would not exist in the mount
380/// tree), but so the model gets a clear containment error instead of a
381/// confusing `No such file or directory`.
382///
383/// Returns `Err(violation)` if any path is outside the allowed roots, or the
384/// arguments with paths rewritten to absolute form.
385fn resolve_tool_args_guarded(
386    guard: &crate::path_guard::PathGuard,
387    tool_name: &str,
388    arguments: &serde_json::Value,
389) -> Result<serde_json::Value, String> {
390    let arg_str = |name: &str| -> Option<String> {
391        arguments
392            .get(name)
393            .and_then(|v| v.as_str())
394            .map(|s| s.to_string())
395    };
396    let mut out = arguments.clone();
397    let Some(map) = out.as_object_mut() else {
398        return Ok(out);
399    };
400
401    let mut resolve_into = |key: &str, value: String| -> Result<(), String> {
402        let resolved = guard.resolve_contained(&value)?;
403        map.insert(
404            key.to_string(),
405            serde_json::Value::String(resolved.to_string_lossy().into_owned()),
406        );
407        Ok(())
408    };
409
410    match tool_name {
411        // Tools with a required "path" argument.
412        "ls" | "read" | "write" | "edit" => {
413            let path = arg_str("path").unwrap_or_default();
414            resolve_into("path", path)?;
415        }
416        // grep: optional "path" directory argument (defaults to the workspace root).
417        "grep" => {
418            let path = arg_str("path").unwrap_or_else(|| ".".to_string());
419            resolve_into("path", path)?;
420        }
421        // glob: only the pattern's static prefix can be checked, so it is the
422        // prefix that gets resolved and spliced back in — the wildcards are
423        // not paths. Results are filtered separately (see
424        // [`ToolManager::filter_glob_output`]), because the glob walker
425        // follows symlinks.
426        "glob" => {
427            let pattern = arg_str("pattern").unwrap_or_default();
428            let base = crate::path_guard::glob_static_prefix(&pattern);
429            let resolved = guard.resolve_contained(base)?;
430            let resolved_str = resolved.to_string_lossy().into_owned();
431            // Re-attach the wildcard tail. A pattern whose prefix is "." was
432            // anchored at the working directory, so the whole pattern hangs
433            // off the resolved root.
434            let tail = match pattern.strip_prefix(base) {
435                Some(rest) if base != "." => rest.to_string(),
436                _ => pattern.clone(),
437            };
438            let rewritten = if tail.starts_with('/') {
439                format!("{resolved_str}{tail}")
440            } else {
441                format!("{resolved_str}/{tail}")
442            };
443            map.insert("pattern".to_string(), serde_json::Value::String(rewritten));
444        }
445        // run: only the explicit "cwd" can be checked statically.
446        "run" => {
447            if let Some(cwd) = arg_str("cwd").filter(|s| !s.trim().is_empty()) {
448                resolve_into("cwd", cwd)?;
449            }
450        }
451        // All other tools (signal tools, custom tools without a known path
452        // arg) are not subject to path containment.
453        _ => {}
454    }
455
456    Ok(out)
457}
458
459#[cfg(all(test, unix))]
460mod tests {
461    use super::*;
462    use std::path::Path;
463
464    use crate::path_guard::PathGuard;
465
466    /// Manager with a path guard rooted at `root` and no process sandbox —
467    /// the shape the binary uses on platforms without bwrap/firejail.
468    fn guarded_manager(root: &std::path::Path) -> ToolManager {
469        let mut manager = ToolManager::new();
470        manager.set_path_guard(PathGuard::new(root).unwrap());
471        manager.register_defaults();
472        manager
473    }
474
475    #[tokio::test]
476    async fn guard_blocks_read_outside_root() {
477        let tmp = tempfile::tempdir().unwrap();
478        let manager = guarded_manager(tmp.path());
479        let result = manager
480            .execute_tool_call("read", &serde_json::json!({"path": "/etc/passwd"}))
481            .await;
482        assert!(result.starts_with("Error: Path '"), "result was: {result}");
483        assert!(result.contains("/etc/passwd"), "result was: {result}");
484    }
485
486    #[tokio::test]
487    async fn guard_blocks_write_outside_root() {
488        let tmp = tempfile::tempdir().unwrap();
489        let manager = guarded_manager(tmp.path());
490        let target = tmp.path().join("../escape.txt");
491        let result = manager
492            .execute_tool_call(
493                "write",
494                &serde_json::json!({"path": target.to_str().unwrap(), "content": "x"}),
495            )
496            .await;
497        assert!(result.starts_with("Error: Path '"), "result was: {result}");
498        // Verify the file was NOT created
499        assert!(!target.exists());
500    }
501
502    #[tokio::test]
503    async fn guard_allows_write_inside_root() {
504        let tmp = tempfile::tempdir().unwrap();
505        let manager = guarded_manager(tmp.path());
506        let target = tmp.path().join("ok.txt");
507        let result = manager
508            .execute_tool_call(
509                "write",
510                &serde_json::json!({"path": target.to_str().unwrap(), "content": "hello"}),
511            )
512            .await;
513        assert!(result.starts_with("Wrote"), "result was: {result}");
514        assert_eq!(std::fs::read_to_string(&target).unwrap(), "hello");
515    }
516
517    #[tokio::test]
518    async fn guard_blocks_ls_outside_root() {
519        let tmp = tempfile::tempdir().unwrap();
520        let manager = guarded_manager(tmp.path());
521        let result = manager
522            .execute_tool_call("ls", &serde_json::json!({"path": "/"}))
523            .await;
524        assert!(result.starts_with("Error: Path '"), "result was: {result}");
525    }
526
527    #[tokio::test]
528    async fn guard_blocks_grep_outside_root() {
529        let tmp = tempfile::tempdir().unwrap();
530        let manager = guarded_manager(tmp.path());
531        let result = manager
532            .execute_tool_call("grep", &serde_json::json!({"pattern": "x", "path": "/tmp"}))
533            .await;
534        assert!(result.starts_with("Error: Path '"), "result was: {result}");
535    }
536
537    #[tokio::test]
538    async fn guard_blocks_glob_outside_root() {
539        let tmp = tempfile::tempdir().unwrap();
540        let manager = guarded_manager(tmp.path());
541        let result = manager
542            .execute_tool_call("glob", &serde_json::json!({"pattern": "/etc/**/*"}))
543            .await;
544        assert!(result.starts_with("Error: Path '"), "result was: {result}");
545    }
546
547    #[tokio::test]
548    async fn guard_allows_relative_glob() {
549        let tmp = tempfile::tempdir().unwrap();
550        std::fs::write(tmp.path().join("a.rs"), "fn main() {}").unwrap();
551        let manager = guarded_manager(tmp.path());
552        let result = manager
553            .execute_tool_call("glob", &serde_json::json!({"pattern": "**/*.rs"}))
554            .await;
555        assert!(result.contains("a.rs"), "result was: {result}");
556    }
557
558    #[tokio::test]
559    async fn guard_blocks_run_with_outside_cwd() {
560        let tmp = tempfile::tempdir().unwrap();
561        let manager = guarded_manager(tmp.path());
562        let result = manager
563            .execute_tool_call("run", &serde_json::json!({"command": "pwd", "cwd": "/"}))
564            .await;
565        assert!(result.starts_with("Error: Path '"), "result was: {result}");
566    }
567
568    #[tokio::test]
569    async fn guard_allows_run_without_cwd() {
570        let tmp = tempfile::tempdir().unwrap();
571        let manager = guarded_manager(tmp.path());
572        let result = manager
573            .execute_tool_call("run", &serde_json::json!({"command": "echo hi"}))
574            .await;
575        assert!(result.contains("hi"), "result was: {result}");
576    }
577
578    #[tokio::test]
579    async fn guard_does_not_affect_non_path_tools() {
580        let tmp = tempfile::tempdir().unwrap();
581        let manager = guarded_manager(tmp.path());
582        // switch_mode tool has no path arg — should not be blocked
583        let result = manager
584            .execute_tool_call("switch_mode", &serde_json::json!({"mode": "agent"}))
585            .await;
586        assert!(!result.starts_with("Error: Path '"), "result was: {result}");
587    }
588
589    #[tokio::test]
590    async fn no_guard_allows_everything() {
591        let tmp = tempfile::tempdir().unwrap();
592        let mut manager = ToolManager::new();
593        manager.register_defaults();
594        // Without a guard, reading an arbitrary temp dir works.
595        let result = manager
596            .execute_tool_call(
597                "ls",
598                &serde_json::json!({"path": tmp.path().to_str().unwrap()}),
599            )
600            .await;
601        assert!(!result.starts_with("Error: Path '"), "result was: {result}");
602    }
603
604    #[tokio::test]
605    async fn guard_rejects_symlink_escape_through_tools() {
606        let tmp = tempfile::tempdir().unwrap();
607        let outside = tempfile::tempdir().unwrap();
608        std::fs::write(outside.path().join("secret.txt"), "top secret").unwrap();
609        std::os::unix::fs::symlink(outside.path(), tmp.path().join("link")).unwrap();
610
611        let manager = guarded_manager(tmp.path());
612        let result = manager
613            .execute_tool_call(
614                "read",
615                &serde_json::json!({"path": format!("{}/link/secret.txt", tmp.path().display())}),
616            )
617            .await;
618        assert!(result.starts_with("Error: Path '"), "result was: {result}");
619        assert!(!result.contains("top secret"), "leaked: {result}");
620    }
621
622    /// A symlink plus `..` must not reach outside the root: the guard used to
623    /// normalize `..` lexically (collapsing `<root>/link/../etc/passwd` to
624    /// `<root>/etc/passwd`, in bounds) while the kernel resolved the symlink
625    /// first and opened `/etc/passwd`.
626    #[tokio::test]
627    async fn guard_blocks_symlink_dotdot_read() {
628        let tmp = tempfile::tempdir().unwrap();
629        std::os::unix::fs::symlink(Path::new("/usr"), tmp.path().join("link")).unwrap();
630        let manager = guarded_manager(tmp.path());
631
632        let raw = format!("{}/link/../etc/passwd", tmp.path().display());
633        let result = manager
634            .execute_tool_call("read", &serde_json::json!({"path": raw}))
635            .await;
636        assert!(result.starts_with("Error: Path '"), "result was: {result}");
637        assert!(!result.contains("nologin"), "leaked /etc/passwd: {result}");
638    }
639
640    /// Same shape, but for a write: previously the payload landed outside the
641    /// workspace while the guard believed it had authorized `<root>/x`.
642    #[tokio::test]
643    async fn guard_blocks_symlink_dotdot_write() {
644        let tmp = tempfile::tempdir().unwrap();
645        let outside = tempfile::tempdir().unwrap();
646        let sub = outside.path().join("sub");
647        std::fs::create_dir_all(&sub).unwrap();
648        std::os::unix::fs::symlink(&sub, tmp.path().join("link")).unwrap();
649
650        let manager = guarded_manager(tmp.path());
651        let raw = format!("{}/link/../dropped.txt", tmp.path().display());
652        let _ = manager
653            .execute_tool_call("write", &serde_json::json!({"path": raw, "content": "PWN"}))
654            .await;
655
656        assert!(
657            !outside.path().join("dropped.txt").exists(),
658            "wrote outside the workspace via symlink+.."
659        );
660    }
661
662    /// The guard resolves a relative path against the workspace root, so the
663    /// handler must receive that resolved path — not the raw string, which
664    /// `std::fs` would resolve against the *process* cwd. Those coincide only
665    /// when the harness is started inside the workspace, so a relative
666    /// `write("victim.txt")` could otherwise clobber a file next to the cwd
667    /// while the guard believed it had authorized `<root>/victim.txt`.
668    #[tokio::test]
669    async fn guard_substitutes_resolved_path_for_relative_args() {
670        let tmp = tempfile::tempdir().unwrap();
671        let manager = guarded_manager(tmp.path());
672
673        // The resolved argument is absolute and rooted at the workspace, which
674        // is what makes the handler's `fs::write` land in a predictable place.
675        let args = manager
676            .guard_arguments(
677                "write",
678                &serde_json::json!({"path": "victim.txt", "content": "x"}),
679            )
680            .unwrap();
681        let path = args.get("path").and_then(|v| v.as_str()).unwrap();
682        assert!(
683            Path::new(path).is_absolute(),
684            "handler still got a relative path: {path}"
685        );
686        assert_eq!(
687            Path::new(path),
688            tmp.path().canonicalize().unwrap().join("victim.txt")
689        );
690
691        // End-to-end: the file lands in the workspace, wherever the test binary
692        // happens to have been started from.
693        let result = manager
694            .execute_tool_call(
695                "write",
696                &serde_json::json!({"path": "victim.txt", "content": "OVERWRITTEN"}),
697            )
698            .await;
699        assert!(result.starts_with("Wrote"), "result was: {result}");
700        assert_eq!(
701            std::fs::read_to_string(tmp.path().join("victim.txt")).unwrap(),
702            "OVERWRITTEN"
703        );
704    }
705
706    /// `grep` walks a directory tree, so checking only its root argument is
707    /// not containment: the walker used to descend into symlinked directories
708    /// and copy outside content straight into the model's context.
709    #[tokio::test]
710    async fn grep_does_not_follow_symlinked_dirs() {
711        let tmp = tempfile::tempdir().unwrap();
712        let outside = tempfile::tempdir().unwrap();
713        std::fs::write(outside.path().join("leak.txt"), "CANARY-CONTENT\n").unwrap();
714        std::os::unix::fs::symlink(outside.path(), tmp.path().join("link")).unwrap();
715        std::fs::write(tmp.path().join("local.txt"), "CANARY-CONTENT\n").unwrap();
716
717        let manager = guarded_manager(tmp.path());
718        let result = manager
719            .execute_tool_call(
720                "grep",
721                &serde_json::json!({"pattern": "CANARY-CONTENT", "path": tmp.path()}),
722            )
723            .await;
724        assert!(
725            result.contains("local.txt"),
726            "missed the in-tree file: {result}"
727        );
728        assert!(
729            !result.contains("link/leak.txt"),
730            "grep followed a symlink outside the workspace: {result}"
731        );
732    }
733
734    /// `glob` only has a *pattern* to check, and the pattern's static prefix
735    /// passing the guard says nothing about where the walker ends up. Results
736    /// reached through a symlink must be filtered out.
737    #[tokio::test]
738    async fn glob_results_are_confined_to_the_workspace() {
739        let tmp = tempfile::tempdir().unwrap();
740        let outside = tempfile::tempdir().unwrap();
741        std::fs::write(outside.path().join("canary.env"), "A=1\n").unwrap();
742        std::os::unix::fs::symlink(outside.path(), tmp.path().join("link")).unwrap();
743        std::fs::write(tmp.path().join("local.env"), "B=2\n").unwrap();
744
745        let manager = guarded_manager(tmp.path());
746        let result = manager
747            .execute_tool_call("glob", &serde_json::json!({"pattern": "**/*.env"}))
748            .await;
749        assert!(
750            result.contains("local.env"),
751            "missed the in-tree file: {result}"
752        );
753        assert!(
754            !result.contains("canary.env"),
755            "glob listed a file outside the workspace through a symlink: {result}"
756        );
757    }
758
759    /// `glob` must keep working for ordinary in-tree patterns, including after
760    /// the pattern is rewritten to an absolute one by the guard.
761    #[tokio::test]
762    async fn glob_still_finds_in_tree_files() {
763        let tmp = tempfile::tempdir().unwrap();
764        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
765        std::fs::write(tmp.path().join("src/a.rs"), "// a").unwrap();
766        std::fs::write(tmp.path().join("src/b.rs"), "// b").unwrap();
767
768        let manager = guarded_manager(tmp.path());
769        for pattern in ["**/*.rs", "src/**/*.rs", "./src/*.rs"] {
770            let result = manager
771                .execute_tool_call("glob", &serde_json::json!({"pattern": pattern}))
772                .await;
773            assert!(
774                result.contains("a.rs") && result.contains("b.rs"),
775                "pattern {pattern:?} returned: {result}"
776            );
777        }
778    }
779
780    /// `run`'s `cwd` is resolved the same way, so a sandboxed command starts in
781    /// the directory the guard authorized rather than a raw relative string.
782    #[tokio::test]
783    async fn run_cwd_is_resolved_against_the_workspace_root() {
784        let tmp = tempfile::tempdir().unwrap();
785        std::fs::create_dir_all(tmp.path().join("sub")).unwrap();
786        let manager = guarded_manager(tmp.path());
787
788        let args = manager
789            .guard_arguments("run", &serde_json::json!({"command": "pwd", "cwd": "."}))
790            .unwrap();
791        assert_eq!(
792            args.get("cwd").and_then(|v| v.as_str()).unwrap(),
793            tmp.path().canonicalize().unwrap().to_string_lossy()
794        );
795
796        let sub = manager
797            .guard_arguments("run", &serde_json::json!({"command": "pwd", "cwd": "sub"}))
798            .unwrap();
799        assert_eq!(
800            sub.get("cwd").and_then(|v| v.as_str()).unwrap(),
801            tmp.path()
802                .canonicalize()
803                .unwrap()
804                .join("sub")
805                .to_string_lossy()
806        );
807
808        // An escaping cwd is still rejected before the handler sees it.
809        let err = manager
810            .guard_arguments(
811                "run",
812                &serde_json::json!({"command": "pwd", "cwd": "../escape"}),
813            )
814            .unwrap_err();
815        assert!(err.starts_with("Error: Path '"), "{err}");
816    }
817
818    #[tokio::test]
819    async fn guard_honours_allowed_paths() {
820        let tmp = tempfile::tempdir().unwrap();
821        let extra = tempfile::tempdir().unwrap();
822        std::fs::write(extra.path().join("note.txt"), "from allowed").unwrap();
823
824        let mut manager = ToolManager::new();
825        manager.set_path_guard(
826            PathGuard::configured(
827                tmp.path(),
828                &[extra.path().to_string_lossy().to_string()],
829                None,
830                &[],
831            )
832            .unwrap(),
833        );
834        manager.register_defaults();
835
836        let result = manager
837            .execute_tool_call(
838                "read",
839                &serde_json::json!({"path": extra.path().join("note.txt").to_str().unwrap()}),
840            )
841            .await;
842        assert!(result.contains("from allowed"), "result was: {result}");
843    }
844}