perspt-agent 0.5.7

SRBN Orchestrator and Agent logic for Perspt
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Agent Tooling
//!
//! Tools available to agents for interacting with the workspace.
//! Implements: read_file, search_code, apply_patch, run_command

use diffy::{apply, Patch};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command as AsyncCommand;

/// Tool result from agent execution
#[derive(Debug, Clone)]
pub struct ToolResult {
    pub tool_name: String,
    pub success: bool,
    pub output: String,
    pub error: Option<String>,
}

impl ToolResult {
    pub fn success(tool_name: &str, output: String) -> Self {
        Self {
            tool_name: tool_name.to_string(),
            success: true,
            output,
            error: None,
        }
    }

    pub fn failure(tool_name: &str, error: String) -> Self {
        Self {
            tool_name: tool_name.to_string(),
            success: false,
            output: String::new(),
            error: Some(error),
        }
    }
}

/// Tool call request from LLM
#[derive(Debug, Clone)]
pub struct ToolCall {
    pub name: String,
    pub arguments: HashMap<String, String>,
}

/// Agent tools for workspace interaction
pub struct AgentTools {
    /// Working directory (sandbox root)
    working_dir: PathBuf,
    /// Whether to require user approval for commands
    require_approval: bool,
    /// Event sender for streaming output
    event_sender: Option<perspt_core::events::channel::EventSender>,
}

impl AgentTools {
    /// Create new agent tools instance
    pub fn new(working_dir: PathBuf, require_approval: bool) -> Self {
        Self {
            working_dir,
            require_approval,
            event_sender: None,
        }
    }

    /// Set event sender for streaming output
    pub fn set_event_sender(&mut self, sender: perspt_core::events::channel::EventSender) {
        self.event_sender = Some(sender);
    }

    /// Execute a tool call
    pub async fn execute(&self, call: &ToolCall) -> ToolResult {
        match call.name.as_str() {
            "read_file" => self.read_file(call),
            "search_code" => self.search_code(call),
            "apply_patch" => self.apply_patch(call),
            "run_command" => self.run_command(call).await,
            "list_files" => self.list_files(call),
            "write_file" => self.write_file(call),
            "apply_diff" => self.apply_diff(call),
            "delete_file" => self.delete_file(call),
            "move_file" => self.move_file(call),
            // Power Tools (OS-level)
            "sed_replace" => self.sed_replace(call),
            "awk_filter" => self.awk_filter(call),
            "diff_files" => self.diff_files(call),
            _ => ToolResult::failure(&call.name, format!("Unknown tool: {}", call.name)),
        }
    }

    /// Read a file's contents
    fn read_file(&self, call: &ToolCall) -> ToolResult {
        let path = match call.arguments.get("path") {
            Some(p) => self.resolve_path(p),
            None => return ToolResult::failure("read_file", "Missing 'path' argument".to_string()),
        };

        match fs::read_to_string(&path) {
            Ok(content) => ToolResult::success("read_file", content),
            Err(e) => ToolResult::failure("read_file", format!("Failed to read {:?}: {}", path, e)),
        }
    }

    /// Search for code patterns using grep
    fn search_code(&self, call: &ToolCall) -> ToolResult {
        let query = match call.arguments.get("query") {
            Some(q) => q,
            None => {
                return ToolResult::failure("search_code", "Missing 'query' argument".to_string())
            }
        };

        let path = call
            .arguments
            .get("path")
            .map(|p| self.resolve_path(p))
            .unwrap_or_else(|| self.working_dir.clone());

        // Use ripgrep if available, fallback to grep
        let output = Command::new("rg")
            .args(["--json", "-n", query])
            .current_dir(&path)
            .output()
            .or_else(|_| {
                Command::new("grep")
                    .args(["-rn", query, "."])
                    .current_dir(&path)
                    .output()
            });

        match output {
            Ok(out) => {
                let stdout = String::from_utf8_lossy(&out.stdout).to_string();
                ToolResult::success("search_code", stdout)
            }
            Err(e) => ToolResult::failure("search_code", format!("Search failed: {}", e)),
        }
    }

    /// Apply a patch to a file
    fn apply_patch(&self, call: &ToolCall) -> ToolResult {
        let path = match call.arguments.get("path") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("apply_patch", "Missing 'path' argument".to_string())
            }
        };

        let content = match call.arguments.get("content") {
            Some(c) => c,
            None => {
                return ToolResult::failure("apply_patch", "Missing 'content' argument".to_string())
            }
        };

        // Create parent directories if needed
        if let Some(parent) = path.parent() {
            if let Err(e) = fs::create_dir_all(parent) {
                return ToolResult::failure(
                    "apply_patch",
                    format!("Failed to create directories: {}", e),
                );
            }
        }

        match fs::write(&path, content) {
            Ok(_) => ToolResult::success("apply_patch", format!("Successfully wrote {:?}", path)),
            Err(e) => {
                ToolResult::failure("apply_patch", format!("Failed to write {:?}: {}", path, e))
            }
        }
    }

    /// Apply a unified diff patch to a file
    fn apply_diff(&self, call: &ToolCall) -> ToolResult {
        let path = match call.arguments.get("path") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("apply_diff", "Missing 'path' argument".to_string())
            }
        };

        let diff_content = match call.arguments.get("diff") {
            Some(c) => c,
            None => {
                return ToolResult::failure("apply_diff", "Missing 'diff' argument".to_string())
            }
        };

        // Read original file
        let original = match fs::read_to_string(&path) {
            Ok(c) => c,
            Err(e) => {
                // If file doesn't exist, we can't patch it.
                // (Unless it's a new file creation patch, but diffy usually assumes base text)
                return ToolResult::failure(
                    "apply_diff",
                    format!("Failed to read base file {:?}: {}", path, e),
                );
            }
        };

        // Parse patch
        let patch = match Patch::from_str(diff_content) {
            Ok(p) => p,
            Err(e) => {
                return ToolResult::failure("apply_diff", format!("Failed to parse diff: {}", e));
            }
        };

        // Apply patch
        match apply(&original, &patch) {
            Ok(patched) => match fs::write(&path, patched) {
                Ok(_) => {
                    ToolResult::success("apply_diff", format!("Successfully patched {:?}", path))
                }
                Err(e) => ToolResult::failure(
                    "apply_diff",
                    format!("Failed to write patched file: {}", e),
                ),
            },
            Err(e) => ToolResult::failure("apply_diff", format!("Failed to apply patch: {}", e)),
        }
    }

    /// Run a shell command (requires approval unless auto-approve is set)
    async fn run_command(&self, call: &ToolCall) -> ToolResult {
        let cmd_str = match call.arguments.get("command") {
            Some(c) => c,
            None => {
                return ToolResult::failure("run_command", "Missing 'command' argument".to_string())
            }
        };

        // Honor explicit working_dir from the caller (e.g. sandbox path),
        // falling back to self.working_dir (the main workspace).
        let effective_dir = call
            .arguments
            .get("working_dir")
            .map(PathBuf::from)
            .filter(|d| d.is_dir())
            .unwrap_or_else(|| self.working_dir.clone());

        // PSP-5 Phase 4: Sanitize command through policy before execution
        match perspt_policy::sanitize_command(cmd_str) {
            Ok(sr) if sr.rejected => {
                return ToolResult::failure(
                    "run_command",
                    format!(
                        "Command rejected by policy: {}",
                        sr.rejection_reason
                            .unwrap_or_else(|| "unknown reason".to_string())
                    ),
                );
            }
            Ok(sr) => {
                for warning in &sr.warnings {
                    log::warn!("Command policy warning: {}", warning);
                }
            }
            Err(e) => {
                return ToolResult::failure(
                    "run_command",
                    format!("Command sanitization failed: {}", e),
                );
            }
        }

        // Validate workspace bounds
        if let Err(e) = perspt_policy::validate_workspace_bound(cmd_str, &self.working_dir) {
            return ToolResult::failure("run_command", format!("Command rejected: {}", e));
        }

        if self.require_approval {
            log::info!("Command requires approval: {}", cmd_str);
        }

        let mut child = match AsyncCommand::new("sh")
            .args(["-c", cmd_str])
            .current_dir(&effective_dir)
            .env_remove("VIRTUAL_ENV")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
        {
            Ok(child) => child,
            Err(e) => return ToolResult::failure("run_command", format!("Failed to spawn: {}", e)),
        };

        let stdout = child.stdout.take().expect("Failed to open stdout");
        let stderr = child.stderr.take().expect("Failed to open stderr");
        let sender = self.event_sender.clone();

        let stdout_handle = tokio::spawn(async move {
            let mut reader = BufReader::new(stdout).lines();
            let mut output = String::new();
            while let Ok(Some(line)) = reader.next_line().await {
                if let Some(ref s) = sender {
                    let _ = s.send(perspt_core::AgentEvent::Log(line.clone()));
                }
                output.push_str(&line);
                output.push('\n');
            }
            output
        });

        let sender_err = self.event_sender.clone();
        let stderr_handle = tokio::spawn(async move {
            let mut reader = BufReader::new(stderr).lines();
            let mut output = String::new();
            while let Ok(Some(line)) = reader.next_line().await {
                if let Some(ref s) = sender_err {
                    let _ = s.send(perspt_core::AgentEvent::Log(format!("ERR: {}", line)));
                }
                output.push_str(&line);
                output.push('\n');
            }
            output
        });

        let status = match child.wait().await {
            Ok(s) => s,
            Err(e) => return ToolResult::failure("run_command", format!("Failed to wait: {}", e)),
        };

        let stdout_str = stdout_handle.await.unwrap_or_default();
        let stderr_str = stderr_handle.await.unwrap_or_default();

        if status.success() {
            ToolResult::success("run_command", stdout_str)
        } else {
            ToolResult::failure(
                "run_command",
                format!("Exit code: {:?}\n{}", status.code(), stderr_str),
            )
        }
    }

    /// List files in a directory
    fn list_files(&self, call: &ToolCall) -> ToolResult {
        let path = call
            .arguments
            .get("path")
            .map(|p| self.resolve_path(p))
            .unwrap_or_else(|| self.working_dir.clone());

        match fs::read_dir(&path) {
            Ok(entries) => {
                let files: Vec<String> = entries
                    .filter_map(|e| e.ok())
                    .map(|e| {
                        let name = e.file_name().to_string_lossy().to_string();
                        if e.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                            format!("{}/", name)
                        } else {
                            name
                        }
                    })
                    .collect();
                ToolResult::success("list_files", files.join("\n"))
            }
            Err(e) => {
                ToolResult::failure("list_files", format!("Failed to list {:?}: {}", path, e))
            }
        }
    }

    /// Write content to a file
    fn write_file(&self, call: &ToolCall) -> ToolResult {
        // Alias for apply_patch with different semantics
        self.apply_patch(call)
    }

    /// Delete a file from the workspace
    fn delete_file(&self, call: &ToolCall) -> ToolResult {
        let path = match call.arguments.get("path") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("delete_file", "Missing 'path' argument".to_string())
            }
        };

        if !path.exists() {
            return ToolResult::success(
                "delete_file",
                format!("Path does not exist, nothing to delete: {:?}", path),
            );
        }

        if path.is_dir() {
            return ToolResult::failure(
                "delete_file",
                format!(
                    "Cannot delete directory {:?}; only files are supported",
                    path
                ),
            );
        }

        match std::fs::remove_file(&path) {
            Ok(()) => ToolResult::success("delete_file", format!("Deleted {:?}", path)),
            Err(e) => {
                ToolResult::failure("delete_file", format!("Failed to delete {:?}: {}", path, e))
            }
        }
    }

    /// Move/rename a file within the workspace
    fn move_file(&self, call: &ToolCall) -> ToolResult {
        let from = match call.arguments.get("from") {
            Some(p) => self.resolve_path(p),
            None => return ToolResult::failure("move_file", "Missing 'from' argument".to_string()),
        };
        let to = match call.arguments.get("to") {
            Some(p) => self.resolve_path(p),
            None => return ToolResult::failure("move_file", "Missing 'to' argument".to_string()),
        };

        if !from.exists() {
            return ToolResult::failure(
                "move_file",
                format!("Source path does not exist: {:?}", from),
            );
        }

        // Ensure destination parent directory exists
        if let Some(parent) = to.parent() {
            if !parent.exists() {
                if let Err(e) = std::fs::create_dir_all(parent) {
                    return ToolResult::failure(
                        "move_file",
                        format!("Failed to create destination directory {:?}: {}", parent, e),
                    );
                }
            }
        }

        match std::fs::rename(&from, &to) {
            Ok(()) => ToolResult::success("move_file", format!("Moved {:?} -> {:?}", from, to)),
            Err(e) => ToolResult::failure(
                "move_file",
                format!("Failed to move {:?} -> {:?}: {}", from, to, e),
            ),
        }
    }

    /// Resolve a path relative to working directory
    fn resolve_path(&self, path: &str) -> PathBuf {
        let p = Path::new(path);
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            self.working_dir.join(p)
        }
    }

    // =========================================================================
    // Power Tools (OS-level operations)
    // =========================================================================

    /// Replace text in a file using sed-like pattern matching
    fn sed_replace(&self, call: &ToolCall) -> ToolResult {
        let path = match call.arguments.get("path") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("sed_replace", "Missing 'path' argument".to_string())
            }
        };

        let pattern = match call.arguments.get("pattern") {
            Some(p) => p,
            None => {
                return ToolResult::failure("sed_replace", "Missing 'pattern' argument".to_string())
            }
        };

        let replacement = match call.arguments.get("replacement") {
            Some(r) => r,
            None => {
                return ToolResult::failure(
                    "sed_replace",
                    "Missing 'replacement' argument".to_string(),
                )
            }
        };

        // Read file, perform replacement, write back
        match fs::read_to_string(&path) {
            Ok(content) => {
                let new_content = content.replace(pattern, replacement);
                match fs::write(&path, &new_content) {
                    Ok(_) => ToolResult::success(
                        "sed_replace",
                        format!(
                            "Replaced '{}' with '{}' in {:?}",
                            pattern, replacement, path
                        ),
                    ),
                    Err(e) => ToolResult::failure("sed_replace", format!("Failed to write: {}", e)),
                }
            }
            Err(e) => {
                ToolResult::failure("sed_replace", format!("Failed to read {:?}: {}", path, e))
            }
        }
    }

    /// Filter file content using awk-like field selection
    fn awk_filter(&self, call: &ToolCall) -> ToolResult {
        let path = match call.arguments.get("path") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("awk_filter", "Missing 'path' argument".to_string())
            }
        };

        let filter = match call.arguments.get("filter") {
            Some(f) => f,
            None => {
                return ToolResult::failure("awk_filter", "Missing 'filter' argument".to_string())
            }
        };

        // Use awk command for filtering
        let output = Command::new("awk").arg(filter).arg(&path).output();

        match output {
            Ok(out) => {
                if out.status.success() {
                    ToolResult::success(
                        "awk_filter",
                        String::from_utf8_lossy(&out.stdout).to_string(),
                    )
                } else {
                    ToolResult::failure(
                        "awk_filter",
                        String::from_utf8_lossy(&out.stderr).to_string(),
                    )
                }
            }
            Err(e) => ToolResult::failure("awk_filter", format!("Failed to run awk: {}", e)),
        }
    }

    /// Show differences between two files
    fn diff_files(&self, call: &ToolCall) -> ToolResult {
        let file1 = match call.arguments.get("file1") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("diff_files", "Missing 'file1' argument".to_string())
            }
        };

        let file2 = match call.arguments.get("file2") {
            Some(p) => self.resolve_path(p),
            None => {
                return ToolResult::failure("diff_files", "Missing 'file2' argument".to_string())
            }
        };

        // Use diff command
        let output = Command::new("diff")
            .args([
                "--unified",
                &file1.to_string_lossy(),
                &file2.to_string_lossy(),
            ])
            .output();

        match output {
            Ok(out) => {
                // diff exits with 0 if files are same, 1 if different, 2 if error
                let stdout = String::from_utf8_lossy(&out.stdout).to_string();
                if stdout.is_empty() {
                    ToolResult::success("diff_files", "Files are identical".to_string())
                } else {
                    ToolResult::success("diff_files", stdout)
                }
            }
            Err(e) => ToolResult::failure("diff_files", format!("Failed to run diff: {}", e)),
        }
    }
}

/// Get tool definitions for LLM function calling
pub fn get_tool_definitions() -> Vec<ToolDefinition> {
    vec![
        ToolDefinition {
            name: "read_file".to_string(),
            description: "Read the contents of a file".to_string(),
            parameters: vec![ToolParameter {
                name: "path".to_string(),
                description: "Path to the file to read".to_string(),
                required: true,
            }],
        },
        ToolDefinition {
            name: "search_code".to_string(),
            description: "Search for code patterns in the workspace using grep/ripgrep".to_string(),
            parameters: vec![
                ToolParameter {
                    name: "query".to_string(),
                    description: "Search pattern (regex supported)".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "path".to_string(),
                    description: "Directory to search in (default: working directory)".to_string(),
                    required: false,
                },
            ],
        },
        ToolDefinition {
            name: "apply_patch".to_string(),
            description: "Write or replace file contents".to_string(),
            parameters: vec![
                ToolParameter {
                    name: "path".to_string(),
                    description: "Path to the file to write".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "content".to_string(),
                    description: "New file contents".to_string(),
                    required: true,
                },
            ],
        },
        ToolDefinition {
            name: "apply_diff".to_string(),
            description: "Apply a Unified Diff patch to a file".to_string(),
            parameters: vec![
                ToolParameter {
                    name: "path".to_string(),
                    description: "Path to the file to patch".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "diff".to_string(),
                    description: "Unified Diff content".to_string(),
                    required: true,
                },
            ],
        },
        ToolDefinition {
            name: "run_command".to_string(),
            description: "Execute a shell command in the working directory".to_string(),
            parameters: vec![ToolParameter {
                name: "command".to_string(),
                description: "Shell command to execute".to_string(),
                required: true,
            }],
        },
        ToolDefinition {
            name: "list_files".to_string(),
            description: "List files in a directory".to_string(),
            parameters: vec![ToolParameter {
                name: "path".to_string(),
                description: "Directory path (default: working directory)".to_string(),
                required: false,
            }],
        },
        // Power Tools
        ToolDefinition {
            name: "sed_replace".to_string(),
            description: "Replace text in a file using sed-like pattern matching".to_string(),
            parameters: vec![
                ToolParameter {
                    name: "path".to_string(),
                    description: "Path to the file".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "pattern".to_string(),
                    description: "Search pattern".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "replacement".to_string(),
                    description: "Replacement text".to_string(),
                    required: true,
                },
            ],
        },
        ToolDefinition {
            name: "awk_filter".to_string(),
            description: "Filter file content using awk-like field selection".to_string(),
            parameters: vec![
                ToolParameter {
                    name: "path".to_string(),
                    description: "Path to the file".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "filter".to_string(),
                    description: "Awk filter expression (e.g., '$1 == \"error\"')".to_string(),
                    required: true,
                },
            ],
        },
        ToolDefinition {
            name: "diff_files".to_string(),
            description: "Show differences between two files".to_string(),
            parameters: vec![
                ToolParameter {
                    name: "file1".to_string(),
                    description: "First file path".to_string(),
                    required: true,
                },
                ToolParameter {
                    name: "file2".to_string(),
                    description: "Second file path".to_string(),
                    required: true,
                },
            ],
        },
    ]
}

/// Tool definition for LLM function calling
#[derive(Debug, Clone)]
pub struct ToolDefinition {
    pub name: String,
    pub description: String,
    pub parameters: Vec<ToolParameter>,
}

/// Tool parameter definition
#[derive(Debug, Clone)]
pub struct ToolParameter {
    pub name: String,
    pub description: String,
    pub required: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env::temp_dir;

    #[tokio::test]
    async fn test_read_file() {
        let dir = temp_dir();
        let test_file = dir.join("test_read.txt");
        fs::write(&test_file, "Hello, World!").unwrap();

        let tools = AgentTools::new(dir.clone(), false);
        let call = ToolCall {
            name: "read_file".to_string(),
            arguments: [("path".to_string(), test_file.to_string_lossy().to_string())]
                .into_iter()
                .collect(),
        };

        let result = tools.execute(&call).await;
        assert!(result.success);
        assert_eq!(result.output, "Hello, World!");
    }

    #[tokio::test]
    async fn test_list_files() {
        let dir = temp_dir();
        let tools = AgentTools::new(dir.clone(), false);
        let call = ToolCall {
            name: "list_files".to_string(),
            arguments: HashMap::new(),
        };

        let result = tools.execute(&call).await;
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_apply_diff_tool() {
        use std::collections::HashMap;
        use std::io::Write;
        let temp_dir = temp_dir();
        let file_path = temp_dir.join("test_diff.txt");
        let mut file = std::fs::File::create(&file_path).unwrap();
        // Explicitly write bytes with unix newlines
        file.write_all(b"Hello world\nThis is a test\n").unwrap();

        let tools = AgentTools::new(temp_dir.clone(), true);

        // Exact string with newlines
        let diff = "--- test_diff.txt\n+++ test_diff.txt\n@@ -1,2 +1,2 @@\n-Hello world\n+Hello diffy\n This is a test\n";

        let mut args = HashMap::new();
        args.insert("path".to_string(), "test_diff.txt".to_string());
        args.insert("diff".to_string(), diff.to_string());

        let call = ToolCall {
            name: "apply_diff".to_string(),
            arguments: args,
        };

        let result = tools.apply_diff(&call);
        assert!(
            result.success,
            "Diff application failed: {:?}",
            result.error
        );

        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "Hello diffy\nThis is a test\n");
    }

    #[tokio::test]
    async fn test_delete_file() {
        let dir = temp_dir();
        let test_file = dir.join("test_delete_me.txt");
        fs::write(&test_file, "temporary").unwrap();
        assert!(test_file.exists());

        let tools = AgentTools::new(dir.clone(), false);
        let mut args = HashMap::new();
        args.insert("path".to_string(), test_file.to_string_lossy().to_string());
        let call = ToolCall {
            name: "delete_file".to_string(),
            arguments: args,
        };
        let result = tools.execute(&call).await;
        assert!(result.success, "Delete should succeed: {:?}", result.error);
        assert!(!test_file.exists(), "File should be gone");
    }

    #[tokio::test]
    async fn test_delete_nonexistent_file_succeeds() {
        let dir = temp_dir();
        let tools = AgentTools::new(dir.clone(), false);
        let mut args = HashMap::new();
        args.insert(
            "path".to_string(),
            "/tmp/does_not_exist_xyz.txt".to_string(),
        );
        let call = ToolCall {
            name: "delete_file".to_string(),
            arguments: args,
        };
        let result = tools.execute(&call).await;
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_move_file() {
        let dir = temp_dir();
        let src = dir.join("test_move_src.txt");
        let dst = dir.join("test_move_dst.txt");
        fs::write(&src, "move me").unwrap();

        let tools = AgentTools::new(dir.clone(), false);
        let mut args = HashMap::new();
        args.insert("from".to_string(), src.to_string_lossy().to_string());
        args.insert("to".to_string(), dst.to_string_lossy().to_string());
        // move_file also needs "path" in args (set by bundle handler)
        args.insert("path".to_string(), src.to_string_lossy().to_string());
        let call = ToolCall {
            name: "move_file".to_string(),
            arguments: args,
        };
        let result = tools.execute(&call).await;
        assert!(result.success, "Move should succeed: {:?}", result.error);
        assert!(!src.exists(), "Source should be gone");
        assert!(dst.exists(), "Destination should exist");
        assert_eq!(fs::read_to_string(&dst).unwrap(), "move me");
        let _ = fs::remove_file(&dst);
    }

    #[tokio::test]
    async fn test_delete_directory_rejected() {
        let dir = temp_dir().join("test_delete_dir");
        fs::create_dir_all(&dir).unwrap();

        let tools = AgentTools::new(temp_dir(), false);
        let mut args = HashMap::new();
        args.insert("path".to_string(), dir.to_string_lossy().to_string());
        let call = ToolCall {
            name: "delete_file".to_string(),
            arguments: args,
        };
        let result = tools.execute(&call).await;
        assert!(!result.success, "Should reject directory deletion");
        let _ = fs::remove_dir(&dir);
    }

    #[tokio::test]
    async fn test_move_file_creates_parent_dirs() {
        let dir = temp_dir();
        let src = dir.join("test_move_nested_src.txt");
        let dst = dir
            .join("nested")
            .join("deep")
            .join("test_move_nested_dst.txt");
        fs::write(&src, "nested move").unwrap();

        let tools = AgentTools::new(dir.clone(), false);
        let mut args = HashMap::new();
        args.insert("from".to_string(), src.to_string_lossy().to_string());
        args.insert("to".to_string(), dst.to_string_lossy().to_string());
        args.insert("path".to_string(), src.to_string_lossy().to_string());
        let call = ToolCall {
            name: "move_file".to_string(),
            arguments: args,
        };
        let result = tools.execute(&call).await;
        assert!(
            result.success,
            "Move with nested dirs should succeed: {:?}",
            result.error
        );
        assert!(!src.exists());
        assert!(dst.exists());
        assert_eq!(fs::read_to_string(&dst).unwrap(), "nested move");
        let _ = fs::remove_dir_all(dir.join("nested"));
    }
}

// =============================================================================
// PSP-5 Phase 6: Sandbox workspace helpers
// =============================================================================

/// Create a sandbox workspace for provisional verification.
///
/// Copies key project files into a session-scoped temporary directory so
/// speculative verification does not pollute committed workspace state.
/// Returns the path to the sandbox root.
pub fn create_sandbox(
    working_dir: &Path,
    session_id: &str,
    branch_id: &str,
) -> std::io::Result<PathBuf> {
    let sandbox_root = working_dir
        .join(".perspt")
        .join("sandboxes")
        .join(session_id)
        .join(branch_id);

    fs::create_dir_all(&sandbox_root)?;

    log::debug!("Created sandbox workspace at {}", sandbox_root.display());

    Ok(sandbox_root)
}

/// Seed a sandbox with plugin-identified project manifests (Cargo.toml,
/// pyproject.toml, etc.) so that build/test commands can find them.
///
/// Walks the workspace looking for each plugin's `key_files()` and copies
/// any that exist into the sandbox at the same relative path.
pub fn seed_sandbox_manifests(
    working_dir: &Path,
    sandbox_dir: &Path,
    plugins: &[&str],
) -> std::io::Result<()> {
    let registry = perspt_core::plugin::PluginRegistry::new();
    let mut seeded = Vec::new();

    for plugin_name in plugins {
        if let Some(plugin) = registry.get(plugin_name) {
            for key_file in plugin.key_files() {
                // Check workspace root
                if working_dir.join(key_file).exists() {
                    copy_to_sandbox(working_dir, sandbox_dir, key_file)?;
                    seeded.push(key_file.to_string());
                }
                // Also walk up to two levels of subdirectories
                // (e.g. crates/*/Cargo.toml, packages/*/package.json)
                if let Ok(entries) = fs::read_dir(working_dir) {
                    for entry in entries.flatten() {
                        let path = entry.path();
                        if path.is_dir() && path.file_name().is_none_or(|n| n != ".perspt") {
                            // Level 1: e.g. crates/Cargo.toml (unlikely but check)
                            let sub_key = path.join(key_file);
                            if sub_key.exists() {
                                let rel = sub_key
                                    .strip_prefix(working_dir)
                                    .unwrap_or(&sub_key)
                                    .to_string_lossy()
                                    .to_string();
                                let _ = copy_to_sandbox(working_dir, sandbox_dir, &rel);
                                seeded.push(rel);
                            }
                            // Level 2: e.g. crates/cfd-core/Cargo.toml
                            if let Ok(sub_entries) = fs::read_dir(&path) {
                                for sub_entry in sub_entries.flatten() {
                                    let sub_path = sub_entry.path();
                                    if sub_path.is_dir() {
                                        let deep_key = sub_path.join(key_file);
                                        if deep_key.exists() {
                                            let rel = deep_key
                                                .strip_prefix(working_dir)
                                                .unwrap_or(&deep_key)
                                                .to_string_lossy()
                                                .to_string();
                                            let _ = copy_to_sandbox(working_dir, sandbox_dir, &rel);
                                            seeded.push(rel);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if !seeded.is_empty() {
        log::debug!("Seeded sandbox with manifests: {}", seeded.join(", "));
    }

    // For Rust workspaces: ensure every workspace member in the sandbox has
    // at minimum a valid Cargo.toml + source target, so commands like
    // `cargo add -p <crate>` can resolve the workspace graph.
    if plugins.contains(&"rust") {
        ensure_rust_workspace_members_in_sandbox(working_dir, sandbox_dir);
    }

    // For Python projects: symlink .venv and seed src/<pkg>/ so uv run
    // commands work immediately in the sandbox.
    if plugins.contains(&"python") {
        seed_python_sandbox(working_dir, sandbox_dir);
    }

    Ok(())
}

/// Ensure all Cargo workspace members in a sandbox have valid Cargo.toml +
/// source target stubs.  Without this, `cargo add -p X` (or any cargo
/// command) fails with "failed to load manifest for workspace member Y"
/// because the sandbox only gets the current node's files but the root
/// Cargo.toml references ALL members.
fn ensure_rust_workspace_members_in_sandbox(working_dir: &Path, sandbox_dir: &Path) {
    let cargo_toml = sandbox_dir.join("Cargo.toml");
    let content = match fs::read_to_string(&cargo_toml) {
        Ok(c) => c,
        Err(_) => return,
    };

    // Quick parse: extract [workspace] members
    let mut in_workspace = false;
    let mut members: Vec<String> = Vec::new();
    for raw_line in content.lines() {
        let line = raw_line.trim();
        if line.starts_with('[') {
            in_workspace = line == "[workspace]";
            continue;
        }
        if in_workspace && line.starts_with("members") {
            if let Some((_, value)) = line.split_once('=') {
                let raw = value.trim();
                if raw.starts_with('[') {
                    let inner = raw.trim_start_matches('[').trim_end_matches(']');
                    for item in inner.split(',') {
                        let member = item.trim().trim_matches('"').trim_matches('\'');
                        if !member.is_empty() {
                            members.push(member.to_string());
                        }
                    }
                }
            }
        }
    }

    for member in &members {
        let member_dir = sandbox_dir.join(member);
        let member_cargo = member_dir.join("Cargo.toml");

        // Try to copy from main workspace first (preserves any real content)
        let src_cargo = working_dir.join(member).join("Cargo.toml");
        if src_cargo.exists() && !member_cargo.exists() {
            let _ = fs::create_dir_all(&member_dir);
            let _ = fs::copy(&src_cargo, &member_cargo);
        }

        // Create a stub Cargo.toml if still missing
        if !member_cargo.exists() {
            let _ = fs::create_dir_all(&member_dir);
            let name = member.rsplit('/').next().unwrap_or(member);
            let stub = format!(
                "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
                name
            );
            let _ = fs::write(&member_cargo, &stub);
        }

        // Ensure at least one source target exists (src/lib.rs or src/main.rs)
        let src_dir = member_dir.join("src");
        let has_lib = src_dir.join("lib.rs").exists();
        let has_main = src_dir.join("main.rs").exists();
        if !has_lib && !has_main {
            let _ = fs::create_dir_all(&src_dir);
            // Try copying from main workspace
            let ws_lib = working_dir.join(member).join("src").join("lib.rs");
            let ws_main = working_dir.join(member).join("src").join("main.rs");
            if ws_lib.exists() {
                let _ = fs::copy(&ws_lib, src_dir.join("lib.rs"));
            } else if ws_main.exists() {
                let _ = fs::copy(&ws_main, src_dir.join("main.rs"));
            } else {
                // Create minimal stub so cargo doesn't complain about missing targets
                let _ = fs::write(
                    src_dir.join("lib.rs"),
                    "// stub — will be replaced by agent\n",
                );
            }
        }
    }

    if !members.is_empty() {
        log::debug!(
            "Ensured {} workspace member(s) have valid stubs in sandbox",
            members.len()
        );
    }
}

/// Seed a Python project sandbox with the workspace `.venv/` (via symlink)
/// and the `src/<pkg>/` package directory tree so that `uv run` commands
/// work immediately without a full re-sync.
fn seed_python_sandbox(working_dir: &Path, sandbox_dir: &Path) {
    // Symlink .venv/ so uv run reuses the workspace venv instead of
    // recreating one per sandbox (saves ~2-3s per node).
    let workspace_venv = working_dir.join(".venv");
    let sandbox_venv = sandbox_dir.join(".venv");
    if workspace_venv.is_dir() && !sandbox_venv.exists() {
        #[cfg(unix)]
        {
            if let Err(e) = std::os::unix::fs::symlink(&workspace_venv, &sandbox_venv) {
                log::debug!("Could not symlink .venv into sandbox: {}", e);
            } else {
                log::debug!("Symlinked .venv into sandbox");
            }
        }
        #[cfg(not(unix))]
        {
            // On Windows, symlinks require elevated privileges; skip the
            // optimisation — uv will auto-create a venv when needed.
            log::debug!("Skipping .venv symlink on non-Unix platform");
        }
    }

    // Seed ancillary files that `uv add` / `uv sync` need when building
    // the project inside the sandbox.  In particular, `uv init` generates
    // `readme = "README.md"` in pyproject.toml, so the sandbox build fails
    // with "failed to open file README.md" if we don't copy it.
    for ancillary in &["README.md", "README.rst", "README", ".python-version"] {
        let src = working_dir.join(ancillary);
        if src.is_file() {
            let dst = sandbox_dir.join(ancillary);
            if !dst.exists() {
                let _ = fs::copy(&src, &dst);
            }
        }
    }

    // Copy the src/<pkg>/ directory tree so imports resolve.  We walk one
    // level under src/ looking for Python packages (__init__.py present).
    let workspace_src = working_dir.join("src");
    if workspace_src.is_dir() {
        if let Ok(entries) = fs::read_dir(&workspace_src) {
            for entry in entries.flatten() {
                let pkg_dir = entry.path();
                if pkg_dir.is_dir() && pkg_dir.join("__init__.py").exists() {
                    // Recursively copy all .py files from this package
                    if let Err(e) = copy_dir_to_sandbox(working_dir, sandbox_dir, &pkg_dir) {
                        log::debug!(
                            "Could not seed src/{} into sandbox: {}",
                            entry.file_name().to_string_lossy(),
                            e
                        );
                    }
                }
            }
        }
    }

    // Also copy conftest.py / tests/ directory if present (needed for pytest)
    for extra in &["conftest.py", "tests"] {
        let src = working_dir.join(extra);
        if src.is_file() {
            let rel = extra.to_string();
            let _ = copy_to_sandbox(working_dir, sandbox_dir, &rel);
        } else if src.is_dir() {
            let _ = copy_dir_to_sandbox(working_dir, sandbox_dir, &src);
        }
    }
}

/// Recursively copy a directory from workspace into sandbox, preserving
/// relative paths.  Skips `.venv`, `__pycache__`, and bytecode files.
fn copy_dir_to_sandbox(
    working_dir: &Path,
    sandbox_dir: &Path,
    src_dir: &Path,
) -> std::io::Result<()> {
    const SKIP: &[&str] = &[".venv", "__pycache__", ".mypy_cache", ".pytest_cache"];
    for entry in fs::read_dir(src_dir)? {
        let entry = entry?;
        let path = entry.path();
        let name = entry.file_name();
        let name_str = name.to_string_lossy();

        if path.is_dir() {
            if SKIP.iter().any(|s| *s == &*name_str) {
                continue;
            }
            copy_dir_to_sandbox(working_dir, sandbox_dir, &path)?;
        } else if !name_str.ends_with(".pyc") {
            if let Ok(rel) = path.strip_prefix(working_dir) {
                let rel_str = rel.to_string_lossy().to_string();
                copy_to_sandbox(working_dir, sandbox_dir, &rel_str)?;
            }
        }
    }
    Ok(())
}

/// Clean up a specific sandbox workspace.
pub fn cleanup_sandbox(sandbox_dir: &Path) -> std::io::Result<()> {
    if sandbox_dir.exists() {
        fs::remove_dir_all(sandbox_dir)?;
        log::debug!("Cleaned up sandbox at {}", sandbox_dir.display());
    }
    Ok(())
}

/// Clean up all sandbox workspaces for a session.
pub fn cleanup_session_sandboxes(working_dir: &Path, session_id: &str) -> std::io::Result<()> {
    let session_sandbox = working_dir
        .join(".perspt")
        .join("sandboxes")
        .join(session_id);

    if session_sandbox.exists() {
        fs::remove_dir_all(&session_sandbox)?;
        log::debug!("Cleaned up all sandboxes for session {}", session_id);
    }
    Ok(())
}

/// Copy a file from the workspace into a sandbox, preserving relative paths.
pub fn copy_to_sandbox(
    working_dir: &Path,
    sandbox_dir: &Path,
    relative_path: &str,
) -> std::io::Result<()> {
    let src = working_dir.join(relative_path);
    let dst = sandbox_dir.join(relative_path);

    if let Some(parent) = dst.parent() {
        fs::create_dir_all(parent)?;
    }

    if src.exists() {
        fs::copy(&src, &dst)?;
    }
    Ok(())
}

/// Copy a file from a sandbox back to the live workspace, preserving relative paths.
pub fn copy_from_sandbox(
    sandbox_dir: &Path,
    working_dir: &Path,
    relative_path: &str,
) -> std::io::Result<()> {
    let src = sandbox_dir.join(relative_path);
    let dst = working_dir.join(relative_path);

    if let Some(parent) = dst.parent() {
        fs::create_dir_all(parent)?;
    }

    if src.exists() {
        fs::copy(&src, &dst)?;
    }
    Ok(())
}

/// List all files in a sandbox directory as workspace-relative paths.
pub fn list_sandbox_files(sandbox_dir: &Path) -> std::io::Result<Vec<String>> {
    let mut files = Vec::new();
    if !sandbox_dir.exists() {
        return Ok(files);
    }
    /// Directories that should never be exported from sandbox back to
    /// workspace — virtual-environments, bytecode caches, build artifacts.
    const SKIP_DIRS: &[&str] = &[
        ".venv",
        "__pycache__",
        "node_modules",
        ".mypy_cache",
        ".pytest_cache",
        ".ruff_cache",
    ];
    fn walk(dir: &Path, base: &Path, out: &mut Vec<String>) -> std::io::Result<()> {
        for entry in fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy();
                if SKIP_DIRS.iter().any(|s| *s == &*name_str) {
                    continue;
                }
                walk(&path, base, out)?;
            } else if let Ok(rel) = path.strip_prefix(base) {
                let normalized = rel
                    .components()
                    .map(|component| component.as_os_str().to_string_lossy().into_owned())
                    .collect::<Vec<_>>()
                    .join("/");
                // Skip bytecode / lock artifacts that shouldn't transfer
                if !normalized.ends_with(".pyc") {
                    out.push(normalized);
                }
            }
        }
        Ok(())
    }
    walk(sandbox_dir, sandbox_dir, &mut files)?;
    Ok(files)
}

#[cfg(test)]
mod sandbox_tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_create_sandbox() {
        let dir = tempdir().unwrap();
        let sandbox = create_sandbox(dir.path(), "sess1", "branch1").unwrap();
        assert!(sandbox.exists());
        assert!(sandbox.ends_with("sess1/branch1"));
    }

    #[test]
    fn test_cleanup_sandbox() {
        let dir = tempdir().unwrap();
        let sandbox = create_sandbox(dir.path(), "sess1", "branch1").unwrap();
        assert!(sandbox.exists());
        cleanup_sandbox(&sandbox).unwrap();
        assert!(!sandbox.exists());
    }

    #[test]
    fn test_cleanup_session_sandboxes() {
        let dir = tempdir().unwrap();
        create_sandbox(dir.path(), "sess1", "b1").unwrap();
        create_sandbox(dir.path(), "sess1", "b2").unwrap();
        let session_dir = dir.path().join(".perspt").join("sandboxes").join("sess1");
        assert!(session_dir.exists());
        cleanup_session_sandboxes(dir.path(), "sess1").unwrap();
        assert!(!session_dir.exists());
    }

    #[test]
    fn test_copy_to_sandbox() {
        let dir = tempdir().unwrap();
        // Create a source file
        let src_dir = dir.path().join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(src_dir.join("main.rs"), "fn main() {}").unwrap();

        let sandbox = create_sandbox(dir.path(), "sess1", "b1").unwrap();
        copy_to_sandbox(dir.path(), &sandbox, "src/main.rs").unwrap();

        let copied = sandbox.join("src/main.rs");
        assert!(copied.exists());
        assert_eq!(fs::read_to_string(copied).unwrap(), "fn main() {}");
    }

    #[test]
    fn test_copy_from_sandbox() {
        let dir = tempdir().unwrap();
        let sandbox = create_sandbox(dir.path(), "sess1", "b1").unwrap();

        // Create a file inside the sandbox
        let sandbox_src = sandbox.join("out");
        fs::create_dir_all(&sandbox_src).unwrap();
        fs::write(sandbox_src.join("result.txt"), "hello").unwrap();

        // Copy back to live workspace
        copy_from_sandbox(&sandbox, dir.path(), "out/result.txt").unwrap();

        let dest = dir.path().join("out/result.txt");
        assert!(dest.exists());
        assert_eq!(fs::read_to_string(dest).unwrap(), "hello");
    }

    #[test]
    fn test_list_sandbox_files_empty() {
        let dir = tempdir().unwrap();
        let sandbox = create_sandbox(dir.path(), "sess1", "b1").unwrap();
        let files = list_sandbox_files(&sandbox).unwrap();
        assert!(files.is_empty());
    }

    #[test]
    fn test_list_sandbox_files_nested() {
        let dir = tempdir().unwrap();
        let sandbox = create_sandbox(dir.path(), "sess1", "b1").unwrap();

        // Create nested structure
        let nested = sandbox.join("a/b");
        fs::create_dir_all(&nested).unwrap();
        fs::write(sandbox.join("top.txt"), "x").unwrap();
        fs::write(nested.join("deep.txt"), "y").unwrap();

        let mut files = list_sandbox_files(&sandbox).unwrap();
        files.sort();
        assert_eq!(files, vec!["a/b/deep.txt", "top.txt"]);
    }
}