1use std::path::Path;
10use std::sync::LazyLock;
11
12use regex::Regex;
13use serde_json::Value;
14
15use crate::adapters::all_tool_vocabulary;
16
17pub fn is_write_tool(tool_name: &str) -> bool {
20 all_tool_vocabulary()
21 .write_tools
22 .iter()
23 .any(|t| t == tool_name)
24}
25
26pub fn is_patch_tool(tool_name: &str) -> bool {
29 all_tool_vocabulary()
30 .patch_tools
31 .iter()
32 .any(|t| t == tool_name)
33}
34
35pub fn is_shell_tool(tool_name: &str) -> bool {
38 all_tool_vocabulary()
39 .shell_tools
40 .iter()
41 .any(|t| t == tool_name)
42}
43
44static BASH_MUTATION_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
52 let config_dirs = crate::adapters::all_config_dir_names()
53 .iter()
54 .map(|d| regex::escape(d))
55 .collect::<Vec<_>>()
56 .join("|");
57 [
58 (
59 r"\b(npm|pnpm|yarn|bun)\s+(install|add|ci|i)\b".to_string(),
60 "package install/add",
61 ),
62 (r"\bpip3?\s+install\b".to_string(), "pip install"),
63 (r"\bsed\s+-i\b".to_string(), "in-place file edit (sed -i)"),
64 (
65 r"\bgit\s+(commit|add|push|checkout|reset|restore|merge|rebase)\b".to_string(),
66 "git mutation",
67 ),
68 (
69 r"\bgit\s+worktree\s+add\b".to_string(),
70 "git worktree add (working tree outside the sandbox)",
71 ),
72 (
78 format!(r"\b(cp|mv|mkdir|touch|ln|rsync|install)\b[^|;&\n]*({config_dirs})(/|\b)"),
79 "path under a harness config dir",
80 ),
81 (
86 r#"\b(cp|mv|mkdir|touch|ln|rsync)\b[^|;&\n]*[\s'"=/]\.{0,2}/?skills(/|\s|$)"#
87 .to_string(),
88 "creates a bare skills/ dir",
89 ),
90 (
91 r"(^|\s)(>>?|tee)\s".to_string(),
92 "output redirection to a file",
93 ),
94 ]
95 .into_iter()
96 .map(|(re, reason)| {
97 (
98 Regex::new(&re)
99 .unwrap_or_else(|e| panic!("bundled bash pattern {re:?} is invalid: {e}")),
100 reason,
101 )
102 })
103 .collect()
104});
105
106pub fn path_arg(args: &Value) -> Option<&str> {
110 let obj = args.as_object()?;
111 ["file_path", "notebook_path", "path"]
112 .iter()
113 .find_map(|k| obj.get(*k).and_then(Value::as_str))
114}
115
116pub fn apply_patch_paths(args: &Value) -> Vec<String> {
120 let mut out = Vec::new();
121 let Some(obj) = args.as_object() else {
122 return out;
123 };
124
125 if let Some(files) = obj.get("files") {
126 collect_file_values(files, &mut out);
127 }
128
129 for key in ["patch", "input", "content"] {
130 if let Some(text) = obj.get(key).and_then(Value::as_str) {
131 collect_patch_header_paths(text, &mut out);
132 }
133 }
134
135 out.sort();
136 out.dedup();
137 out
138}
139
140fn collect_file_values(value: &Value, out: &mut Vec<String>) {
141 match value {
142 Value::String(path) => out.push(path.to_string()),
143 Value::Array(items) => {
144 for item in items {
145 collect_file_values(item, out);
146 }
147 }
148 Value::Object(obj) => {
149 for key in ["file_path", "path", "absolute_file_path", "move_path"] {
150 if let Some(path) = obj.get(key).and_then(Value::as_str) {
151 out.push(path.to_string());
152 }
153 }
154 }
155 _ => {}
156 }
157}
158
159fn collect_patch_header_paths(text: &str, out: &mut Vec<String>) {
160 for line in text.lines() {
161 for prefix in [
162 "*** Add File: ",
163 "*** Update File: ",
164 "*** Delete File: ",
165 "*** Move to: ",
166 ] {
167 if let Some(path) = line.strip_prefix(prefix) {
168 let path = path.trim();
169 if !path.is_empty() {
170 out.push(path.to_string());
171 }
172 }
173 }
174 }
175}
176
177fn absolutize(target: &str, repo_root: &Path) -> std::path::PathBuf {
180 let joined = if Path::new(target).is_absolute() {
181 std::path::PathBuf::from(target)
182 } else {
183 repo_root.join(target)
184 };
185 std::path::absolute(&joined).unwrap_or(joined)
187}
188
189pub fn is_under(target: &str, dir: &str, repo_root: &Path) -> bool {
193 let base = absolutize(dir, repo_root);
194 let abs = absolutize(target, repo_root);
195 abs.starts_with(&base)
196}
197
198pub fn is_under_any(target: &str, dirs: &[String], repo_root: &Path) -> bool {
200 dirs.iter().any(|d| is_under(target, d, repo_root))
201}
202
203pub fn classify_bash(command: &str, allowed_roots: &[String]) -> Option<&'static str> {
207 if command.is_empty() {
208 return None;
209 }
210 if allowed_roots.iter().any(|r| command.contains(r)) {
211 return None;
212 }
213 BASH_MUTATION_PATTERNS
214 .iter()
215 .find(|(re, _)| re.is_match(command))
216 .map(|(_, reason)| *reason)
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222 use serde_json::json;
223
224 const ROOTS: [&str; 2] = ["/work/.eval-magic", "/work/.claude/skills"];
225
226 fn roots() -> Vec<String> {
227 ROOTS.iter().map(|s| s.to_string()).collect()
228 }
229
230 #[test]
231 fn is_write_tool_matches_every_harness_write_tool() {
232 for t in ["Write", "Edit", "MultiEdit", "NotebookEdit", "file_change"] {
233 assert!(is_write_tool(t), "{t} should be a write tool");
234 }
235 for t in ["Read", "Bash", "Grep", "apply_patch", ""] {
236 assert!(!is_write_tool(t), "{t} should not be a write tool");
237 }
238 }
239
240 #[test]
241 fn is_patch_tool_matches_apply_patch_style_tools_only() {
242 assert!(is_patch_tool("apply_patch"));
243 for t in ["Write", "Bash", "file_change", ""] {
244 assert!(!is_patch_tool(t), "{t} should not be a patch tool");
245 }
246 }
247
248 #[test]
249 fn is_shell_tool_matches_every_harness_shell_tool() {
250 for t in ["Bash", "command_execution"] {
251 assert!(is_shell_tool(t), "{t} should be a shell tool");
252 }
253 for t in ["Write", "apply_patch", ""] {
254 assert!(!is_shell_tool(t), "{t} should not be a shell tool");
255 }
256 }
257
258 #[test]
259 fn path_arg_prefers_file_path_then_notebook_then_path() {
260 assert_eq!(path_arg(&json!({ "file_path": "/a" })), Some("/a"));
261 assert_eq!(path_arg(&json!({ "notebook_path": "/b" })), Some("/b"));
262 assert_eq!(path_arg(&json!({ "path": "/c" })), Some("/c"));
263 assert_eq!(
264 path_arg(&json!({ "file_path": "/a", "path": "/c" })),
265 Some("/a")
266 );
267 assert_eq!(path_arg(&json!({ "command": "ls" })), None);
268 assert_eq!(path_arg(&json!("not an object")), None);
269 }
270
271 #[test]
272 fn apply_patch_paths_collects_structured_and_freeform_targets() {
273 let paths = apply_patch_paths(&json!({
274 "files": [
275 "/tmp/out.md",
276 { "path": "src/lib.rs" },
277 { "move_path": "src/new.rs" }
278 ],
279 "patch": "*** Begin Patch\n*** Update File: docs/a.md\n*** Move to: docs/b.md\n*** End Patch\n"
280 }));
281 assert_eq!(
282 paths,
283 vec![
284 "/tmp/out.md".to_string(),
285 "docs/a.md".to_string(),
286 "docs/b.md".to_string(),
287 "src/lib.rs".to_string(),
288 "src/new.rs".to_string(),
289 ]
290 );
291 }
292
293 #[test]
294 fn is_under_matches_dir_and_descendants() {
295 let repo = Path::new("/work");
296 assert!(is_under("/work/.eval-magic", "/work/.eval-magic", repo));
297 assert!(is_under(
298 "/work/.eval-magic/x/out.md",
299 "/work/.eval-magic",
300 repo
301 ));
302 assert!(!is_under("/work/runner/run.ts", "/work/.eval-magic", repo));
303 assert!(!is_under("/work/.eval-magic2/x", "/work/.eval-magic", repo));
305 }
306
307 #[test]
308 fn is_under_resolves_relative_targets_against_repo_root() {
309 let repo = Path::new("/work");
310 assert!(is_under(".eval-magic/x", "/work/.eval-magic", repo));
311 }
312
313 #[test]
314 fn is_under_any_checks_every_root() {
315 let repo = Path::new("/work");
316 assert!(is_under_any("/work/.claude/skills/s", &roots(), repo));
317 assert!(!is_under_any("/etc/passwd", &roots(), repo));
318 }
319
320 #[test]
321 fn classify_bash_flags_install_and_git_mutations() {
322 assert_eq!(
323 classify_bash("npm install left-pad", &roots()),
324 Some("package install/add")
325 );
326 assert_eq!(
327 classify_bash("git worktree add ../wt -b scratch", &roots()),
328 Some("git worktree add (working tree outside the sandbox)")
329 );
330 assert_eq!(
331 classify_bash("echo hi > out.log", &roots()),
332 Some("output redirection to a file")
333 );
334 }
335
336 #[test]
337 fn classify_bash_flags_creates_under_every_harness_config_dir_but_allows_reads() {
338 for dir in crate::adapters::all_config_dir_names() {
339 assert_eq!(
340 classify_bash(&format!("mkdir -p {dir}/x"), &[]),
341 Some("path under a harness config dir"),
342 "mkdir under {dir} should be flagged"
343 );
344 assert_eq!(
345 classify_bash(&format!("cp evil.json {dir}/hooks.json"), &[]),
346 Some("path under a harness config dir"),
347 "cp into {dir} should be flagged"
348 );
349 assert_eq!(
350 classify_bash(&format!("cat {dir}/settings.json"), &[]),
351 None,
352 "read of {dir} should stay allowed"
353 );
354 assert_eq!(classify_bash(&format!("ls {dir}"), &[]), None);
355 }
356 }
357
358 #[test]
359 fn classify_bash_allows_scoped_and_readonly_commands() {
360 assert_eq!(
362 classify_bash("echo hi > /work/.eval-magic/x/log", &roots()),
363 None
364 );
365 assert_eq!(classify_bash("ls -la /", &roots()), None);
366 assert_eq!(classify_bash("", &roots()), None);
367 }
368}