heroforge-core 0.2.2

Pure Rust core library for reading and writing Fossil SCM repositories
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
//! Filesystem operations builder for high-level file manipulation.
//!
//! This module provides a fluent API for performing filesystem-like operations
//! on repository contents. All modifications are staged and committed atomically.
//!
//! # Overview
//!
//! Access filesystem operations through [`Repository::fs()`](crate::Repository::fs):
//!
//! ```no_run
//! use heroforge_core::Repository;
//!
//! let repo = Repository::open_rw("project.forge")?;
//!
//! // Modify files (copy, move, delete, etc.)
//! repo.fs().modify()
//!     .message("Reorganize project")
//!     .author("developer")
//!     .copy_file("README.md", "docs/README.md")
//!     .move_dir("scripts", "tools")
//!     .delete_file("old.txt")
//!     .execute()?;
//!
//! // Find files with patterns
//! let rust_files = repo.fs().find()
//!     .pattern("**/*.rs")
//!     .ignore("target/**")
//!     .paths()?;
//!
//! // Utility functions
//! let exists = repo.fs().exists("README.md")?;
//! let size = repo.fs().du("**/*.rs")?;
//! # Ok::<(), heroforge_core::FossilError>(())
//! ```
//!
//! # Modification Operations
//!
//! Use [`FsOpsBuilder::modify()`] to start a modification chain:
//!
//! ## Copy Operations
//! - [`FsBuilder::copy_file()`] - Copy a single file
//! - [`FsBuilder::copy_dir()`] - Copy a directory recursively
//!
//! ## Move/Rename Operations
//! - [`FsBuilder::move_file()`] - Move or rename a file
//! - [`FsBuilder::move_dir()`] - Move or rename a directory
//! - [`FsBuilder::rename()`] - Alias for move_file
//!
//! ## Delete Operations
//! - [`FsBuilder::delete_file()`] - Delete a file (silent if missing)
//! - [`FsBuilder::delete_dir()`] - Delete a directory recursively
//! - [`FsBuilder::delete_matching()`] - Delete files matching a glob pattern
//!
//! ## Permission Operations
//! - [`FsBuilder::chmod()`] - Change file permissions (octal)
//! - [`FsBuilder::chmod_dir()`] - Change directory permissions recursively
//! - [`FsBuilder::make_executable()`] - Make a file executable (755)
//!
//! ## Symlink Operations
//! - [`FsBuilder::symlink()`] - Create a symbolic link
//!
//! ## Write Operations
//! - [`FsBuilder::write()`] - Write bytes to a file
//! - [`FsBuilder::write_str()`] - Write a string to a file
//! - [`FsBuilder::touch()`] - Create an empty file
//!
//! # Find Operations
//!
//! Use [`FsOpsBuilder::find()`] to search for files:
//!
//! ```no_run
//! # use heroforge_core::Repository;
//! # let repo = Repository::open("project.forge")?;
//! // Find all Rust files, excluding target directory
//! let files = repo.fs().find()
//!     .pattern("**/*.rs")
//!     .ignore("target/**")
//!     .ignore_hidden()
//!     .max_depth(5)
//!     .paths()?;
//!
//! // Use gitignore-style defaults
//! let clean = repo.fs().find()
//!     .pattern("**/*")
//!     .use_gitignore()
//!     .execute()?;
//! # Ok::<(), heroforge_core::FossilError>(())
//! ```
//!
//! # Utility Functions
//!
//! Quick checks without building operations:
//!
//! - [`FsOpsBuilder::exists()`] - Check if a file exists
//! - [`FsOpsBuilder::is_dir()`] - Check if a path is a directory
//! - [`FsOpsBuilder::stat()`] - Get file metadata
//! - [`FsOpsBuilder::du()`] - Calculate total size of matching files
//! - [`FsOpsBuilder::count()`] - Count matching files
//! - [`FsOpsBuilder::list_symlinks()`] - List all symbolic links

use crate::error::{FossilError, Result};
use crate::repo::Repository;
use std::collections::HashMap;

/// Unix-style file permissions.
///
/// # Examples
///
/// ```
/// use heroforge_core::Permissions;
///
/// // Create from octal
/// let perms = Permissions::from_octal(0o755);
/// assert_eq!(perms.to_string_repr(), "rwxr-xr-x");
///
/// // Use preset
/// let exec = Permissions::executable();
/// assert_eq!(exec.to_octal(), 0o755);
///
/// let readonly = Permissions::readonly();
/// assert_eq!(readonly.to_octal(), 0o444);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Permissions {
    /// Read permission for owner
    pub owner_read: bool,
    /// Write permission for owner
    pub owner_write: bool,
    /// Execute permission for owner
    pub owner_exec: bool,
    /// Read permission for group
    pub group_read: bool,
    /// Write permission for group
    pub group_write: bool,
    /// Execute permission for group
    pub group_exec: bool,
    /// Read permission for others
    pub other_read: bool,
    /// Write permission for others
    pub other_write: bool,
    /// Execute permission for others
    pub other_exec: bool,
}

impl Permissions {
    /// Create permissions from octal (e.g., 0o755).
    ///
    /// # Examples
    ///
    /// ```
    /// use heroforge_core::Permissions;
    ///
    /// let perms = Permissions::from_octal(0o644);
    /// assert!(perms.owner_read);
    /// assert!(perms.owner_write);
    /// assert!(!perms.owner_exec);
    /// ```
    pub fn from_octal(mode: u32) -> Self {
        Self {
            owner_read: mode & 0o400 != 0,
            owner_write: mode & 0o200 != 0,
            owner_exec: mode & 0o100 != 0,
            group_read: mode & 0o040 != 0,
            group_write: mode & 0o020 != 0,
            group_exec: mode & 0o010 != 0,
            other_read: mode & 0o004 != 0,
            other_write: mode & 0o002 != 0,
            other_exec: mode & 0o001 != 0,
        }
    }

    /// Convert to octal representation.
    ///
    /// # Examples
    ///
    /// ```
    /// use heroforge_core::Permissions;
    ///
    /// let perms = Permissions::executable();
    /// assert_eq!(perms.to_octal(), 0o755);
    /// ```
    pub fn to_octal(&self) -> u32 {
        let mut mode = 0u32;
        if self.owner_read {
            mode |= 0o400;
        }
        if self.owner_write {
            mode |= 0o200;
        }
        if self.owner_exec {
            mode |= 0o100;
        }
        if self.group_read {
            mode |= 0o040;
        }
        if self.group_write {
            mode |= 0o020;
        }
        if self.group_exec {
            mode |= 0o010;
        }
        if self.other_read {
            mode |= 0o004;
        }
        if self.other_write {
            mode |= 0o002;
        }
        if self.other_exec {
            mode |= 0o001;
        }
        mode
    }

    /// Convert to string representation (e.g., "rwxr-xr-x").
    ///
    /// # Examples
    ///
    /// ```
    /// use heroforge_core::Permissions;
    ///
    /// assert_eq!(Permissions::from_octal(0o755).to_string_repr(), "rwxr-xr-x");
    /// assert_eq!(Permissions::from_octal(0o644).to_string_repr(), "rw-r--r--");
    /// ```
    pub fn to_string_repr(&self) -> String {
        format!(
            "{}{}{}{}{}{}{}{}{}",
            if self.owner_read { 'r' } else { '-' },
            if self.owner_write { 'w' } else { '-' },
            if self.owner_exec { 'x' } else { '-' },
            if self.group_read { 'r' } else { '-' },
            if self.group_write { 'w' } else { '-' },
            if self.group_exec { 'x' } else { '-' },
            if self.other_read { 'r' } else { '-' },
            if self.other_write { 'w' } else { '-' },
            if self.other_exec { 'x' } else { '-' },
        )
    }

    /// Create permissions for a regular file (644 = rw-r--r--).
    pub fn file() -> Self {
        Self::from_octal(0o644)
    }

    /// Create permissions for an executable file (755 = rwxr-xr-x).
    pub fn executable() -> Self {
        Self::from_octal(0o755)
    }

    /// Create permissions for a read-only file (444 = r--r--r--).
    pub fn readonly() -> Self {
        Self::from_octal(0o444)
    }
}

/// Type of file entry in the repository.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileType {
    /// Regular file
    Regular,
    /// Executable file
    Executable,
    /// Symbolic link with target path
    Symlink(String),
}

/// Extended file information including permissions and type.
///
/// Returned by [`FsOpsBuilder::stat()`] and [`FindBuilder::execute()`].
#[derive(Debug, Clone)]
pub struct FileEntry {
    /// File path relative to repository root
    pub path: String,
    /// SHA3-256 hash of file content
    pub hash: String,
    /// Type of file (regular, executable, symlink)
    pub file_type: FileType,
    /// Unix permissions (if tracked)
    pub permissions: Option<Permissions>,
    /// File size in bytes
    pub size: Option<usize>,
}

/// A staged filesystem operation.
///
/// These are created by [`FsBuilder`] methods and applied atomically
/// when [`FsBuilder::execute()`] is called.
#[derive(Debug, Clone)]
pub enum FsOperation {
    /// Copy file or directory
    Copy {
        /// Source path
        src: String,
        /// Destination path
        dst: String,
    },
    /// Move/rename file or directory
    Move {
        /// Source path
        src: String,
        /// Destination path
        dst: String,
    },
    /// Delete file or directory
    Delete {
        /// Path to delete
        path: String,
        /// Whether to delete recursively
        recursive: bool,
    },
    /// Change permissions
    Chmod {
        /// Path to modify
        path: String,
        /// New permissions
        permissions: Permissions,
        /// Whether to apply recursively
        recursive: bool,
    },
    /// Create symlink
    Symlink {
        /// Path where symlink will be created
        link_path: String,
        /// Target the symlink points to
        target: String,
    },
    /// Write file content
    Write {
        /// File path
        path: String,
        /// Content to write
        content: Vec<u8>,
    },
    /// Make file executable
    MakeExecutable {
        /// File path
        path: String,
    },
}

/// Result of a find operation with metadata.
///
/// # Examples
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open("project.forge")?;
/// let result = repo.fs().find()
///     .pattern("**/*.rs")
///     .execute()?;
///
/// println!("Found {} files in {} directories", result.count, result.dirs_traversed);
/// for file in result.files {
///     println!("  {} ({} bytes)", file.path, file.size.unwrap_or(0));
/// }
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
#[derive(Debug, Clone)]
pub struct FindResult {
    /// Matched files with metadata
    pub files: Vec<FileEntry>,
    /// Total number of matches
    pub count: usize,
    /// Number of directories traversed during search
    pub dirs_traversed: usize,
}

/// Builder for advanced file search operations.
///
/// Create via [`FsOpsBuilder::find()`]. Supports glob patterns, ignore patterns,
/// depth limits, and various filters.
///
/// # Examples
///
/// ## Basic Pattern Matching
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open("project.forge")?;
/// // Find all Rust source files
/// let rust_files = repo.fs().find()
///     .pattern("**/*.rs")
///     .paths()?;
///
/// // Find multiple patterns
/// let source_files = repo.fs().find()
///     .patterns(&["**/*.rs", "**/*.toml", "**/*.md"])
///     .paths()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Ignore Patterns
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open("project.forge")?;
/// // Exclude build artifacts
/// let files = repo.fs().find()
///     .pattern("**/*.rs")
///     .ignore("target/**")
///     .ignore("**/generated/**")
///     .paths()?;
///
/// // Use common gitignore patterns
/// let clean = repo.fs().find()
///     .pattern("**/*")
///     .use_gitignore()
///     .ignore_hidden()
///     .paths()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Directory and Depth Limits
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open("project.forge")?;
/// // Search only in src directory
/// let src_files = repo.fs().find()
///     .in_dir("src")
///     .pattern("**/*.rs")
///     .paths()?;
///
/// // Limit depth to 2 levels
/// let shallow = repo.fs().find()
///     .pattern("**/*")
///     .max_depth(2)
///     .paths()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
pub struct FindBuilder<'a> {
    repo: &'a Repository,
    base_commit: Option<String>,
    patterns: Vec<String>,
    ignore_patterns: Vec<String>,
    ignore_hidden: bool,
    ignore_case: bool,
    max_depth: Option<usize>,
    file_type_filter: Option<FileType>,
    min_size: Option<usize>,
    max_size: Option<usize>,
    base_dir: Option<String>,
}

impl<'a> FindBuilder<'a> {
    fn new(repo: &'a Repository) -> Self {
        Self {
            repo,
            base_commit: None,
            patterns: Vec::new(),
            ignore_patterns: Vec::new(),
            ignore_hidden: false,
            ignore_case: false,
            max_depth: None,
            file_type_filter: None,
            min_size: None,
            max_size: None,
            base_dir: None,
        }
    }

    /// Search at a specific commit hash.
    ///
    /// By default, searches at the trunk tip.
    pub fn at_commit(mut self, hash: &str) -> Self {
        self.base_commit = Some(hash.to_string());
        self
    }

    /// Search on trunk (default).
    pub fn on_trunk(mut self) -> Self {
        self.base_commit = None;
        self
    }

    /// Search on a specific branch.
    pub fn on_branch(mut self, branch: &str) -> Result<Self> {
        let tip = self.repo.branch_tip_internal(branch)?;
        self.base_commit = Some(tip.hash);
        Ok(self)
    }

    /// Add a glob pattern to match files.
    ///
    /// Supports standard glob syntax:
    /// - `*` matches any sequence of characters in a path segment
    /// - `**` matches any sequence of path segments
    /// - `?` matches any single character
    /// - `[abc]` matches any character in the brackets
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let files = repo.fs().find()
    ///     .pattern("**/*.rs")      // All Rust files
    ///     .pattern("src/**/*.rs")  // Rust files in src/
    ///     .paths()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn pattern(mut self, pattern: &str) -> Self {
        self.patterns.push(pattern.to_string());
        self
    }

    /// Add multiple glob patterns at once.
    pub fn patterns(mut self, patterns: &[&str]) -> Self {
        for p in patterns {
            self.patterns.push(p.to_string());
        }
        self
    }

    /// Exclude files matching this pattern.
    ///
    /// Files matching any ignore pattern will be excluded from results.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let files = repo.fs().find()
    ///     .pattern("**/*")
    ///     .ignore("target/**")
    ///     .ignore("node_modules/**")
    ///     .ignore("*.log")
    ///     .paths()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn ignore(mut self, pattern: &str) -> Self {
        self.ignore_patterns.push(pattern.to_string());
        self
    }

    /// Add multiple ignore patterns at once.
    pub fn ignore_patterns(mut self, patterns: &[&str]) -> Self {
        for p in patterns {
            self.ignore_patterns.push(p.to_string());
        }
        self
    }

    /// Exclude hidden files (files starting with `.`).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let visible = repo.fs().find()
    ///     .pattern("**/*")
    ///     .ignore_hidden()
    ///     .paths()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn ignore_hidden(mut self) -> Self {
        self.ignore_hidden = true;
        self
    }

    /// Apply common gitignore-style patterns.
    ///
    /// Automatically excludes:
    /// - `.git/**`, `node_modules/**`, `target/**`
    /// - `__pycache__/**`, `*.pyc`
    /// - `.DS_Store`, `*.swp`, `*.swo`, `*~`
    pub fn use_gitignore(mut self) -> Self {
        self.ignore_patterns.extend(vec![
            ".git/**".to_string(),
            ".gitignore".to_string(),
            "node_modules/**".to_string(),
            "target/**".to_string(),
            "*.pyc".to_string(),
            "__pycache__/**".to_string(),
            ".DS_Store".to_string(),
            "*.swp".to_string(),
            "*.swo".to_string(),
            "*~".to_string(),
        ]);
        self
    }

    /// Enable case-insensitive pattern matching.
    pub fn ignore_case(mut self) -> Self {
        self.ignore_case = true;
        self
    }

    /// Limit search to a maximum directory depth.
    ///
    /// A depth of 0 matches only files in the base directory.
    /// A depth of 1 includes one level of subdirectories, etc.
    pub fn max_depth(mut self, depth: usize) -> Self {
        self.max_depth = Some(depth);
        self
    }

    /// Only match regular files (exclude executables and symlinks).
    pub fn files_only(mut self) -> Self {
        self.file_type_filter = Some(FileType::Regular);
        self
    }

    /// Only match executable files.
    pub fn executables_only(mut self) -> Self {
        self.file_type_filter = Some(FileType::Executable);
        self
    }

    /// Only match symbolic links.
    pub fn symlinks_only(mut self) -> Self {
        self.file_type_filter = Some(FileType::Symlink(String::new()));
        self
    }

    /// Filter to files at least this size (in bytes).
    pub fn min_size(mut self, bytes: usize) -> Self {
        self.min_size = Some(bytes);
        self
    }

    /// Filter to files at most this size (in bytes).
    pub fn max_size(mut self, bytes: usize) -> Self {
        self.max_size = Some(bytes);
        self
    }

    /// Restrict search to a specific directory.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let src_files = repo.fs().find()
    ///     .in_dir("src")
    ///     .pattern("**/*.rs")
    ///     .paths()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn in_dir(mut self, dir: &str) -> Self {
        self.base_dir = Some(dir.trim_end_matches('/').to_string());
        self
    }

    /// Execute the search and return full results with metadata.
    ///
    /// Use [`paths()`](Self::paths) for just file paths, or
    /// [`count()`](Self::count) for just the count.
    pub fn execute(&self) -> Result<FindResult> {
        let commit_hash = if let Some(ref hash) = self.base_commit {
            hash.clone()
        } else {
            let tip = self.repo.branch_tip_internal("trunk")?;
            tip.hash
        };

        let all_files = self.repo.list_files_internal(&commit_hash)?;
        let mut matched_files = Vec::new();
        let mut dirs_seen = std::collections::HashSet::new();

        let match_patterns: Vec<glob::Pattern> = self
            .patterns
            .iter()
            .filter_map(|p| {
                let p = if self.ignore_case {
                    p.to_lowercase()
                } else {
                    p.clone()
                };
                glob::Pattern::new(&p).ok()
            })
            .collect();

        let ignore_patterns: Vec<glob::Pattern> = self
            .ignore_patterns
            .iter()
            .filter_map(|p| {
                let p = if self.ignore_case {
                    p.to_lowercase()
                } else {
                    p.clone()
                };
                glob::Pattern::new(&p).ok()
            })
            .collect();

        for file in all_files {
            let file_path = if self.ignore_case {
                file.name.to_lowercase()
            } else {
                file.name.clone()
            };

            if let Some(idx) = file.name.rfind('/') {
                dirs_seen.insert(file.name[..idx].to_string());
            }

            if let Some(ref base) = self.base_dir {
                if !file.name.starts_with(base) && !file.name.starts_with(&format!("{}/", base)) {
                    continue;
                }
            }

            if let Some(max_depth) = self.max_depth {
                let depth = file.name.matches('/').count();
                let base_depth = self
                    .base_dir
                    .as_ref()
                    .map(|b| b.matches('/').count())
                    .unwrap_or(0);
                if depth - base_depth > max_depth {
                    continue;
                }
            }

            if self.ignore_hidden {
                let file_name = file.name.rsplit('/').next().unwrap_or(&file.name);
                if file_name.starts_with('.') {
                    continue;
                }
            }

            let ignored = ignore_patterns.iter().any(|p| p.matches(&file_path));
            if ignored {
                continue;
            }

            let matches = if match_patterns.is_empty() {
                true
            } else {
                match_patterns.iter().any(|p| p.matches(&file_path))
            };

            if matches {
                matched_files.push(FileEntry {
                    path: file.name.clone(),
                    hash: file.hash.clone(),
                    file_type: FileType::Regular,
                    permissions: file.permissions.as_ref().map(|p| {
                        Permissions::from_octal(u32::from_str_radix(p, 8).unwrap_or(0o644))
                    }),
                    size: file.size,
                });
            }
        }

        Ok(FindResult {
            count: matched_files.len(),
            files: matched_files,
            dirs_traversed: dirs_seen.len(),
        })
    }

    /// Execute and return just the file paths.
    ///
    /// More efficient than [`execute()`](Self::execute) when you only need paths.
    pub fn paths(&self) -> Result<Vec<String>> {
        Ok(self.execute()?.files.into_iter().map(|f| f.path).collect())
    }

    /// Execute and return only the count of matching files.
    pub fn count(&self) -> Result<usize> {
        Ok(self.execute()?.count)
    }
}

/// Builder for filesystem modification operations.
///
/// All operations are staged and then committed atomically when
/// [`execute()`](Self::execute) is called.
///
/// # Examples
///
/// ## Copy and Move Files
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open_rw("project.forge")?;
/// let hash = repo.fs().modify()
///     .message("Reorganize project structure")
///     .author("developer")
///     .copy_file("README.md", "docs/README.md")
///     .copy_dir("src", "src_backup")
///     .move_file("old_name.rs", "new_name.rs")
///     .move_dir("scripts", "tools")
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Delete Files
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open_rw("project.forge")?;
/// let hash = repo.fs().modify()
///     .message("Clean up old files")
///     .author("developer")
///     .delete_file("deprecated.rs")          // Silent if missing
///     .delete_dir("old_module")              // Recursive delete
///     .delete_matching("**/*.bak")           // Glob pattern
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Change Permissions
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open_rw("project.forge")?;
/// let hash = repo.fs().modify()
///     .message("Fix permissions")
///     .author("developer")
///     .make_executable("scripts/build.sh")
///     .chmod("config.toml", 0o644)
///     .chmod_dir("bin", 0o755)
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Create Symlinks
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open_rw("project.forge")?;
/// let hash = repo.fs().modify()
///     .message("Add convenience symlinks")
///     .author("developer")
///     .symlink("build", "scripts/build.sh")
///     .symlink("latest", "releases/v1.0.0")
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Write Files
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open_rw("project.forge")?;
/// let hash = repo.fs().modify()
///     .message("Update configuration")
///     .author("developer")
///     .write_str("VERSION", "1.0.0\n")
///     .write("data.bin", &[0x00, 0x01, 0x02])
///     .touch(".gitkeep")
///     .execute()?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
///
/// ## Preview Without Committing
///
/// ```no_run
/// # use heroforge_core::Repository;
/// # let repo = Repository::open("project.forge")?;
/// let preview = repo.fs().modify()
///     .copy_file("a.txt", "b.txt")
///     .delete_dir("old")
///     .preview()?;
///
/// println!("Base: {}", preview.base_commit);
/// for desc in preview.describe() {
///     println!("  {}", desc);
/// }
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
pub struct FsBuilder<'a> {
    repo: &'a Repository,
    base_commit: Option<String>,
    operations: Vec<FsOperation>,
    commit_message: Option<String>,
    author: Option<String>,
    branch: Option<String>,
}

impl<'a> FsBuilder<'a> {
    pub(crate) fn new(repo: &'a Repository) -> Self {
        Self {
            repo,
            base_commit: None,
            operations: Vec::new(),
            commit_message: None,
            author: None,
            branch: None,
        }
    }

    /// Apply operations starting from a specific commit.
    pub fn at_commit(mut self, hash: &str) -> Self {
        self.base_commit = Some(hash.to_string());
        self
    }

    /// Apply operations to trunk tip (default).
    pub fn on_trunk(self) -> Self {
        self
    }

    /// Apply operations to a branch tip.
    pub fn on_branch(mut self, branch: &str) -> Result<Self> {
        let tip = self.repo.branch_tip_internal(branch)?;
        self.base_commit = Some(tip.hash);
        self.branch = Some(branch.to_string());
        Ok(self)
    }

    /// Set the commit message (required).
    pub fn message(mut self, msg: &str) -> Self {
        self.commit_message = Some(msg.to_string());
        self
    }

    /// Set the commit author (required).
    pub fn author(mut self, author: &str) -> Self {
        self.author = Some(author.to_string());
        self
    }

    // ========================================================================
    // Copy Operations
    // ========================================================================

    /// Copy a file to a new location.
    ///
    /// The source file remains unchanged.
    pub fn copy_file(mut self, src: &str, dst: &str) -> Self {
        self.operations.push(FsOperation::Copy {
            src: src.to_string(),
            dst: dst.to_string(),
        });
        self
    }

    /// Copy a directory and all its contents recursively.
    pub fn copy_dir(mut self, src: &str, dst: &str) -> Self {
        self.operations.push(FsOperation::Copy {
            src: format!("{}/", src.trim_end_matches('/')),
            dst: format!("{}/", dst.trim_end_matches('/')),
        });
        self
    }

    // ========================================================================
    // Move/Rename Operations
    // ========================================================================

    /// Move or rename a file.
    ///
    /// The source file is removed after copying.
    pub fn move_file(mut self, src: &str, dst: &str) -> Self {
        self.operations.push(FsOperation::Move {
            src: src.to_string(),
            dst: dst.to_string(),
        });
        self
    }

    /// Move or rename a directory.
    pub fn move_dir(mut self, src: &str, dst: &str) -> Self {
        self.operations.push(FsOperation::Move {
            src: format!("{}/", src.trim_end_matches('/')),
            dst: format!("{}/", dst.trim_end_matches('/')),
        });
        self
    }

    /// Rename a file (alias for [`move_file`](Self::move_file)).
    pub fn rename(self, old_path: &str, new_path: &str) -> Self {
        self.move_file(old_path, new_path)
    }

    // ========================================================================
    // Delete Operations
    // ========================================================================

    /// Delete a file.
    ///
    /// Silently succeeds if the file doesn't exist.
    pub fn delete_file(mut self, path: &str) -> Self {
        self.operations.push(FsOperation::Delete {
            path: path.to_string(),
            recursive: false,
        });
        self
    }

    /// Delete a directory and all its contents.
    ///
    /// Silently succeeds if the directory doesn't exist.
    pub fn delete_dir(mut self, path: &str) -> Self {
        self.operations.push(FsOperation::Delete {
            path: format!("{}/", path.trim_end_matches('/')),
            recursive: true,
        });
        self
    }

    /// Delete all files matching a glob pattern.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open_rw("project.forge")?;
    /// repo.fs().modify()
    ///     .message("Clean backup files")
    ///     .author("dev")
    ///     .delete_matching("**/*.bak")
    ///     .delete_matching("**/*.tmp")
    ///     .execute()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn delete_matching(mut self, pattern: &str) -> Self {
        self.operations.push(FsOperation::Delete {
            path: format!("glob:{}", pattern),
            recursive: false,
        });
        self
    }

    // ========================================================================
    // Permission Operations
    // ========================================================================

    /// Change file permissions using octal notation.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open_rw("project.forge")?;
    /// repo.fs().modify()
    ///     .message("Fix permissions")
    ///     .author("dev")
    ///     .chmod("script.sh", 0o755)   // rwxr-xr-x
    ///     .chmod("config.toml", 0o644) // rw-r--r--
    ///     .chmod("secret.key", 0o600)  // rw-------
    ///     .execute()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn chmod(mut self, path: &str, mode: u32) -> Self {
        self.operations.push(FsOperation::Chmod {
            path: path.to_string(),
            permissions: Permissions::from_octal(mode),
            recursive: false,
        });
        self
    }

    /// Change permissions using a [`Permissions`] struct.
    pub fn chmod_permissions(mut self, path: &str, perms: Permissions) -> Self {
        self.operations.push(FsOperation::Chmod {
            path: path.to_string(),
            permissions: perms,
            recursive: false,
        });
        self
    }

    /// Change permissions for all files in a directory recursively.
    pub fn chmod_dir(mut self, path: &str, mode: u32) -> Self {
        self.operations.push(FsOperation::Chmod {
            path: format!("{}/", path.trim_end_matches('/')),
            permissions: Permissions::from_octal(mode),
            recursive: true,
        });
        self
    }

    /// Make a file executable (sets mode to 755).
    pub fn make_executable(mut self, path: &str) -> Self {
        self.operations.push(FsOperation::MakeExecutable {
            path: path.to_string(),
        });
        self
    }

    // ========================================================================
    // Symlink Operations
    // ========================================================================

    /// Create a symbolic link.
    ///
    /// # Arguments
    ///
    /// * `link_path` - Path where the symlink will be created
    /// * `target` - Path the symlink points to
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open_rw("project.forge")?;
    /// repo.fs().modify()
    ///     .message("Add symlinks")
    ///     .author("dev")
    ///     .symlink("current", "releases/v2.0.0")
    ///     .symlink("build", "scripts/build.sh")
    ///     .execute()?;
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn symlink(mut self, link_path: &str, target: &str) -> Self {
        self.operations.push(FsOperation::Symlink {
            link_path: link_path.to_string(),
            target: target.to_string(),
        });
        self
    }

    /// Create a symbolic link to a file (alias for [`symlink`](Self::symlink)).
    pub fn symlink_file(self, link_path: &str, target_file: &str) -> Self {
        self.symlink(link_path, target_file)
    }

    /// Create a symbolic link to a directory (alias for [`symlink`](Self::symlink)).
    pub fn symlink_dir(self, link_path: &str, target_dir: &str) -> Self {
        self.symlink(link_path, target_dir)
    }

    // ========================================================================
    // Write Operations
    // ========================================================================

    /// Write binary content to a file.
    ///
    /// Creates the file if it doesn't exist, overwrites if it does.
    pub fn write(mut self, path: &str, content: &[u8]) -> Self {
        self.operations.push(FsOperation::Write {
            path: path.to_string(),
            content: content.to_vec(),
        });
        self
    }

    /// Write a string to a file.
    ///
    /// Creates the file if it doesn't exist, overwrites if it does.
    pub fn write_str(self, path: &str, content: &str) -> Self {
        self.write(path, content.as_bytes())
    }

    /// Create an empty file or update its timestamp.
    pub fn touch(self, path: &str) -> Self {
        self.write(path, &[])
    }

    // ========================================================================
    // Execute
    // ========================================================================

    /// Execute all staged operations and create a commit.
    ///
    /// Returns the hash of the new commit.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No commit message was set
    /// - No author was set
    /// - Any file operation fails
    pub fn execute(self) -> Result<String> {
        let message = self.commit_message.ok_or_else(|| {
            FossilError::InvalidArtifact("commit message required for fs operations".to_string())
        })?;
        let author = self.author.ok_or_else(|| {
            FossilError::InvalidArtifact("author required for fs operations".to_string())
        })?;

        let base_hash = if let Some(hash) = self.base_commit {
            hash
        } else {
            let tip = self.repo.branch_tip_internal("trunk")?;
            tip.hash
        };

        let base_files = self.repo.list_files_internal(&base_hash)?;
        let mut file_contents: HashMap<String, Vec<u8>> = HashMap::new();
        let mut file_permissions: HashMap<String, String> = HashMap::new();
        let mut symlinks: HashMap<String, String> = HashMap::new();

        for file in &base_files {
            let content = self.repo.read_file_internal(&base_hash, &file.name)?;
            file_contents.insert(file.name.clone(), content);
            if let Some(ref perms) = file.permissions {
                file_permissions.insert(file.name.clone(), perms.clone());
            }
        }

        for op in &self.operations {
            match op {
                FsOperation::Copy { src, dst } => {
                    if src.ends_with('/') {
                        let src_prefix = src.trim_end_matches('/');
                        let dst_prefix = dst.trim_end_matches('/');
                        let to_copy: Vec<_> = file_contents
                            .keys()
                            .filter(|k| k.starts_with(src_prefix))
                            .cloned()
                            .collect();
                        for path in to_copy {
                            let new_path = path.replacen(src_prefix, dst_prefix, 1);
                            if let Some(content) = file_contents.get(&path).cloned() {
                                file_contents.insert(new_path.clone(), content);
                            }
                            if let Some(perms) = file_permissions.get(&path).cloned() {
                                file_permissions.insert(new_path, perms);
                            }
                        }
                    } else {
                        if let Some(content) = file_contents.get(src).cloned() {
                            file_contents.insert(dst.clone(), content);
                        }
                        if let Some(perms) = file_permissions.get(src).cloned() {
                            file_permissions.insert(dst.clone(), perms);
                        }
                    }
                }

                FsOperation::Move { src, dst } => {
                    if src.ends_with('/') {
                        let src_prefix = src.trim_end_matches('/');
                        let dst_prefix = dst.trim_end_matches('/');
                        let to_move: Vec<_> = file_contents
                            .keys()
                            .filter(|k| k.starts_with(src_prefix))
                            .cloned()
                            .collect();
                        for path in to_move {
                            let new_path = path.replacen(src_prefix, dst_prefix, 1);
                            if let Some(content) = file_contents.remove(&path) {
                                file_contents.insert(new_path.clone(), content);
                            }
                            if let Some(perms) = file_permissions.remove(&path) {
                                file_permissions.insert(new_path, perms);
                            }
                        }
                    } else {
                        if let Some(content) = file_contents.remove(src) {
                            file_contents.insert(dst.clone(), content);
                        }
                        if let Some(perms) = file_permissions.remove(src) {
                            file_permissions.insert(dst.clone(), perms);
                        }
                    }
                }

                FsOperation::Delete { path, recursive } => {
                    if path.starts_with("glob:") {
                        let pattern = &path[5..];
                        if let Ok(glob_pattern) = glob::Pattern::new(pattern) {
                            let to_delete: Vec<_> = file_contents
                                .keys()
                                .filter(|k| glob_pattern.matches(k))
                                .cloned()
                                .collect();
                            for p in to_delete {
                                file_contents.remove(&p);
                                file_permissions.remove(&p);
                            }
                        }
                    } else if *recursive || path.ends_with('/') {
                        let prefix = path.trim_end_matches('/');
                        let to_delete: Vec<_> = file_contents
                            .keys()
                            .filter(|k| k.starts_with(prefix) || *k == prefix)
                            .cloned()
                            .collect();
                        for p in to_delete {
                            file_contents.remove(&p);
                            file_permissions.remove(&p);
                        }
                    } else {
                        file_contents.remove(path);
                        file_permissions.remove(path);
                    }
                }

                FsOperation::Chmod {
                    path,
                    permissions,
                    recursive,
                } => {
                    let perm_str = format!("{:o}", permissions.to_octal());
                    if *recursive || path.ends_with('/') {
                        let prefix = path.trim_end_matches('/');
                        let to_chmod: Vec<_> = file_contents
                            .keys()
                            .filter(|k| k.starts_with(prefix))
                            .cloned()
                            .collect();
                        for p in to_chmod {
                            file_permissions.insert(p, perm_str.clone());
                        }
                    } else if file_contents.contains_key(path) {
                        file_permissions.insert(path.clone(), perm_str);
                    }
                }

                FsOperation::MakeExecutable { path } => {
                    if file_contents.contains_key(path) {
                        file_permissions.insert(path.clone(), "755".to_string());
                    }
                }

                FsOperation::Symlink { link_path, target } => {
                    let symlink_content = format!("link {}", target);
                    file_contents.insert(link_path.clone(), symlink_content.into_bytes());
                    symlinks.insert(link_path.clone(), target.clone());
                }

                FsOperation::Write { path, content } => {
                    file_contents.insert(path.clone(), content.clone());
                }
            }
        }

        let files: Vec<(&str, &[u8])> = file_contents
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_slice()))
            .collect();

        self.repo.commit_internal(
            &files,
            &message,
            &author,
            Some(&base_hash),
            self.branch.as_deref(),
        )
    }

    /// Preview the operations without committing.
    ///
    /// Returns information about what would happen if [`execute()`](Self::execute)
    /// were called.
    pub fn preview(&self) -> Result<FsPreview> {
        let base_hash = if let Some(ref hash) = self.base_commit {
            hash.clone()
        } else {
            let tip = self.repo.branch_tip_internal("trunk")?;
            tip.hash
        };

        let base_files = self.repo.list_files_internal(&base_hash)?;

        Ok(FsPreview {
            base_commit: base_hash,
            base_file_count: base_files.len(),
            operations: self.operations.clone(),
        })
    }
}

/// Preview of staged filesystem operations.
///
/// Created by [`FsBuilder::preview()`] to inspect what operations
/// would be performed without actually committing them.
#[derive(Debug)]
pub struct FsPreview {
    /// Hash of the commit operations would be applied to
    pub base_commit: String,
    /// Number of files in the base commit
    pub base_file_count: usize,
    /// List of operations that would be performed
    pub operations: Vec<FsOperation>,
}

impl FsPreview {
    /// Get human-readable descriptions of all operations.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let preview = repo.fs().modify()
    ///     .copy_file("a.txt", "b.txt")
    ///     .delete_dir("old")
    ///     .preview()?;
    ///
    /// for desc in preview.describe() {
    ///     println!("{}", desc);
    /// }
    /// // Output:
    /// // COPY a.txt -> b.txt
    /// // DELETE old/ (recursive)
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn describe(&self) -> Vec<String> {
        self.operations
            .iter()
            .map(|op| match op {
                FsOperation::Copy { src, dst } => format!("COPY {} -> {}", src, dst),
                FsOperation::Move { src, dst } => format!("MOVE {} -> {}", src, dst),
                FsOperation::Delete { path, recursive } => {
                    if *recursive {
                        format!("DELETE {} (recursive)", path)
                    } else if path.starts_with("glob:") {
                        format!("DELETE matching {}", &path[5..])
                    } else {
                        format!("DELETE {}", path)
                    }
                }
                FsOperation::Chmod {
                    path,
                    permissions,
                    recursive,
                } => {
                    if *recursive {
                        format!("CHMOD {} {:o} (recursive)", path, permissions.to_octal())
                    } else {
                        format!("CHMOD {} {:o}", path, permissions.to_octal())
                    }
                }
                FsOperation::Symlink { link_path, target } => {
                    format!("SYMLINK {} -> {}", link_path, target)
                }
                FsOperation::Write { path, content } => {
                    format!("WRITE {} ({} bytes)", path, content.len())
                }
                FsOperation::MakeExecutable { path } => format!("MAKE_EXECUTABLE {}", path),
            })
            .collect()
    }
}

/// Entry point for filesystem operations.
///
/// Access via [`Repository::fs()`](crate::Repository::fs).
///
/// # Examples
///
/// ```no_run
/// use heroforge_core::Repository;
///
/// let repo = Repository::open_rw("project.forge")?;
///
/// // Modify files
/// repo.fs().modify()
///     .message("Update files")
///     .author("dev")
///     .copy_file("a.txt", "b.txt")
///     .execute()?;
///
/// // Find files
/// let files = repo.fs().find()
///     .pattern("**/*.rs")
///     .paths()?;
///
/// // Quick utilities
/// let exists = repo.fs().exists("README.md")?;
/// let size = repo.fs().du("**/*")?;
/// let count = repo.fs().count("**/*.rs")?;
/// # Ok::<(), heroforge_core::FossilError>(())
/// ```
pub struct FsOpsBuilder<'a> {
    repo: &'a Repository,
}

impl<'a> FsOpsBuilder<'a> {
    pub(crate) fn new(repo: &'a Repository) -> Self {
        Self { repo }
    }

    /// Start building filesystem modification operations.
    ///
    /// Returns a [`FsBuilder`] for chaining copy, move, delete, and other operations.
    pub fn modify(self) -> FsBuilder<'a> {
        FsBuilder::new(self.repo)
    }

    /// Start building a file search operation.
    ///
    /// Returns a [`FindBuilder`] for specifying patterns and filters.
    pub fn find(self) -> FindBuilder<'a> {
        FindBuilder::new(self.repo)
    }

    /// Shorthand to find files matching a single pattern.
    ///
    /// Equivalent to `repo.fs().find().pattern(pattern)`.
    pub fn find_pattern(self, pattern: &str) -> FindBuilder<'a> {
        FindBuilder::new(self.repo).pattern(pattern)
    }

    /// List all symbolic links in the repository.
    ///
    /// Returns pairs of (link_path, target_path).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let symlinks = repo.fs().list_symlinks()?;
    /// for (link, target) in symlinks {
    ///     println!("{} -> {}", link, target);
    /// }
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn list_symlinks(&self) -> Result<Vec<(String, String)>> {
        let tip = self.repo.branch_tip_internal("trunk")?;
        let files = self.repo.list_files_internal(&tip.hash)?;
        let mut symlinks = Vec::new();

        for file in files {
            if let Ok(content) = self.repo.read_file_internal(&tip.hash, &file.name) {
                if let Ok(text) = String::from_utf8(content) {
                    if text.starts_with("link ") {
                        let target = text[5..].trim().to_string();
                        symlinks.push((file.name, target));
                    }
                }
            }
        }

        Ok(symlinks)
    }

    /// Check if a file or directory exists at the given path.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// if repo.fs().exists("README.md")? {
    ///     println!("README exists!");
    /// }
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn exists(&self, path: &str) -> Result<bool> {
        let tip = self.repo.branch_tip_internal("trunk")?;
        let files = self.repo.list_files_internal(&tip.hash)?;
        Ok(files.iter().any(|f| f.name == path))
    }

    /// Check if a path represents a directory (has files under it).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// if repo.fs().is_dir("src")? {
    ///     println!("src is a directory");
    /// }
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn is_dir(&self, path: &str) -> Result<bool> {
        let tip = self.repo.branch_tip_internal("trunk")?;
        let files = self.repo.list_files_internal(&tip.hash)?;
        let prefix = format!("{}/", path.trim_end_matches('/'));
        Ok(files.iter().any(|f| f.name.starts_with(&prefix)))
    }

    /// Get detailed information about a file.
    ///
    /// Returns `None` if the file doesn't exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// if let Some(info) = repo.fs().stat("README.md")? {
    ///     println!("Path: {}", info.path);
    ///     println!("Hash: {}", info.hash);
    ///     println!("Size: {:?} bytes", info.size);
    /// }
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn stat(&self, path: &str) -> Result<Option<FileEntry>> {
        let tip = self.repo.branch_tip_internal("trunk")?;
        let files = self.repo.list_files_internal(&tip.hash)?;

        for file in files {
            if file.name == path {
                let content = self.repo.read_file_internal(&tip.hash, path)?;
                let file_type = if let Ok(text) = String::from_utf8(content.clone()) {
                    if text.starts_with("link ") {
                        FileType::Symlink(text[5..].trim().to_string())
                    } else {
                        FileType::Regular
                    }
                } else {
                    FileType::Regular
                };

                return Ok(Some(FileEntry {
                    path: file.name,
                    hash: file.hash,
                    file_type,
                    permissions: file.permissions.as_ref().map(|p| {
                        Permissions::from_octal(u32::from_str_radix(p, 8).unwrap_or(0o644))
                    }),
                    size: Some(content.len()),
                }));
            }
        }

        Ok(None)
    }

    /// Calculate total size of files matching a glob pattern.
    ///
    /// Similar to the Unix `du` command.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let rust_size = repo.fs().du("**/*.rs")?;
    /// println!("Total Rust code: {} bytes", rust_size);
    ///
    /// let total = repo.fs().du("**/*")?;
    /// println!("Total repository size: {} bytes", total);
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn du(&self, pattern: &str) -> Result<usize> {
        let tip = self.repo.branch_tip_internal("trunk")?;
        let files = self.repo.find_files_internal(&tip.hash, pattern)?;
        let mut total = 0;

        for file in files {
            if let Ok(content) = self.repo.read_file_internal(&tip.hash, &file.name) {
                total += content.len();
            }
        }

        Ok(total)
    }

    /// Count files matching a glob pattern.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use heroforge_core::Repository;
    /// # let repo = Repository::open("project.forge")?;
    /// let rust_files = repo.fs().count("**/*.rs")?;
    /// println!("Found {} Rust files", rust_files);
    /// # Ok::<(), heroforge_core::FossilError>(())
    /// ```
    pub fn count(&self, pattern: &str) -> Result<usize> {
        let tip = self.repo.branch_tip_internal("trunk")?;
        let files = self.repo.find_files_internal(&tip.hash, pattern)?;
        Ok(files.len())
    }
}