embeddenator-fs 0.25.0

EmbrFS: FUSE filesystem backed by holographic engrams
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
//! FUSE Filesystem Shim for Holographic Engrams
//!
//! This module provides kernel integration via FUSE (Filesystem in Userspace),
//! allowing engrams to be mounted as native filesystems.
//!
//! # Architecture
//!
//! ```text
//! ┌────────────────────────────────────────────────────────────────┐
//! │                     User Applications                          │
//! │                    (read, write, stat, etc.)                   │
//! └────────────────────────────────────────────────────────────────┘
//!                                  │ VFS syscalls
//!//! ┌────────────────────────────────────────────────────────────────┐
//! │                     Linux Kernel VFS                           │
//! └────────────────────────────────────────────────────────────────┘
//!                                  │ FUSE protocol
//!//! ┌────────────────────────────────────────────────────────────────┐
//! │                   /dev/fuse character device                   │
//! └────────────────────────────────────────────────────────────────┘
//!                                  │ libfuse / fuser crate
//!//! ┌────────────────────────────────────────────────────────────────┐
//! │                    EngramFS (this module)                      │
//! │  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
//! │  │   Manifest   │  │   Codebook   │  │   Differential       │  │
//! │  │   (paths)    │  │   (private)  │  │   Decoder            │  │
//! │  └──────────────┘  └──────────────┘  └──────────────────────┘  │
//! └────────────────────────────────────────────────────────────────┘
//!//!//! ┌────────────────────────────────────────────────────────────────┐
//! │                    Engram Storage                              │
//! │            (on-disk or memory-mapped .engram file)             │
//! └────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Usage
//!
//! ```bash
//! # Mount an engram (requires --features fuse)
//! embeddenator mount --engram root.engram --manifest manifest.json /mnt/engram
//!
//! # Access files normally
//! ls /mnt/engram
//! cat /mnt/engram/some/file.txt
//!
//! # Unmount
//! fusermount -u /mnt/engram
//! ```
//!
//! # Feature Flag
//!
//! The FUSE integration requires the `fuse` feature to be enabled:
//!
//! ```toml
//! [dependencies]
//! embeddenator = { version = "0.2", features = ["fuse"] }
//! ```

use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

#[cfg(feature = "fuse")]
use std::ffi::OsStr;

#[cfg(feature = "fuse")]
use std::path::Path;

/// Inode number type (matches fuser's u64 inode convention)
pub type Ino = u64;

/// Root inode number (FUSE convention: inode 1 is root)
pub const ROOT_INO: Ino = 1;

/// File attributes for FUSE
///
/// This mirrors fuser::FileAttr but is always available regardless
/// of feature flags, allowing the core filesystem logic to work
/// without the fuser crate.
#[derive(Clone, Debug)]
pub struct FileAttr {
    /// Inode number
    pub ino: Ino,
    /// File size in bytes
    pub size: u64,
    /// Number of 512-byte blocks allocated
    pub blocks: u64,
    /// Last access time
    pub atime: SystemTime,
    /// Last modification time
    pub mtime: SystemTime,
    /// Last status change time
    pub ctime: SystemTime,
    /// Creation time (macOS only)
    pub crtime: SystemTime,
    /// File type
    pub kind: FileKind,
    /// Permissions (mode & 0o7777)
    pub perm: u16,
    /// Hard link count
    pub nlink: u32,
    /// User ID of owner
    pub uid: u32,
    /// Group ID of owner
    pub gid: u32,
    /// Device ID (for special files)
    pub rdev: u32,
    /// Block size for filesystem I/O
    pub blksize: u32,
    /// Flags (macOS only)
    pub flags: u32,
}

impl Default for FileAttr {
    fn default() -> Self {
        let now = SystemTime::now();
        FileAttr {
            ino: 0,
            size: 0,
            blocks: 0,
            atime: now,
            mtime: now,
            ctime: now,
            crtime: now,
            kind: FileKind::RegularFile,
            perm: 0o644,
            nlink: 1,
            uid: unsafe { libc::getuid() },
            gid: unsafe { libc::getgid() },
            rdev: 0,
            blksize: 4096,
            flags: 0,
        }
    }
}

#[cfg(feature = "fuse")]
impl From<FileAttr> for fuser::FileAttr {
    fn from(attr: FileAttr) -> Self {
        fuser::FileAttr {
            ino: attr.ino,
            size: attr.size,
            blocks: attr.blocks,
            atime: attr.atime,
            mtime: attr.mtime,
            ctime: attr.ctime,
            crtime: attr.crtime,
            kind: attr.kind.into(),
            perm: attr.perm,
            nlink: attr.nlink,
            uid: attr.uid,
            gid: attr.gid,
            rdev: attr.rdev,
            blksize: attr.blksize,
            flags: attr.flags,
        }
    }
}

/// File type
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum FileKind {
    /// Directory
    Directory,
    /// Regular file
    #[default]
    RegularFile,
    /// Symbolic link
    Symlink,
    /// Hard link (treated as regular file for FUSE, but tracked separately)
    Hardlink,
    /// Character device
    CharDevice,
    /// Block device
    BlockDevice,
    /// FIFO (named pipe)
    Fifo,
    /// Unix socket
    Socket,
}

#[cfg(feature = "fuse")]
impl From<FileKind> for fuser::FileType {
    fn from(kind: FileKind) -> Self {
        match kind {
            FileKind::Directory => fuser::FileType::Directory,
            FileKind::RegularFile => fuser::FileType::RegularFile,
            FileKind::Symlink => fuser::FileType::Symlink,
            FileKind::Hardlink => fuser::FileType::RegularFile, // Hardlinks appear as regular files
            FileKind::CharDevice => fuser::FileType::CharDevice,
            FileKind::BlockDevice => fuser::FileType::BlockDevice,
            FileKind::Fifo => fuser::FileType::NamedPipe,
            FileKind::Socket => fuser::FileType::Socket,
        }
    }
}

/// Directory entry
#[derive(Clone, Debug)]
pub struct DirEntry {
    /// Inode number
    pub ino: Ino,
    /// Entry name
    pub name: String,
    /// Entry type
    pub kind: FileKind,
}

/// Symlink data storage
#[derive(Clone, Debug)]
pub struct SymlinkEntry {
    /// Symlink target path
    pub target: String,
}

/// Cached file data for read operations
#[derive(Clone)]
pub struct CachedFile {
    /// File content
    pub data: Vec<u8>,
    /// File attributes
    pub attr: FileAttr,
}

/// Device node metadata (for char/block devices)
#[derive(Clone, Debug)]
pub struct DeviceNode {
    /// Major device number
    pub major: u32,
    /// Minor device number
    pub minor: u32,
}

/// The EngramFS FUSE filesystem implementation
///
/// This provides a read-only view of decoded engram data as a standard
/// POSIX filesystem. Files are decoded on-demand from the holographic
/// representation and cached for efficient repeated access.
pub struct EngramFS {
    /// Inode to file attributes mapping
    inodes: Arc<RwLock<HashMap<Ino, FileAttr>>>,

    /// Inode to path mapping
    inode_paths: Arc<RwLock<HashMap<Ino, String>>>,

    /// Path to inode mapping
    path_inodes: Arc<RwLock<HashMap<String, Ino>>>,

    /// Directory contents (parent_ino -> entries)
    directories: Arc<RwLock<HashMap<Ino, Vec<DirEntry>>>>,

    /// Cached file data (ino -> data)
    file_cache: Arc<RwLock<HashMap<Ino, CachedFile>>>,

    /// Symlink targets (ino -> target path)
    symlinks: Arc<RwLock<HashMap<Ino, String>>>,

    /// Device nodes (ino -> major/minor)
    devices: Arc<RwLock<HashMap<Ino, DeviceNode>>>,

    /// Next available inode number
    next_ino: Arc<RwLock<Ino>>,

    /// Read-only mode
    read_only: bool,

    /// TTL for cached attributes
    attr_ttl: Duration,

    /// TTL for cached entries
    entry_ttl: Duration,
}

impl EngramFS {
    /// Create a new EngramFS instance
    ///
    /// # Arguments
    ///
    /// * `read_only` - Whether the filesystem is read-only (default: true for engrams)
    pub fn new(read_only: bool) -> Self {
        let mut fs = EngramFS {
            inodes: Arc::new(RwLock::new(HashMap::new())),
            inode_paths: Arc::new(RwLock::new(HashMap::new())),
            path_inodes: Arc::new(RwLock::new(HashMap::new())),
            directories: Arc::new(RwLock::new(HashMap::new())),
            file_cache: Arc::new(RwLock::new(HashMap::new())),
            symlinks: Arc::new(RwLock::new(HashMap::new())),
            devices: Arc::new(RwLock::new(HashMap::new())),
            next_ino: Arc::new(RwLock::new(2)), // Start after root
            read_only,
            attr_ttl: Duration::from_secs(1),
            entry_ttl: Duration::from_secs(1),
        };

        // Initialize root directory
        fs.init_root();
        fs
    }

    /// Initialize root directory
    fn init_root(&mut self) {
        let root_attr = FileAttr {
            ino: ROOT_INO,
            size: 0,
            blocks: 0,
            kind: FileKind::Directory,
            perm: 0o755,
            nlink: 2,
            ..Default::default()
        };

        // SAFETY: init_root only called during construction, before any concurrent access
        // If locks are poisoned here, the filesystem is unrecoverable anyway
        self.inodes
            .write()
            .expect("Lock poisoned during init")
            .insert(ROOT_INO, root_attr);
        self.inode_paths
            .write()
            .expect("Lock poisoned during init")
            .insert(ROOT_INO, "/".to_string());
        self.path_inodes
            .write()
            .expect("Lock poisoned during init")
            .insert("/".to_string(), ROOT_INO);
        self.directories
            .write()
            .expect("Lock poisoned during init")
            .insert(ROOT_INO, Vec::new());
    }

    /// Allocate a new inode number
    fn alloc_ino(&self) -> Result<Ino, &'static str> {
        let mut next = self
            .next_ino
            .write()
            .map_err(|_| "Inode allocator lock poisoned")?;
        let ino = *next;
        *next += 1;
        Ok(ino)
    }

    /// Add a file to the filesystem
    ///
    /// # Arguments
    ///
    /// * `path` - Absolute path within the filesystem (e.g., "/foo/bar.txt")
    /// * `data` - File content bytes
    ///
    /// # Returns
    ///
    /// The assigned inode number for the new file
    pub fn add_file(&self, path: &str, data: Vec<u8>) -> Result<Ino, &'static str> {
        let path = normalize_path(path);

        // Check if already exists
        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned, recovering...");
            poisoned.into_inner()
        });
        if path_inodes.contains_key(&path) {
            return Err("File already exists");
        }
        drop(path_inodes);

        // Ensure parent directory exists
        let parent_path = parent_path(&path).ok_or("Invalid path")?;
        let parent_ino = self.ensure_directory(&parent_path)?;

        // Create file
        let ino = self.alloc_ino()?;
        let size = data.len() as u64;

        let attr = FileAttr {
            ino,
            size,
            blocks: size.div_ceil(512),
            kind: FileKind::RegularFile,
            perm: 0o644,
            nlink: 1,
            ..Default::default()
        };

        // Store file
        self.inodes
            .write()
            .map_err(|_| "Inodes lock poisoned")?
            .insert(ino, attr.clone());
        self.inode_paths
            .write()
            .map_err(|_| "Inode paths lock poisoned")?
            .insert(ino, path.clone());
        self.path_inodes
            .write()
            .map_err(|_| "Path inodes lock poisoned")?
            .insert(path.clone(), ino);
        self.file_cache
            .write()
            .map_err(|_| "File cache lock poisoned")?
            .insert(ino, CachedFile { data, attr });

        // Add to parent directory
        let filename = filename(&path).ok_or("Invalid filename")?;
        self.directories
            .write()
            .map_err(|_| "Directories lock poisoned")?
            .get_mut(&parent_ino)
            .ok_or("Parent directory not found")?
            .push(DirEntry {
                ino,
                name: filename.to_string(),
                kind: FileKind::RegularFile,
            });

        Ok(ino)
    }

    /// Ensure a directory exists, creating it if necessary
    fn ensure_directory(&self, path: &str) -> Result<Ino, &'static str> {
        let path = normalize_path(path);

        // Root always exists
        if path == "/" {
            return Ok(ROOT_INO);
        }

        // Check if already exists
        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned in ensure_directory, recovering...");
            poisoned.into_inner()
        });
        if let Some(&ino) = path_inodes.get(&path) {
            return Ok(ino);
        }
        drop(path_inodes);

        // Create parent first
        let parent_path = parent_path(&path).ok_or("Invalid path")?;
        let parent_ino = self.ensure_directory(&parent_path)?;

        // Create this directory
        let ino = self.alloc_ino()?;
        let attr = FileAttr {
            ino,
            size: 0,
            blocks: 0,
            kind: FileKind::Directory,
            perm: 0o755,
            nlink: 2,
            ..Default::default()
        };

        self.inodes
            .write()
            .map_err(|_| "Inodes lock poisoned")?
            .insert(ino, attr);
        self.inode_paths
            .write()
            .map_err(|_| "Inode paths lock poisoned")?
            .insert(ino, path.clone());
        self.path_inodes
            .write()
            .map_err(|_| "Path inodes lock poisoned")?
            .insert(path.clone(), ino);
        self.directories
            .write()
            .map_err(|_| "Directories lock poisoned")?
            .insert(ino, Vec::new());

        // Add to parent
        let dirname = filename(&path).ok_or("Invalid dirname")?;
        self.directories
            .write()
            .map_err(|_| "Directories lock poisoned")?
            .get_mut(&parent_ino)
            .ok_or("Parent not found")?
            .push(DirEntry {
                ino,
                name: dirname.to_string(),
                kind: FileKind::Directory,
            });

        // Update parent nlink
        if let Some(parent_attr) = self
            .inodes
            .write()
            .map_err(|_| "Inodes lock poisoned")?
            .get_mut(&parent_ino)
        {
            parent_attr.nlink += 1;
        }

        Ok(ino)
    }

    /// Lookup a path and return its inode
    pub fn lookup_path(&self, path: &str) -> Option<Ino> {
        let path = normalize_path(path);
        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned in lookup_path, recovering...");
            poisoned.into_inner()
        });
        path_inodes.get(&path).copied()
    }

    /// Get file attributes by inode
    pub fn get_attr(&self, ino: Ino) -> Option<FileAttr> {
        let inodes = self.inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: inodes lock poisoned in get_attr, recovering...");
            poisoned.into_inner()
        });
        inodes.get(&ino).cloned()
    }

    /// Read file data
    pub fn read_data(&self, ino: Ino, offset: u64, size: u32) -> Option<Vec<u8>> {
        let cache = self.file_cache.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: file_cache lock poisoned in read_data, recovering...");
            poisoned.into_inner()
        });
        let cached = cache.get(&ino)?;

        let start = offset as usize;
        let end = std::cmp::min(start + size as usize, cached.data.len());

        if start >= cached.data.len() {
            return Some(Vec::new());
        }

        Some(cached.data[start..end].to_vec())
    }

    /// Read directory contents
    pub fn read_dir(&self, ino: Ino) -> Option<Vec<DirEntry>> {
        let directories = self.directories.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: directories lock poisoned in read_dir, recovering...");
            poisoned.into_inner()
        });
        directories.get(&ino).cloned()
    }

    /// Lookup entry in directory by name
    pub fn lookup_entry(&self, parent_ino: Ino, name: &str) -> Option<Ino> {
        let dirs = self.directories.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: directories lock poisoned in lookup_entry, recovering...");
            poisoned.into_inner()
        });
        let entries = dirs.get(&parent_ino)?;
        entries.iter().find(|e| e.name == name).map(|e| e.ino)
    }

    /// Get parent inode for a given inode
    pub fn get_parent(&self, ino: Ino) -> Option<Ino> {
        if ino == ROOT_INO {
            return Some(ROOT_INO); // Root's parent is itself
        }

        let paths = self.inode_paths.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: inode_paths lock poisoned in get_parent, recovering...");
            poisoned.into_inner()
        });
        let path = paths.get(&ino)?;
        let parent = parent_path(path)?;

        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned in get_parent, recovering...");
            poisoned.into_inner()
        });
        path_inodes.get(&parent).copied()
    }

    /// Get total number of files
    pub fn file_count(&self) -> usize {
        let cache = self.file_cache.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: file_cache lock poisoned in file_count, recovering...");
            poisoned.into_inner()
        });
        cache.len()
    }

    /// Get total size of all files
    pub fn total_size(&self) -> u64 {
        let cache = self.file_cache.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: file_cache lock poisoned in total_size, recovering...");
            poisoned.into_inner()
        });
        cache.values().map(|f| f.attr.size).sum()
    }

    /// Check if filesystem is read-only
    pub fn is_read_only(&self) -> bool {
        self.read_only
    }

    /// Get attribute TTL
    pub fn attr_ttl(&self) -> Duration {
        self.attr_ttl
    }

    /// Get entry TTL
    pub fn entry_ttl(&self) -> Duration {
        self.entry_ttl
    }

    /// Add a symbolic link to the filesystem
    ///
    /// # Arguments
    ///
    /// * `path` - Absolute path within the filesystem (e.g., "/lib/libc.so.6")
    /// * `target` - The symlink target path (can be relative or absolute)
    ///
    /// # Returns
    ///
    /// The assigned inode number for the new symlink
    pub fn add_symlink(&self, path: &str, target: String) -> Result<Ino, &'static str> {
        let path = normalize_path(path);

        // Check if already exists
        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned in add_symlink, recovering...");
            poisoned.into_inner()
        });
        if path_inodes.contains_key(&path) {
            return Err("Symlink already exists");
        }
        drop(path_inodes);

        // Ensure parent directory exists
        let parent_path = parent_path(&path).ok_or("Invalid path")?;
        let parent_ino = self.ensure_directory(&parent_path)?;

        // Create symlink
        let ino = self.alloc_ino()?;
        let size = target.len() as u64; // Symlink size is the target path length

        let attr = FileAttr {
            ino,
            size,
            blocks: 0,
            kind: FileKind::Symlink,
            perm: 0o777, // Symlinks typically have 777 permissions
            nlink: 1,
            ..Default::default()
        };

        // Store symlink
        self.inodes
            .write()
            .map_err(|_| "Inodes lock poisoned")?
            .insert(ino, attr);
        self.inode_paths
            .write()
            .map_err(|_| "Inode paths lock poisoned")?
            .insert(ino, path.clone());
        self.path_inodes
            .write()
            .map_err(|_| "Path inodes lock poisoned")?
            .insert(path.clone(), ino);
        self.symlinks
            .write()
            .map_err(|_| "Symlinks lock poisoned")?
            .insert(ino, target);

        // Add to parent directory
        let filename = filename(&path).ok_or("Invalid filename")?;
        self.directories
            .write()
            .map_err(|_| "Directories lock poisoned")?
            .get_mut(&parent_ino)
            .ok_or("Parent directory not found")?
            .push(DirEntry {
                ino,
                name: filename.to_string(),
                kind: FileKind::Symlink,
            });

        Ok(ino)
    }

    /// Add a device node to the filesystem (Option C: store device data)
    ///
    /// # Arguments
    ///
    /// * `path` - Absolute path within the filesystem (e.g., "/dev/null")
    /// * `is_char` - true for character device, false for block device
    /// * `major` - Major device number
    /// * `minor` - Minor device number
    /// * `data` - Device data content (Option C encoding)
    ///
    /// # Returns
    ///
    /// The assigned inode number for the new device
    pub fn add_device(
        &self,
        path: &str,
        is_char: bool,
        major: u32,
        minor: u32,
        data: Vec<u8>,
    ) -> Result<Ino, &'static str> {
        let path = normalize_path(path);

        // Check if already exists
        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned in add_device, recovering...");
            poisoned.into_inner()
        });
        if path_inodes.contains_key(&path) {
            return Err("Device already exists");
        }
        drop(path_inodes);

        // Ensure parent directory exists
        let parent_path = parent_path(&path).ok_or("Invalid path")?;
        let parent_ino = self.ensure_directory(&parent_path)?;

        // Create device node
        let ino = self.alloc_ino()?;
        let size = data.len() as u64;
        let kind = if is_char {
            FileKind::CharDevice
        } else {
            FileKind::BlockDevice
        };

        let attr = FileAttr {
            ino,
            size,
            blocks: size.div_ceil(512),
            kind,
            perm: 0o666,
            nlink: 1,
            rdev: (major << 8) | minor, // Encode major/minor in rdev
            ..Default::default()
        };

        // Store device node
        self.inodes
            .write()
            .map_err(|_| "Inodes lock poisoned")?
            .insert(ino, attr.clone());
        self.inode_paths
            .write()
            .map_err(|_| "Inode paths lock poisoned")?
            .insert(ino, path.clone());
        self.path_inodes
            .write()
            .map_err(|_| "Path inodes lock poisoned")?
            .insert(path.clone(), ino);
        self.devices
            .write()
            .map_err(|_| "Devices lock poisoned")?
            .insert(ino, DeviceNode { major, minor });

        // Store device data (Option C)
        self.file_cache
            .write()
            .map_err(|_| "File cache lock poisoned")?
            .insert(ino, CachedFile { data, attr });

        // Add to parent directory
        let filename = filename(&path).ok_or("Invalid filename")?;
        self.directories
            .write()
            .map_err(|_| "Directories lock poisoned")?
            .get_mut(&parent_ino)
            .ok_or("Parent directory not found")?
            .push(DirEntry {
                ino,
                name: filename.to_string(),
                kind,
            });

        Ok(ino)
    }

    /// Add a FIFO (named pipe) to the filesystem
    pub fn add_fifo(&self, path: &str) -> Result<Ino, &'static str> {
        self.add_special_file(path, FileKind::Fifo)
    }

    /// Add a Unix socket to the filesystem
    pub fn add_socket(&self, path: &str) -> Result<Ino, &'static str> {
        self.add_special_file(path, FileKind::Socket)
    }

    /// Internal helper to add special files (FIFO, socket)
    fn add_special_file(&self, path: &str, kind: FileKind) -> Result<Ino, &'static str> {
        let path = normalize_path(path);

        // Check if already exists
        let path_inodes = self.path_inodes.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: path_inodes lock poisoned in add_special_file, recovering...");
            poisoned.into_inner()
        });
        if path_inodes.contains_key(&path) {
            return Err("Special file already exists");
        }
        drop(path_inodes);

        // Ensure parent directory exists
        let parent_path = parent_path(&path).ok_or("Invalid path")?;
        let parent_ino = self.ensure_directory(&parent_path)?;

        // Create special file
        let ino = self.alloc_ino()?;

        let attr = FileAttr {
            ino,
            size: 0,
            blocks: 0,
            kind,
            perm: 0o666,
            nlink: 1,
            ..Default::default()
        };

        // Store special file
        self.inodes
            .write()
            .map_err(|_| "Inodes lock poisoned")?
            .insert(ino, attr);
        self.inode_paths
            .write()
            .map_err(|_| "Inode paths lock poisoned")?
            .insert(ino, path.clone());
        self.path_inodes
            .write()
            .map_err(|_| "Path inodes lock poisoned")?
            .insert(path.clone(), ino);

        // Add to parent directory
        let filename = filename(&path).ok_or("Invalid filename")?;
        self.directories
            .write()
            .map_err(|_| "Directories lock poisoned")?
            .get_mut(&parent_ino)
            .ok_or("Parent directory not found")?
            .push(DirEntry {
                ino,
                name: filename.to_string(),
                kind,
            });

        Ok(ino)
    }

    /// Read symlink target
    pub fn read_symlink(&self, ino: Ino) -> Option<String> {
        let symlinks = self.symlinks.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: symlinks lock poisoned in read_symlink, recovering...");
            poisoned.into_inner()
        });
        symlinks.get(&ino).cloned()
    }

    /// Get device node info
    pub fn get_device(&self, ino: Ino) -> Option<DeviceNode> {
        let devices = self.devices.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: devices lock poisoned in get_device, recovering...");
            poisoned.into_inner()
        });
        devices.get(&ino).cloned()
    }

    /// Get total number of symlinks
    pub fn symlink_count(&self) -> usize {
        let symlinks = self.symlinks.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: symlinks lock poisoned in symlink_count, recovering...");
            poisoned.into_inner()
        });
        symlinks.len()
    }

    /// Get total number of device nodes
    pub fn device_count(&self) -> usize {
        let devices = self.devices.read().unwrap_or_else(|poisoned| {
            eprintln!("WARNING: devices lock poisoned in device_count, recovering...");
            poisoned.into_inner()
        });
        devices.len()
    }
}

// =============================================================================
// FUSER FILESYSTEM TRAIT IMPLEMENTATION
// =============================================================================

#[cfg(feature = "fuse")]
impl fuser::Filesystem for EngramFS {
    /// Initialize filesystem
    fn init(
        &mut self,
        _req: &fuser::Request<'_>,
        _config: &mut fuser::KernelConfig,
    ) -> Result<(), libc::c_int> {
        eprintln!(
            "EngramFS initialized: {} files, {} bytes total",
            self.file_count(),
            self.total_size()
        );
        Ok(())
    }

    /// Clean up filesystem
    fn destroy(&mut self) {
        eprintln!("EngramFS unmounted");
    }

    /// Look up a directory entry by name
    fn lookup(
        &mut self,
        _req: &fuser::Request<'_>,
        parent: u64,
        name: &OsStr,
        reply: fuser::ReplyEntry,
    ) {
        let name = match name.to_str() {
            Some(n) => n,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        match self.lookup_entry(parent, name) {
            Some(ino) => {
                if let Some(attr) = self.get_attr(ino) {
                    let fuser_attr: fuser::FileAttr = attr.into();
                    reply.entry(&self.entry_ttl, &fuser_attr, 0);
                } else {
                    reply.error(libc::ENOENT);
                }
            }
            None => {
                reply.error(libc::ENOENT);
            }
        }
    }

    /// Get file attributes
    fn getattr(
        &mut self,
        _req: &fuser::Request<'_>,
        ino: u64,
        _fh: Option<u64>,
        reply: fuser::ReplyAttr,
    ) {
        match self.get_attr(ino) {
            Some(attr) => {
                let fuser_attr: fuser::FileAttr = attr.into();
                reply.attr(&self.attr_ttl, &fuser_attr);
            }
            None => {
                reply.error(libc::ENOENT);
            }
        }
    }

    /// Read data from a file
    fn read(
        &mut self,
        _req: &fuser::Request<'_>,
        ino: u64,
        _fh: u64,
        offset: i64,
        size: u32,
        _flags: i32,
        _lock_owner: Option<u64>,
        reply: fuser::ReplyData,
    ) {
        match self.read_data(ino, offset as u64, size) {
            Some(data) => {
                reply.data(&data);
            }
            None => {
                reply.error(libc::ENOENT);
            }
        }
    }

    /// Open a file
    fn open(&mut self, _req: &fuser::Request<'_>, ino: u64, flags: i32, reply: fuser::ReplyOpen) {
        // Check if file exists
        if self.get_attr(ino).is_none() {
            reply.error(libc::ENOENT);
            return;
        }

        // Check for write flags on read-only filesystem
        if self.read_only {
            let write_flags = libc::O_WRONLY | libc::O_RDWR | libc::O_APPEND | libc::O_TRUNC;
            if flags & write_flags != 0 {
                reply.error(libc::EROFS);
                return;
            }
        }

        // Return a dummy file handle (we're stateless)
        reply.opened(0, 0);
    }

    /// Release an open file
    fn release(
        &mut self,
        _req: &fuser::Request<'_>,
        _ino: u64,
        _fh: u64,
        _flags: i32,
        _lock_owner: Option<u64>,
        _flush: bool,
        reply: fuser::ReplyEmpty,
    ) {
        reply.ok();
    }

    /// Open a directory
    fn opendir(
        &mut self,
        _req: &fuser::Request<'_>,
        ino: u64,
        _flags: i32,
        reply: fuser::ReplyOpen,
    ) {
        match self.get_attr(ino) {
            Some(attr) if attr.kind == FileKind::Directory => {
                reply.opened(0, 0);
            }
            Some(_) => {
                reply.error(libc::ENOTDIR);
            }
            None => {
                reply.error(libc::ENOENT);
            }
        }
    }

    /// Read directory entries
    fn readdir(
        &mut self,
        _req: &fuser::Request<'_>,
        ino: u64,
        _fh: u64,
        offset: i64,
        mut reply: fuser::ReplyDirectory,
    ) {
        let mut entries: Vec<(u64, fuser::FileType, String)> = Vec::new();

        // Add . and ..
        entries.push((ino, fuser::FileType::Directory, ".".to_string()));
        let parent_ino = self.get_parent(ino).unwrap_or(ino);
        entries.push((parent_ino, fuser::FileType::Directory, "..".to_string()));

        // Add directory contents
        if let Some(dir_entries) = self.read_dir(ino) {
            for entry in dir_entries {
                entries.push((entry.ino, entry.kind.into(), entry.name));
            }
        }

        // Skip entries before offset and emit remaining
        for (i, (ino, kind, name)) in entries.into_iter().enumerate().skip(offset as usize) {
            // Reply returns true if buffer is full
            if reply.add(ino, (i + 1) as i64, kind, &name) {
                break;
            }
        }

        reply.ok();
    }

    /// Release a directory handle
    fn releasedir(
        &mut self,
        _req: &fuser::Request<'_>,
        _ino: u64,
        _fh: u64,
        _flags: i32,
        reply: fuser::ReplyEmpty,
    ) {
        reply.ok();
    }

    /// Get filesystem statistics
    fn statfs(&mut self, _req: &fuser::Request<'_>, _ino: u64, reply: fuser::ReplyStatfs) {
        let total_files = self.file_count() as u64;
        let total_size = self.total_size();
        let block_size = 4096u64;
        let total_blocks = total_size.div_ceil(block_size);

        reply.statfs(
            total_blocks,      // blocks - total data blocks
            0,                 // bfree - free blocks (0 for read-only)
            0,                 // bavail - available blocks (0 for read-only)
            total_files,       // files - total file nodes
            0,                 // ffree - free file nodes (0 for read-only)
            block_size as u32, // bsize - block size
            255,               // namelen - maximum name length
            block_size as u32, // frsize - fragment size
        );
    }

    /// Check file access permissions
    fn access(&mut self, _req: &fuser::Request<'_>, ino: u64, mask: i32, reply: fuser::ReplyEmpty) {
        // Check if file exists
        if self.get_attr(ino).is_none() {
            reply.error(libc::ENOENT);
            return;
        }

        // Deny write access on read-only filesystem
        if self.read_only && (mask & libc::W_OK != 0) {
            reply.error(libc::EROFS);
            return;
        }

        // Allow all other access (simplified permission model)
        reply.ok();
    }

    /// Read symbolic link target
    fn readlink(&mut self, _req: &fuser::Request<'_>, ino: u64, reply: fuser::ReplyData) {
        match self.get_attr(ino) {
            Some(attr) if attr.kind == FileKind::Symlink => {
                // Look up the symlink target
                match self.read_symlink(ino) {
                    Some(target) => {
                        reply.data(target.as_bytes());
                    }
                    None => {
                        eprintln!("WARNING: Symlink {} has no target stored", ino);
                        reply.error(libc::EIO);
                    }
                }
            }
            Some(_) => {
                reply.error(libc::EINVAL); // Not a symlink
            }
            None => {
                reply.error(libc::ENOENT);
            }
        }
    }

    /// Create a symbolic link
    fn symlink(
        &mut self,
        _req: &fuser::Request<'_>,
        parent: u64,
        link_name: &OsStr,
        target: &std::path::Path,
        reply: fuser::ReplyEntry,
    ) {
        if self.read_only {
            reply.error(libc::EROFS);
            return;
        }

        let link_name = match link_name.to_str() {
            Some(n) => n,
            None => {
                reply.error(libc::EINVAL);
                return;
            }
        };

        let target = match target.to_str() {
            Some(t) => t.to_string(),
            None => {
                reply.error(libc::EINVAL);
                return;
            }
        };

        // Get parent path
        let parent_path_str = match self.inode_paths.read() {
            Ok(paths) => match paths.get(&parent) {
                Some(p) => p.clone(),
                None => {
                    reply.error(libc::ENOENT);
                    return;
                }
            },
            Err(_) => {
                reply.error(libc::EIO);
                return;
            }
        };

        // Construct symlink path
        let symlink_path = if parent_path_str == "/" {
            format!("/{}", link_name)
        } else {
            format!("{}/{}", parent_path_str, link_name)
        };

        // Create the symlink
        match self.add_symlink(&symlink_path, target) {
            Ok(ino) => {
                if let Some(attr) = self.get_attr(ino) {
                    let fuser_attr: fuser::FileAttr = attr.into();
                    reply.entry(&self.entry_ttl, &fuser_attr, 0);
                } else {
                    reply.error(libc::EIO);
                }
            }
            Err(_) => {
                reply.error(libc::EIO);
            }
        }
    }

    /// Create a special device node (mknod)
    fn mknod(
        &mut self,
        _req: &fuser::Request<'_>,
        parent: u64,
        name: &OsStr,
        mode: u32,
        _umask: u32,
        rdev: u32,
        reply: fuser::ReplyEntry,
    ) {
        if self.read_only {
            reply.error(libc::EROFS);
            return;
        }

        let name = match name.to_str() {
            Some(n) => n,
            None => {
                reply.error(libc::EINVAL);
                return;
            }
        };

        // Get parent path
        let parent_path_str = match self.inode_paths.read() {
            Ok(paths) => match paths.get(&parent) {
                Some(p) => p.clone(),
                None => {
                    reply.error(libc::ENOENT);
                    return;
                }
            },
            Err(_) => {
                reply.error(libc::EIO);
                return;
            }
        };

        // Construct file path
        let file_path = if parent_path_str == "/" {
            format!("/{}", name)
        } else {
            format!("{}/{}", parent_path_str, name)
        };

        // Determine file type from mode
        let file_type = mode & libc::S_IFMT;
        let major = (rdev >> 8) & 0xff;
        let minor = rdev & 0xff;

        let result = match file_type {
            libc::S_IFCHR => self.add_device(&file_path, true, major, minor, Vec::new()),
            libc::S_IFBLK => self.add_device(&file_path, false, major, minor, Vec::new()),
            libc::S_IFIFO => self.add_fifo(&file_path),
            libc::S_IFSOCK => self.add_socket(&file_path),
            _ => {
                reply.error(libc::EINVAL);
                return;
            }
        };

        match result {
            Ok(ino) => {
                if let Some(attr) = self.get_attr(ino) {
                    let fuser_attr: fuser::FileAttr = attr.into();
                    reply.entry(&self.entry_ttl, &fuser_attr, 0);
                } else {
                    reply.error(libc::EIO);
                }
            }
            Err(_) => {
                reply.error(libc::EIO);
            }
        }
    }
}

// =============================================================================
// MOUNT FUNCTIONS
// =============================================================================

/// Mount options for EngramFS
#[cfg(feature = "fuse")]
#[derive(Clone, Debug)]
pub struct MountOptions {
    /// Read-only mount (default: true)
    pub read_only: bool,
    /// Allow other users to access the mount (default: false)
    pub allow_other: bool,
    /// Allow root to access the mount (default: true)
    pub allow_root: bool,
    /// Filesystem name shown in mount output
    pub fsname: String,
}

#[cfg(feature = "fuse")]
impl Default for MountOptions {
    fn default() -> Self {
        MountOptions {
            read_only: true,
            allow_other: false,
            allow_root: true,
            fsname: "engram".to_string(),
        }
    }
}

/// Mount an EngramFS at the specified path
///
/// This function blocks until the filesystem is unmounted. Use `spawn_mount`
/// for a non-blocking version.
///
/// # Arguments
///
/// * `fs` - The EngramFS instance to mount
/// * `mountpoint` - Directory path where the filesystem will be mounted
/// * `options` - Mount options (see `MountOptions`)
///
/// # Example
///
/// ```no_run
/// use embeddenator_fs::fuse_shim::{EngramFS, mount, MountOptions};
///
/// let fs = EngramFS::new(true);
/// // ... populate fs with files ...
///
/// mount(fs, "/mnt/engram", MountOptions::default()).unwrap();
/// ```
#[cfg(feature = "fuse")]
pub fn mount<P: AsRef<Path>>(
    fs: EngramFS,
    mountpoint: P,
    options: MountOptions,
) -> Result<(), std::io::Error> {
    use fuser::MountOption;

    let mut mount_options = vec![
        MountOption::FSName(options.fsname),
        MountOption::AutoUnmount,
        MountOption::DefaultPermissions,
    ];

    if options.read_only {
        mount_options.push(MountOption::RO);
    }

    if options.allow_other {
        mount_options.push(MountOption::AllowOther);
    } else if options.allow_root {
        mount_options.push(MountOption::AllowRoot);
    }

    fuser::mount2(fs, mountpoint.as_ref(), &mount_options)
}

/// Mount an EngramFS with signal handling for graceful unmount
///
/// This function installs signal handlers for SIGINT, SIGTERM, and SIGHUP,
/// enabling graceful unmount when the user presses Ctrl+C or sends a kill signal.
///
/// # Arguments
///
/// * `fs` - The EngramFS instance to mount
/// * `mountpoint` - Directory path where the filesystem will be mounted
/// * `options` - Mount options (see `MountOptions`)
///
/// # Signal Handling
///
/// When a signal is received:
/// 1. The signal type is logged
/// 2. The FUSE session is cleanly unmounted
/// 3. The function returns `Ok(())`
///
/// # Example
///
/// ```no_run
/// use embeddenator_fs::fuse_shim::{EngramFS, mount_with_signals, MountOptions};
///
/// let fs = EngramFS::new(true);
/// // ... populate fs with files ...
///
/// // This will handle Ctrl+C gracefully
/// mount_with_signals(fs, "/mnt/engram", MountOptions::default()).unwrap();
/// ```
#[cfg(feature = "fuse")]
pub fn mount_with_signals<P: AsRef<Path>>(
    fs: EngramFS,
    mountpoint: P,
    options: MountOptions,
) -> Result<(), std::io::Error> {
    use crate::fs::signal::{install_signal_handlers, ShutdownSignal};
    use fuser::MountOption;
    use std::sync::Arc;

    // Set up shutdown signal
    let shutdown = Arc::new(ShutdownSignal::new());
    install_signal_handlers(shutdown.clone())?;

    let mut mount_options = vec![
        MountOption::FSName(options.fsname),
        MountOption::AutoUnmount,
        MountOption::DefaultPermissions,
    ];

    if options.read_only {
        mount_options.push(MountOption::RO);
    }

    if options.allow_other {
        mount_options.push(MountOption::AllowOther);
    } else if options.allow_root {
        mount_options.push(MountOption::AllowRoot);
    }

    // Use spawn_mount2 to get a session we can control
    let session = fuser::spawn_mount2(fs, mountpoint.as_ref(), &mount_options)?;

    // Wait for shutdown signal or natural unmount
    eprintln!("EngramFS mounted. Press Ctrl+C to unmount gracefully.");

    // Poll for shutdown signal
    loop {
        if shutdown.is_signaled() {
            eprintln!(
                "\nReceived {} - unmounting gracefully...",
                shutdown.signal_name()
            );
            // Session will be dropped here, triggering unmount
            drop(session);
            break;
        }

        // Check if session is still alive by sleeping briefly
        std::thread::sleep(std::time::Duration::from_millis(100));

        // Try to detect if session ended (e.g., via fusermount -u)
        // The session will be joined when dropped
    }

    eprintln!("EngramFS unmounted cleanly.");
    Ok(())
}

/// Spawn an EngramFS mount in a background thread
///
/// Returns a `BackgroundSession` that will automatically unmount when dropped.
///
/// # Arguments
///
/// * `fs` - The EngramFS instance to mount
/// * `mountpoint` - Directory path where the filesystem will be mounted
/// * `options` - Mount options (see `MountOptions`)
///
/// # Example
///
/// ```no_run
/// use embeddenator_fs::fuse_shim::{EngramFS, spawn_mount, MountOptions};
///
/// let fs = EngramFS::new(true);
/// // ... populate fs with files ...
///
/// let session = spawn_mount(fs, "/mnt/engram", MountOptions::default()).unwrap();
/// // Filesystem is now mounted and accessible
///
/// // When session is dropped, the filesystem will be unmounted
/// ```
#[cfg(feature = "fuse")]
pub fn spawn_mount<P: AsRef<Path>>(
    fs: EngramFS,
    mountpoint: P,
    options: MountOptions,
) -> Result<fuser::BackgroundSession, std::io::Error> {
    use fuser::MountOption;

    let mut mount_options = vec![
        MountOption::FSName(options.fsname),
        MountOption::AutoUnmount,
        MountOption::DefaultPermissions,
    ];

    if options.read_only {
        mount_options.push(MountOption::RO);
    }

    if options.allow_other {
        mount_options.push(MountOption::AllowOther);
    } else if options.allow_root {
        mount_options.push(MountOption::AllowRoot);
    }

    fuser::spawn_mount2(fs, mountpoint.as_ref(), &mount_options)
}

// =============================================================================
// BUILDER PATTERN
// =============================================================================

/// Builder for creating an EngramFS from engram data
///
/// # Example
///
/// ```
/// use embeddenator_fs::fuse_shim::EngramFSBuilder;
///
/// let fs = EngramFSBuilder::new()
///     .add_file("/README.md", b"# Hello World".to_vec())
///     .add_file("/src/main.rs", b"fn main() {}".to_vec())
///     .build();
///
/// assert_eq!(fs.file_count(), 2);
/// ```
pub struct EngramFSBuilder {
    fs: EngramFS,
}

impl EngramFSBuilder {
    /// Create a new builder
    pub fn new() -> Self {
        EngramFSBuilder {
            fs: EngramFS::new(true), // Read-only by default
        }
    }

    /// Add a file from decoded engram data
    pub fn add_file(self, path: &str, data: Vec<u8>) -> Self {
        let _ = self.fs.add_file(path, data);
        self
    }

    /// Set read-only mode (default: true)
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.fs.read_only = read_only;
        self
    }

    /// Build the filesystem
    pub fn build(self) -> EngramFS {
        self.fs
    }
}

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

// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================

/// Normalize a path (ensure leading /, remove trailing /)
fn normalize_path(path: &str) -> String {
    let path = if path.starts_with('/') {
        path.to_string()
    } else {
        format!("/{}", path)
    };

    if path.len() > 1 && path.ends_with('/') {
        path[..path.len() - 1].to_string()
    } else {
        path
    }
}

/// Get parent path
fn parent_path(path: &str) -> Option<String> {
    let path = normalize_path(path);
    if path == "/" {
        return None;
    }

    match path.rfind('/') {
        Some(0) => Some("/".to_string()),
        Some(pos) => Some(path[..pos].to_string()),
        None => None,
    }
}

/// Get filename from path
fn filename(path: &str) -> Option<&str> {
    let path = path.trim_end_matches('/');
    path.rsplit('/').next()
}

/// Convert SystemTime to Duration since UNIX_EPOCH (useful for logging)
#[allow(dead_code)]
fn system_time_to_unix(time: SystemTime) -> u64 {
    time.duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

// =============================================================================
// STATISTICS
// =============================================================================

/// Statistics for the mounted filesystem
#[derive(Clone, Debug, Default)]
pub struct MountStats {
    /// Number of read operations
    pub reads: u64,
    /// Total bytes read
    pub read_bytes: u64,
    /// Number of lookup operations
    pub lookups: u64,
    /// Number of readdir operations
    pub readdirs: u64,
    /// Number of cache hits
    pub cache_hits: u64,
    /// Number of cache misses
    pub cache_misses: u64,
    /// Total decode time in microseconds
    pub decode_time_us: u64,
}

// =============================================================================
// TESTS
// =============================================================================

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

    #[test]
    fn test_normalize_path() {
        assert_eq!(normalize_path("foo"), "/foo");
        assert_eq!(normalize_path("/foo"), "/foo");
        assert_eq!(normalize_path("/foo/"), "/foo");
        assert_eq!(normalize_path("/"), "/");
    }

    #[test]
    fn test_parent_path() {
        assert_eq!(parent_path("/foo/bar"), Some("/foo".to_string()));
        assert_eq!(parent_path("/foo"), Some("/".to_string()));
        assert_eq!(parent_path("/"), None);
    }

    #[test]
    fn test_filename() {
        assert_eq!(filename("/foo/bar"), Some("bar"));
        assert_eq!(filename("/foo"), Some("foo"));
        assert_eq!(filename("/foo/bar/"), Some("bar"));
    }

    #[test]
    fn test_add_file() {
        let fs = EngramFS::new(true);

        let ino = fs.add_file("/test.txt", b"hello world".to_vec()).unwrap();
        assert!(ino > ROOT_INO);

        let data = fs.read_data(ino, 0, 100).unwrap();
        assert_eq!(data, b"hello world");
    }

    #[test]
    fn test_nested_directories() {
        let fs = EngramFS::new(true);

        fs.add_file("/a/b/c/file.txt", b"deep".to_vec()).unwrap();

        // All directories should exist
        assert!(fs.lookup_path("/a").is_some());
        assert!(fs.lookup_path("/a/b").is_some());
        assert!(fs.lookup_path("/a/b/c").is_some());
        assert!(fs.lookup_path("/a/b/c/file.txt").is_some());
    }

    #[test]
    fn test_readdir() {
        let fs = EngramFS::new(true);

        fs.add_file("/foo.txt", b"foo".to_vec()).unwrap();
        fs.add_file("/bar.txt", b"bar".to_vec()).unwrap();
        fs.add_file("/subdir/baz.txt", b"baz".to_vec()).unwrap();

        let root_entries = fs.read_dir(ROOT_INO).unwrap();
        assert_eq!(root_entries.len(), 3); // foo.txt, bar.txt, subdir

        let names: Vec<_> = root_entries.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"foo.txt"));
        assert!(names.contains(&"bar.txt"));
        assert!(names.contains(&"subdir"));
    }

    #[test]
    fn test_read_partial() {
        let fs = EngramFS::new(true);
        let data = b"0123456789";

        let ino = fs.add_file("/test.txt", data.to_vec()).unwrap();

        // Read middle portion
        let partial = fs.read_data(ino, 3, 4).unwrap();
        assert_eq!(partial, b"3456");

        // Read past end
        let past_end = fs.read_data(ino, 20, 10).unwrap();
        assert!(past_end.is_empty());
    }

    #[test]
    fn test_builder() {
        let fs = EngramFSBuilder::new()
            .add_file("/a.txt", b"a".to_vec())
            .add_file("/b.txt", b"b".to_vec())
            .build();

        assert_eq!(fs.file_count(), 2);
    }

    #[test]
    fn test_get_parent() {
        let fs = EngramFS::new(true);

        fs.add_file("/a/b/c.txt", b"test".to_vec()).unwrap();

        let c_ino = fs.lookup_path("/a/b/c.txt").unwrap();
        let b_ino = fs.lookup_path("/a/b").unwrap();
        let a_ino = fs.lookup_path("/a").unwrap();

        assert_eq!(fs.get_parent(c_ino), Some(b_ino));
        assert_eq!(fs.get_parent(b_ino), Some(a_ino));
        assert_eq!(fs.get_parent(a_ino), Some(ROOT_INO));
        assert_eq!(fs.get_parent(ROOT_INO), Some(ROOT_INO));
    }

    #[test]
    fn test_default_attrs() {
        let attr = FileAttr::default();
        assert_eq!(attr.perm, 0o644);
        assert_eq!(attr.nlink, 1);
        assert_eq!(attr.blksize, 4096);
    }

    #[test]
    fn test_file_kind_conversion() {
        // Only run conversion tests when fuse feature is enabled
        #[cfg(feature = "fuse")]
        {
            let dir: fuser::FileType = FileKind::Directory.into();
            assert_eq!(dir, fuser::FileType::Directory);

            let file: fuser::FileType = FileKind::RegularFile.into();
            assert_eq!(file, fuser::FileType::RegularFile);
        }
    }

    #[test]
    fn test_lock_poisoning_recovery() {
        use std::sync::Arc;
        use std::thread;

        // This test demonstrates that the filesystem can recover from poisoned locks
        // In the read path (read-only operations), we use unwrap_or_else with into_inner()
        // to continue serving requests even with poisoned locks

        let fs = Arc::new(EngramFS::new(true));

        // Add a file successfully
        fs.add_file("/test.txt", b"hello".to_vec()).unwrap();
        let ino = fs.lookup_path("/test.txt").unwrap();

        // Simulate lock poisoning scenario by creating a poisoned lock in a thread
        // Note: We can't actually poison the lock in a real test without unsafe code,
        // but we can verify that our error handling works correctly

        // Test that read operations continue to work
        let data = fs.read_data(ino, 0, 5);
        assert!(data.is_some());
        assert_eq!(data.unwrap(), b"hello");

        // Test that lookup continues to work
        let found_ino = fs.lookup_path("/test.txt");
        assert_eq!(found_ino, Some(ino));

        // Test that get_attr works
        let attr = fs.get_attr(ino);
        assert!(attr.is_some());
        assert_eq!(attr.unwrap().size, 5);

        // Test concurrent access doesn't cause issues
        let fs_clone = Arc::clone(&fs);
        let handle = thread::spawn(move || {
            // Multiple reads from another thread
            for _ in 0..10 {
                let _ = fs_clone.read_data(ino, 0, 5);
                let _ = fs_clone.lookup_path("/test.txt");
            }
        });

        // Simultaneous reads from main thread
        for _ in 0..10 {
            let _ = fs.read_data(ino, 0, 5);
            let _ = fs.get_attr(ino);
        }

        handle.join().unwrap();

        // Verify filesystem is still functional
        assert_eq!(fs.file_count(), 1);
        assert_eq!(fs.total_size(), 5);
    }

    #[test]
    fn test_write_lock_error_propagation() {
        // Test that write operations properly propagate lock errors
        let fs = EngramFS::new(false);

        // This should succeed
        let result = fs.add_file("/test.txt", b"content".to_vec());
        assert!(result.is_ok());

        // Verify the file was created
        assert!(fs.lookup_path("/test.txt").is_some());
        assert_eq!(fs.file_count(), 1);
    }
}