Skip to main content

ragfs_fuse/filesystem/
mod.rs

1//! FUSE filesystem implementation.
2
3use fuser::{
4    BsdFileFlags, FileAttr, FileHandle, FileType, Filesystem, FopenFlags, Generation, INodeNo,
5    LockOwner, OpenFlags, RenameFlags, ReplyAttr, ReplyCreate, ReplyData, ReplyDirectory,
6    ReplyEmpty, ReplyEntry, ReplyOpen, ReplyWrite, Request, TimeOrNow, WriteFlags,
7};
8use ragfs_core::{Embedder, VectorStore};
9use ragfs_query::QueryExecutor;
10use std::collections::HashMap;
11use std::ffi::OsStr;
12use std::fs;
13use std::os::unix::fs::MetadataExt;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use std::time::{Duration, SystemTime, UNIX_EPOCH};
17use tokio::runtime::Handle;
18use tokio::sync::{RwLock, mpsc};
19use tracing::debug;
20
21use crate::inode::{
22    APPROVE_FILE_INO, CLEANUP_FILE_INO, CONFIG_FILE_INO, DEDUPE_FILE_INO, HELP_FILE_INO,
23    HISTORY_FILE_INO, INDEX_FILE_INO, InodeKind, InodeTable, OPS_BATCH_INO, OPS_CREATE_INO,
24    OPS_DELETE_INO, OPS_DIR_INO, OPS_MOVE_INO, OPS_RESULT_INO, ORGANIZE_FILE_INO, PENDING_DIR_INO,
25    QUERY_DIR_INO, RAGFS_DIR_INO, REINDEX_FILE_INO, REJECT_FILE_INO, ROOT_INO, SAFETY_DIR_INO,
26    SEARCH_DIR_INO, SEMANTIC_DIR_INO, SIMILAR_DIR_INO, SIMILAR_OPS_FILE_INO, TRASH_DIR_INO,
27    UNDO_FILE_INO,
28};
29use crate::ops::OpsManager;
30use crate::safety::SafetyManager;
31use crate::semantic::SemanticManager;
32
33mod ops;
34mod passthrough;
35mod query;
36mod safety;
37mod semantic;
38
39pub(crate) const TTL: Duration = Duration::from_secs(1);
40pub(crate) const BLOCK_SIZE: u64 = 512;
41pub(crate) const GENERATION: Generation = Generation(0);
42
43/// RAGFS FUSE filesystem.
44pub struct RagFs {
45    /// Source directory being indexed
46    source: PathBuf,
47    /// Inode table
48    inodes: Arc<RwLock<InodeTable>>,
49    /// Vector store for queries and stats
50    store: Option<Arc<dyn VectorStore>>,
51    /// Query executor
52    query_executor: Option<Arc<QueryExecutor>>,
53    /// Tokio runtime handle for async operations
54    runtime: Handle,
55    /// Cache for virtual file contents (query results, index status)
56    content_cache: Arc<RwLock<HashMap<u64, Vec<u8>>>>,
57    /// Channel sender for reindex requests
58    reindex_sender: Option<mpsc::Sender<PathBuf>>,
59    /// Operations manager for agent file management
60    ops_manager: Arc<OpsManager>,
61    /// Safety manager for trash/history/undo
62    safety_manager: Arc<SafetyManager>,
63    /// Semantic manager for intelligent operations
64    semantic_manager: Arc<SemanticManager>,
65}
66
67impl RagFs {
68    /// Create a new RAGFS filesystem (basic, for passthrough only).
69    #[must_use]
70    pub fn new(source: PathBuf) -> Self {
71        let safety_manager = Arc::new(SafetyManager::new(&source, None));
72        let ops_manager = Arc::new(OpsManager::with_safety(
73            source.clone(),
74            None,
75            None,
76            safety_manager.clone(),
77        ));
78        let semantic_manager = Arc::new(SemanticManager::with_ops(
79            source.clone(),
80            None,
81            None,
82            None,
83            ops_manager.clone(),
84        ));
85        Self {
86            source,
87            inodes: Arc::new(RwLock::new(InodeTable::new())),
88            store: None,
89            query_executor: None,
90            runtime: Handle::current(),
91            content_cache: Arc::new(RwLock::new(HashMap::new())),
92            reindex_sender: None,
93            ops_manager,
94            safety_manager,
95            semantic_manager,
96        }
97    }
98
99    /// Create a new RAGFS filesystem with full RAG capabilities.
100    ///
101    /// Hybrid search defaults to on (same as `[query].hybrid` in config.toml).
102    pub fn with_rag(
103        source: PathBuf,
104        store: Arc<dyn VectorStore>,
105        embedder: Arc<dyn Embedder>,
106        runtime: Handle,
107        reindex_sender: Option<mpsc::Sender<PathBuf>>,
108    ) -> Self {
109        Self::with_rag_query(
110            source,
111            store,
112            embedder,
113            runtime,
114            reindex_sender,
115            10,
116            true,
117            100,
118        )
119    }
120
121    /// Create a RAG-enabled filesystem with query settings from config / CLI.
122    pub fn with_rag_query(
123        source: PathBuf,
124        store: Arc<dyn VectorStore>,
125        embedder: Arc<dyn Embedder>,
126        runtime: Handle,
127        reindex_sender: Option<mpsc::Sender<PathBuf>>,
128        default_limit: usize,
129        hybrid: bool,
130        max_limit: usize,
131    ) -> Self {
132        let query_executor = Arc::new(
133            QueryExecutor::new(store.clone(), embedder.clone(), default_limit, hybrid)
134                .with_max_limit(max_limit),
135        );
136
137        let safety_manager = Arc::new(SafetyManager::new(&source, None));
138        let ops_manager = Arc::new(OpsManager::with_safety(
139            source.clone(),
140            Some(store.clone()),
141            reindex_sender.clone(),
142            safety_manager.clone(),
143        ));
144        let semantic_manager = Arc::new(SemanticManager::with_ops(
145            source.clone(),
146            Some(store.clone()),
147            Some(embedder.clone()),
148            None,
149            ops_manager.clone(),
150        ));
151
152        Self {
153            source,
154            inodes: Arc::new(RwLock::new(InodeTable::new())),
155            store: Some(store),
156            query_executor: Some(query_executor),
157            runtime,
158            content_cache: Arc::new(RwLock::new(HashMap::new())),
159            reindex_sender,
160            ops_manager,
161            safety_manager,
162            semantic_manager,
163        }
164    }
165
166    /// Get the source directory.
167    #[must_use]
168    pub fn source(&self) -> &PathBuf {
169        &self.source
170    }
171
172    /// Resolve a `.reindex` path and reject anything that escapes the source root.
173    fn jail_reindex_path(&self, path: &Path) -> Result<PathBuf, String> {
174        ragfs_core::resolve_under_root(&self.source, path)
175    }
176
177    /// Convert a real path to a FUSE inode.
178    fn real_path_to_attr(&self, path: &PathBuf, ino: u64) -> Option<FileAttr> {
179        let metadata = fs::metadata(path).ok()?;
180        let kind = if metadata.is_dir() {
181            FileType::Directory
182        } else if metadata.is_file() {
183            FileType::RegularFile
184        } else if metadata.file_type().is_symlink() {
185            FileType::Symlink
186        } else {
187            return None;
188        };
189
190        let atime = metadata.accessed().unwrap_or(SystemTime::UNIX_EPOCH);
191        let mtime = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH);
192        let ctime = UNIX_EPOCH + Duration::from_secs(metadata.ctime() as u64);
193
194        Some(FileAttr {
195            ino: INodeNo(ino),
196            size: metadata.len(),
197            blocks: metadata.len().div_ceil(BLOCK_SIZE),
198            atime,
199            mtime,
200            ctime,
201            crtime: ctime,
202            kind,
203            perm: (metadata.mode() & 0o7777) as u16,
204            nlink: metadata.nlink() as u32,
205            uid: metadata.uid(),
206            gid: metadata.gid(),
207            rdev: metadata.rdev() as u32,
208            blksize: BLOCK_SIZE as u32,
209            flags: 0,
210        })
211    }
212
213    #[allow(unsafe_code)]
214    fn make_attr(&self, ino: u64, kind: FileType, size: u64) -> FileAttr {
215        let now = SystemTime::now();
216        // SAFETY: getuid() and getgid() are always safe to call
217        let uid = unsafe { libc::getuid() };
218        let gid = unsafe { libc::getgid() };
219        FileAttr {
220            ino: INodeNo(ino),
221            size,
222            blocks: size.div_ceil(BLOCK_SIZE),
223            atime: now,
224            mtime: now,
225            ctime: now,
226            crtime: now,
227            kind,
228            perm: if kind == FileType::Directory {
229                0o755
230            } else {
231                0o644
232            },
233            nlink: if kind == FileType::Directory { 2 } else { 1 },
234            uid,
235            gid,
236            rdev: 0,
237            blksize: BLOCK_SIZE as u32,
238            flags: 0,
239        }
240    }
241
242    /// Get index status as JSON.
243    fn get_index_status(&self) -> Vec<u8> {
244        if let Some(ref store) = self.store {
245            let store = store.clone();
246            let result = self.runtime.block_on(async { store.stats().await });
247
248            match result {
249                Ok(stats) => {
250                    let json = serde_json::json!({
251                        "status": "indexed",
252                        "total_files": stats.total_files,
253                        "total_chunks": stats.total_chunks,
254                        "index_size_bytes": stats.index_size_bytes,
255                        "last_updated": stats.last_updated.map(|t| t.to_rfc3339()),
256                    });
257                    serde_json::to_string_pretty(&json)
258                        .unwrap_or_default()
259                        .into_bytes()
260                }
261                Err(e) => {
262                    let json = serde_json::json!({
263                        "status": "error",
264                        "error": e.to_string(),
265                    });
266                    serde_json::to_string_pretty(&json)
267                        .unwrap_or_default()
268                        .into_bytes()
269                }
270            }
271        } else {
272            let json = serde_json::json!({
273                "status": "not_initialized",
274                "message": "No store configured",
275            });
276            serde_json::to_string_pretty(&json)
277                .unwrap_or_default()
278                .into_bytes()
279        }
280    }
281
282    /// Execute a query and return results as JSON.
283    pub(crate) fn execute_query(&self, query: &str) -> Vec<u8> {
284        if let Some(ref executor) = self.query_executor {
285            let executor = executor.clone();
286            let query_str = query.to_string();
287            let query_for_result = query_str.clone();
288            let result = self
289                .runtime
290                .block_on(async move { executor.execute(&query_str).await });
291
292            match result {
293                Ok(results) => {
294                    let json_results: Vec<_> = results
295                        .iter()
296                        .map(|r| {
297                            serde_json::json!({
298                                "modality": r.media.modality,
299                                "start_ms": r.media.start_ms,
300                                "end_ms": r.media.end_ms,
301                                "file": r.file_path.to_string_lossy(),
302                                "score": r.score,
303                                "content": truncate(&r.content, 500),
304                                "byte_range": [r.byte_range.start, r.byte_range.end],
305                                "line_range": r.line_range.as_ref().map(|lr| [lr.start, lr.end]),
306                            })
307                        })
308                        .collect();
309
310                    let json = serde_json::json!({
311                        "query": query_for_result,
312                        "results": json_results,
313                    });
314                    serde_json::to_string_pretty(&json)
315                        .unwrap_or_default()
316                        .into_bytes()
317                }
318                Err(e) => {
319                    let json = serde_json::json!({
320                        "query": query_for_result,
321                        "error": e.to_string(),
322                    });
323                    serde_json::to_string_pretty(&json)
324                        .unwrap_or_default()
325                        .into_bytes()
326                }
327            }
328        } else {
329            let json = serde_json::json!({
330                "error": "Query executor not configured",
331            });
332            serde_json::to_string_pretty(&json)
333                .unwrap_or_default()
334                .into_bytes()
335        }
336    }
337
338    /// Get configuration as JSON.
339    ///
340    /// This is mount wiring, not `~/.config/ragfs/config.toml`.
341    fn get_config(&self) -> Vec<u8> {
342        let json = serde_json::json!({
343            "api_version": "0.2",
344            "source": self.source.to_string_lossy(),
345            "store_configured": self.store.is_some(),
346            "query_executor_configured": self.query_executor.is_some(),
347            "interfaces": {
348                "query": true,
349                "ops": true,
350                "safety": true,
351                "semantic": true
352            },
353            "note": "Mount wiring only. User TOML is not echoed here.",
354        });
355        serde_json::to_string_pretty(&json)
356            .unwrap_or_default()
357            .into_bytes()
358    }
359
360    /// Resolve a parent inode to a real path.
361    /// Returns None if the parent doesn't exist or is not a directory.
362    fn resolve_parent_path(&self, parent: u64) -> Option<PathBuf> {
363        if parent == ROOT_INO {
364            return Some(self.source.clone());
365        }
366
367        let inodes = self.runtime.block_on(self.inodes.read());
368        if let Some(entry) = inodes.get(parent)
369            && let InodeKind::Real { path, .. } = &entry.kind
370        {
371            Some(path.clone())
372        } else {
373            None
374        }
375    }
376
377    /// Get help content for the virtual control directory.
378    fn get_help_content(&self) -> Vec<u8> {
379        r#"RAGFS Virtual Control Directory
380================================
381
382The .ragfs directory is the agent control plane: search, file ops,
383soft-delete, and propose/approve semantic plans.
384
385Search and index
386----------------
387  .index          Read index statistics (JSON).
388  .config         Read mount wiring (JSON). Includes api_version.
389                  This is not ~/.config/ragfs/config.toml.
390  .reindex        Write a path to queue reindex (relative paths join source).
391                  Absolute paths and escapes that leave the source are rejected.
392                  Example: echo "src/main.rs" > .ragfs/.reindex
393  .query/<q>      Semantic search. Filename is the query.
394                  Returns JSON results.
395                  Example: cat ".ragfs/.query/authentication"
396  .search/<q>     Symlinks to matching files.
397  .similar/<path> Symlinks to files similar to <path>.
398  .help           This file.
399
400Agent operations (.ops/)
401------------------------
402  .ops/.create    Write: path<newline>content
403  .ops/.delete    Write: path  (soft-delete when safety is on)
404  .ops/.move      Write: src<newline>dst
405  .ops/.batch     Write: JSON BatchRequest (create/delete/move/copy/write/mkdir/symlink)
406  .ops/.result    Read:  JSON OperationResult of the last op (global; not per-agent)
407
408  echo -e "notes.md\n# Hello" > .ragfs/.ops/.create
409  cat .ragfs/.ops/.result
410
411Safety (.safety/)
412-----------------
413  .safety/.trash/   Soft-deleted files (recoverable)
414  .safety/.history  Audit log (JSONL)
415  .safety/.undo     Write the history operation_id (same as undo_id in .result)
416
417  echo "<undo_id>" > .ragfs/.safety/.undo
418
419Semantic (.semantic/) — Beta
420----------------------------
421  .semantic/.organize  Write OrganizeRequest JSON → plan in .pending/
422  .semantic/.similar   Write a path → similar files JSON
423  .semantic/.cleanup   Read cleanup analysis (duplicates today)
424  .semantic/.dedupe    Read duplicate groups
425  .semantic/.pending/  Proposed plans
426  .semantic/.approve   Write plan_id to execute
427  .semantic/.reject    Write plan_id to cancel
428
429Limits (honest)
430---------------
431  - .ops/.semantic/.reindex paths are jailed to the source root. Absolute paths
432    and `..`/symlink hops that leave the source are rejected.
433  - .ops/.result is the last operation only; concurrent agents overwrite it.
434  - Semantic ByProject/cleanup is Beta: organize may only mkdir; cleanup is mostly duplicates.
435  - allow_other (if enabled) exposes .ops/.safety/.semantic to every local user.
436  - Code chunking is pattern-based (function/class signatures), not tree-sitter.
437  - Default extractors: UTF-8 text/code, PDF, images. Binary .doc is not supported.
438"#
439        .as_bytes()
440        .to_vec()
441    }
442}
443
444pub(crate) fn reply_file_bytes(reply: ReplyData, content: &[u8], offset: u64, size: u32) {
445    let offset = offset as usize;
446    let size = size as usize;
447    if offset >= content.len() {
448        reply.data(&[]);
449    } else {
450        let end = (offset + size).min(content.len());
451        reply.data(&content[offset..end]);
452    }
453}
454
455impl Filesystem for RagFs {
456    fn init(&mut self, _req: &Request, _config: &mut fuser::KernelConfig) -> std::io::Result<()> {
457        debug!("FUSE init for source: {:?}", self.source);
458        Ok(())
459    }
460
461    fn destroy(&mut self) {
462        debug!("FUSE destroy");
463    }
464
465    fn lookup(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEntry) {
466        let parent = u64::from(parent);
467        let name_str = name.to_string_lossy();
468        debug!("lookup: parent={}, name={}", parent, name_str);
469
470        match parent {
471            ROOT_INO => self.lookup_root(&name_str, reply),
472            RAGFS_DIR_INO => self.lookup_ragfs_dir(&name_str, reply),
473            SEMANTIC_DIR_INO => self.lookup_semantic_dir(&name_str, reply),
474            PENDING_DIR_INO => self.lookup_pending_dir(&name_str, reply),
475            SAFETY_DIR_INO => self.lookup_safety_dir(&name_str, reply),
476            OPS_DIR_INO => self.lookup_ops_dir(&name_str, reply),
477            QUERY_DIR_INO => self.lookup_query_dir(&name_str, reply),
478            _ => self.lookup_passthrough(parent, &name_str, reply),
479        }
480    }
481
482    fn getattr(&self, _req: &Request, ino: INodeNo, _fh: Option<FileHandle>, reply: ReplyAttr) {
483        let ino = u64::from(ino);
484        debug!("getattr: ino={}", ino);
485
486        match ino {
487            ROOT_INO => {
488                let attr = self.make_attr(ROOT_INO, FileType::Directory, 0);
489                reply.attr(&TTL, &attr);
490            }
491            RAGFS_DIR_INO => {
492                let attr = self.make_attr(RAGFS_DIR_INO, FileType::Directory, 0);
493                reply.attr(&TTL, &attr);
494            }
495            QUERY_DIR_INO | SEARCH_DIR_INO | SIMILAR_DIR_INO | INDEX_FILE_INO | CONFIG_FILE_INO
496            | REINDEX_FILE_INO | HELP_FILE_INO => self.getattr_query(ino, reply),
497            OPS_DIR_INO | OPS_CREATE_INO | OPS_DELETE_INO | OPS_MOVE_INO | OPS_BATCH_INO
498            | OPS_RESULT_INO => self.getattr_ops(ino, reply),
499            SAFETY_DIR_INO | TRASH_DIR_INO | HISTORY_FILE_INO | UNDO_FILE_INO => {
500                self.getattr_safety(ino, reply);
501            }
502            SEMANTIC_DIR_INO | PENDING_DIR_INO | SIMILAR_OPS_FILE_INO | CLEANUP_FILE_INO
503            | DEDUPE_FILE_INO | ORGANIZE_FILE_INO | APPROVE_FILE_INO | REJECT_FILE_INO => {
504                self.getattr_semantic(ino, reply);
505            }
506            _ => self.getattr_cached_or_passthrough(ino, reply),
507        }
508    }
509
510    fn read(
511        &self,
512        _req: &Request,
513        ino: INodeNo,
514        _fh: FileHandle,
515        offset: u64,
516        size: u32,
517        _flags: OpenFlags,
518        _lock_owner: Option<LockOwner>,
519        reply: ReplyData,
520    ) {
521        let ino = u64::from(ino);
522        debug!("read: ino={}, offset={}, size={}", ino, offset, size);
523
524        let cache = self.runtime.block_on(self.content_cache.read());
525        if let Some(content) = cache.get(&ino) {
526            reply_file_bytes(reply, content, offset, size);
527            return;
528        }
529        drop(cache);
530
531        match ino {
532            INDEX_FILE_INO | CONFIG_FILE_INO | REINDEX_FILE_INO | HELP_FILE_INO => {
533                self.read_query(ino, offset, size, reply);
534            }
535            OPS_RESULT_INO | OPS_CREATE_INO | OPS_DELETE_INO | OPS_MOVE_INO | OPS_BATCH_INO => {
536                self.read_ops(ino, offset, size, reply);
537            }
538            HISTORY_FILE_INO | UNDO_FILE_INO => self.read_safety(ino, offset, size, reply),
539            SIMILAR_OPS_FILE_INO | CLEANUP_FILE_INO | DEDUPE_FILE_INO | ORGANIZE_FILE_INO
540            | APPROVE_FILE_INO | REJECT_FILE_INO => self.read_semantic(ino, offset, size, reply),
541            _ => self.read_passthrough(ino, offset, size, reply),
542        }
543    }
544
545    fn readdir(
546        &self,
547        _req: &Request,
548        ino: INodeNo,
549        _fh: FileHandle,
550        offset: u64,
551        reply: ReplyDirectory,
552    ) {
553        let ino = u64::from(ino);
554        debug!("readdir: ino={}, offset={}", ino, offset);
555
556        match ino {
557            ROOT_INO => self.readdir_root(offset, reply),
558            RAGFS_DIR_INO => self.readdir_ragfs(offset, reply),
559            QUERY_DIR_INO | SEARCH_DIR_INO | SIMILAR_DIR_INO => {
560                self.readdir_query(ino, offset, reply);
561            }
562            OPS_DIR_INO => self.readdir_ops(offset, reply),
563            SAFETY_DIR_INO | TRASH_DIR_INO => self.readdir_safety(ino, offset, reply),
564            SEMANTIC_DIR_INO | PENDING_DIR_INO => self.readdir_semantic(ino, offset, reply),
565            _ => self.readdir_passthrough(ino, offset, reply),
566        }
567    }
568
569    fn open(&self, _req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
570        debug!("open: ino={}, flags={:?}", ino, flags);
571        reply.opened(FileHandle(0), FopenFlags::empty());
572    }
573
574    fn opendir(&self, _req: &Request, ino: INodeNo, flags: OpenFlags, reply: ReplyOpen) {
575        debug!("opendir: ino={}, flags={:?}", ino, flags);
576        reply.opened(FileHandle(0), FopenFlags::empty());
577    }
578
579    fn write(
580        &self,
581        _req: &Request,
582        ino: INodeNo,
583        _fh: FileHandle,
584        _offset: u64,
585        data: &[u8],
586        _write_flags: WriteFlags,
587        _flags: OpenFlags,
588        _lock_owner: Option<LockOwner>,
589        reply: ReplyWrite,
590    ) {
591        let ino = u64::from(ino);
592        debug!("write: ino={}, len={}", ino, data.len());
593
594        match ino {
595            REINDEX_FILE_INO => self.write_reindex(data, reply),
596            OPS_CREATE_INO | OPS_DELETE_INO | OPS_MOVE_INO | OPS_BATCH_INO => {
597                self.write_ops(ino, data, reply);
598            }
599            UNDO_FILE_INO => self.write_safety(ino, data, reply),
600            ORGANIZE_FILE_INO | SIMILAR_OPS_FILE_INO | APPROVE_FILE_INO | REJECT_FILE_INO => {
601                self.write_semantic(ino, data, reply);
602            }
603            _ => self.write_passthrough(ino, data, reply),
604        }
605    }
606
607    fn forget(&self, _req: &Request, ino: INodeNo, nlookup: u64) {
608        let ino = u64::from(ino);
609        debug!("forget: ino={}, nlookup={}", ino, nlookup);
610        let mut inodes = self.runtime.block_on(self.inodes.write());
611        inodes.forget(ino, nlookup);
612    }
613
614    fn create(
615        &self,
616        _req: &Request,
617        parent: INodeNo,
618        name: &OsStr,
619        mode: u32,
620        umask: u32,
621        flags: i32,
622        reply: ReplyCreate,
623    ) {
624        self.create_passthrough(u64::from(parent), name, mode, umask, flags, reply);
625    }
626
627    fn unlink(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
628        self.unlink_passthrough(u64::from(parent), name, reply);
629    }
630
631    fn mkdir(
632        &self,
633        _req: &Request,
634        parent: INodeNo,
635        name: &OsStr,
636        mode: u32,
637        umask: u32,
638        reply: ReplyEntry,
639    ) {
640        self.mkdir_passthrough(u64::from(parent), name, mode, umask, reply);
641    }
642
643    fn rmdir(&self, _req: &Request, parent: INodeNo, name: &OsStr, reply: ReplyEmpty) {
644        self.rmdir_passthrough(u64::from(parent), name, reply);
645    }
646
647    fn rename(
648        &self,
649        _req: &Request,
650        parent: INodeNo,
651        name: &OsStr,
652        newparent: INodeNo,
653        newname: &OsStr,
654        flags: RenameFlags,
655        reply: ReplyEmpty,
656    ) {
657        self.rename_passthrough(
658            u64::from(parent),
659            name,
660            u64::from(newparent),
661            newname,
662            flags,
663            reply,
664        );
665    }
666
667    fn setattr(
668        &self,
669        _req: &Request,
670        ino: INodeNo,
671        mode: Option<u32>,
672        uid: Option<u32>,
673        gid: Option<u32>,
674        size: Option<u64>,
675        atime: Option<TimeOrNow>,
676        mtime: Option<TimeOrNow>,
677        ctime: Option<SystemTime>,
678        fh: Option<FileHandle>,
679        crtime: Option<SystemTime>,
680        chgtime: Option<SystemTime>,
681        bkuptime: Option<SystemTime>,
682        flags: Option<BsdFileFlags>,
683        reply: ReplyAttr,
684    ) {
685        self.setattr_passthrough(
686            u64::from(ino),
687            mode,
688            uid,
689            gid,
690            size,
691            atime,
692            mtime,
693            ctime,
694            fh,
695            crtime,
696            chgtime,
697            bkuptime,
698            flags,
699            reply,
700        );
701    }
702}
703
704/// Truncate a string to max length, adding ellipsis if needed.
705fn truncate(s: &str, max_len: usize) -> String {
706    let s = s.replace('\n', " ").replace('\r', "");
707    if s.len() <= max_len {
708        s
709    } else {
710        format!("{}...", &s[..max_len.saturating_sub(3)])
711    }
712}
713
714#[cfg(test)]
715mod tests {
716    use super::*;
717
718    // ========== truncate() Helper Function Tests ==========
719
720    #[test]
721    fn test_truncate_short_string() {
722        let result = truncate("Hello", 10);
723        assert_eq!(result, "Hello");
724    }
725
726    #[test]
727    fn test_truncate_exact_length() {
728        let result = truncate("Hello", 5);
729        assert_eq!(result, "Hello");
730    }
731
732    #[test]
733    fn test_truncate_long_string() {
734        let result = truncate("Hello, World!", 8);
735        assert_eq!(result, "Hello...");
736    }
737
738    #[test]
739    fn test_truncate_removes_newlines() {
740        let result = truncate("Hello\nWorld\nTest", 100);
741        assert_eq!(result, "Hello World Test");
742    }
743
744    #[test]
745    fn test_truncate_removes_carriage_returns() {
746        // \n is replaced with space, \r is deleted
747        let result = truncate("Hello\r\nWorld", 100);
748        assert_eq!(result, "Hello World");
749    }
750
751    #[test]
752    fn test_truncate_empty_string() {
753        let result = truncate("", 10);
754        assert_eq!(result, "");
755    }
756
757    #[test]
758    fn test_truncate_very_short_max() {
759        let result = truncate("Hello", 3);
760        assert_eq!(result, "...");
761    }
762
763    #[test]
764    fn test_truncate_max_zero() {
765        let result = truncate("Hello", 0);
766        assert_eq!(result, "...");
767    }
768
769    #[test]
770    fn test_truncate_unicode() {
771        let result = truncate("こんにちは世界", 100);
772        assert_eq!(result, "こんにちは世界");
773    }
774
775    #[test]
776    fn test_truncate_with_mixed_whitespace() {
777        // \n\n -> "  ", \r\n\r\n -> "  " (two \n->space, two \r->deleted)
778        let result = truncate("Line1\n\nLine2\r\n\r\nLine3", 100);
779        assert_eq!(result, "Line1  Line2  Line3");
780    }
781
782    // ========== RagFs Construction Tests ==========
783
784    #[tokio::test]
785    async fn test_ragfs_new() {
786        let source = PathBuf::from("/tmp/test");
787        let fs = RagFs::new(source.clone());
788
789        assert_eq!(fs.source(), &source);
790        assert!(fs.store.is_none());
791        assert!(fs.query_executor.is_none());
792    }
793
794    #[tokio::test]
795    async fn test_ragfs_source_getter() {
796        let source = PathBuf::from("/my/test/directory");
797        let fs = RagFs::new(source.clone());
798
799        assert_eq!(fs.source(), &source);
800    }
801
802    #[tokio::test]
803    async fn test_ragfs_inode_table_initialized() {
804        let fs = RagFs::new(PathBuf::from("/tmp/test"));
805
806        let inodes = fs.inodes.read().await;
807        // Virtual inodes should be initialized
808        assert!(inodes.get(ROOT_INO).is_some());
809        assert!(inodes.get(RAGFS_DIR_INO).is_some());
810        assert!(inodes.get(QUERY_DIR_INO).is_some());
811    }
812
813    #[tokio::test]
814    async fn test_ragfs_content_cache_empty() {
815        let fs = RagFs::new(PathBuf::from("/tmp/test"));
816
817        let cache = fs.content_cache.read().await;
818        assert!(cache.is_empty());
819    }
820
821    // ========== get_config() Tests ==========
822
823    #[tokio::test]
824    async fn test_get_config_without_rag() {
825        let fs = RagFs::new(PathBuf::from("/tmp/test-config"));
826        let config = fs.get_config();
827
828        let json: serde_json::Value = serde_json::from_slice(&config).expect("Valid JSON");
829
830        assert_eq!(json["source"], "/tmp/test-config");
831        assert_eq!(json["store_configured"], false);
832        assert_eq!(json["query_executor_configured"], false);
833        assert_eq!(json["api_version"], "0.2");
834        assert_eq!(json["interfaces"]["ops"], true);
835    }
836
837    #[tokio::test]
838    async fn test_get_config_returns_valid_json() {
839        let fs = RagFs::new(PathBuf::from("/test/path"));
840        let config = fs.get_config();
841
842        // Should be valid UTF-8
843        let config_str = String::from_utf8(config).expect("Valid UTF-8");
844
845        // Should be parseable JSON
846        let json: serde_json::Value = serde_json::from_str(&config_str).expect("Valid JSON");
847
848        // Should have expected fields
849        assert!(json.get("source").is_some());
850        assert!(json.get("store_configured").is_some());
851        assert!(json.get("query_executor_configured").is_some());
852        assert_eq!(json["api_version"], "0.2");
853        assert!(json.get("interfaces").is_some());
854    }
855
856    #[tokio::test]
857    async fn test_help_mentions_agent_interfaces() {
858        let fs = RagFs::new(PathBuf::from("/tmp/test-help"));
859        let help = String::from_utf8(fs.get_help_content()).expect("Valid UTF-8");
860        assert!(help.contains(".ops/"), "help must document .ops/");
861        assert!(help.contains(".safety/"), "help must document .safety/");
862        assert!(help.contains(".semantic/"), "help must document .semantic/");
863        assert!(help.contains(".undo"), "help must document undo");
864        assert!(help.contains("api_version"));
865        assert!(
866            help.contains("jailed to the source root"),
867            "help must document the source-root path jail"
868        );
869        assert!(
870            !help.contains("not path-jailed"),
871            "help must not claim .reindex is unjailed"
872        );
873    }
874
875    // ========== get_index_status() Tests ==========
876
877    #[tokio::test]
878    async fn test_get_index_status_without_store() {
879        let fs = RagFs::new(PathBuf::from("/tmp/test"));
880        let status = fs.get_index_status();
881
882        let json: serde_json::Value = serde_json::from_slice(&status).expect("Valid JSON");
883
884        assert_eq!(json["status"], "not_initialized");
885        assert_eq!(json["message"], "No store configured");
886    }
887
888    #[tokio::test]
889    async fn test_get_index_status_returns_valid_json() {
890        let fs = RagFs::new(PathBuf::from("/test/path"));
891        let status = fs.get_index_status();
892
893        // Should be valid UTF-8
894        let status_str = String::from_utf8(status).expect("Valid UTF-8");
895
896        // Should be parseable JSON
897        let _json: serde_json::Value = serde_json::from_str(&status_str).expect("Valid JSON");
898    }
899
900    // ========== execute_query() Tests ==========
901
902    #[tokio::test]
903    async fn test_execute_query_without_executor() {
904        let fs = RagFs::new(PathBuf::from("/tmp/test"));
905        let result = fs.execute_query("test query");
906
907        let json: serde_json::Value = serde_json::from_slice(&result).expect("Valid JSON");
908
909        assert_eq!(json["error"], "Query executor not configured");
910    }
911
912    #[tokio::test]
913    async fn test_execute_query_returns_valid_json() {
914        let fs = RagFs::new(PathBuf::from("/test/path"));
915        let result = fs.execute_query("any query");
916
917        // Should be valid UTF-8
918        let result_str = String::from_utf8(result).expect("Valid UTF-8");
919
920        // Should be parseable JSON
921        let _json: serde_json::Value = serde_json::from_str(&result_str).expect("Valid JSON");
922    }
923
924    #[tokio::test]
925    async fn test_jail_reindex_rejects_absolute_outside_source() {
926        let temp = tempfile::TempDir::new().unwrap();
927        let fs = RagFs::new(temp.path().to_path_buf());
928        let outside = tempfile::TempDir::new().unwrap();
929        let err = fs
930            .jail_reindex_path(&outside.path().join("secret.txt"))
931            .unwrap_err();
932        assert!(err.contains("escapes"), "{err}");
933    }
934
935    #[tokio::test]
936    async fn test_jail_reindex_allows_relative_inside_source() {
937        let temp = tempfile::TempDir::new().unwrap();
938        let fs = RagFs::new(temp.path().to_path_buf());
939        let resolved = fs.jail_reindex_path(Path::new("src/main.rs")).unwrap();
940        assert!(resolved.starts_with(temp.path().canonicalize().unwrap()));
941    }
942
943    // ========== Constants Tests ==========
944
945    #[test]
946    fn test_ttl_is_reasonable() {
947        assert_eq!(TTL, Duration::from_secs(1));
948    }
949
950    #[test]
951    fn test_block_size_is_standard() {
952        assert_eq!(BLOCK_SIZE, 512);
953    }
954
955    // ========== make_attr() Tests ==========
956
957    #[tokio::test]
958    async fn test_make_attr_directory() {
959        let fs = RagFs::new(PathBuf::from("/tmp/test"));
960        let attr = fs.make_attr(100, fuser::FileType::Directory, 0);
961
962        assert_eq!(u64::from(attr.ino), 100);
963        assert_eq!(attr.size, 0);
964        assert_eq!(attr.kind, fuser::FileType::Directory);
965        assert_eq!(attr.perm, 0o755);
966        assert_eq!(attr.nlink, 2);
967    }
968
969    #[tokio::test]
970    async fn test_make_attr_regular_file() {
971        let fs = RagFs::new(PathBuf::from("/tmp/test"));
972        let attr = fs.make_attr(200, fuser::FileType::RegularFile, 1024);
973
974        assert_eq!(u64::from(attr.ino), 200);
975        assert_eq!(attr.size, 1024);
976        assert_eq!(attr.kind, fuser::FileType::RegularFile);
977        assert_eq!(attr.perm, 0o644);
978        assert_eq!(attr.nlink, 1);
979    }
980
981    #[tokio::test]
982    async fn test_make_attr_blocks_calculation() {
983        let fs = RagFs::new(PathBuf::from("/tmp/test"));
984
985        // Test exact block boundary
986        let attr = fs.make_attr(1, fuser::FileType::RegularFile, 512);
987        assert_eq!(attr.blocks, 1);
988
989        // Test one byte over
990        let attr = fs.make_attr(1, fuser::FileType::RegularFile, 513);
991        assert_eq!(attr.blocks, 2);
992
993        // Test empty file
994        let attr = fs.make_attr(1, fuser::FileType::RegularFile, 0);
995        assert_eq!(attr.blocks, 0);
996    }
997
998    #[tokio::test]
999    async fn test_make_attr_has_current_uid_gid() {
1000        let fs = RagFs::new(PathBuf::from("/tmp/test"));
1001        let attr = fs.make_attr(1, fuser::FileType::RegularFile, 0);
1002
1003        // Should have current user's uid/gid
1004        #[allow(unsafe_code)]
1005        let expected_uid = unsafe { libc::getuid() };
1006        #[allow(unsafe_code)]
1007        let expected_gid = unsafe { libc::getgid() };
1008
1009        assert_eq!(attr.uid, expected_uid);
1010        assert_eq!(attr.gid, expected_gid);
1011    }
1012
1013    /// Mount path: `IndexerService::start` (same as `ragfs mount`) + FUSE `.query`.
1014    #[tokio::test]
1015    async fn mount_index_and_query_exclude_hidden_and_secrets() {
1016        use ragfs_chunker::{ChunkerRegistry, FixedSizeChunker};
1017        use ragfs_core::{
1018            EmbedError, Embedder, EmbeddingConfig, EmbeddingOutput, Indexer, Modality, VectorStore,
1019        };
1020        use ragfs_embed::EmbedderPool;
1021        use ragfs_extract::{ExtractorRegistry, TextExtractor};
1022        use ragfs_index::{IndexerConfig, IndexerService};
1023        use ragfs_store::MemoryStore;
1024        use std::sync::Arc;
1025
1026        struct ConstantEmbedder;
1027
1028        #[async_trait::async_trait]
1029        impl Embedder for ConstantEmbedder {
1030            fn model_name(&self) -> &str {
1031                "test-constant"
1032            }
1033            fn dimension(&self) -> usize {
1034                8
1035            }
1036            fn max_tokens(&self) -> usize {
1037                512
1038            }
1039            fn modalities(&self) -> &[Modality] {
1040                &[Modality::Text]
1041            }
1042            async fn embed_text(
1043                &self,
1044                texts: &[&str],
1045                _config: &EmbeddingConfig,
1046            ) -> std::result::Result<Vec<EmbeddingOutput>, EmbedError> {
1047                Ok(texts
1048                    .iter()
1049                    .map(|_| EmbeddingOutput {
1050                        embedding: vec![0.1; 8],
1051                        token_count: 4,
1052                    })
1053                    .collect())
1054            }
1055        }
1056
1057        let temp = tempfile::TempDir::new().unwrap();
1058        let root = temp.path();
1059        std::fs::write(root.join("keyboard.md"), "VISIBLE_TOKEN keyboard shortcuts").unwrap();
1060        std::fs::write(root.join("server.pem"), "SECRETPEM_TOKEN private cert").unwrap();
1061        std::fs::create_dir(root.join(".obsidian")).unwrap();
1062        std::fs::write(root.join(".obsidian").join("x.md"), "HIDDENDIR_TOKEN").unwrap();
1063        std::fs::write(root.join(".hidden.md"), "HIDDENFILE_TOKEN").unwrap();
1064        std::fs::create_dir(root.join(".ssh")).unwrap();
1065        std::fs::write(root.join(".ssh").join("id_rsa"), "SSHKEY_TOKEN").unwrap();
1066
1067        let store = Arc::new(MemoryStore::new(8));
1068        let mut extractors = ExtractorRegistry::new();
1069        extractors.register("text", TextExtractor::new());
1070        let mut chunkers = ChunkerRegistry::new();
1071        chunkers.register("fixed", FixedSizeChunker::new());
1072        chunkers.set_default("fixed");
1073        let embedder: Arc<dyn Embedder> = Arc::new(ConstantEmbedder);
1074        let pool = Arc::new(EmbedderPool::new(Arc::clone(&embedder), 1));
1075
1076        let indexer = IndexerService::new(
1077            root.to_path_buf(),
1078            store.clone() as Arc<dyn VectorStore>,
1079            Arc::new(extractors),
1080            Arc::new(chunkers),
1081            pool,
1082            IndexerConfig::default(),
1083        );
1084        indexer.start().await.unwrap();
1085        tokio::time::timeout(
1086            std::time::Duration::from_secs(10),
1087            indexer.wait_until_idle(),
1088        )
1089        .await
1090        .expect("mount initial scan should idle");
1091
1092        let files = store.get_all_files().await.unwrap();
1093        assert_eq!(files.len(), 1, "mount scan indexes only the visible note");
1094        assert!(files[0].path.ends_with("keyboard.md"));
1095
1096        let fs = RagFs::with_rag_query(
1097            root.to_path_buf(),
1098            store.clone() as Arc<dyn VectorStore>,
1099            embedder,
1100            tokio::runtime::Handle::current(),
1101            None,
1102            10,
1103            false,
1104            100,
1105        );
1106        // execute_query uses Handle::block_on; call it off the test runtime.
1107        let json: serde_json::Value = tokio::task::spawn_blocking(move || {
1108            serde_json::from_slice(&fs.execute_query("keyboard")).expect("query JSON")
1109        })
1110        .await
1111        .expect("execute_query should run off the async worker");
1112        let blob = json.to_string();
1113        assert!(
1114            !blob.contains("server.pem")
1115                && !blob.contains("SECRETPEM")
1116                && !blob.contains("id_rsa")
1117                && !blob.contains(".obsidian")
1118                && !blob.contains(".hidden.md"),
1119            "FUSE .query must not return excluded paths: {blob}"
1120        );
1121        indexer.stop().await.unwrap();
1122    }
1123}