selfware 0.6.1

Your personal AI workshop — software you own, software that lasts
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
use super::Tool;
use crate::config::SafetyConfig;
use crate::errors::ToolError;
use crate::safety::path_validator::PathValidator;
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock, RwLock};
use tempfile::NamedTempFile;

/// Global safety configuration set at startup from the user-loaded config.
///
/// `validate_tool_path` no longer reads this directly — `resolve_safety_config()`
/// does. The global exists only as the last-resort fallback when a tool lacks
/// a per-instance config. New tools should always use `with_safety_config()`.
pub(super) static SAFETY_CONFIG: OnceLock<RwLock<SafetyConfig>> = OnceLock::new();

/// Register the runtime-loaded safety configuration for tool path validation.
///
/// This should be called once during agent initialization (before any file tools
/// execute) so that `validate_tool_path` honours user settings.
///
/// DEPRECATED: For multi-agent scenarios where each agent needs a different
/// safety config, use the per-instance `with_safety_config()` constructor on
/// each tool struct instead. This global initializer will be removed once all
/// call sites are migrated to per-instance configs.
pub fn init_safety_config(config: &SafetyConfig) {
    let lock = SAFETY_CONFIG.get_or_init(|| RwLock::new(config.clone()));
    if let Ok(mut guard) = lock.write() {
        *guard = config.clone();
    }
}

/// Reset the process-global safety config to the default for tests.
///
/// This prevents tests that run after agent-initialization tests from
/// inheriting a permissive config left behind in `SAFETY_CONFIG`.
#[cfg(test)]
pub(crate) fn reset_safety_config_for_tests() {
    let lock = SAFETY_CONFIG.get_or_init(|| RwLock::new(SafetyConfig::default()));
    if let Ok(mut guard) = lock.write() {
        *guard = SafetyConfig::default();
    }
}

/// Maximum file size for reads (50 MB) to prevent OOM from accidentally reading huge files.
const MAX_READ_SIZE: u64 = 50 * 1024 * 1024;
/// Maximum file size for writes (10 MB) to prevent accidentally writing huge files.
const MAX_WRITE_SIZE: usize = 10 * 1024 * 1024;

// ---------------------------------------------------------------------------
// File snapshot tracking for stale-guard protection
// ---------------------------------------------------------------------------

/// Snapshot of a file at the time it was last read by `file_read`.
#[derive(Debug, Clone)]
struct FileSnapshot {
    content_hash: u64,
    last_modified: u64,
}

static FILE_SNAPSHOTS: OnceLock<Mutex<HashMap<String, FileSnapshot>>> = OnceLock::new();

fn get_snapshots() -> &'static Mutex<HashMap<String, FileSnapshot>> {
    FILE_SNAPSHOTS.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Record a snapshot of a file after reading it.
pub(crate) fn record_file_snapshot(path: &str, content: &str) {
    let last_modified = std::fs::metadata(path)
        .ok()
        .and_then(|m| m.modified().ok())
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs())
        .unwrap_or(0);

    let mut hasher = DefaultHasher::new();
    content.hash(&mut hasher);
    let content_hash = hasher.finish();

    if let Ok(mut guard) = get_snapshots().lock() {
        guard.insert(
            path.to_string(),
            FileSnapshot {
                content_hash,
                last_modified,
            },
        );
    }
}

/// Remove a file snapshot (e.g. after deletion).
pub(crate) fn clear_file_snapshot(path: &str) {
    if let Ok(mut guard) = get_snapshots().lock() {
        guard.remove(path);
    }
}

/// Check whether a file on disk has changed since the last recorded snapshot.
/// Returns `Some(true)` if stale, `Some(false)` if unchanged, `None` if no snapshot exists.
pub(crate) fn is_file_stale(path: &str) -> Option<bool> {
    let guard = get_snapshots().lock().ok()?;
    let snapshot = guard.get(path)?;

    let metadata = std::fs::metadata(path).ok()?;
    let current_mtime = metadata
        .modified()
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| d.as_secs())?;

    if snapshot.last_modified != current_mtime {
        return Some(true);
    }

    // Secondary hash check for same-mtime modifications
    let current_bytes = std::fs::read(path).ok()?;
    let current_text = String::from_utf8_lossy(&current_bytes);
    let mut hasher = DefaultHasher::new();
    current_text.hash(&mut hasher);
    let current_hash = hasher.finish();

    Some(snapshot.content_hash != current_hash)
}

/// Read a file as raw bytes and convert to String, handling non-UTF8 gracefully.
pub(crate) async fn read_file_with_encoding(path: &Path) -> Result<(String, Vec<u8>)> {
    let bytes = tokio::fs::read(path).await?;
    let text = String::from_utf8_lossy(&bytes).into_owned();
    Ok((text, bytes))
}

/// Detect the line ending style of existing content.
fn detect_line_ending(text: &str) -> &'static str {
    if text.contains("\r\n") {
        "\r\n"
    } else {
        "\n"
    }
}

/// Normalize content to use the given line ending style.
pub(crate) fn preserve_line_endings(content: &str, line_ending: &str) -> String {
    let normalized = content.replace("\r\n", "\n");
    if line_ending == "\r\n" {
        normalized.replace('\n', "\r\n")
    } else {
        normalized
    }
}

/// Read file contents. Supports optional per-instance safety configuration
/// for multi-agent scenarios via [`FileRead::with_safety_config`].
#[derive(Default)]
pub struct FileRead {
    /// Per-instance safety config. When `Some`, overrides the global `SAFETY_CONFIG`.
    /// When `None`, falls back to the global or default config (backward compatible).
    pub safety_config: Option<SafetyConfig>,
}

/// Write or overwrite entire file. Supports optional per-instance safety configuration
/// for multi-agent scenarios via [`FileWrite::with_safety_config`].
#[derive(Default)]
pub struct FileWrite {
    /// Per-instance safety config. When `Some`, overrides the global `SAFETY_CONFIG`.
    pub safety_config: Option<SafetyConfig>,
}

/// Apply surgical edit to file. Supports optional per-instance safety configuration
/// for multi-agent scenarios via [`FileEdit::with_safety_config`].
#[derive(Default)]
pub struct FileEdit {
    /// Per-instance safety config. When `Some`, overrides the global `SAFETY_CONFIG`.
    pub safety_config: Option<SafetyConfig>,
}

/// Delete a file. Supports optional per-instance safety configuration
/// for multi-agent scenarios via [`FileDelete::with_safety_config`].
#[derive(Default)]
pub struct FileDelete {
    /// Per-instance safety config. When `Some`, overrides the global `SAFETY_CONFIG`.
    pub safety_config: Option<SafetyConfig>,
}

/// Apply multiple surgical edits atomically. Supports optional per-instance
/// safety configuration via [`FileMultiEdit::with_safety_config`].
#[derive(Default)]
pub struct FileMultiEdit {
    /// Per-instance safety config. When `Some`, overrides the global `SAFETY_CONFIG`.
    pub safety_config: Option<SafetyConfig>,
}

/// List directory structure. Supports optional per-instance safety configuration
/// for multi-agent scenarios via [`DirectoryTree::with_safety_config`].
#[derive(Default)]
pub struct DirectoryTree {
    /// Per-instance safety config. When `Some`, overrides the global `SAFETY_CONFIG`.
    pub safety_config: Option<SafetyConfig>,
}

// ---------------------------------------------------------------------------
// Constructors for dependency-injected safety configuration.
//
// Each file tool can be created with either:
// - `Tool::new()` / `Tool::default()` -- no per-instance config; uses the global or default
// - `Tool::with_safety_config(config)` -- uses the given config, ignoring the global
// ---------------------------------------------------------------------------

impl FileRead {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl FileWrite {
    pub fn new() -> Self {
        Self {
            safety_config: None,
        }
    }
    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl FileEdit {
    pub fn new() -> Self {
        Self {
            safety_config: None,
        }
    }
    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl FileDelete {
    pub fn new() -> Self {
        Self {
            safety_config: None,
        }
    }
    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl FileMultiEdit {
    pub fn new() -> Self {
        Self {
            safety_config: None,
        }
    }
    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

impl DirectoryTree {
    pub fn new() -> Self {
        Self {
            safety_config: None,
        }
    }
    pub fn with_safety_config(config: SafetyConfig) -> Self {
        Self {
            safety_config: Some(config),
        }
    }
}

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

    fn description(&self) -> &str {
        "Read file contents. Use for examining code, configs, or any text file."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Absolute or relative path to the file"
                },
                "line_range": {
                    "type": "array",
                    "items": {"type": "integer"},
                    "minItems": 2,
                    "maxItems": 2,
                    "description": "Optional [start, end] line range (1-indexed, inclusive)"
                }
            },
            "required": ["path"]
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        #[derive(Deserialize)]
        struct Args {
            path: String,
            line_range: Option<(usize, usize)>,
        }

        let args: Args = serde_json::from_value(args)?;
        let safety = resolve_safety_config(self.safety_config.as_ref());
        validate_tool_path(&args.path, &safety)?;
        let path = PathBuf::from(&args.path);

        // A line_range lets us stream ONLY the requested slice, so a large file
        // can be sliced without loading it whole or tripping the size limit.
        if let Some((start, end)) = args.line_range {
            let (selected_content, lines_scanned, lossy, reached_eof) =
                read_line_slice(&path, start, end).await?;
            let lines_returned = selected_content.lines().count();
            if reached_eof {
                // The scan consumed the whole file, so lines_scanned is the
                // true total line count — safe to report honestly.
                return Ok(serde_json::json!({
                    "content": selected_content,
                    "lines_returned": lines_returned,
                    "total_lines": lines_scanned,
                    "truncated": false,
                    "encoding": if lossy { "utf-8-lossy" } else { "utf-8" },
                    "valid_utf8": !lossy
                }));
            } else {
                // The slice ended before EOF — we do NOT know the true total.
                // Report has_more instead of a misleading total_lines.
                return Ok(serde_json::json!({
                    "content": selected_content,
                    "lines_returned": lines_returned,
                    "total_lines": null,
                    "has_more": true,
                    "truncated": true,
                    "encoding": if lossy { "utf-8-lossy" } else { "utf-8" },
                    "valid_utf8": !lossy
                }));
            }
        }

        // Whole-file read: guard against OOM on huge files.
        if let Ok(metadata) = tokio::fs::metadata(&path).await {
            if metadata.len() > MAX_READ_SIZE {
                return Err(ToolError::FileTooLarge {
                    size: metadata.len(),
                    limit: MAX_READ_SIZE,
                }
                .into());
            }
        }

        let (content, bytes) = read_file_with_encoding(&path).await?;
        let valid_utf8 = std::str::from_utf8(&bytes).is_ok();

        // Record snapshot for stale-guard detection
        record_file_snapshot(&args.path, &content);

        let total_lines = content.lines().count();

        Ok(serde_json::json!({
            "content": content,
            "total_lines": total_lines,
            "truncated": false,
            "encoding": if valid_utf8 { "utf-8" } else { "utf-8-lossy" },
            "valid_utf8": valid_utf8
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::read_only()
    }
}

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

    fn description(&self) -> &str {
        "Write or overwrite entire file. Creates parent directories if needed."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "content": {"type": "string"},
                "backup": {"type": "boolean", "default": true}
            },
            "required": ["path", "content"]
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        #[derive(Deserialize)]
        struct Args {
            path: String,
            content: String,
            #[serde(default = "default_true")]
            backup: bool,
        }

        let args: Args = serde_json::from_value(args)?;
        let safety = resolve_safety_config(self.safety_config.as_ref());
        validate_tool_path(&args.path, &safety)?;
        let path = PathBuf::from(&args.path);

        // Check write size limit to prevent accidentally writing huge files
        if args.content.len() > MAX_WRITE_SIZE {
            return Err(ToolError::WriteTooLarge {
                size: args.content.len(),
                limit: MAX_WRITE_SIZE,
            }
            .into());
        }

        // Stale-guard: reject if file changed since last read
        if path.exists() {
            if let Some(true) = is_file_stale(&args.path) {
                return Err(ToolError::FileStale {
                    path: args.path.clone(),
                }
                .into());
            }
        }

        // Detect existing line endings and preserve them
        let content_to_write = if path.exists() {
            let (existing, existing_bytes) = read_file_with_encoding(&path).await?;
            // Overwriting is a full replace, but refuse to touch a non-UTF-8
            // file: the caller likely believes it is text, and the lossy read
            // above hides what is actually on disk.
            ensure_valid_utf8(&existing_bytes, &args.path, "file_write")?;
            let line_ending = detect_line_ending(&existing);
            preserve_line_endings(&args.content, line_ending)
        } else {
            args.content.clone()
        };

        // Detect no-op writes (content identical to existing file)
        if path.exists() {
            if let Ok(existing) = tokio::fs::read_to_string(&path).await {
                if existing == content_to_write {
                    return Err(ToolError::EditNoOp.into());
                }
            }
        }

        validate_rust_source_if_needed(&path, &content_to_write)?;

        // Create backup if exists
        if args.backup && path.exists() {
            let backup_path = format!("{}.bak", args.path);
            tokio::fs::copy(&path, &backup_path).await?;
        }

        write_atomic(&path, &content_to_write).await?;
        clear_file_snapshot(&args.path);

        Ok(serde_json::json!({
            "success": true,
            "bytes_written": content_to_write.len(),
            "path": args.path
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::file_write()
    }
}

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

    fn description(&self) -> &str {
        "Apply surgical edit to file. The old_str must match EXACTLY once. Include enough context to ensure unique match."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "old_str": {"type": "string", "description": "Exact string to find (must be unique)"},
                "new_str": {"type": "string", "description": "Replacement string (empty to delete)"}
            },
            "required": ["path", "old_str", "new_str"]
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        #[derive(Deserialize)]
        struct Args {
            path: String,
            old_str: String,
            new_str: String,
        }

        let args: Args = serde_json::from_value(args)?;
        let safety = resolve_safety_config(self.safety_config.as_ref());
        validate_tool_path(&args.path, &safety)?;

        // Stale-guard: reject if file changed since last read
        if let Some(true) = is_file_stale(&args.path) {
            return Err(ToolError::FileStale {
                path: args.path.clone(),
            }
            .into());
        }

        let (content, original_bytes) = read_file_with_encoding(Path::new(&args.path)).await?;
        ensure_valid_utf8(&original_bytes, &args.path, "file_edit")?;
        let line_ending = detect_line_ending(&content);

        // Check for exactly one match
        let matches = content.matches(&args.old_str).count();
        if matches == 0 {
            return Err(ToolError::EditStringNotFound.into());
        }
        if matches > 1 {
            return Err(ToolError::EditStringMultiple { count: matches }.into());
        }
        if args.old_str == args.new_str {
            return Err(ToolError::EditNoOp.into());
        }
        if args.new_str.contains(&args.old_str) && content.contains(&args.new_str) {
            bail!(
                "file_edit duplicate insertion rejected: the requested replacement block is already present in {}. Re-read the file and make a different targeted edit.",
                args.path
            );
        }

        // Catastrophic whole-file replacement guard. Replacing the vast majority
        // of a file is almost always an accidental loss of context; prefer
        // smaller, targeted edits. Use file_write if a full rewrite is intended.
        if !content.is_empty() {
            let ratio = args.old_str.len() as f64 / content.len() as f64;
            if ratio > 0.85 {
                bail!(
                    "file_edit rejected: old_str matches {:.0}% of {}. \
                     Use a smaller, targeted edit with surrounding context, \
                     or use file_write if you truly intend to replace the entire file.",
                    ratio * 100.0,
                    args.path
                );
            }
        }

        let new_content = content.replace(&args.old_str, &args.new_str);
        let new_content = preserve_line_endings(&new_content, line_ending);
        validate_rust_source_if_needed(Path::new(&args.path), &new_content)?;
        write_atomic(Path::new(&args.path), &new_content).await?;
        clear_file_snapshot(&args.path);

        Ok(serde_json::json!({
            "success": true,
            "matches_found": 1,
            "path": args.path
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::file_write()
    }
}

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

    fn description(&self) -> &str {
        "Delete a file. Use with caution -- this is irreversible without version control."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {
                    "type": "string",
                    "description": "Absolute or relative path to the file to delete"
                }
            },
            "required": ["path"]
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        #[derive(Deserialize)]
        struct Args {
            path: String,
        }

        let args: Args = serde_json::from_value(args)?;
        let safety = resolve_safety_config(self.safety_config.as_ref());
        validate_tool_path(&args.path, &safety)?;
        let path = PathBuf::from(&args.path);

        if !path.exists() {
            return Err(ToolError::FileNotFound {
                path: args.path.clone(),
            }
            .into());
        }
        if path.is_dir() {
            return Err(ToolError::PathIsDirectory {
                path: args.path.clone(),
            }
            .into());
        }

        // Stale-guard: reject if file changed since last read
        if let Some(true) = is_file_stale(&args.path) {
            return Err(ToolError::FileStale {
                path: args.path.clone(),
            }
            .into());
        }

        tokio::fs::remove_file(&path)
            .await
            .with_context(|| format!("Failed to delete file: {}", args.path))?;

        clear_file_snapshot(&args.path);

        Ok(serde_json::json!({
            "deleted": true,
            "path": args.path
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::file_destructive()
    }
}

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

    fn description(&self) -> &str {
        "Apply multiple surgical edits atomically. If any edit fails validation, NONE are applied."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "edits": {
                    "type": "array",
                    "description": "Ordered list of edits to apply",
                    "items": {
                        "type": "object",
                        "properties": {
                            "path": {"type": "string"},
                            "old_str": {"type": "string", "description": "Exact string to find (must be unique)"},
                            "new_str": {"type": "string", "description": "Replacement string"}
                        },
                        "required": ["path", "old_str", "new_str"]
                    }
                }
            },
            "required": ["edits"]
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        #[derive(Deserialize)]
        struct EditItem {
            path: String,
            old_str: String,
            new_str: String,
        }

        #[derive(Deserialize)]
        struct Args {
            edits: Vec<EditItem>,
        }

        let args: Args = serde_json::from_value(args)?;
        let safety = resolve_safety_config(self.safety_config.as_ref());

        if args.edits.is_empty() {
            return Err(ToolError::InvalidToolCall {
                name: "file_multi_edit".to_string(),
                message: "No edits provided".to_string(),
            }
            .into());
        }

        // Validate paths and stale-guard first
        for edit in &args.edits {
            validate_tool_path(&edit.path, &safety)?;
            if let Some(true) = is_file_stale(&edit.path) {
                return Err(ToolError::FileStale {
                    path: edit.path.clone(),
                }
                .into());
            }
        }

        // Group edits by file path
        let mut edits_by_file: HashMap<String, Vec<(usize, &EditItem)>> = HashMap::new();
        for (idx, edit) in args.edits.iter().enumerate() {
            edits_by_file
                .entry(edit.path.clone())
                .or_default()
                .push((idx, edit));
        }

        // Phase 1: read all files and validate edits (find line ranges, check overlaps, unique matches)
        let mut file_contents: HashMap<String, String> = HashMap::new();
        let mut file_line_endings: HashMap<String, &'static str> = HashMap::new();

        for (path, edits) in &edits_by_file {
            let (content, original_bytes) = read_file_with_encoding(Path::new(path)).await?;
            ensure_valid_utf8(&original_bytes, path, "file_multi_edit")?;
            file_line_endings.insert(path.clone(), detect_line_ending(&content));

            // Validate each edit: exactly one match
            for (idx, edit) in edits {
                let matches = content.matches(&edit.old_str).count();
                if matches == 0 {
                    return Err(ToolError::Execution {
                        name: "file_multi_edit".to_string(),
                        message: format!("Edit {}: old_str not found in {}", idx, edit.path),
                    }
                    .into());
                }
                if matches > 1 {
                    return Err(ToolError::Execution {
                        name: "file_multi_edit".to_string(),
                        message: format!(
                            "Edit {}: old_str matches {} times in {} (expected exactly 1)",
                            idx, matches, edit.path
                        ),
                    }
                    .into());
                }
                if edit.old_str == edit.new_str {
                    return Err(ToolError::Execution {
                        name: "file_multi_edit".to_string(),
                        message: format!(
                            "Edit {}: old_str and new_str are identical in {} — no-op edit",
                            idx, edit.path
                        ),
                    }
                    .into());
                }
            }

            // Check for overlapping edits in the same file
            if edits.len() > 1 {
                let mut ranges = Vec::new();
                for (_idx, edit) in edits {
                    let byte_pos =
                        content
                            .find(&edit.old_str)
                            .ok_or_else(|| ToolError::Execution {
                                name: "file_multi_edit".to_string(),
                                message: format!("old_str not found in {}", edit.path),
                            })?;
                    let before = &content[..byte_pos];
                    let start_line = before.lines().count() + 1;
                    let end_line = start_line + edit.old_str.lines().count().saturating_sub(1);
                    ranges.push((start_line, end_line, edit));
                }

                for i in 0..ranges.len() {
                    for j in (i + 1)..ranges.len() {
                        let (s1, e1, edit1) = &ranges[i];
                        let (s2, e2, _edit2) = &ranges[j];
                        if s1 <= e2 && s2 <= e1 {
                            return Err(ToolError::Execution {
                                name: "file_multi_edit".to_string(),
                                message: format!(
                                    "Edits overlap in {}: lines {}-{} and {}-{}",
                                    edit1.path, s1, e1, s2, e2
                                ),
                            }
                            .into());
                        }
                    }
                }
            }

            file_contents.insert(path.clone(), content);
        }

        // Phase 2: compute every file's final content up front (including Rust
        // syntax validation), THEN write them all in one batch. If any write
        // fails, `write_all_atomic` rolls back the files already persisted from
        // their pre-images — a failed batch never leaves 1..N-1 files modified.
        // Paths are processed in sorted order so the batch is deterministic
        // (HashMap iteration order is not).
        let mut sorted_paths: Vec<&String> = edits_by_file.keys().collect();
        sorted_paths.sort();

        let mut finals: Vec<(PathBuf, String)> = Vec::with_capacity(sorted_paths.len());
        for path in sorted_paths {
            let edits = &edits_by_file[path];
            let content = file_contents.get_mut(path).unwrap();
            let line_ending = file_line_endings.get(path).copied().unwrap_or("\n");

            // Build (byte_pos, old_len, new_str) for each edit
            let mut replacements: Vec<(usize, usize, String)> = Vec::new();
            for (_idx, edit) in edits {
                let pos = content.find(&edit.old_str).unwrap();
                replacements.push((pos, edit.old_str.len(), edit.new_str.clone()));
            }

            // Sort by position descending so earlier replacements don't shift later ones
            replacements.sort_by_key(|r| r.0);
            replacements.reverse();

            for (pos, len, new_str) in replacements {
                content.replace_range(pos..pos + len, &new_str);
            }

            let final_content = preserve_line_endings(content, line_ending);
            validate_rust_source_if_needed(Path::new(path), &final_content)?;
            finals.push((PathBuf::from(path), final_content));
        }

        write_all_atomic(&finals).await?;
        for (path, _) in &finals {
            clear_file_snapshot(&path.to_string_lossy());
        }

        let files_changed: Vec<String> = finals
            .iter()
            .map(|(path, _)| path.to_string_lossy().into_owned())
            .collect();
        Ok(serde_json::json!({
            "success": true,
            "edits_applied": args.edits.len(),
            "files_changed": files_changed.len(),
            "files": files_changed
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::file_write()
    }
}

/// Nested node returned by the `directory_tree` tool.
#[derive(Serialize)]
struct TreeNode {
    name: String,
    #[serde(rename = "type")]
    type_: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    size: Option<u64>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    children: Vec<TreeNode>,
}

/// Insert a walked entry into the nested tree based on its relative path.
fn insert_tree_entry(root: &mut TreeNode, relative: &Path, type_: &str, size: u64) {
    let mut components: Vec<String> = relative
        .components()
        .map(|c| c.as_os_str().to_string_lossy().to_string())
        .collect();
    if components.is_empty() {
        return;
    }
    let file_name = components.pop().unwrap();

    let mut current = root;
    for component in components {
        let child_idx = current
            .children
            .iter()
            .position(|c| c.name == component && c.type_ == "directory");
        let idx = match child_idx {
            Some(idx) => idx,
            None => {
                current.children.push(TreeNode {
                    name: component,
                    type_: "directory".to_string(),
                    size: None,
                    children: Vec::new(),
                });
                current.children.len() - 1
            }
        };
        current = &mut current.children[idx];
    }

    // If this entry is a directory, it may already exist as a parent placeholder
    // from a previously-inserted child. Reuse that node and just mark it.
    if type_ == "directory" {
        if let Some(existing) = current
            .children
            .iter_mut()
            .find(|c| c.name == file_name && c.type_ == "directory")
        {
            existing.size = Some(size);
            return;
        }
    }

    current.children.push(TreeNode {
        name: file_name,
        type_: type_.to_string(),
        size: Some(size),
        children: Vec::new(),
    });
}

/// Recursively sort a tree node: directories first, then files alphabetically.
fn sort_tree_node(node: &mut TreeNode) {
    node.children.sort_by(|a, b| {
        let a_dir = a.type_ == "directory";
        let b_dir = b.type_ == "directory";
        match (a_dir, b_dir) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => a.name.cmp(&b.name),
        }
    });
    for child in &mut node.children {
        sort_tree_node(child);
    }
}

/// Count all nodes in the tree (including the root).
fn count_tree_nodes(node: &TreeNode) -> usize {
    1 + node.children.iter().map(count_tree_nodes).sum::<usize>()
}

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

    fn description(&self) -> &str {
        "Return a nested directory tree. Use to understand project layout and parent/child relationships."
    }

    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "path": {"type": "string"},
                "max_depth": {"type": "integer", "default": 3},
                "include_hidden": {"type": "boolean", "default": false}
            },
            "required": ["path"]
        })
    }

    async fn execute(&self, args: Value) -> Result<Value> {
        #[derive(Deserialize)]
        struct Args {
            path: String,
            #[serde(default = "default_three")]
            max_depth: usize,
            #[serde(default)]
            include_hidden: bool,
        }

        let args: Args = serde_json::from_value(args)?;
        let safety = resolve_safety_config(self.safety_config.as_ref());
        validate_tool_path(&args.path, &safety)?;

        let walk_path = args.path.clone();
        let max_depth = args.max_depth;
        let include_hidden = args.include_hidden;

        let tree: TreeNode = tokio::task::spawn_blocking(move || {
            // Use filter_entry (not filter_map) so hidden directories are not descended into.
            // filter_map would skip the hidden entry from output but still walk its children.
            /// Directories to never descend into — build artifacts, caches, VCS internals.
            const SKIP_DIRS: &[&str] = &[
                "target",
                "node_modules",
                "dist",
                "build",
                "__pycache__",
                ".worktrees",
                "vendor",
                "pkg",
                "out",
                "cmake-build-debug",
            ];

            let walker = walkdir::WalkDir::new(&walk_path)
                .max_depth(max_depth)
                .into_iter()
                .filter_entry(|e| {
                    if include_hidden {
                        return true;
                    }
                    if e.depth() == 0 {
                        return true;
                    }
                    let name = e.file_name().to_str().unwrap_or("");
                    // Skip hidden entries and known-large directories
                    !name.starts_with('.') && !SKIP_DIRS.contains(&name)
                });

            #[derive(Serialize)]
            struct EntryInfo {
                path: PathBuf,
                type_: &'static str,
                size: u64,
            }

            let mut entries: Vec<EntryInfo> = Vec::new();
            for entry in walker.filter_map(|e| e.ok()) {
                let path = entry.path();
                let metadata = match entry.metadata() {
                    Ok(m) => m,
                    Err(_) => continue,
                };

                entries.push(EntryInfo {
                    path: path.to_path_buf(),
                    type_: if metadata.is_dir() {
                        "directory"
                    } else {
                        "file"
                    },
                    size: metadata.len(),
                });
            }

            let root_name = Path::new(&walk_path)
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| walk_path.clone());

            let mut root = TreeNode {
                name: root_name,
                type_: "directory".to_string(),
                size: None,
                children: Vec::new(),
            };

            let walk_path_buf = PathBuf::from(&walk_path);
            for entry in entries {
                let relative = match entry.path.strip_prefix(&walk_path_buf) {
                    Ok(r) if !r.as_os_str().is_empty() => r,
                    _ => continue,
                };
                insert_tree_entry(&mut root, relative, entry.type_, entry.size);
            }

            sort_tree_node(&mut root);
            root
        })
        .await?;

        let total = count_tree_nodes(&tree);

        Ok(serde_json::json!({
            "root": args.path,
            "tree": tree,
            "total": total
        }))
    }

    fn metadata(&self) -> crate::safety::ToolMetadata {
        crate::safety::ToolMetadata::read_only()
    }
}

fn default_true() -> bool {
    true
}
fn default_three() -> usize {
    3
}

/// Resolve which `SafetyConfig` to use for path validation.
///
/// Priority: per-instance config > process-global > default.
/// Call this at the tool level, then pass the result to `validate_tool_path`.
/// This keeps the global state lookup at the tool boundary rather than
/// buried inside the validation function.
pub(crate) fn resolve_safety_config(instance_config: Option<&SafetyConfig>) -> SafetyConfig {
    if let Some(cfg) = instance_config {
        return cfg.clone();
    }
    SAFETY_CONFIG
        .get()
        .and_then(|lock| lock.read().ok().map(|guard| guard.clone()))
        .unwrap_or_default()
}

/// Validate that a tool path is safe to access.
///
/// Takes a resolved `&SafetyConfig` — callers should use
/// `resolve_safety_config()` to pick the right config before calling this.
pub(crate) fn validate_tool_path(path: &str, config: &SafetyConfig) -> Result<()> {
    #[cfg(test)]
    {
        if std::env::var("SELFWARE_TEST_MODE").is_ok() {
            if !path.starts_with("tests/e2e-projects/") && !path.starts_with("/tmp/selfware-test-")
            {
                anyhow::bail!("Test mode only valid for test fixtures, got: {}", path);
            }
            return Ok(());
        }
    }
    let working_dir = std::env::current_dir().unwrap_or_else(|_| ".".into());
    PathValidator::new(config, working_dir)
        .validate(path)
        .map_err(|e| anyhow::anyhow!(e))
}

fn validate_rust_source_if_needed(path: &Path, content: &str) -> Result<()> {
    let is_rust_source = path
        .extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| ext.eq_ignore_ascii_case("rs"));
    if !is_rust_source {
        return Ok(());
    }

    syn::parse_file(content).map(|_| ()).map_err(|err| {
        ToolError::InvalidRustSyntax {
            path: path.display().to_string(),
            message: err.to_string(),
        }
        .into()
    })
}

/// Read only lines `start..=end` (1-based, inclusive) by streaming the file, so
/// a large file can be sliced without loading it all into memory. Bytes are
/// decoded as UTF-8 lossily (adequate for a line slice of source/text files).
/// Returns the joined slice, the number of lines scanned (== the true total
/// only when the scan reached EOF), and whether any returned line contained
/// invalid UTF-8 (i.e. the returned text is lossy rather than exact).
async fn read_line_slice(
    path: &Path,
    start: usize,
    end: usize,
) -> Result<(String, usize, bool, bool)> {
    use tokio::io::{AsyncBufReadExt, BufReader};
    // Preserve the legacy contract that an inverted range (end < start) yields
    // the single line at `start`.
    let effective_end = end.max(start);
    let file = tokio::fs::File::open(path).await?;
    let mut reader = BufReader::new(file);
    let mut selected: Vec<String> = Vec::new();
    let mut lineno = 0usize;
    let mut lossy = false;
    let mut reached_eof = false;
    let mut buf: Vec<u8> = Vec::new();
    loop {
        buf.clear();
        let n = reader.read_until(b'\n', &mut buf).await?;
        if n == 0 {
            reached_eof = true;
            break;
        }
        lineno += 1;
        if lineno >= start && lineno <= effective_end {
            if std::str::from_utf8(&buf).is_err() {
                lossy = true;
            }
            let mut line = String::from_utf8_lossy(&buf).into_owned();
            if line.ends_with('\n') {
                line.pop();
                if line.ends_with('\r') {
                    line.pop();
                }
            }
            selected.push(line);
        }
        if lineno >= effective_end {
            break; // stop early — don't read the rest of a huge file
        }
    }
    Ok((selected.join("\n"), lineno, lossy, reached_eof))
}

/// Write content to a file atomically using a temporary file and rename.
///
/// The existing file's permission mode is carried over to the replacement —
/// `NamedTempFile` is created `0600`, so without this an executable would
/// silently lose `+x` and a shared config would become owner-only on every
/// edit. New files keep the temp-file default.
pub(crate) async fn write_atomic(path: &Path, content: &str) -> Result<()> {
    write_all_atomic(&[(path.to_path_buf(), content.to_string())]).await
}

/// Capture the unix permission mode of an existing file, if it exists.
#[cfg(unix)]
fn existing_file_mode(path: &Path) -> Option<u32> {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path).ok().map(|m| m.permissions().mode())
}

/// Atomically write several files at once: stage every replacement in a temp
/// file first, then persist them all. If any persist fails, files already
/// persisted are rolled back from their captured pre-images so a multi-file
/// batch never commits half-way. Each replacement inherits the target's
/// existing permission mode (see [`write_atomic`]).
pub(crate) async fn write_all_atomic(files: &[(PathBuf, String)]) -> Result<()> {
    // Capture pre-images up front so a mid-batch persist failure can roll back.
    let mut pre_images: Vec<(PathBuf, Option<Vec<u8>>)> = Vec::with_capacity(files.len());
    for (path, _) in files {
        pre_images.push((path.clone(), tokio::fs::read(path).await.ok()));
    }

    // NamedTempFile and Write::write_all are sync APIs; offload to a blocking
    // thread so we don't block the async executor.
    let files_owned: Vec<(PathBuf, String)> = files.to_vec();
    tokio::task::spawn_blocking(move || {
        // Phase 1: stage every replacement in a temp file in the target dir.
        let mut staged: Vec<(NamedTempFile, PathBuf)> = Vec::with_capacity(files_owned.len());
        for (path, content) in &files_owned {
            let parent = path
                .parent()
                .ok_or_else(|| anyhow::anyhow!("Invalid file path (no parent)"))?;
            std::fs::create_dir_all(parent)?;
            let mut temp = NamedTempFile::new_in(parent)?;
            temp.write_all(content.as_bytes())?;
            #[cfg(unix)]
            if let Some(mode) = existing_file_mode(path) {
                use std::os::unix::fs::PermissionsExt;
                std::fs::set_permissions(
                    temp.path(),
                    std::fs::Permissions::from_mode(mode & 0o7777),
                )?;
            }
            staged.push((temp, path.clone()));
        }

        // Phase 2: persist them all; roll back earlier persists on failure.
        for (idx, (temp, path)) in staged.into_iter().enumerate() {
            if let Err(e) = temp.persist(&path) {
                for (rb_path, pre_image) in pre_images.iter().take(idx) {
                    match pre_image {
                        Some(bytes) => {
                            let _ = std::fs::write(rb_path, bytes);
                        }
                        None => {
                            let _ = std::fs::remove_file(rb_path);
                        }
                    }
                }
                return Err(anyhow::anyhow!(
                    "Failed to persist atomic write to {}: {} (rolled back {} earlier file(s))",
                    path.display(),
                    e,
                    idx
                ));
            }
        }
        Ok(())
    })
    .await?
}

/// Refuse to rewrite a file whose bytes are not valid UTF-8.
///
/// The edit pipeline decodes via `String::from_utf8_lossy`; writing the lossy
/// view back would replace every invalid byte with U+FFFD and silently corrupt
/// binary (or otherwise-encoded) files. Better to fail loudly.
fn ensure_valid_utf8(bytes: &[u8], path: &str, tool: &str) -> Result<()> {
    if std::str::from_utf8(bytes).is_err() {
        return Err(ToolError::Execution {
            name: tool.to_string(),
            message: format!(
                "Refusing to modify {}: the file is not valid UTF-8 (binary or another \
                 encoding). Editing it through a lossy decode would corrupt its contents. \
                 If a full overwrite of a non-text file is truly intended, delete it first.",
                path
            ),
        }
        .into());
    }
    Ok(())
}

#[cfg(test)]
#[path = "../../tests/unit/tools/file/file_test.rs"]
mod tests;