-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtools.rs
More file actions
1544 lines (1348 loc) · 53.6 KB
/
tools.rs
File metadata and controls
1544 lines (1348 loc) · 53.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use anyhow::{Result, bail};
use serde_json::{Value, json};
use tokio::process::Command;
use tokio::time::{Duration, timeout};
use crate::util;
/// Resolve a tool path argument against the project root.
/// Relative paths are joined to project_root; absolute paths are used as-is.
fn resolve_tool_path(path: &str, project_root: &Path) -> PathBuf {
let p = Path::new(path);
if p.is_absolute() {
p.to_path_buf()
} else {
project_root.join(p)
}
}
/// Count occurrences of `needle` in `haystack`, including overlapping matches.
/// For example, "aa" in "aaa" returns 2 (positions 0 and 1).
/// Advances by one character (not one byte) to safely handle multibyte UTF-8.
fn count_occurrences(haystack: &str, needle: &str) -> usize {
if needle.is_empty() {
return 0;
}
let mut count = 0;
let mut start = 0;
while start + needle.len() <= haystack.len() {
if let Some(pos) = haystack[start..].find(needle) {
count += 1;
// Advance past the start of this match by one character, not one byte,
// to avoid slicing inside a multibyte character.
let match_start = start + pos;
let next = match_start
+ haystack[match_start..]
.chars()
.next()
.map_or(1, |c| c.len_utf8());
start = next;
} else {
break;
}
}
count
}
/// Typed result from tool execution, replacing bare strings.
/// `success` indicates whether the tool executed without error.
#[derive(Debug, Clone)]
pub struct ToolOutcome {
/// Whether the tool executed successfully (file was written, command ran, etc.).
/// False for errors, permission denials, and validation failures.
/// Used by tests and future phases; checkpoint emission uses hash comparison.
#[allow(dead_code)]
pub success: bool,
/// Human-readable output to send back to the model.
pub output: String,
}
#[derive(Debug, Clone)]
pub enum Tool {
FileRead,
FileWrite,
FileEdit,
ListFiles,
ShellExec,
Grep,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ToolCall {
pub call_id: String,
pub name: String,
pub arguments: String,
}
impl Tool {
pub fn all() -> Vec<Tool> {
vec![
Tool::FileRead,
Tool::FileWrite,
Tool::FileEdit,
Tool::ListFiles,
Tool::ShellExec,
Tool::Grep,
]
}
pub fn definitions() -> Vec<Value> {
Tool::all().iter().map(|t| t.definition()).collect()
}
pub fn from_name(name: &str) -> Option<Tool> {
match name {
"file_read" => Some(Tool::FileRead),
"file_write" => Some(Tool::FileWrite),
"file_edit" => Some(Tool::FileEdit),
"list_files" => Some(Tool::ListFiles),
"shell_exec" => Some(Tool::ShellExec),
"grep" => Some(Tool::Grep),
_ => None,
}
}
pub fn definition(&self) -> Value {
match self {
Tool::FileRead => json!({
"type": "function",
"name": "file_read",
"description": "Read the contents of a file at the given path. Returns the file contents as a string.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The absolute or relative path to the file to read"
}
},
"required": ["path"],
"additionalProperties": false
}
}),
Tool::FileWrite => json!({
"type": "function",
"name": "file_write",
"description": "Write content to a file. Creates the file if it doesn't exist, or overwrites if it does. Parent directories are created automatically.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to write"
},
"content": {
"type": "string",
"description": "The content to write to the file"
}
},
"required": ["path", "content"],
"additionalProperties": false
}
}),
Tool::FileEdit => json!({
"type": "function",
"name": "file_edit",
"description": "Edit a file by replacing occurrences of a string. By default, old_string must match exactly one location (use enough context to ensure uniqueness). Set replace_all to true to replace every occurrence.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to edit"
},
"old_string": {
"type": "string",
"description": "The exact string to find and replace"
},
"new_string": {
"type": "string",
"description": "The replacement string"
},
"replace_all": {
"type": "boolean",
"description": "Replace all occurrences (default: false, which requires exactly one match)"
}
},
"required": ["path", "old_string", "new_string"],
"additionalProperties": false
}
}),
Tool::ListFiles => json!({
"type": "function",
"name": "list_files",
"description": "List the contents of a directory. Returns file and directory names, one per line. Use this to explore project structure and discover files before reading them.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The directory path to list (default: current directory)"
}
},
"required": ["path"],
"additionalProperties": false
}
}),
Tool::Grep => json!({
"type": "function",
"name": "grep",
"description": "Search file contents by regex. Returns matching lines with file paths and line numbers. Use this to find code patterns, function definitions, imports, and references across the codebase. Respects .gitignore.",
"parameters": {
"type": "object",
"properties": {
"pattern": {
"type": "string",
"description": "Regex pattern to search for"
},
"path": {
"type": "string",
"description": "Directory or file to search in (defaults to project root)"
},
"glob": {
"type": "string",
"description": "Glob pattern to filter files (e.g. '*.rs', '*.ts')"
},
"case_insensitive": {
"type": "boolean",
"description": "Case-insensitive search (default: false)"
},
"max_results": {
"type": "integer",
"description": "Maximum number of matching lines to return (default: 100)"
}
},
"required": ["pattern"],
"additionalProperties": false
}
}),
Tool::ShellExec => json!({
"type": "function",
"name": "shell_exec",
"description": "Execute a shell command and return its output (stdout + stderr). Commands run in the project root by default. Use this for build commands, git operations, running tests, and other shell tasks.",
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The shell command to execute"
},
"cwd": {
"type": "string",
"description": "Working directory for the command (defaults to project root)"
},
"timeout_secs": {
"type": "integer",
"description": "Timeout in seconds (default: 60, max: 300)"
}
},
"required": ["command"],
"additionalProperties": false
}
}),
}
}
pub async fn execute(&self, arguments: &str, project_root: &std::path::Path) -> ToolOutcome {
let result = match self {
Tool::FileRead => execute_file_read(arguments, project_root),
Tool::FileWrite => execute_file_write(arguments, project_root),
Tool::FileEdit => execute_file_edit(arguments, project_root),
Tool::ListFiles => execute_list_files(arguments, project_root),
Tool::ShellExec => execute_shell_exec(arguments, project_root).await,
Tool::Grep => execute_grep(arguments, project_root).await,
};
match result {
Ok(output) => ToolOutcome {
success: true,
output,
},
Err(e) => ToolOutcome {
success: false,
output: format!("Error: {e}"),
},
}
}
}
fn execute_file_read(arguments: &str, project_root: &std::path::Path) -> Result<String> {
let args: Value = serde_json::from_str(arguments)?;
let path = args["path"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
let resolved = resolve_tool_path(path, project_root);
// Read as bytes first for binary detection
let bytes = std::fs::read(&resolved)
.map_err(|e| anyhow::anyhow!("Failed to read file '{}': {}", path, e))?;
if util::is_binary(&bytes) {
anyhow::bail!(
"File '{}' appears to be binary — cannot display contents",
path
);
}
let content = String::from_utf8(bytes)
.map_err(|_| anyhow::anyhow!("File '{}' contains invalid UTF-8", path))?;
Ok(util::clip_for_model(&content))
}
fn execute_file_write(arguments: &str, project_root: &std::path::Path) -> Result<String> {
let args: Value = serde_json::from_str(arguments)?;
let path = args["path"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
let content = args["content"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: content"))?;
let target = resolve_tool_path(path, project_root);
// For nested paths, create parent directories first so validate_path can resolve them.
// We create within the project root to ensure safety before canonicalization.
if let Some(parent) = target.parent()
&& !parent.exists()
{
// Ensure the parent chain stays within project root by checking the
// closest existing ancestor resolves inside the root
let mut ancestor = parent.to_path_buf();
while !ancestor.exists() {
if !ancestor.pop() {
break;
}
}
if ancestor.exists() {
let canonical_ancestor = ancestor.canonicalize()?;
let canonical_root = project_root.canonicalize()?;
if !canonical_ancestor.starts_with(&canonical_root) {
anyhow::bail!(
"Path '{}' is outside the project root '{}'",
target.display(),
project_root.display()
);
}
}
std::fs::create_dir_all(parent).map_err(|e| {
anyhow::anyhow!("Failed to create directory '{}': {}", parent.display(), e)
})?;
}
// Validate the final path is within project root (symlink-safe)
let resolved = util::validate_path(&target, project_root)?;
std::fs::write(&resolved, content)
.map_err(|e| anyhow::anyhow!("Failed to write file '{}': {}", path, e))?;
Ok(format!("Wrote {} bytes to {}", content.len(), path))
}
fn execute_file_edit(arguments: &str, project_root: &std::path::Path) -> Result<String> {
let args: Value = serde_json::from_str(arguments)?;
let path = args["path"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
let old_string = args["old_string"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: old_string"))?;
let new_string = args["new_string"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: new_string"))?;
let replace_all = args["replace_all"].as_bool().unwrap_or(false);
if old_string.is_empty() {
bail!("old_string must not be empty");
}
if old_string == new_string {
bail!("old_string and new_string are identical — nothing to change");
}
let target = resolve_tool_path(path, project_root);
let resolved = util::validate_path(&target, project_root)?;
// Read as bytes first for binary detection
let bytes = std::fs::read(&resolved)
.map_err(|e| anyhow::anyhow!("Failed to read file '{}': {}", path, e))?;
if util::is_binary(&bytes) {
bail!("File '{}' appears to be binary — cannot edit", path);
}
let content = String::from_utf8(bytes)
.map_err(|_| anyhow::anyhow!("File '{}' contains invalid UTF-8", path))?;
if replace_all {
// Non-overlapping left-to-right count, consistent with str::replace semantics
let count = content.matches(old_string).count();
if count == 0 {
bail!("old_string not found in '{}'", path);
}
let new_content = content.replace(old_string, new_string);
std::fs::write(&resolved, &new_content)
.map_err(|e| anyhow::anyhow!("Failed to write file '{}': {}", path, e))?;
Ok(format!("Replaced {} occurrences in {}", count, path))
} else {
// Count occurrences with overlapping detection.
// str::matches is non-overlapping, so we scan manually to catch cases
// like old_string="aa" in "aaa" (positions 0 and 1).
let count = count_occurrences(&content, old_string);
if count == 0 {
bail!("old_string not found in '{}'", path);
}
if count > 1 {
bail!(
"old_string matches {} locations in '{}' — provide more context to match exactly once",
count,
path
);
}
let new_content = content.replacen(old_string, new_string, 1);
std::fs::write(&resolved, &new_content)
.map_err(|e| anyhow::anyhow!("Failed to write file '{}': {}", path, e))?;
// Return a few lines of surrounding context
let replacement_start = content.find(old_string).unwrap();
let byte_offset_in_new = replacement_start;
let context_snippet =
extract_edit_context(&new_content, byte_offset_in_new, new_string.len());
Ok(format!("Edited {}\n\n{}", path, context_snippet))
}
}
/// Extract a few lines of context around the edited region.
fn extract_edit_context(content: &str, byte_offset: usize, replacement_len: usize) -> String {
let lines: Vec<&str> = content.lines().collect();
let context_lines = 3;
// Find which line the edit starts and ends on
let mut byte_pos = 0;
let mut start_line = 0;
let mut end_line = 0;
for (i, line) in lines.iter().enumerate() {
let line_end = byte_pos + line.len() + 1; // +1 for newline
if byte_pos <= byte_offset && byte_offset < line_end {
start_line = i;
}
if byte_pos <= byte_offset + replacement_len && byte_offset + replacement_len <= line_end {
end_line = i;
break;
}
byte_pos = line_end;
}
let from = start_line.saturating_sub(context_lines);
let to = (end_line + context_lines + 1).min(lines.len());
lines[from..to]
.iter()
.enumerate()
.map(|(i, line)| format!("{:>4} | {}", from + i + 1, line))
.collect::<Vec<_>>()
.join("\n")
}
async fn execute_shell_exec(arguments: &str, project_root: &Path) -> Result<String> {
let args: Value = serde_json::from_str(arguments)?;
let command = args["command"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: command"))?;
let cwd = match args["cwd"].as_str() {
Some(cwd_str) => {
// Resolve relative cwd against project_root
let raw = Path::new(cwd_str);
if raw.is_absolute() {
raw.to_path_buf()
} else {
project_root.join(raw)
}
}
None => project_root.to_path_buf(),
};
let timeout_secs = args["timeout_secs"].as_u64().unwrap_or(60).min(300);
if !cwd.exists() {
bail!("Working directory does not exist: {}", cwd.display());
}
// Containment check: cwd must resolve inside project root (symlink-safe)
let canonical_cwd = cwd
.canonicalize()
.map_err(|e| anyhow::anyhow!("Failed to resolve cwd '{}': {e}", cwd.display()))?;
let canonical_root = project_root
.canonicalize()
.map_err(|e| anyhow::anyhow!("Failed to resolve project root: {e}"))?;
if !canonical_cwd.starts_with(&canonical_root) {
bail!(
"Working directory '{}' is outside the project root",
cwd.display()
);
}
let child = Command::new("sh")
.arg("-c")
.arg(command)
.current_dir(&canonical_cwd)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|e| anyhow::anyhow!("Failed to spawn command: {e}"))?;
let output = match timeout(Duration::from_secs(timeout_secs), child.wait_with_output()).await {
Ok(Ok(output)) => output,
Ok(Err(e)) => bail!("Failed to execute command: {e}"),
Err(_) => bail!("Command timed out after {timeout_secs}s"),
};
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let mut result = String::new();
if !stdout.is_empty() {
result.push_str(&stdout);
}
if !stderr.is_empty() {
if !result.is_empty() {
result.push('\n');
}
result.push_str("[stderr]\n");
result.push_str(&stderr);
}
if !output.status.success() {
let code = output.status.code().unwrap_or(-1);
if !result.is_empty() {
result.push('\n');
}
result.push_str(&format!("[exit code: {code}]"));
}
if result.is_empty() {
result.push_str("(no output)");
}
Ok(util::clip_for_model(&result))
}
async fn execute_grep(arguments: &str, project_root: &Path) -> Result<String> {
let args: Value = serde_json::from_str(arguments)?;
let pattern = args["pattern"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: pattern"))?;
let search_path = args["path"]
.as_str()
.map(|p| resolve_tool_path(p, project_root))
.unwrap_or_else(|| project_root.to_path_buf());
let max_results = args["max_results"].as_u64().unwrap_or(100) as usize;
let case_insensitive = args["case_insensitive"].as_bool().unwrap_or(false);
let glob_pattern = args["glob"].as_str().map(|s| s.to_string());
// Build the regex
let re = regex::RegexBuilder::new(pattern)
.case_insensitive(case_insensitive)
.build()
.map_err(|e| anyhow::anyhow!("Grep error: {e}"))?;
// Build the directory walker (respects .gitignore automatically)
let mut walker = ignore::WalkBuilder::new(&search_path);
walker.hidden(true).git_ignore(true).git_global(true);
if let Some(ref glob) = glob_pattern {
let mut override_builder = ignore::overrides::OverrideBuilder::new(&search_path);
override_builder
.add(glob)
.map_err(|e| anyhow::anyhow!("Grep error: invalid glob: {e}"))?;
let overrides = override_builder
.build()
.map_err(|e| anyhow::anyhow!("Grep error: invalid glob: {e}"))?;
walker.overrides(overrides);
}
// Search files on a blocking thread to avoid blocking the async runtime
let results = tokio::task::spawn_blocking(move || {
let mut matches = Vec::new();
for entry in walker.build().flatten() {
if matches.len() >= max_results {
break;
}
let path = entry.path();
if !path.is_file() {
continue;
}
// Skip binary files (check first 8KB for null bytes)
if let Ok(f) = std::fs::File::open(path) {
let mut reader = BufReader::new(f);
let mut is_binary = false;
{
let buf = reader.fill_buf().unwrap_or(&[]);
let check_len = buf.len().min(8192);
if buf[..check_len].contains(&0) {
is_binary = true;
}
}
if is_binary {
continue;
}
// Re-open for line-by-line reading after the borrow is released
drop(reader);
}
if let Ok(f) = std::fs::File::open(path) {
let reader = BufReader::new(f);
for (line_num, line) in reader.lines().enumerate() {
if matches.len() >= max_results {
break;
}
if let Ok(line) = line
&& re.is_match(&line)
{
let display_path =
path.strip_prefix(&search_path).unwrap_or(path);
matches.push(format!(
"{}:{}:{}",
display_path.display(),
line_num + 1,
line
));
}
}
}
}
matches
})
.await
.map_err(|e| anyhow::anyhow!("Grep search failed: {e}"))?;
if results.is_empty() {
return Ok("No matches found.".to_string());
}
let output = results.join("\n");
if results.len() >= max_results {
Ok(format!("{output}\n\n... (results capped at {max_results})"))
} else {
Ok(util::clip_for_model(&output))
}
}
fn execute_list_files(arguments: &str, project_root: &std::path::Path) -> Result<String> {
let args: Value = serde_json::from_str(arguments)?;
let path = args["path"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("Missing required parameter: path"))?;
let resolved = resolve_tool_path(path, project_root);
let mut entries: Vec<String> = Vec::new();
let read_dir = std::fs::read_dir(&resolved)
.map_err(|e| anyhow::anyhow!("Failed to list directory '{}': {}", path, e))?;
for entry in read_dir {
let entry = entry?;
let name = entry.file_name().to_string_lossy().to_string();
if entry.file_type()?.is_dir() {
entries.push(format!("{name}/"));
} else {
entries.push(name);
}
}
entries.sort();
Ok(entries.join("\n"))
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::path::Path;
// Dummy root for tools that don't need path validation
fn dummy_root() -> &'static Path {
Path::new("/tmp")
}
#[tokio::test]
async fn file_read_success() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
write!(tmp, "hello world").unwrap();
let path = tmp.path().to_str().unwrap();
let args = json!({"path": path}).to_string();
let result = Tool::FileRead.execute(&args, dummy_root()).await;
assert_eq!(result.output, "hello world");
}
#[tokio::test]
async fn file_read_not_found() {
let args = json!({"path": "/nonexistent/file.txt"}).to_string();
let result = Tool::FileRead.execute(&args, dummy_root()).await;
assert!(!result.success);
assert!(result.output.contains("Failed to read file"));
}
#[tokio::test]
async fn file_read_missing_path_param() {
let args = json!({}).to_string();
let result = Tool::FileRead.execute(&args, dummy_root()).await;
assert!(!result.success);
assert!(result.output.contains("Missing required parameter"));
}
#[test]
fn from_name_known() {
assert!(Tool::from_name("file_read").is_some());
assert!(Tool::from_name("file_write").is_some());
assert!(Tool::from_name("file_edit").is_some());
assert!(Tool::from_name("list_files").is_some());
assert!(Tool::from_name("shell_exec").is_some());
assert!(Tool::from_name("grep").is_some());
}
#[test]
fn from_name_unknown() {
assert!(Tool::from_name("unknown_tool").is_none());
}
#[test]
fn definition_has_required_fields() {
for tool in Tool::all() {
let def = tool.definition();
assert!(def["name"].is_string());
assert_eq!(def["type"], "function");
assert!(def["parameters"].is_object());
}
}
#[tokio::test]
async fn file_read_binary_rejected() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
Write::write_all(&mut tmp, &[0x89, 0x50, 0x4E, 0x47, 0x00, 0x00]).unwrap();
let path = tmp.path().to_str().unwrap();
let args = json!({"path": path}).to_string();
let result = Tool::FileRead.execute(&args, dummy_root()).await;
assert!(!result.success);
assert!(result.output.contains("binary"));
}
#[tokio::test]
async fn file_read_large_file_clipped() {
let mut tmp = tempfile::NamedTempFile::new().unwrap();
let content = "x".repeat(50_000);
Write::write_all(&mut tmp, content.as_bytes()).unwrap();
let path = tmp.path().to_str().unwrap();
let args = json!({"path": path}).to_string();
let result = Tool::FileRead.execute(&args, dummy_root()).await;
assert!(result.output.len() < content.len());
assert!(result.output.contains("truncated"));
}
// --- file_write tests ---
#[tokio::test]
async fn file_write_creates_file() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("new.txt");
let args = json!({
"path": file_path.to_str().unwrap(),
"content": "hello write"
})
.to_string();
let result = Tool::FileWrite.execute(&args, dir.path()).await;
assert!(result.output.contains("11 bytes"));
assert_eq!(std::fs::read_to_string(&file_path).unwrap(), "hello write");
}
#[tokio::test]
async fn file_write_creates_parent_dirs() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("deep/nested/file.txt");
let args = json!({
"path": file_path.to_str().unwrap(),
"content": "nested"
})
.to_string();
let result = Tool::FileWrite.execute(&args, dir.path()).await;
assert!(result.output.contains("bytes"));
assert_eq!(std::fs::read_to_string(&file_path).unwrap(), "nested");
}
#[cfg(unix)]
#[tokio::test]
async fn file_write_rejects_symlink_escape() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let link = dir.path().join("escape_link");
std::os::unix::fs::symlink(outside.path(), &link).unwrap();
let file_path = link.join("evil.txt");
let args = json!({
"path": file_path.to_str().unwrap(),
"content": "evil"
})
.to_string();
let result = Tool::FileWrite.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("outside the project root"));
}
// --- file_edit tests ---
#[tokio::test]
async fn file_edit_single_match() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.txt");
std::fs::write(&file_path, "hello world").unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "hello",
"new_string": "goodbye"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(result.output.contains("Edited"));
assert_eq!(
std::fs::read_to_string(&file_path).unwrap(),
"goodbye world"
);
}
#[tokio::test]
async fn file_edit_returns_context() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.txt");
let content = "line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\n";
std::fs::write(&file_path, content).unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "line 4",
"new_string": "LINE FOUR"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(result.output.contains("LINE FOUR"));
// Should show surrounding lines
assert!(result.output.contains("line 2") || result.output.contains("line 3"));
}
#[tokio::test]
async fn file_edit_zero_matches() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.txt");
std::fs::write(&file_path, "hello world").unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "nonexistent",
"new_string": "replacement"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("not found"));
}
#[tokio::test]
async fn file_edit_multiple_matches() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.txt");
std::fs::write(&file_path, "hello hello hello").unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "hello",
"new_string": "goodbye"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
let err = &result.output;
assert!(err.contains("3 locations"));
// File should be unchanged
assert_eq!(
std::fs::read_to_string(&file_path).unwrap(),
"hello hello hello"
);
}
#[tokio::test]
async fn file_edit_empty_old_string() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.txt");
std::fs::write(&file_path, "hello").unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "",
"new_string": "x"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("must not be empty"));
}
#[tokio::test]
async fn file_edit_identical_strings() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("test.txt");
std::fs::write(&file_path, "hello").unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "hello",
"new_string": "hello"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("identical"));
}
#[tokio::test]
async fn file_edit_file_not_found() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("nonexistent.txt");
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "hello",
"new_string": "goodbye"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
}
#[tokio::test]
async fn file_edit_binary_file() {
let dir = tempfile::tempdir().unwrap();
let file_path = dir.path().join("binary.bin");
std::fs::write(&file_path, [0x89, 0x50, 0x4E, 0x47, 0x00, 0x00]).unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "PNG",
"new_string": "JPG"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("binary"));
}
#[tokio::test]
async fn file_edit_outside_project_root() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let file_path = outside.path().join("escape.txt");
std::fs::write(&file_path, "secret").unwrap();
let args = json!({
"path": file_path.to_str().unwrap(),
"old_string": "secret",
"new_string": "safe"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("outside the project root"));
}
#[cfg(unix)]
#[tokio::test]
async fn file_edit_rejects_symlink_escape() {
let dir = tempfile::tempdir().unwrap();
let outside = tempfile::tempdir().unwrap();
let outside_file = outside.path().join("target.txt");
std::fs::write(&outside_file, "secret data").unwrap();
let link = dir.path().join("link.txt");
std::os::unix::fs::symlink(&outside_file, &link).unwrap();
let args = json!({
"path": link.to_str().unwrap(),
"old_string": "secret",
"new_string": "safe"
})
.to_string();
let result = Tool::FileEdit.execute(&args, dir.path()).await;
assert!(!result.success);
assert!(result.output.contains("outside the project root"));