clausura-core 1.0.6

Core library for Clausura — a CI-native agent for deterministic pipeline gating
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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
use crate::types::ToolDef;
use crate::types::ToolError;
use async_trait::async_trait;
use regex_lite::Regex;
use serde_json::Value;
use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Tool trait
// ---------------------------------------------------------------------------

/// A tool that the agent can invoke.
#[async_trait]
pub trait Tool: Send + Sync {
    /// Tool name (used by LLM to invoke)
    fn name(&self) -> &str;
    /// Description of what the tool does
    fn description(&self) -> &str;
    /// JSON Schema for tool parameters
    fn parameters(&self) -> Value;
    /// Execute the tool with given arguments
    async fn execute(&self, args: Value) -> Result<String, ToolError>;
}

// ---------------------------------------------------------------------------
// ToolRegistry
// ---------------------------------------------------------------------------

/// Registry of available tools for the agent.
pub struct ToolRegistry {
    tools: HashMap<String, Arc<dyn Tool>>,
}

impl ToolRegistry {
    pub fn new() -> Self {
        Self {
            tools: HashMap::new(),
        }
    }

    /// Register a tool.
    pub fn register<T: Tool + 'static>(&mut self, tool: T) {
        let name = tool.name().to_string();
        self.tools.insert(name, Arc::new(tool));
    }

    /// Get a tool by name.
    pub fn get(&self, name: &str) -> Option<Arc<dyn Tool>> {
        self.tools.get(name).cloned()
    }

    /// Get all tool definitions for LLM function calling.
    pub fn list_definitions(&self) -> Vec<ToolDef> {
        self.tools
            .values()
            .map(|t| ToolDef {
                name: t.name().to_string(),
                description: t.description().to_string(),
                parameters: t.parameters(),
            })
            .collect()
    }
}

impl Default for ToolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// ReadFileTool
// ---------------------------------------------------------------------------

/// Reads a file relative to the workspace root. Path traversal is rejected.
pub struct ReadFileTool {
    workspace_root: PathBuf,
}

/// Resolve a path relative to the workspace root, enforcing sandbox restrictions.
/// Returns the canonicalized absolute path, or a ToolError.
pub fn resolve_sandboxed_path(workspace_root: &Path, path_str: &str) -> Result<PathBuf, ToolError> {
    let requested = Path::new(path_str);
    // Reject absolute paths
    if requested.is_absolute() {
        return Err(ToolError::SandboxViolation(format!(
            "Absolute paths not allowed: {}",
            path_str
        )));
    }
    // Reject paths with ..
    if requested.components().any(|c| c.as_os_str() == "..") {
        return Err(ToolError::SandboxViolation(format!(
            "Path traversal not allowed: {}",
            path_str
        )));
    }
    // Canonicalize to prevent symlink-based escapes
    let full_path = workspace_root.join(requested);
    let canonical = full_path
        .canonicalize()
        .map_err(|_| ToolError::ExecutionFailed(format!("File not found: {}", path_str)))?;
    // Verify we're still inside workspace root
    if !canonical.starts_with(workspace_root) {
        return Err(ToolError::SandboxViolation(
            "Path escapes workspace root".into(),
        ));
    }
    Ok(canonical)
}

impl ReadFileTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        // Canonicalize workspace root once so symlinks are resolved consistently
        let canonical_root = workspace_root.canonicalize().unwrap_or(workspace_root);
        Self {
            workspace_root: canonical_root,
        }
    }

    fn resolve_path(&self, path_str: &str) -> Result<PathBuf, ToolError> {
        resolve_sandboxed_path(&self.workspace_root, path_str)
    }
}

#[async_trait]
impl Tool for ReadFileTool {
    fn name(&self) -> &str {
        "read_file"
    }

    fn description(&self) -> &str {
        "Read the contents of a file. Path is relative to the workspace root."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Path relative to workspace root"
                },
                "offset": {
                    "type": "integer",
                    "description": "1-based starting line (default: 1, read from start)"
                },
                "limit": {
                    "type": "integer",
                    "description": "Max lines to read (default: read to end)"
                }
            },
            "required": ["path"]
        })
    }

    async fn execute(&self, args: Value) -> Result<String, ToolError> {
        let path_str = args["path"]
            .as_str()
            .ok_or_else(|| ToolError::ExecutionFailed("Missing 'path' argument".into()))?;
        let resolved = self.resolve_path(path_str)?;
        let content = tokio::fs::read_to_string(&resolved)
            .await
            .map_err(|e| ToolError::ExecutionFailed(format!("Read error: {}", e)))?;

        let offset = args["offset"].as_u64().unwrap_or(1) as usize;
        let limit = args["limit"].as_u64().map(|l| l as usize);

        // offset is 1-based: offset=1 means no skip
        let lines: Vec<&str> = content.lines().skip(offset.saturating_sub(1)).collect();

        let result = if let Some(limit) = limit {
            if limit == 0 {
                String::new()
            } else {
                lines.into_iter().take(limit).collect::<Vec<_>>().join("\n")
            }
        } else {
            lines.join("\n")
        };

        Ok(result)
    }
}

// ---------------------------------------------------------------------------
// GitDiffTool
// ---------------------------------------------------------------------------

/// Runs git diff to get code changes.
pub struct GitDiffTool {
    workspace_root: PathBuf,
}

impl GitDiffTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        Self { workspace_root }
    }

    async fn run_git(&self, args: &[&str]) -> Result<String, ToolError> {
        let output = tokio::process::Command::new("git")
            .current_dir(&self.workspace_root)
            .args(args)
            .output()
            .await
            .map_err(|e| ToolError::ExecutionFailed(format!("Git error: {}", e)))?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).to_string())
        } else {
            let stderr = String::from_utf8_lossy(&output.stderr);
            Err(ToolError::ExecutionFailed(format!(
                "Git failed: {}",
                stderr
            )))
        }
    }
}

#[async_trait]
impl Tool for GitDiffTool {
    fn name(&self) -> &str {
        "git_diff"
    }

    fn description(&self) -> &str {
        "Get the git diff. Use with 'base' to diff against a branch, or 'staged' for staged changes only."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "base": {
                    "type": "string",
                    "description": "Base ref to diff against (e.g., HEAD~1, main)"
                },
                "staged": {
                    "type": "boolean",
                    "description": "Show staged changes only"
                }
            }
        })
    }

    async fn execute(&self, args: Value) -> Result<String, ToolError> {
        let base = args["base"].as_str();
        let staged = args["staged"].as_bool().unwrap_or(false);

        let git_args: &[&str] = if let Some(base_ref) = base {
            &["diff", base_ref]
        } else if staged {
            &["diff", "--cached"]
        } else {
            &["diff"]
        };

        self.run_git(git_args).await
    }
}

// ---------------------------------------------------------------------------
// ShellExecTool
// ---------------------------------------------------------------------------

/// Executes shell commands from a configured allowlist.
pub struct ShellExecTool {
    workspace_root: PathBuf,
    allowlist: Vec<String>,
}

impl ShellExecTool {
    pub fn new(workspace_root: PathBuf, allowlist: Vec<String>) -> Self {
        Self {
            workspace_root,
            allowlist,
        }
    }

    fn check_allowed(&self, command: &str) -> Result<(), ToolError> {
        let cmd_name = command.split_whitespace().next().unwrap_or("");
        if self.allowlist.is_empty() {
            return Err(ToolError::SandboxViolation(
                "No commands allowed (empty allowlist)".into(),
            ));
        }
        // Check both the raw token and its basename to support "/usr/bin/git" style
        let basename = Path::new(cmd_name)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(cmd_name);
        let allowed = self.allowlist.contains(&cmd_name.to_string())
            || self.allowlist.contains(&basename.to_string());
        if !allowed {
            return Err(ToolError::SandboxViolation(format!(
                "Command not in allowlist: {} (basename: {}). Allowed: {:?}",
                cmd_name, basename, self.allowlist
            )));
        }
        Ok(())
    }
}

#[async_trait]
impl Tool for ShellExecTool {
    fn name(&self) -> &str {
        "shell_exec"
    }

    fn description(&self) -> &str {
        "Execute a shell command from the allowed list."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "command": {
                    "type": "string",
                    "description": "Shell command to execute"
                }
            },
            "required": ["command"]
        })
    }

    async fn execute(&self, args: Value) -> Result<String, ToolError> {
        let command = args["command"]
            .as_str()
            .ok_or_else(|| ToolError::ExecutionFailed("Missing 'command' argument".into()))?;

        self.check_allowed(command)?;

        let output = tokio::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .current_dir(&self.workspace_root)
            .output()
            .await
            .map_err(|e| ToolError::ExecutionFailed(format!("Shell error: {}", e)))?;

        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);

        if output.status.success() {
            Ok(stdout.to_string())
        } else {
            // Return stderr as the output even on failure (tool result, not error)
            Ok(format!(
                "Exit code: {}\nStderr: {}",
                output.status.code().unwrap_or(-1),
                stderr
            ))
        }
    }
}

// ---------------------------------------------------------------------------
// ListFilesTool
// ---------------------------------------------------------------------------

/// List files and directories within the workspace.
pub struct ListFilesTool {
    workspace_root: PathBuf,
}

/// Simple glob-like filename matching.
fn matches_glob(filename: &str, glob: &str) -> bool {
    if let Some(inner) = glob.strip_prefix('*').and_then(|s| s.strip_suffix('*')) {
        filename.contains(inner)
    } else if let Some(suffix) = glob.strip_prefix('*') {
        filename.ends_with(suffix)
    } else if let Some(prefix) = glob.strip_suffix('*') {
        filename.starts_with(prefix)
    } else {
        filename == glob
    }
}

/// Recursively list directory contents.
fn list_directory(
    root: &Path,
    dir: &Path,
    depth: u32,
    max_depth: u32,
    glob: Option<&str>,
    include_size: bool,
) -> Vec<String> {
    let mut result = Vec::new();

    let mut entries: Vec<_> = match std::fs::read_dir(dir) {
        Ok(reader) => reader.filter_map(|e| e.ok()).collect(),
        Err(e) => {
            let rel = dir.strip_prefix(root).unwrap_or(dir);
            result.push(format!("! {} ({})", rel.display(), e));
            return result;
        }
    };

    entries.sort_by_key(|a| a.file_name());

    for entry in &entries {
        let path = entry.path();
        let file_name = entry.file_name();
        let file_name_str = file_name.to_string_lossy();

        if file_name_str == ".clausura" {
            continue;
        }

        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(e) => {
                let rel = path.strip_prefix(root).unwrap_or(&path);
                result.push(format!("! {} ({})", rel.display(), e));
                continue;
            }
        };

        if file_type.is_dir() {
            let rel = path.strip_prefix(root).unwrap_or(&path);
            result.push(format!("{}/", rel.display()));

            if depth < max_depth {
                result.extend(list_directory(
                    root,
                    &path,
                    depth + 1,
                    max_depth,
                    glob,
                    include_size,
                ));
            }
        } else {
            if let Some(g) = glob {
                if !g.is_empty() && !matches_glob(&file_name_str, g) {
                    continue;
                }
            }

            let rel = path.strip_prefix(root).unwrap_or(&path);
            if include_size {
                match std::fs::symlink_metadata(&path) {
                    Ok(meta) => {
                        result.push(format!("{} ({} B)", rel.display(), meta.len()));
                    }
                    Err(e) => {
                        result.push(format!("! {} ({})", rel.display(), e));
                    }
                }
            } else {
                result.push(rel.display().to_string());
            }
        }
    }

    result
}

impl ListFilesTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        let canonical_root = workspace_root.canonicalize().unwrap_or(workspace_root);
        Self {
            workspace_root: canonical_root,
        }
    }
}

#[async_trait]
impl Tool for ListFilesTool {
    fn name(&self) -> &str {
        "list_files"
    }

    fn description(&self) -> &str {
        "List files and directories. Path is relative to the workspace root."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Relative path to list"
                },
                "recursive": {
                    "type": "boolean",
                    "description": "Recursively list subdirectories"
                },
                "max_depth": {
                    "type": "integer",
                    "description": "Max recursion depth"
                },
                "glob": {
                    "type": "string",
                    "description": "Filename filter pattern"
                },
                "include_size": {
                    "type": "boolean",
                    "description": "Show file sizes"
                }
            },
            "required": ["path"]
        })
    }

    async fn execute(&self, args: Value) -> Result<String, ToolError> {
        let path_str = args["path"]
            .as_str()
            .ok_or_else(|| ToolError::ExecutionFailed("Missing 'path' argument".into()))?;

        let resolved = resolve_sandboxed_path(&self.workspace_root, path_str)?;

        if !resolved.is_dir() {
            return Err(ToolError::ExecutionFailed(format!(
                "Not a directory: {}",
                path_str
            )));
        }

        let recursive = args["recursive"].as_bool().unwrap_or(true);
        let max_depth_raw = args["max_depth"].as_u64().unwrap_or(3) as u32;
        let max_depth = if recursive { max_depth_raw.min(3) } else { 0 };
        let glob = args["glob"].as_str();
        let include_size = args["include_size"].as_bool().unwrap_or(false);

        let lines = list_directory(
            &self.workspace_root,
            &resolved,
            0,
            max_depth,
            glob,
            include_size,
        );

        Ok(lines.join("\n"))
    }
}

// ---------------------------------------------------------------------------
// GrepTool
// ---------------------------------------------------------------------------

/// Returns true if the first 8 KB of the file contains a null byte.
fn is_binary_file(path: &Path) -> bool {
    let mut buf = [0u8; 8192];
    let mut f = match std::fs::File::open(path) {
        Ok(f) => f,
        Err(_) => return false, // can't read → treat as non-binary (will fail later)
    };
    let n = f.read(&mut buf).unwrap_or(0);
    buf[..n].contains(&0)
}

/// Configuration for grep search operations, bundling the parameters shared
/// across search_file and grep_directory.
struct GrepCfg<'a> {
    root: &'a Path,
    pattern: &'a str,
    is_regex: bool,
    file_types: &'a [String],
    regex: Option<&'a Regex>,
}

/// Search a single file for pattern matches, returning false when max_results
/// is reached.
/// Returns true if the path (after symlink resolution) is within the root.
fn path_in_root(root: &Path, path: &Path) -> bool {
    let resolved = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    resolved.starts_with(root)
}

fn search_file(
    path: &Path,
    cfg: &GrepCfg,
    max_results: &mut usize,
    remaining: &mut usize,
    results: &mut Vec<String>,
) -> bool {
    if is_binary_file(path) {
        return true;
    }
    // Skip symlinks that resolve outside the workspace root
    if !path_in_root(cfg.root, path) {
        return true;
    }
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(_) => return true,
    };
    let rel = path.strip_prefix(cfg.root).unwrap_or(path);
    for (line_num, line) in content.lines().enumerate() {
        if *max_results > 0 && results.len() >= *max_results {
            *remaining += 1;
            continue;
        }
        let matched = if cfg.is_regex {
            cfg.regex.is_some_and(|re| re.is_match(line))
        } else {
            line.contains(cfg.pattern)
        };
        if matched {
            let truncated = if line.len() > 200 { &line[..200] } else { line };
            results.push(format!("{}:{}: {}", rel.display(), line_num + 1, truncated));
        }
    }
    true
}

fn grep_directory(
    cfg: &GrepCfg,
    dir: &Path,
    max_results: &mut usize,
    remaining: &mut usize,
    results: &mut Vec<String>,
) {
    let to_skip = [".git", "target", ".clausura", "node_modules"];

    let mut entries: Vec<_> = match std::fs::read_dir(dir) {
        Ok(reader) => reader.filter_map(|e| e.ok()).collect(),
        Err(_) => return,
    };

    entries.sort_by_key(|a| a.file_name());

    for entry in &entries {
        let path = entry.path();
        let file_name = entry.file_name();
        let file_name_str = file_name.to_string_lossy();

        if to_skip.contains(&file_name_str.as_ref()) {
            continue;
        }

        let file_type = match entry.file_type() {
            Ok(ft) => ft,
            Err(_) => continue,
        };

        if file_type.is_dir() {
            grep_directory(cfg, &path, max_results, remaining, results);
        } else {
            if !cfg.file_types.is_empty() {
                let matches_ext = cfg
                    .file_types
                    .iter()
                    .any(|ext| file_name_str.ends_with(ext.as_str()));
                if !matches_ext {
                    continue;
                }
            }
            // Skip symlinks that resolve outside workspace
            if path.is_symlink() && !path_in_root(cfg.root, &path) {
                continue;
            }
            let more = search_file(&path, cfg, max_results, remaining, results);
            if !more {
                break;
            }
        }
    }
}

/// Searches for text patterns across files in the workspace, supporting both
/// literal and regex matching.
pub struct GrepTool {
    workspace_root: PathBuf,
}

impl GrepTool {
    pub fn new(workspace_root: PathBuf) -> Self {
        let canonical_root = workspace_root.canonicalize().unwrap_or(workspace_root);
        Self {
            workspace_root: canonical_root,
        }
    }
}

#[async_trait]
impl Tool for GrepTool {
    fn name(&self) -> &str {
        "grep"
    }

    fn description(&self) -> &str {
        "Search for text patterns in files. Supports literal (default) and regex matching. Path is relative to the workspace root. Note: regex mode uses a simplified engine without lookahead, lookbehind, backreferences, or Unicode property escapes."
    }

    fn parameters(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "File or directory to search (relative path)"
                },
                "pattern": {
                    "type": "string",
                    "description": "Text pattern to search for"
                },
                "regex": {
                    "type": "boolean",
                    "description": "Use regex search via regex-lite (default: false)"
                },
                "file_types": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Only search files with these extensions, e.g., [\".rs\", \".toml\"]"
                },
                "max_results": {
                    "type": "integer",
                    "description": "Maximum number of results to return (default: 50, max: 200)"
                }
            },
            "required": ["path", "pattern"]
        })
    }

    async fn execute(&self, args: Value) -> Result<String, ToolError> {
        let path_str = args["path"]
            .as_str()
            .ok_or_else(|| ToolError::ExecutionFailed("Missing 'path' argument".into()))?;
        let pattern = args["pattern"]
            .as_str()
            .ok_or_else(|| ToolError::ExecutionFailed("Missing 'pattern' argument".into()))?;
        let is_regex = args["regex"].as_bool().unwrap_or(false);

        let file_types: Vec<String> = args["file_types"]
            .as_array()
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();

        let max_results_raw = args["max_results"].as_u64().unwrap_or(50) as usize;
        let max_results = max_results_raw.min(200);

        let resolved = resolve_sandboxed_path(&self.workspace_root, path_str)?;

        let regex = if is_regex {
            match Regex::new(pattern) {
                Ok(re) => Some(re),
                Err(e) => {
                    return Err(ToolError::ExecutionFailed(format!(
                        "Invalid regex pattern: {pattern}{e}"
                    )));
                }
            }
        } else {
            None
        };

        let mut remaining = 0usize;
        let mut max = max_results;

        let cfg = GrepCfg {
            root: &self.workspace_root,
            pattern,
            is_regex,
            file_types: &file_types,
            regex: regex.as_ref(),
        };

        let mut results = Vec::new();
        if resolved.is_file() {
            search_file(&resolved, &cfg, &mut max, &mut remaining, &mut results);
        } else if resolved.is_dir() {
            grep_directory(&cfg, &resolved, &mut max, &mut remaining, &mut results);
        } else {
            return Err(ToolError::ExecutionFailed(format!(
                "Not a file or directory: {}",
                path_str
            )));
        };

        let mut output = results.join("\n");

        if remaining > 0 {
            if !output.is_empty() {
                output.push('\n');
            }
            output.push_str(&format!(
                "... and {} more matches (use more specific pattern or narrower path)",
                remaining
            ));
        }

        Ok(output)
    }
}

/// Create the default set of tools for the given workspace root.
/// If allowlist is empty, shell_exec is disabled (no commands allowed).
pub fn default_tools(workspace_root: PathBuf, allowlist: &[String]) -> ToolRegistry {
    let mut registry = ToolRegistry::new();
    registry.register(ReadFileTool::new(workspace_root.clone()));
    registry.register(GitDiffTool::new(workspace_root.clone()));
    registry.register(ShellExecTool::new(
        workspace_root.clone(),
        allowlist.to_vec(),
    ));
    registry.register(ListFilesTool::new(workspace_root.clone()));
    registry.register(GrepTool::new(workspace_root));
    registry
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn setup_workspace() -> (TempDir, PathBuf) {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().to_path_buf();
        (tmp, path)
    }

    // -----------------------------------------------------------------------
    // ReadFileTool tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_read_file_success() {
        let (_tmp, root) = setup_workspace();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "hello world").unwrap();

        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt"}))
            .await
            .unwrap();
        assert_eq!(result, "hello world");
    }

    #[tokio::test]
    async fn test_read_file_rejects_traversal() {
        let (_tmp, root) = setup_workspace();
        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "../etc/passwd"}))
            .await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_read_file_rejects_absolute() {
        let (_tmp, root) = setup_workspace();
        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "/etc/passwd"}))
            .await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_read_file_missing_path_arg() {
        let (_tmp, root) = setup_workspace();
        let tool = ReadFileTool::new(root);
        let result = tool.execute(serde_json::json!({})).await;
        assert!(matches!(result, Err(ToolError::ExecutionFailed(_))));
    }

    #[tokio::test]
    async fn test_read_file_not_found() {
        let (_tmp, root) = setup_workspace();
        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "nonexistent.txt"}))
            .await;
        assert!(matches!(result, Err(ToolError::ExecutionFailed(_))));
    }

    #[tokio::test]
    async fn test_read_file_with_offset() {
        let (_tmp, root) = setup_workspace();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "line1\nline2\nline3\nline4\nline5").unwrap();

        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "offset": 3}))
            .await
            .unwrap();
        assert_eq!(result, "line3\nline4\nline5");
    }

    #[tokio::test]
    async fn test_read_file_with_limit() {
        let (_tmp, root) = setup_workspace();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "line1\nline2\nline3\nline4\nline5").unwrap();

        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "limit": 2}))
            .await
            .unwrap();
        assert_eq!(result, "line1\nline2");
    }

    #[tokio::test]
    async fn test_read_file_offset_and_limit() {
        let (_tmp, root) = setup_workspace();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "line1\nline2\nline3\nline4\nline5").unwrap();

        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "offset": 2, "limit": 2}))
            .await
            .unwrap();
        assert_eq!(result, "line2\nline3");
    }

    #[tokio::test]
    async fn test_read_file_offset_exceeds_file() {
        let (_tmp, root) = setup_workspace();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "line1\nline2\nline3").unwrap();

        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "offset": 10}))
            .await
            .unwrap();
        assert_eq!(result, "");
    }

    #[tokio::test]
    async fn test_read_file_limit_zero() {
        let (_tmp, root) = setup_workspace();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "line1\nline2\nline3").unwrap();

        let tool = ReadFileTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "limit": 0}))
            .await
            .unwrap();
        assert_eq!(result, "");
    }

    // -----------------------------------------------------------------------
    // resolve_sandboxed_path tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_resolve_sandboxed_accepts_valid() {
        let (_tmp, root) = setup_workspace();
        let root = root.canonicalize().unwrap();
        let test_file = root.join("test.txt");
        std::fs::write(&test_file, "hello").unwrap();

        let result = resolve_sandboxed_path(&root, "test.txt");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), test_file.canonicalize().unwrap());
    }

    #[tokio::test]
    async fn test_resolve_sandboxed_rejects_absolute() {
        let (_tmp, root) = setup_workspace();
        let result = resolve_sandboxed_path(&root, "/etc/passwd");
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_resolve_sandboxed_rejects_traversal() {
        let (_tmp, root) = setup_workspace();
        let result = resolve_sandboxed_path(&root, "../outside");
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    // -----------------------------------------------------------------------
    // GitDiffTool tests
    // -----------------------------------------------------------------------

    async fn init_git_repo(root: &Path) {
        tokio::process::Command::new("git")
            .args(["init"])
            .current_dir(root)
            .output()
            .await
            .unwrap();
        tokio::process::Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(root)
            .output()
            .await
            .unwrap();
        tokio::process::Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(root)
            .output()
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_git_diff_basic() {
        let (_tmp, root) = setup_workspace();
        init_git_repo(&root).await;

        std::fs::write(root.join("file.txt"), "v1").unwrap();
        tokio::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&root)
            .output()
            .await
            .unwrap();
        tokio::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(&root)
            .output()
            .await
            .unwrap();

        std::fs::write(root.join("file.txt"), "v2").unwrap();

        let tool = GitDiffTool::new(root);
        let result = tool
            .execute(serde_json::json!({"staged": false}))
            .await
            .unwrap();
        assert!(
            result.contains("v1") || result.contains("v2") || result.contains("file.txt"),
            "Expected diff to mention changes, got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_git_diff_with_base() {
        let (_tmp, root) = setup_workspace();
        init_git_repo(&root).await;

        std::fs::write(root.join("file.txt"), "v1").unwrap();
        tokio::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&root)
            .output()
            .await
            .unwrap();
        tokio::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(&root)
            .output()
            .await
            .unwrap();

        std::fs::write(root.join("file.txt"), "v2").unwrap();

        let tool = GitDiffTool::new(root);
        let result = tool
            .execute(serde_json::json!({"base": "HEAD"}))
            .await
            .unwrap();
        assert!(!result.is_empty(), "Expected non-empty diff against HEAD");
    }

    #[tokio::test]
    async fn test_git_diff_staged() {
        let (_tmp, root) = setup_workspace();
        init_git_repo(&root).await;

        std::fs::write(root.join("file.txt"), "v1").unwrap();
        tokio::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&root)
            .output()
            .await
            .unwrap();
        tokio::process::Command::new("git")
            .args(["commit", "-m", "initial"])
            .current_dir(&root)
            .output()
            .await
            .unwrap();

        std::fs::write(root.join("file.txt"), "v2").unwrap();
        tokio::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&root)
            .output()
            .await
            .unwrap();

        let tool = GitDiffTool::new(root);
        let result = tool
            .execute(serde_json::json!({"staged": true}))
            .await
            .unwrap();
        assert!(
            result.contains("v1") || result.contains("v2"),
            "Expected staged diff to mention file content, got: {}",
            result
        );
    }

    // -----------------------------------------------------------------------
    // ShellExecTool tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_shell_exec_allowed_command() {
        let (_tmp, root) = setup_workspace();
        let allowlist = vec!["git".into(), "grep".into()];
        let tool = ShellExecTool::new(root, allowlist);

        let result = tool
            .execute(serde_json::json!({"command": "git status"}))
            .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_shell_exec_denied_command() {
        let (_tmp, root) = setup_workspace();
        let allowlist = vec!["git".into(), "grep".into()];
        let tool = ShellExecTool::new(root, allowlist);

        let result = tool
            .execute(serde_json::json!({"command": "rm -rf /"}))
            .await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_shell_exec_empty_allowlist() {
        let (_tmp, root) = setup_workspace();
        let allowlist: Vec<String> = vec![];
        let tool = ShellExecTool::new(root, allowlist);

        let result = tool.execute(serde_json::json!({"command": "ls"})).await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_shell_exec_missing_arg() {
        let (_tmp, root) = setup_workspace();
        let allowlist = vec!["git".into()];
        let tool = ShellExecTool::new(root, allowlist);

        let result = tool.execute(serde_json::json!({})).await;
        assert!(matches!(result, Err(ToolError::ExecutionFailed(_))));
    }

    // -----------------------------------------------------------------------
    // ListFilesTool tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_list_files_basic() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("a.txt"), "").unwrap();
        std::fs::write(root.join("b.txt"), "").unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "recursive": false}))
            .await
            .unwrap();
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 2);
        assert!(lines.contains(&"a.txt"));
        assert!(lines.contains(&"b.txt"));
    }

    #[tokio::test]
    async fn test_list_files_recursive() {
        let (_tmp, root) = setup_workspace();
        std::fs::create_dir_all(root.join("sub/nested")).unwrap();
        std::fs::write(root.join("top.txt"), "").unwrap();
        std::fs::write(root.join("sub/inner.txt"), "").unwrap();
        std::fs::write(root.join("sub/nested/deep.txt"), "").unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "max_depth": 2}))
            .await
            .unwrap();
        let lines: Vec<&str> = result.lines().collect();
        assert!(lines.contains(&"top.txt"));
        assert!(lines.contains(&"sub/"));
        assert!(lines.contains(&"sub/inner.txt"));
        assert!(lines.contains(&"sub/nested/"));
        assert!(lines.contains(&"sub/nested/deep.txt"));
    }

    #[tokio::test]
    async fn test_list_files_glob_filter() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("main.rs"), "").unwrap();
        std::fs::write(root.join("lib.rs"), "").unwrap();
        std::fs::write(root.join("README.md"), "").unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "glob": "*.rs", "recursive": false}))
            .await
            .unwrap();
        let lines: Vec<&str> = result.lines().collect();
        assert_eq!(lines.len(), 2);
        assert!(lines.contains(&"main.rs"));
        assert!(lines.contains(&"lib.rs"));
    }

    #[tokio::test]
    async fn test_list_files_include_size() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("data.bin"), "hello").unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "include_size": true, "recursive": false}))
            .await
            .unwrap();
        assert!(
            result.contains(" B"),
            "Expected size suffix, got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_list_files_rejects_absolute() {
        let (_tmp, root) = setup_workspace();
        let tool = ListFilesTool::new(root);
        let result = tool.execute(serde_json::json!({"path": "/etc"})).await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_list_files_rejects_traversal() {
        let (_tmp, root) = setup_workspace();
        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "../outside"}))
            .await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_list_files_empty_directory() {
        let (_tmp, root) = setup_workspace();
        std::fs::create_dir(root.join("empty")).unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "empty"}))
            .await
            .unwrap();
        assert_eq!(result, "");
    }

    #[tokio::test]
    async fn test_list_files_excludes_clausura_dir() {
        let (_tmp, root) = setup_workspace();
        std::fs::create_dir(root.join(".clausura")).unwrap();
        std::fs::write(root.join(".clausura/config.yaml"), "").unwrap();
        std::fs::write(root.join("visible.txt"), "").unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "recursive": true}))
            .await
            .unwrap();
        assert!(
            !result.contains(".clausura"),
            "Output should not contain .clausura:\n{}",
            result
        );
        assert!(result.contains("visible.txt"));
    }

    #[tokio::test]
    async fn test_list_files_max_depth() {
        let (_tmp, root) = setup_workspace();
        std::fs::create_dir_all(root.join("a/b/c/d")).unwrap();
        std::fs::write(root.join("a/b/c/d/deep.txt"), "").unwrap();
        std::fs::write(root.join("a/top.txt"), "").unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "max_depth": 5}))
            .await
            .unwrap();
        assert!(
            result.contains("a/top.txt"),
            "Expected a/top.txt in output:\n{}",
            result
        );
        assert!(
            result.contains("a/b/c/d/"),
            "Expected a/b/c/d/ (level 3) in output:\n{}",
            result
        );
        assert!(
            !result.contains("a/b/c/d/deep.txt"),
            "Did not expect a/b/c/d/deep.txt (depth > 3) in output:\n{}",
            result
        );
    }

    // -----------------------------------------------------------------------
    // ToolRegistry tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_tool_registry_register_and_get() {
        let (_tmp, root) = setup_workspace();
        let mut registry = ToolRegistry::new();
        registry.register(ReadFileTool::new(root));

        let defs = registry.list_definitions();
        assert_eq!(defs.len(), 1);
        assert_eq!(defs[0].name, "read_file");

        let tool = registry.get("read_file");
        assert!(tool.is_some());
        assert_eq!(tool.unwrap().name(), "read_file");

        let missing = registry.get("nonexistent");
        assert!(missing.is_none());
    }

    #[test]
    fn test_tool_registry_multiple_tools() {
        let (_tmp, root) = setup_workspace();
        let mut registry = ToolRegistry::new();
        registry.register(ReadFileTool::new(root.clone()));
        registry.register(GitDiffTool::new(root));

        let defs = registry.list_definitions();
        assert_eq!(defs.len(), 2);
        let names: Vec<&str> = defs.iter().map(|d| d.name.as_str()).collect();
        assert!(names.contains(&"read_file"));
        assert!(names.contains(&"git_diff"));
    }

    // -----------------------------------------------------------------------
    // default_tools tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_default_tools_contains_all() {
        let (_tmp, root) = setup_workspace();
        let registry = default_tools(root, &[]);
        let defs = registry.list_definitions();
        assert_eq!(defs.len(), 5);
        let names: Vec<&str> = defs.iter().map(|d| d.name.as_str()).collect();
        assert!(names.contains(&"read_file"));
        assert!(names.contains(&"git_diff"));
        assert!(names.contains(&"shell_exec"));
        assert!(names.contains(&"list_files"));
        assert!(names.contains(&"grep"));
    }

    #[test]
    fn test_tool_registry_default() {
        let registry: ToolRegistry = Default::default();
        let defs = registry.list_definitions();
        assert!(defs.is_empty());
    }

    // -----------------------------------------------------------------------
    // GrepTool tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_grep_literal_basic() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("test.txt"), "hello world\nfoo bar\nhello again").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "pattern": "hello"}))
            .await
            .unwrap();
        assert!(result.contains("test.txt:1: hello world"));
        assert!(result.contains("test.txt:3: hello again"));
        assert!(!result.contains("foo bar"));
    }

    #[tokio::test]
    async fn test_grep_literal_no_matches() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("test.txt"), "hello world\nfoo bar").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "pattern": "nonexistent"}))
            .await
            .unwrap();
        assert_eq!(result, "");
    }

    #[tokio::test]
    async fn test_grep_regex_basic() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(
            root.join("test.txt"),
            "line1 alpha\nline2 beta\nother gamma",
        )
        .unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "pattern": "line\\d+", "regex": true}))
            .await
            .unwrap();
        assert!(result.contains("test.txt:1: line1 alpha"));
        assert!(result.contains("test.txt:2: line2 beta"));
        assert!(!result.contains("other gamma"));
    }

    #[tokio::test]
    async fn test_grep_regex_invalid() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("test.txt"), "content").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "test.txt", "pattern": "[invalid", "regex": true}))
            .await;
        assert!(matches!(result, Err(ToolError::ExecutionFailed(_))));
        let err_msg = format!("{:?}", result.unwrap_err());
        assert!(err_msg.contains("Invalid regex pattern"));
    }

    #[tokio::test]
    async fn test_grep_file_types_filter() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("main.rs"), "fn main() {}\nhello fn").unwrap();
        std::fs::write(root.join("README.md"), "hello readme").unwrap();
        std::fs::write(root.join("Cargo.toml"), "hello cargo").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({
                "path": ".",
                "pattern": "hello",
                "file_types": [".rs", ".toml"]
            }))
            .await
            .unwrap();
        assert!(result.contains("main.rs"));
        assert!(result.contains("Cargo.toml"));
        assert!(!result.contains("README.md"));
    }

    #[tokio::test]
    async fn test_grep_excludes_dirs() {
        let (_tmp, root) = setup_workspace();
        std::fs::create_dir_all(root.join(".git")).unwrap();
        std::fs::write(root.join(".git/config"), "hello git").unwrap();
        std::fs::create_dir_all(root.join("target/debug")).unwrap();
        std::fs::write(root.join("target/debug/output"), "hello target").unwrap();
        std::fs::create_dir_all(root.join("node_modules/pkg")).unwrap();
        std::fs::write(root.join("node_modules/pkg/index.js"), "hello node").unwrap();
        std::fs::write(root.join("src.txt"), "hello src").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "pattern": "hello"}))
            .await
            .unwrap();
        assert!(
            result.contains("src.txt"),
            "Should find src.txt, got: {}",
            result
        );
        assert!(
            !result.contains(".git"),
            "Should exclude .git, got: {}",
            result
        );
        assert!(
            !result.contains("target"),
            "Should exclude target, got: {}",
            result
        );
        assert!(
            !result.contains("node_modules"),
            "Should exclude node_modules, got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_grep_skips_binary() {
        let (_tmp, root) = setup_workspace();
        let binary_content: Vec<u8> = vec![0x00, 0x01, 0x02, 0x68, 0x65, 0x6c, 0x6c, 0x6f]; // null + "hello"
        std::fs::write(root.join("data.bin"), binary_content).unwrap();
        std::fs::write(root.join("text.txt"), "hello world").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "pattern": "hello"}))
            .await
            .unwrap();
        assert!(
            result.contains("text.txt"),
            "Should find text.txt, got: {}",
            result
        );
        assert!(
            !result.contains("data.bin"),
            "Should skip binary data.bin, got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_grep_max_results_truncation() {
        let (_tmp, root) = setup_workspace();
        let mut content = String::new();
        for i in 1..=100 {
            content.push_str(&format!("line {} match\n", i));
        }
        std::fs::write(root.join("big.txt"), content).unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "big.txt", "pattern": "match", "max_results": 20}))
            .await
            .unwrap();
        let lines: Vec<&str> = result.lines().collect();
        let match_lines = lines.iter().filter(|l| l.contains(":")).count();
        let truncation_line = lines.iter().find(|l| l.starts_with("... and "));
        assert_eq!(match_lines, 20, "Expected 20 match lines, got: {}", result);
        assert!(
            truncation_line.is_some(),
            "Expected truncation notice, got: {}",
            result
        );
    }

    #[tokio::test]
    async fn test_grep_rejects_traversal() {
        let (_tmp, root) = setup_workspace();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "../outside", "pattern": "test"}))
            .await;
        assert!(matches!(result, Err(ToolError::SandboxViolation(_))));
    }

    #[tokio::test]
    async fn test_grep_single_file() {
        let (_tmp, root) = setup_workspace();
        std::fs::write(root.join("a.rs"), "hello a").unwrap();
        std::fs::write(root.join("b.rs"), "hello b").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": "a.rs", "pattern": "hello"}))
            .await
            .unwrap();
        assert!(result.contains("a.rs:1: hello a"));
        assert!(!result.contains("b.rs"));
    }

    // -----------------------------------------------------------------------
    // Symlink security tests (P2-4, P2-5)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_list_files_symlink_metadata_no_leak() {
        let (_tmp, root) = setup_workspace();
        // Create a file outside the workspace
        let outside = std::env::temp_dir().join("clausura-secret.txt");
        std::fs::write(&outside, "SECRET_DATA").unwrap();
        // Create a symlink inside workspace pointing outside
        std::os::unix::fs::symlink(&outside, root.join("link.txt")).unwrap();

        let tool = ListFilesTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "include_size": true, "recursive": false}))
            .await
            .unwrap();
        // Should show the symlink entry without following it for size
        assert!(
            result.contains("link.txt"),
            "Should list symlink: {}",
            result
        );
        // The size should be the symlink's own size, not the target's size
        // (symlink to a file is typically a few bytes, not 11 bytes like "SECRET_DATA")
        let _ = std::fs::remove_file(&outside);
    }

    #[tokio::test]
    async fn test_grep_skips_symlink_outside_workspace() {
        let (_tmp, root) = setup_workspace();
        let root = root.canonicalize().unwrap();
        // Create a file outside workspace with searchable content
        let outside = std::env::temp_dir().join("clausura-outside.txt");
        std::fs::write(&outside, "SHOULD_NOT_FIND").unwrap();
        // Create symlink inside workspace pointing outside
        std::os::unix::fs::symlink(&outside, root.join("outside_link.txt")).unwrap();
        // Create a normal file inside workspace
        std::fs::write(root.join("inside.txt"), "SHOULD_FIND").unwrap();

        let tool = GrepTool::new(root);
        let result = tool
            .execute(serde_json::json!({"path": ".", "pattern": "SHOULD"}))
            .await
            .unwrap();
        assert!(
            result.contains("inside.txt"),
            "Should find inside file: {}",
            result
        );
        assert!(
            !result.contains("SHOULD_NOT_FIND"),
            "Should NOT follow symlink outside workspace: {}",
            result
        );
        let _ = std::fs::remove_file(&outside);
    }

    // -----------------------------------------------------------------------
    // ShellExecTool allowlist tests (P2-6)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_shell_exec_allows_absolute_path_basename() {
        let (_tmp, root) = setup_workspace();
        // Allowlist has "git", command uses "/usr/bin/git style"
        let allowlist = vec!["git".into()];
        let tool = ShellExecTool::new(root, allowlist);

        // /usr/bin/git should match because basename is "git"
        let result = tool
            .execute(serde_json::json!({"command": "git status"}))
            .await;
        assert!(result.is_ok(), "git should be allowed: {:?}", result.err());
    }

    #[tokio::test]
    async fn test_shell_exec_rejects_path_traversal_in_command() {
        let (_tmp, root) = setup_workspace();
        let allowlist = vec!["cat".into()];
        let tool = ShellExecTool::new(root, allowlist);

        // Even though "cat" is in allowlist, /etc/passwd access should be blocked
        // by the shell's own sandboxing (workspace root). But the allowlist check
        // should at minimum not match "/etc/passwd" as "cat".
        let result = tool
            .execute(serde_json::json!({"command": "/etc/passwd"}))
            .await;
        assert!(
            matches!(result, Err(ToolError::SandboxViolation(_))),
            "Should reject /etc/passwd command"
        );
    }
}