agentvfs 0.1.6

Virtual filesystem CLI backed by embedded databases for AI agents
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
//! FUSE filesystem implementation for vfs.

use std::collections::HashMap;
use std::ffi::OsStr;
use std::sync::Mutex;

use fuser::{
    Filesystem, ReplyAttr, ReplyData, ReplyDirectory, ReplyEmpty, ReplyEntry, ReplyOpen,
    ReplyStatfs, ReplyWrite, Request,
};

use crate::error::VfsError;
use crate::fs::FileSystem;

use super::attr::{entry_to_attr, root_attr, BLOCK_SIZE, TTL};

/// Root inode number (FUSE convention).
const ROOT_INODE: u64 = 1;

/// State of an open file handle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OpenFileState {
    Open,
    Dirty,
    Persisting,
    Flushed,
    Closed,
}

/// Information about an open file.
struct OpenFile {
    /// Path to the file (for operations that need it).
    path: String,
    /// Whether opened for writing.
    write: bool,
    /// Buffered file content for write handles.
    buffer: Option<Vec<u8>>,
    /// Current state of the open file handle.
    state: OpenFileState,
}

/// VFS FUSE filesystem implementation.
pub struct VfsFilesystem {
    /// The underlying VFS filesystem.
    fs: FileSystem,
    /// Cache of inode to path mappings.
    inode_to_path: Mutex<HashMap<u64, String>>,
    /// Next file handle to assign.
    next_fh: Mutex<u64>,
    /// Open file handles.
    open_files: Mutex<HashMap<u64, OpenFile>>,
    /// Whether mounted read-only.
    readonly: bool,
}

impl VfsFilesystem {
    /// Create a new VFS FUSE filesystem.
    pub fn new(fs: FileSystem, readonly: bool) -> Self {
        let mut inode_to_path = HashMap::new();
        // Root is always inode 1 and path "/"
        inode_to_path.insert(ROOT_INODE, "/".to_string());

        Self {
            fs,
            inode_to_path: Mutex::new(inode_to_path),
            next_fh: Mutex::new(1),
            open_files: Mutex::new(HashMap::new()),
            readonly,
        }
    }

    /// Get path for an inode, or None if not cached.
    fn get_path(&self, ino: u64) -> Option<String> {
        self.inode_to_path.lock().unwrap().get(&ino).cloned()
    }

    /// Cache a path for an inode.
    fn cache_path(&self, ino: u64, path: String) {
        self.inode_to_path.lock().unwrap().insert(ino, path);
    }

    /// Remove a cached path.
    fn uncache_path(&self, ino: u64) {
        self.inode_to_path.lock().unwrap().remove(&ino);
    }

    /// Get the next file handle.
    fn next_file_handle(&self) -> u64 {
        let mut next = self.next_fh.lock().unwrap();
        let fh = *next;
        *next += 1;
        fh
    }

    /// Convert VfsError to libc errno.
    fn error_to_errno(e: &VfsError) -> i32 {
        match e {
            VfsError::NotFound(_) => libc::ENOENT,
            VfsError::AlreadyExists(_) => libc::EEXIST,
            VfsError::NotADirectory(_) => libc::ENOTDIR,
            VfsError::NotAFile(_) => libc::EISDIR,
            VfsError::NotEmpty(_) => libc::ENOTEMPTY,
            VfsError::InvalidPath(_) => libc::EINVAL,
            VfsError::InvalidInput(_) => libc::EINVAL,
            VfsError::QuotaExceeded(_) => libc::ENOSPC,
            VfsError::Io(_) => libc::EIO,
            _ => libc::EIO,
        }
    }

    /// Build a child path from parent path and name.
    fn child_path(parent: &str, name: &str) -> String {
        if parent == "/" {
            format!("/{}", name)
        } else {
            format!("{}/{}", parent, name)
        }
    }

    fn apply_write(buffer: &mut Vec<u8>, offset: usize, data: &[u8]) {
        if offset + data.len() > buffer.len() {
            buffer.resize(offset + data.len(), 0);
        }
        buffer[offset..offset + data.len()].copy_from_slice(data);
    }

    fn persist_open_file(&self, fh: u64) -> Result<(), VfsError> {
        let mut open_files = self.open_files.lock().unwrap();
        let Some(open_file) = open_files.get_mut(&fh) else {
            return Ok(());
        };

        if !open_file.write || open_file.state != OpenFileState::Dirty {
            return Ok(());
        }

        open_file.state = OpenFileState::Persisting;
        let buffer = open_file.buffer.clone().unwrap_or_default();
        let path = open_file.path.clone();

        // Drop the lock before the potentially-slow storage write to avoid
        // blocking other FUSE callbacks. The state is now Persisting so any
        // concurrent flush/release will see that and skip.
        drop(open_files);

        self.fs.write_file(&path, &buffer)?;

        let mut open_files = self.open_files.lock().unwrap();
        if let Some(open_file) = open_files.get_mut(&fh) {
            if open_file.state == OpenFileState::Persisting {
                open_file.state = OpenFileState::Flushed;
            }
            // If state is Dirty again, another write raced in; it will be
            // handled by the next flush/release.
        }

        Ok(())
    }
}

impl Filesystem for VfsFilesystem {
    /// Look up a directory entry by name.
    fn lookup(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEntry) {
        let name = match name.to_str() {
            Some(n) => n,
            None => {
                reply.error(libc::EINVAL);
                return;
            }
        };

        // Get parent path
        let parent_path = match self.get_path(parent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        // Build child path
        let child_path = Self::child_path(&parent_path, name);

        // Look up the entry
        match self.fs.get_entry(&child_path) {
            Ok(entry) => {
                let attr = entry_to_attr(&entry);
                self.cache_path(entry.id as u64, child_path);
                reply.entry(&TTL, &attr, 0);
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Get file attributes.
    fn getattr(&mut self, _req: &Request, ino: u64, reply: ReplyAttr) {
        if ino == ROOT_INODE {
            // Handle root specially - get it from the filesystem
            match self.fs.get_entry("/") {
                Ok(entry) => {
                    let attr = entry_to_attr(&entry);
                    reply.attr(&TTL, &attr);
                }
                Err(_) => {
                    // Fallback to synthetic root attr
                    reply.attr(&TTL, &root_attr(ROOT_INODE));
                }
            }
            return;
        }

        // Get path for inode
        let path = match self.get_path(ino) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        // Get entry
        match self.fs.get_entry(&path) {
            Ok(entry) => {
                let attr = entry_to_attr(&entry);
                reply.attr(&TTL, &attr);
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Read directory entries.
    fn readdir(
        &mut self,
        _req: &Request,
        ino: u64,
        _fh: u64,
        offset: i64,
        mut reply: ReplyDirectory,
    ) {
        // Get path for inode
        let path = match self.get_path(ino) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        // Get parent inode for ".."
        let parent_ino = if ino == ROOT_INODE {
            ROOT_INODE
        } else {
            // Try to get parent from the entry
            match self.fs.get_entry(&path) {
                Ok(entry) => entry.parent_id.map(|id| id as u64).unwrap_or(ROOT_INODE),
                Err(_) => ROOT_INODE,
            }
        };

        // Build entries list
        let mut entries = vec![
            (ino, fuser::FileType::Directory, ".".to_string()),
            (parent_ino, fuser::FileType::Directory, "..".to_string()),
        ];

        // List directory contents
        match self.fs.list_dir(&path) {
            Ok(dir_entries) => {
                for entry in dir_entries {
                    let child_path = Self::child_path(&path, &entry.name);

                    // Get the file ID for this entry
                    if let Ok(file_entry) = self.fs.get_entry(&child_path) {
                        let kind = if entry.file_type.is_dir() {
                            fuser::FileType::Directory
                        } else {
                            fuser::FileType::RegularFile
                        };

                        self.cache_path(file_entry.id as u64, child_path);
                        entries.push((file_entry.id as u64, kind, entry.name));
                    }
                }
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
                return;
            }
        }

        // Return entries starting from offset
        for (i, (ino, kind, name)) in entries.iter().enumerate().skip(offset as usize) {
            if reply.add(*ino, (i + 1) as i64, *kind, name) {
                break;
            }
        }

        reply.ok();
    }

    /// Open a file.
    fn open(&mut self, _req: &Request, ino: u64, flags: i32, reply: ReplyOpen) {
        // Get path
        let path = match self.get_path(ino) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        // Check if file exists
        match self.fs.get_entry(&path) {
            Ok(entry) => {
                if entry.is_dir() {
                    reply.error(libc::EISDIR);
                    return;
                }

                // Check readonly mode
                let write_flags = libc::O_WRONLY | libc::O_RDWR | libc::O_APPEND | libc::O_TRUNC;
                let is_write = (flags & write_flags) != 0;

                if self.readonly && is_write {
                    reply.error(libc::EROFS);
                    return;
                }

                let truncate = (flags & libc::O_TRUNC) != 0;
                let buffer = if is_write {
                    if truncate {
                        Some(Vec::new())
                    } else {
                        Some(match self.fs.read_file(&path) {
                            Ok(data) => data,
                            Err(VfsError::NotFound(_)) => Vec::new(),
                            Err(e) => {
                                reply.error(Self::error_to_errno(&e));
                                return;
                            }
                        })
                    }
                } else {
                    None
                };

                let fh = self.next_file_handle();
                self.open_files.lock().unwrap().insert(
                    fh,
                    OpenFile {
                        path,
                        write: is_write,
                        buffer,
                        state: OpenFileState::Open,
                    },
                );

                reply.opened(fh, 0);
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Read file contents.
    fn read(
        &mut self,
        _req: &Request,
        ino: u64,
        fh: u64,
        offset: i64,
        size: u32,
        _flags: i32,
        _lock_owner: Option<u64>,
        reply: ReplyData,
    ) {
        // Get path from file handle or inode
        let buffered = {
            let open_files = self.open_files.lock().unwrap();
            if let Some(of) = open_files.get(&fh) {
                of.buffer.clone()
            } else {
                None
            }
        };

        if let Some(data) = buffered {
            let offset = offset as usize;
            let size = size as usize;

            if offset >= data.len() {
                reply.data(&[]);
            } else {
                let end = std::cmp::min(offset + size, data.len());
                reply.data(&data[offset..end]);
            }
            return;
        }

        let path = match self.get_path(ino) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        match self.fs.read_file(&path) {
            Ok(data) => {
                let offset = offset as usize;
                let size = size as usize;

                if offset >= data.len() {
                    reply.data(&[]);
                } else {
                    let end = std::cmp::min(offset + size, data.len());
                    reply.data(&data[offset..end]);
                }
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Write to a file.
    fn write(
        &mut self,
        _req: &Request,
        _ino: u64,
        fh: u64,
        offset: i64,
        data: &[u8],
        _write_flags: u32,
        _flags: i32,
        _lock_owner: Option<u64>,
        reply: ReplyWrite,
    ) {
        if self.readonly {
            reply.error(libc::EROFS);
            return;
        }

        let mut open_files = self.open_files.lock().unwrap();
        let Some(open_file) = open_files.get_mut(&fh) else {
            reply.error(libc::ENOENT);
            return;
        };

        if !open_file.write {
            reply.error(libc::EBADF);
            return;
        }

        let Some(buffer) = open_file.buffer.as_mut() else {
            reply.error(libc::EIO);
            return;
        };

        Self::apply_write(buffer, offset as usize, data);
        open_file.state = OpenFileState::Dirty;
        reply.written(data.len() as u32);
    }

    /// Release (close) a file.
    fn release(
        &mut self,
        _req: &Request,
        _ino: u64,
        fh: u64,
        _flags: i32,
        _lock_owner: Option<u64>,
        _flush: bool,
        reply: ReplyEmpty,
    ) {
        if let Err(e) = self.persist_open_file(fh) {
            reply.error(Self::error_to_errno(&e));
            return;
        }
        self.open_files.lock().unwrap().remove(&fh);
        reply.ok();
    }

    /// Create a file.
    fn create(
        &mut self,
        _req: &Request,
        parent: u64,
        name: &OsStr,
        _mode: u32,
        _umask: u32,
        _flags: i32,
        reply: fuser::ReplyCreate,
    ) {
        if self.readonly {
            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 = match self.get_path(parent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        let child_path = Self::child_path(&parent_path, name);

        // Create empty file
        match self.fs.write_file(&child_path, &[]) {
            Ok(()) => {
                // Get the created entry
                match self.fs.get_entry(&child_path) {
                    Ok(entry) => {
                        let attr = entry_to_attr(&entry);
                        self.cache_path(entry.id as u64, child_path.clone());

                        let fh = self.next_file_handle();
                        self.open_files.lock().unwrap().insert(
                            fh,
                            OpenFile {
                                path: child_path,
                                write: true,
                                buffer: Some(Vec::new()),
                                state: OpenFileState::Open,
                            },
                        );

                        reply.created(&TTL, &attr, 0, fh, 0);
                    }
                    Err(e) => {
                        reply.error(Self::error_to_errno(&e));
                    }
                }
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Remove a file.
    fn unlink(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) {
        if self.readonly {
            reply.error(libc::EROFS);
            return;
        }

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

        let parent_path = match self.get_path(parent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        let child_path = Self::child_path(&parent_path, name);

        // Get entry to find its inode before deletion
        let ino = self.fs.get_entry(&child_path).ok().map(|e| e.id as u64);

        match self.fs.remove(&child_path, false) {
            Ok(()) => {
                if let Some(ino) = ino {
                    self.uncache_path(ino);
                }
                reply.ok();
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Create a directory.
    fn mkdir(
        &mut self,
        _req: &Request,
        parent: u64,
        name: &OsStr,
        _mode: u32,
        _umask: u32,
        reply: ReplyEntry,
    ) {
        if self.readonly {
            reply.error(libc::EROFS);
            return;
        }

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

        let parent_path = match self.get_path(parent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        let child_path = Self::child_path(&parent_path, name);

        match self.fs.create_dir(&child_path) {
            Ok(()) => match self.fs.get_entry(&child_path) {
                Ok(entry) => {
                    let attr = entry_to_attr(&entry);
                    self.cache_path(entry.id as u64, child_path);
                    reply.entry(&TTL, &attr, 0);
                }
                Err(e) => {
                    reply.error(Self::error_to_errno(&e));
                }
            },
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Remove a directory.
    fn rmdir(&mut self, _req: &Request, parent: u64, name: &OsStr, reply: ReplyEmpty) {
        if self.readonly {
            reply.error(libc::EROFS);
            return;
        }

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

        let parent_path = match self.get_path(parent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        let child_path = Self::child_path(&parent_path, name);

        // Get inode before deletion
        let ino = self.fs.get_entry(&child_path).ok().map(|e| e.id as u64);

        match self.fs.remove(&child_path, false) {
            Ok(()) => {
                if let Some(ino) = ino {
                    self.uncache_path(ino);
                }
                reply.ok();
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Rename a file or directory.
    fn rename(
        &mut self,
        _req: &Request,
        parent: u64,
        name: &OsStr,
        newparent: u64,
        newname: &OsStr,
        _flags: u32,
        reply: ReplyEmpty,
    ) {
        if self.readonly {
            reply.error(libc::EROFS);
            return;
        }

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

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

        let parent_path = match self.get_path(parent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        let newparent_path = match self.get_path(newparent) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        let old_path = Self::child_path(&parent_path, name);
        let new_path = Self::child_path(&newparent_path, newname);

        // Get old inode
        let old_ino = self.fs.get_entry(&old_path).ok().map(|e| e.id as u64);

        match self.fs.move_entry(&old_path, &new_path) {
            Ok(()) => {
                // Update path cache
                if let Some(ino) = old_ino {
                    self.uncache_path(ino);
                    self.cache_path(ino, new_path);
                }
                reply.ok();
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Get filesystem statistics.
    fn statfs(&mut self, _req: &Request, _ino: u64, reply: ReplyStatfs) {
        // Get vault stats
        let stats = self.fs.backend().get_vault_stats();

        match stats {
            Ok(stats) => {
                // Report reasonable values
                let blocks = stats.total_size_bytes / BLOCK_SIZE as u64 + 1;
                let files = stats.files + stats.directories;

                reply.statfs(
                    blocks * 10,   // Total blocks (give 10x headroom)
                    blocks * 9,    // Free blocks
                    blocks * 9,    // Available blocks
                    files + 10000, // Total inodes
                    10000,         // Free inodes
                    BLOCK_SIZE,    // Block size
                    255,           // Max name length
                    BLOCK_SIZE,    // Fragment size
                );
            }
            Err(_) => {
                // Return default stats on error
                reply.statfs(
                    1000000, // blocks
                    900000,  // bfree
                    900000,  // bavail
                    100000,  // files
                    90000,   // ffree
                    BLOCK_SIZE, 255, BLOCK_SIZE,
                );
            }
        }
    }

    /// Flush file data.
    fn flush(&mut self, _req: &Request, _ino: u64, fh: u64, _lock_owner: u64, reply: ReplyEmpty) {
        match self.persist_open_file(fh) {
            Ok(()) => reply.ok(),
            Err(e) => reply.error(Self::error_to_errno(&e)),
        }
    }

    /// Sync file data.
    fn fsync(&mut self, _req: &Request, _ino: u64, fh: u64, _datasync: bool, reply: ReplyEmpty) {
        match self.persist_open_file(fh) {
            Ok(()) => reply.ok(),
            Err(e) => reply.error(Self::error_to_errno(&e)),
        }
    }

    /// Open a directory.
    fn opendir(&mut self, _req: &Request, ino: u64, _flags: i32, reply: ReplyOpen) {
        // Verify directory exists
        let path = match self.get_path(ino) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        match self.fs.get_entry(&path) {
            Ok(entry) => {
                if !entry.is_dir() {
                    reply.error(libc::ENOTDIR);
                    return;
                }
                // Return a dummy file handle
                reply.opened(0, 0);
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }

    /// Release (close) a directory.
    fn releasedir(&mut self, _req: &Request, _ino: u64, _fh: u64, _flags: i32, reply: ReplyEmpty) {
        reply.ok();
    }

    /// Set file attributes (mainly for truncate).
    fn setattr(
        &mut self,
        _req: &Request,
        ino: u64,
        _mode: Option<u32>,
        _uid: Option<u32>,
        _gid: Option<u32>,
        size: Option<u64>,
        _atime: Option<fuser::TimeOrNow>,
        _mtime: Option<fuser::TimeOrNow>,
        _ctime: Option<std::time::SystemTime>,
        fh: Option<u64>,
        _crtime: Option<std::time::SystemTime>,
        _chgtime: Option<std::time::SystemTime>,
        _bkuptime: Option<std::time::SystemTime>,
        _flags: Option<u32>,
        reply: ReplyAttr,
    ) {
        if self.readonly {
            reply.error(libc::EROFS);
            return;
        }

        let path = match self.get_path(ino) {
            Some(p) => p,
            None => {
                reply.error(libc::ENOENT);
                return;
            }
        };

        // Handle truncate
        if let Some(new_size) = size {
            if let Some(fh) = fh {
                let mut open_files = self.open_files.lock().unwrap();
                if let Some(open_file) = open_files.get_mut(&fh) {
                    if let Some(buffer) = open_file.buffer.as_mut() {
                        buffer.resize(new_size as usize, 0);
                        open_file.state = OpenFileState::Dirty;
                    } else {
                        reply.error(libc::EBADF);
                        return;
                    }
                } else {
                    reply.error(libc::ENOENT);
                    return;
                }
            } else {
                let content = match self.fs.read_file(&path) {
                    Ok(c) => c,
                    Err(VfsError::NotFound(_)) => Vec::new(),
                    Err(e) => {
                        reply.error(Self::error_to_errno(&e));
                        return;
                    }
                };

                let new_content = if new_size == 0 {
                    Vec::new()
                } else if new_size as usize <= content.len() {
                    content[..new_size as usize].to_vec()
                } else {
                    let mut new = content;
                    new.resize(new_size as usize, 0);
                    new
                };

                if let Err(e) = self.fs.write_file(&path, &new_content) {
                    reply.error(Self::error_to_errno(&e));
                    return;
                }
            }
        }

        // Return updated attributes
        match self.fs.get_entry(&path) {
            Ok(entry) => {
                let attr = entry_to_attr(&entry);
                reply.attr(&TTL, &attr);
            }
            Err(e) => {
                reply.error(Self::error_to_errno(&e));
            }
        }
    }
}