Skip to main content

ragfs_index/
indexer.rs

1//! Main indexing service.
2
3use chrono::Utc;
4use ragfs_chunker::ChunkerRegistry;
5use ragfs_core::{
6    Chunk, ChunkConfig, ChunkMetadata, ChunkOutput, ContentType, DirectoryScope, EmbeddingConfig,
7    Error, FileEvent, FileRecord, FileStatus, IndexStats, Indexer, Result, VectorStore,
8};
9use ragfs_embed::EmbedderPool;
10use ragfs_extract::ExtractorRegistry;
11use std::path::{Path, PathBuf};
12use std::sync::Arc;
13use std::sync::atomic::{AtomicUsize, Ordering};
14use tokio::sync::{Notify, RwLock, broadcast, mpsc};
15use tracing::{debug, error, info, warn};
16use uuid::Uuid;
17
18use crate::exclude::{ExclusionMatcher, ExclusionOptions, default_exclude_patterns};
19use crate::watcher::FileWatcher;
20
21/// Index update events.
22#[derive(Debug, Clone)]
23pub enum IndexUpdate {
24    FileIndexed { path: PathBuf, chunk_count: u32 },
25    FileRemoved { path: PathBuf },
26    FileError { path: PathBuf, error: String },
27    IndexingStarted { path: PathBuf },
28}
29
30/// Configuration for the indexer.
31#[derive(Debug, Clone)]
32pub struct IndexerConfig {
33    /// Chunk configuration
34    pub chunk_config: ChunkConfig,
35    /// Embedding configuration
36    pub embed_config: EmbeddingConfig,
37    /// Include patterns (glob)
38    pub include_patterns: Vec<String>,
39    /// Exclude patterns (glob)
40    pub exclude_patterns: Vec<String>,
41    /// Debounce duration for the file watcher (milliseconds)
42    pub debounce_ms: u64,
43    /// Maximum file size to index (bytes)
44    pub max_file_size: u64,
45    /// Skip the content-hash short-circuit and reindex every eligible file
46    pub force: bool,
47    /// Index hidden files and directories under the root (`--include-hidden`).
48    /// Does not disable the secret-file denylist.
49    pub include_hidden: bool,
50    /// Index files that match the built-in secret denylist.
51    pub include_secret_files: bool,
52    /// Honour `.gitignore` / `.ignore` under the index root only (no parents,
53    /// no global gitignore).
54    pub honor_gitignore: bool,
55    /// Delete store rows whose paths are now excluded, on every index/scan.
56    pub purge_excluded: bool,
57    /// Minimum Unicode letters / decimal digits before embedding.
58    pub min_alnum_chars: usize,
59}
60
61impl Default for IndexerConfig {
62    fn default() -> Self {
63        Self {
64            chunk_config: ChunkConfig::default(),
65            embed_config: EmbeddingConfig::default(),
66            include_patterns: vec!["**/*".to_string()],
67            exclude_patterns: default_exclude_patterns(),
68            debounce_ms: 500,
69            max_file_size: 52_428_800,
70            force: false,
71            include_hidden: false,
72            include_secret_files: false,
73            honor_gitignore: true,
74            purge_excluded: true,
75            min_alnum_chars: 3,
76        }
77    }
78}
79
80impl IndexerConfig {
81    /// Options consumed by [`ExclusionMatcher`].
82    #[must_use]
83    pub fn exclusion_options(&self) -> ExclusionOptions {
84        ExclusionOptions {
85            include_hidden: self.include_hidden,
86            include_secret_files: self.include_secret_files,
87            honor_gitignore: self.honor_gitignore,
88            extra_excludes: self.exclude_patterns.clone(),
89            include_patterns: self.include_patterns.clone(),
90        }
91    }
92
93    /// Matcher bound to `root` (hidden-root exception, secrets, gitignore).
94    #[must_use]
95    pub fn matcher(&self, root: &Path) -> ExclusionMatcher {
96        ExclusionMatcher::new(root, self.exclusion_options())
97    }
98
99    /// Whether `path` is eligible when the index root is unknown.
100    ///
101    /// Prefer [`Self::should_process_path_in`] so a hidden index root is kept.
102    #[must_use]
103    pub fn should_process_path(&self, path: &Path) -> bool {
104        let root = if path.is_absolute() {
105            Path::new("/")
106        } else {
107            Path::new("")
108        };
109        self.should_process_path_in(path, root)
110    }
111
112    /// Whether `path` is eligible under `root`.
113    #[must_use]
114    pub fn should_process_path_in(&self, path: &Path, root: &Path) -> bool {
115        self.matcher(root).should_process(path)
116    }
117}
118
119/// Match a path against a glob-style include/exclude pattern.
120///
121/// Supports `**` (any directories), `*` / `?` within a path segment, and
122/// basename-only patterns such as `test_*.rs` (matched against any component).
123/// Patterns that do not start with `**/` also match as a suffix of an absolute
124/// path (`src/**/*.rs` matches `/proj/src/lib.rs`).
125#[must_use]
126pub fn path_matches_pattern(path: &str, pattern: &str) -> bool {
127    let path = path.replace('\\', "/");
128    let pattern = pattern.replace('\\', "/");
129
130    if pattern.is_empty() {
131        return false;
132    }
133    if pattern == "**/*" || pattern == "**" || pattern == "*" {
134        return true;
135    }
136    if pattern == "**/.*" || pattern == ".*" {
137        // Hidden *files* only — do not treat `/tmp/.tmpXXXX/file.txt` as hidden.
138        return path
139            .rsplit('/')
140            .next()
141            .is_some_and(|name| !name.is_empty() && name.starts_with('.'));
142    }
143
144    if glob_match_path(&path, &pattern) {
145        return true;
146    }
147    // Absolute indexed paths should still match repo-relative globs.
148    if !pattern.starts_with("**/") && !pattern.starts_with('/') {
149        return glob_match_path(&path, &format!("**/{pattern}"));
150    }
151    false
152}
153
154fn glob_match_path(path: &str, pattern: &str) -> bool {
155    let path: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
156    let pat: Vec<&str> = pattern.split('/').filter(|s| !s.is_empty()).collect();
157    glob_match_segments(&path, &pat)
158}
159
160fn glob_match_segments(path: &[&str], pat: &[&str]) -> bool {
161    match pat.split_first() {
162        None => path.is_empty(),
163        Some((&"**", rest)) => {
164            if rest.is_empty() {
165                return true;
166            }
167            glob_match_segments(path, rest)
168                || (!path.is_empty() && glob_match_segments(&path[1..], pat))
169        }
170        Some((seg, rest)) => path.split_first().is_some_and(|(head, tail)| {
171            glob_match_segment(head, seg) && glob_match_segments(tail, rest)
172        }),
173    }
174}
175
176fn glob_match_segment(name: &str, pat: &str) -> bool {
177    glob_match_bytes(name.as_bytes(), pat.as_bytes())
178}
179
180fn glob_match_bytes(name: &[u8], pat: &[u8]) -> bool {
181    match pat.split_first() {
182        None => name.is_empty(),
183        Some((b'*', rest)) => (0..=name.len()).any(|i| glob_match_bytes(&name[i..], rest)),
184        Some((b'?', rest)) => !name.is_empty() && glob_match_bytes(&name[1..], rest),
185        Some((c, rest)) => name.first() == Some(c) && glob_match_bytes(&name[1..], rest),
186    }
187}
188
189/// Main indexing service.
190pub struct IndexerService {
191    /// Root path being indexed
192    root: PathBuf,
193    /// Vector store
194    store: Arc<dyn VectorStore>,
195    /// Extractor registry
196    extractors: Arc<ExtractorRegistry>,
197    /// Chunker registry
198    chunkers: Arc<ChunkerRegistry>,
199    /// Embedder pool
200    embedder: Arc<EmbedderPool>,
201    /// Configuration
202    config: IndexerConfig,
203    /// Current stats
204    stats: Arc<RwLock<IndexStats>>,
205    /// Event sender for file watcher
206    event_tx: mpsc::Sender<FileEvent>,
207    /// Event receiver
208    event_rx: Arc<RwLock<mpsc::Receiver<FileEvent>>>,
209    /// Update broadcast
210    update_tx: broadcast::Sender<IndexUpdate>,
211    /// File watcher (if active)
212    watcher: Arc<RwLock<Option<FileWatcher>>>,
213    /// Running flag
214    running: Arc<RwLock<bool>>,
215    /// Outstanding file events (queued or in flight)
216    pending: Arc<AtomicUsize>,
217    /// Signaled when [`Self::pending`] reaches zero
218    idle_notify: Arc<Notify>,
219}
220
221impl IndexerService {
222    /// Create a new indexer service.
223    pub fn new(
224        root: PathBuf,
225        store: Arc<dyn VectorStore>,
226        extractors: Arc<ExtractorRegistry>,
227        chunkers: Arc<ChunkerRegistry>,
228        embedder: Arc<EmbedderPool>,
229        config: IndexerConfig,
230    ) -> Self {
231        let (event_tx, event_rx) = mpsc::channel(1024);
232        let (update_tx, _) = broadcast::channel(256);
233
234        Self {
235            root,
236            store,
237            extractors,
238            chunkers,
239            embedder,
240            config,
241            stats: Arc::new(RwLock::new(IndexStats::default())),
242            event_tx,
243            event_rx: Arc::new(RwLock::new(event_rx)),
244            update_tx,
245            watcher: Arc::new(RwLock::new(None)),
246            running: Arc::new(RwLock::new(false)),
247            pending: Arc::new(AtomicUsize::new(0)),
248            idle_notify: Arc::new(Notify::new()),
249        }
250    }
251
252    /// Configuration used by this indexer (include/exclude, chunk, force, …).
253    #[must_use]
254    pub fn config(&self) -> &IndexerConfig {
255        &self.config
256    }
257
258    /// Wait until every queued file event has been processed.
259    ///
260    /// Call this after [`Self::start`] for a one-shot index so the CLI does not
261    /// return while the background worker is still embedding files.
262    pub async fn wait_until_idle(&self) {
263        loop {
264            if self.pending.load(Ordering::SeqCst) == 0 {
265                tokio::task::yield_now().await;
266                if self.pending.load(Ordering::SeqCst) == 0 {
267                    return;
268                }
269            }
270            tokio::select! {
271                () = self.idle_notify.notified() => {}
272                () = tokio::time::sleep(std::time::Duration::from_millis(20)) => {}
273            }
274        }
275    }
276
277    /// Subscribe to index updates.
278    #[must_use]
279    pub fn subscribe(&self) -> broadcast::Receiver<IndexUpdate> {
280        self.update_tx.subscribe()
281    }
282
283    /// Get the root path.
284    #[must_use]
285    pub fn root(&self) -> &Path {
286        &self.root
287    }
288
289    /// Start the indexer background task.
290    pub async fn start(&self) -> Result<()> {
291        let mut running = self.running.write().await;
292        if *running {
293            return Ok(());
294        }
295        *running = true;
296        drop(running);
297
298        info!("Starting indexer for {:?}", self.root);
299
300        // A failed open must remain retryable, not look like a running service.
301        if let Err(error) = self.store.init().await {
302            *self.running.write().await = false;
303            return Err(Error::Store(error));
304        }
305
306        // Purge before starting background work; failure must not report a
307        // successful upgrade while excluded content remains searchable.
308        if let Err(error) = self.purge_excluded_files().await {
309            *self.running.write().await = false;
310            return Err(error);
311        }
312
313        // Start file watcher (debounce from config). Same matcher as the scan.
314        let watcher = FileWatcher::with_filter(
315            self.event_tx.clone(),
316            std::time::Duration::from_millis(self.config.debounce_ms),
317            Some(Arc::clone(&self.pending)),
318            Some(Arc::new(self.config.matcher(&self.root))),
319        )
320        .map_err(|e| Error::Other(format!("watcher error: {e}")))?;
321        {
322            let mut w = self.watcher.write().await;
323            *w = Some(watcher);
324        }
325
326        // Watch root directory
327        {
328            let mut w = self.watcher.write().await;
329            if let Some(ref mut watcher) = *w {
330                watcher
331                    .watch(&self.root)
332                    .map_err(|e| Error::Other(format!("watch error: {e}")))?;
333            }
334        }
335
336        // Clone what we need for the background task
337        let event_rx = Arc::clone(&self.event_rx);
338        let update_tx = self.update_tx.clone();
339        let running = Arc::clone(&self.running);
340        let store = Arc::clone(&self.store);
341        let extractors = Arc::clone(&self.extractors);
342        let chunkers = Arc::clone(&self.chunkers);
343        let embedder = Arc::clone(&self.embedder);
344        let config = self.config.clone();
345        let stats = Arc::clone(&self.stats);
346        let pending = Arc::clone(&self.pending);
347        let idle_notify = Arc::clone(&self.idle_notify);
348        let root = self.root.clone();
349
350        // Spawn event processing task
351        tokio::spawn(async move {
352            let mut rx = event_rx.write().await;
353            while *running.read().await {
354                match rx.recv().await {
355                    Some(event) => {
356                        debug!("Received file event: {:?}", event);
357                        match &event {
358                            FileEvent::Created(path) | FileEvent::Modified(path) => {
359                                let _ = update_tx
360                                    .send(IndexUpdate::IndexingStarted { path: path.clone() });
361
362                                match process_file(
363                                    path,
364                                    &root,
365                                    &store,
366                                    &extractors,
367                                    &chunkers,
368                                    &embedder,
369                                    &config,
370                                )
371                                .await
372                                {
373                                    Ok(chunk_count) => {
374                                        info!("Indexed {:?} ({} chunks)", path, chunk_count);
375                                        let _ = update_tx.send(IndexUpdate::FileIndexed {
376                                            path: path.clone(),
377                                            chunk_count,
378                                        });
379
380                                        // Update stats
381                                        let mut s = stats.write().await;
382                                        s.indexed_files += 1;
383                                        s.total_chunks += u64::from(chunk_count);
384                                        s.last_update = Some(Utc::now());
385                                    }
386                                    Err(e) => {
387                                        error!("Failed to index {:?}: {}", path, e);
388                                        let _ = update_tx.send(IndexUpdate::FileError {
389                                            path: path.clone(),
390                                            error: e.to_string(),
391                                        });
392
393                                        // Update stats
394                                        let mut s = stats.write().await;
395                                        s.error_files += 1;
396                                    }
397                                }
398                            }
399                            FileEvent::Deleted(path) => {
400                                if let Err(e) = store.delete_by_file_path(path).await {
401                                    error!("Failed to delete {:?}: {}", path, e);
402                                } else {
403                                    let _ = update_tx
404                                        .send(IndexUpdate::FileRemoved { path: path.clone() });
405                                }
406                            }
407                            FileEvent::Renamed { from, to } => {
408                                // Delete old, index new
409                                if let Err(e) = store.delete_by_file_path(from).await {
410                                    warn!("Failed to delete old path {:?}: {}", from, e);
411                                }
412                                let _ = update_tx
413                                    .send(IndexUpdate::IndexingStarted { path: to.clone() });
414
415                                match process_file(
416                                    to,
417                                    &root,
418                                    &store,
419                                    &extractors,
420                                    &chunkers,
421                                    &embedder,
422                                    &config,
423                                )
424                                .await
425                                {
426                                    Ok(chunk_count) => {
427                                        let _ = update_tx.send(IndexUpdate::FileIndexed {
428                                            path: to.clone(),
429                                            chunk_count,
430                                        });
431                                    }
432                                    Err(e) => {
433                                        let _ = update_tx.send(IndexUpdate::FileError {
434                                            path: to.clone(),
435                                            error: e.to_string(),
436                                        });
437                                    }
438                                }
439                            }
440                        }
441                        finish_pending(&pending, &idle_notify);
442                    }
443                    None => break,
444                }
445            }
446        });
447
448        // Initial scan
449        self.scan().await?;
450
451        Ok(())
452    }
453
454    /// Delete store rows whose paths are now excluded (every index, not only `--force`).
455    async fn purge_excluded_files(&self) -> Result<()> {
456        if !self.config.purge_excluded {
457            return Ok(());
458        }
459        let files = self.store.get_all_files().await.map_err(Error::Store)?;
460        let matcher = self.config.matcher(&self.root);
461        for file in files {
462            if matcher.should_process(&file.path) {
463                continue;
464            }
465            info!("Purging excluded path {:?}", file.path);
466            self.store
467                .delete_by_file_path(&file.path)
468                .await
469                .map_err(Error::Store)?;
470            let _ = self.update_tx.send(IndexUpdate::FileRemoved {
471                path: file.path.clone(),
472            });
473        }
474        Ok(())
475    }
476
477    /// Perform initial scan of the root directory.
478    async fn scan(&self) -> Result<()> {
479        info!("Scanning {:?}", self.root);
480
481        let root = self.root.clone();
482        let event_tx = self.event_tx.clone();
483        let config = self.config.clone();
484        let pending = Arc::clone(&self.pending);
485
486        // Walk directory in background thread (blocking I/O)
487        let complete = tokio::task::spawn_blocking(move || {
488            scan_directory(&root, &event_tx, &config, &pending)
489        })
490        .await
491        .map_err(|e| Error::Other(format!("scan task failed: {e}")))?;
492
493        self.reconcile_missing_files(complete).await
494    }
495
496    /// Remove only confirmed missing paths after a complete walk. Permission
497    /// errors, symlinks, paths outside the root, and unavailable roots preserve
498    /// index records. This is not a filesystem snapshot.
499    async fn reconcile_missing_files(&self, complete: bool) -> Result<()> {
500        if !complete {
501            warn!("Incomplete scan; preserving records for unvisited paths");
502            return Ok(());
503        }
504        for file in self.store.get_all_files().await.map_err(Error::Store)? {
505            if confirmed_missing(&self.root, &file.path) {
506                self.store
507                    .delete_by_file_path(&file.path)
508                    .await
509                    .map_err(Error::Store)?;
510                let _ = self
511                    .update_tx
512                    .send(IndexUpdate::FileRemoved { path: file.path });
513            }
514        }
515        Ok(())
516    }
517
518    /// Process a single file through the pipeline.
519    pub async fn process_single(&self, path: &Path) -> Result<u32> {
520        process_file(
521            path,
522            &self.root,
523            &self.store,
524            &self.extractors,
525            &self.chunkers,
526            &self.embedder,
527            &self.config,
528        )
529        .await
530    }
531
532    /// Reindex a path (file or directory).
533    ///
534    /// If the path is a file, it will be reindexed (existing chunks deleted first).
535    /// If the path is a directory, all files in it will be reindexed recursively.
536    pub async fn reindex_path(&self, path: &Path) -> Result<()> {
537        if !path.exists() {
538            return Err(Error::Other(format!(
539                "Path does not exist: {}",
540                path.display()
541            )));
542        }
543
544        if path.is_file() {
545            // Delete existing chunks and reindex
546            let _ = self.store.delete_by_file_path(path).await;
547
548            let _ = self.update_tx.send(IndexUpdate::IndexingStarted {
549                path: path.to_path_buf(),
550            });
551
552            match process_file(
553                path,
554                &self.root,
555                &self.store,
556                &self.extractors,
557                &self.chunkers,
558                &self.embedder,
559                &self.config,
560            )
561            .await
562            {
563                Ok(chunk_count) => {
564                    info!("Reindexed {:?} ({} chunks)", path, chunk_count);
565                    let _ = self.update_tx.send(IndexUpdate::FileIndexed {
566                        path: path.to_path_buf(),
567                        chunk_count,
568                    });
569                }
570                Err(e) => {
571                    error!("Failed to reindex {:?}: {}", path, e);
572                    let _ = self.update_tx.send(IndexUpdate::FileError {
573                        path: path.to_path_buf(),
574                        error: e.to_string(),
575                    });
576                    return Err(e);
577                }
578            }
579        } else if path.is_dir() {
580            // Reindex all files in directory recursively
581            info!("Reindexing directory {:?}", path);
582            self.reindex_directory(path).await?;
583        }
584
585        Ok(())
586    }
587
588    /// Recursively reindex all files in a directory.
589    async fn reindex_directory(&self, dir: &Path) -> Result<()> {
590        let entries = tokio::fs::read_dir(dir)
591            .await
592            .map_err(|e| Error::Other(format!("Failed to read directory: {e}")))?;
593
594        let mut entries_stream = tokio_stream::wrappers::ReadDirStream::new(entries);
595
596        use tokio_stream::StreamExt;
597        while let Some(entry) = entries_stream.next().await {
598            let entry = match entry {
599                Ok(entry) => entry,
600                Err(error) => {
601                    warn!("Cannot read index entry in {}: {error}", dir.display());
602                    continue;
603                }
604            };
605            let path = entry.path();
606
607            if path.is_dir() {
608                if !self.config.matcher(&self.root).should_descend(&path) {
609                    continue;
610                }
611                // Recurse into subdirectory using a boxed future to avoid infinite recursion
612                Box::pin(self.reindex_directory(&path)).await?;
613            } else if path.is_file() {
614                if !self.config.should_process_path_in(&path, &self.root) {
615                    continue;
616                }
617                // Reindex file - use process_file directly to avoid recursion
618                let _ = self.store.delete_by_file_path(&path).await;
619
620                let _ = self
621                    .update_tx
622                    .send(IndexUpdate::IndexingStarted { path: path.clone() });
623
624                match process_file(
625                    &path,
626                    &self.root,
627                    &self.store,
628                    &self.extractors,
629                    &self.chunkers,
630                    &self.embedder,
631                    &self.config,
632                )
633                .await
634                {
635                    Ok(chunk_count) => {
636                        info!("Reindexed {:?} ({} chunks)", path, chunk_count);
637                        let _ = self.update_tx.send(IndexUpdate::FileIndexed {
638                            path: path.clone(),
639                            chunk_count,
640                        });
641                    }
642                    Err(e) => {
643                        warn!("Failed to reindex {:?}: {}", path, e);
644                        let _ = self.update_tx.send(IndexUpdate::FileError {
645                            path: path.clone(),
646                            error: e.to_string(),
647                        });
648                        // Continue with other files
649                    }
650                }
651            }
652        }
653
654        Ok(())
655    }
656}
657
658/// Scan a directory and send file events.
659fn scan_directory(
660    root: &Path,
661    event_tx: &mpsc::Sender<FileEvent>,
662    config: &IndexerConfig,
663    pending: &AtomicUsize,
664) -> bool {
665    let matcher = config.matcher(root);
666    let (files, complete) = matcher.collect_files_with_status();
667    for path in files {
668        queue_event_blocking(event_tx, pending, FileEvent::Created(path));
669    }
670    complete
671}
672
673fn confirmed_missing(root: &Path, path: &Path) -> bool {
674    let Ok(relative) = path.strip_prefix(root) else {
675        return false;
676    };
677    if !std::fs::symlink_metadata(root).is_ok_and(|m| m.is_dir()) {
678        return false;
679    }
680    let mut current = root.to_path_buf();
681    for component in relative.components() {
682        if !matches!(component, std::path::Component::Normal(_)) {
683            return false;
684        }
685        current.push(component);
686        match std::fs::symlink_metadata(&current) {
687            Ok(metadata) if metadata.file_type().is_symlink() => return false,
688            Ok(_) => {}
689            Err(error) => {
690                return matches!(
691                    error.kind(),
692                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
693                );
694            }
695        }
696    }
697    false
698}
699
700fn queue_event_blocking(
701    event_tx: &mpsc::Sender<FileEvent>,
702    pending: &AtomicUsize,
703    event: FileEvent,
704) {
705    pending.fetch_add(1, Ordering::SeqCst);
706    if let Err(e) = event_tx.blocking_send(event) {
707        pending.fetch_sub(1, Ordering::SeqCst);
708        warn!("Failed to queue file event: {e}");
709    }
710}
711
712fn finish_pending(pending: &AtomicUsize, idle_notify: &Notify) {
713    let prev = pending.fetch_sub(1, Ordering::SeqCst);
714    if prev <= 1 {
715        idle_notify.notify_waiters();
716    }
717}
718
719/// Process a file through the full pipeline: extract → chunk → embed → store.
720async fn process_file(
721    path: &Path,
722    root: &Path,
723    store: &Arc<dyn VectorStore>,
724    extractors: &Arc<ExtractorRegistry>,
725    chunkers: &Arc<ChunkerRegistry>,
726    embedder: &Arc<EmbedderPool>,
727    config: &IndexerConfig,
728) -> Result<u32> {
729    // Get file metadata
730    let metadata = tokio::fs::metadata(path)
731        .await
732        .map_err(|e| Error::Other(format!("Failed to get metadata: {e}")))?;
733
734    if !metadata.is_file() {
735        return Ok(0);
736    }
737
738    if !config.should_process_path_in(path, root) {
739        debug!("Skipping {:?} (include/exclude patterns)", path);
740        if config.purge_excluded {
741            store
742                .delete_by_file_path(path)
743                .await
744                .map_err(Error::Store)?;
745        }
746        return Ok(0);
747    }
748
749    if metadata.len() > config.max_file_size {
750        debug!(
751            "Skipping {:?} ({} bytes > max_file_size {})",
752            path,
753            metadata.len(),
754            config.max_file_size
755        );
756        store
757            .delete_by_file_path(path)
758            .await
759            .map_err(Error::Store)?;
760        return Ok(0);
761    }
762
763    // Compute content hash
764    let content_hash = compute_hash(path).await?;
765
766    // Check if already indexed with same hash (unless --force)
767    if !config.force
768        && let Ok(Some(existing)) = store.get_file(path).await
769        && existing.content_hash == content_hash
770        && existing.status == FileStatus::Indexed
771    {
772        debug!("File {:?} already indexed, skipping", path);
773        return Ok(existing.chunk_count);
774    }
775
776    // Determine MIME type
777    let mime_type = mime_guess::from_path(path)
778        .first_or_text_plain()
779        .to_string();
780
781    // Extract content
782    let content = extractors
783        .extract(path, &mime_type)
784        .await
785        .map_err(Error::Extraction)?;
786
787    let content_type = determine_content_type(path, &mime_type, &content);
788    // Preserve text chunks for documents; standalone images use caption/metadata
789    // chunks only, avoiding duplicate metadata in two content types.
790    let mut chunk_outputs = Vec::new();
791    if !content.text.is_empty() && !mime_type.starts_with("image/") {
792        chunk_outputs.extend(
793            chunkers
794                .chunk(&content, &content_type, &config.chunk_config)
795                .await
796                .map_err(Error::Chunking)?
797                .into_iter()
798                .map(|chunk| (chunk, content_type.clone())),
799        );
800    }
801    for image in &content.images {
802        let text = image
803            .caption
804            .clone()
805            .filter(|text| !text.trim().is_empty())
806            .unwrap_or_else(|| {
807                if mime_type.starts_with("image/") {
808                    content.text.clone()
809                } else {
810                    format!(
811                        "Image in {} on page {} ({})",
812                        path.file_name().unwrap_or_default().to_string_lossy(),
813                        image.page.unwrap_or(0),
814                        image.mime_type
815                    )
816                }
817            });
818        let caption_content = ragfs_core::ExtractedContent {
819            text,
820            elements: vec![],
821            images: vec![],
822            metadata: Default::default(),
823        };
824        for mut chunk in chunkers
825            .chunk(
826                &caption_content,
827                &ContentType::ImageCaption,
828                &config.chunk_config,
829            )
830            .await
831            .map_err(Error::Chunking)?
832        {
833            // Caption offsets are not offsets into the image/PDF container.
834            chunk.byte_range = 0..0;
835            chunk.line_range = None;
836            chunk_outputs.push((chunk, ContentType::ImageCaption));
837        }
838    }
839    chunk_outputs.retain(|(chunk, _)| chunk_has_content(&chunk.content, config.min_alnum_chars));
840    if chunk_outputs.is_empty() {
841        store
842            .delete_by_file_path(path)
843            .await
844            .map_err(Error::Store)?;
845        return Ok(0);
846    }
847
848    // Prepare texts for embedding
849    let texts: Vec<&str> = chunk_outputs
850        .iter()
851        .map(|(c, _)| c.content.as_str())
852        .collect();
853
854    // Generate embeddings
855    let embeddings = embedder
856        .embed_batch(&texts, &config.embed_config)
857        .await
858        .map_err(Error::Embedding)?;
859
860    // Create Chunk objects
861    let file_id = Uuid::new_v4();
862    let now = Utc::now();
863    let model_name = embedder.model_name().to_string();
864
865    let chunks: Vec<Chunk> = chunk_outputs
866        .into_iter()
867        .zip(embeddings)
868        .enumerate()
869        .map(|(idx, ((output, chunk_type), emb_output))| {
870            build_chunk(
871                file_id,
872                path,
873                root,
874                idx as u32,
875                output,
876                emb_output.embedding,
877                &chunk_type,
878                &mime_type,
879                &model_name,
880                now,
881            )
882        })
883        .collect();
884
885    let chunk_count = chunks.len() as u32;
886
887    // Delete old chunks for this file
888    store
889        .delete_by_file_path(path)
890        .await
891        .map_err(Error::Store)?;
892
893    // Store chunks
894    store.upsert_chunks(&chunks).await.map_err(Error::Store)?;
895
896    // Store file record
897    let file_record = FileRecord {
898        id: file_id,
899        path: path.to_path_buf(),
900        size_bytes: metadata.len(),
901        mime_type,
902        content_hash,
903        modified_at: metadata
904            .modified()
905            .map_or_else(|_| now, chrono::DateTime::<Utc>::from),
906        indexed_at: Some(now),
907        chunk_count,
908        status: FileStatus::Indexed,
909        error_message: None,
910    };
911
912    store
913        .upsert_file(&file_record)
914        .await
915        .map_err(Error::Store)?;
916
917    Ok(chunk_count)
918}
919
920/// Unicode general categories L* and Nd; unlike `is_alphanumeric`, this
921/// deliberately excludes `Letter_Number` and `Other_Number` (e.g. fractions).
922fn chunk_has_content(text: &str, minimum: usize) -> bool {
923    use unicode_general_category::{GeneralCategory, get_general_category};
924    text.chars()
925        .filter(|character| {
926            matches!(
927                get_general_category(*character),
928                GeneralCategory::UppercaseLetter
929                    | GeneralCategory::LowercaseLetter
930                    | GeneralCategory::TitlecaseLetter
931                    | GeneralCategory::ModifierLetter
932                    | GeneralCategory::OtherLetter
933                    | GeneralCategory::DecimalNumber
934            )
935        })
936        .take(minimum)
937        .count()
938        >= minimum
939}
940
941/// Compute blake3 hash of file content.
942async fn compute_hash(path: &Path) -> Result<String> {
943    let content = tokio::fs::read(path)
944        .await
945        .map_err(|e| Error::Other(format!("Failed to read file: {e}")))?;
946
947    let hash = blake3::hash(&content);
948    Ok(hash.to_hex().to_string())
949}
950
951/// Determine content type from path, MIME type, and extracted content.
952fn determine_content_type(
953    path: &Path,
954    mime_type: &str,
955    content: &ragfs_core::ExtractedContent,
956) -> ContentType {
957    // Check for code files
958    let code_extensions = [
959        ("rs", "rust"),
960        ("py", "python"),
961        ("js", "javascript"),
962        ("ts", "typescript"),
963        ("tsx", "typescript"),
964        ("jsx", "javascript"),
965        ("java", "java"),
966        ("go", "go"),
967        ("c", "c"),
968        ("cpp", "cpp"),
969        ("h", "c"),
970        ("hpp", "cpp"),
971        ("rb", "ruby"),
972        ("php", "php"),
973        ("swift", "swift"),
974        ("kt", "kotlin"),
975        ("scala", "scala"),
976        ("ex", "elixir"),
977        ("hs", "haskell"),
978        ("ml", "ocaml"),
979        ("lua", "lua"),
980        ("sh", "bash"),
981        ("sql", "sql"),
982    ];
983
984    if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
985        let ext_lower = ext.to_lowercase();
986        for (code_ext, lang) in &code_extensions {
987            if ext_lower == *code_ext {
988                return ContentType::Code {
989                    language: (*lang).to_string(),
990                    symbol: None,
991                };
992            }
993        }
994    }
995
996    // Check for markdown
997    if mime_type.contains("markdown")
998        || path
999            .extension()
1000            .is_some_and(|e| e == "md" || e == "markdown")
1001    {
1002        return ContentType::Markdown;
1003    }
1004
1005    // Check language from extraction metadata
1006    if let Some(ref lang) = content.metadata.language
1007        && !lang.is_empty()
1008    {
1009        return ContentType::Code {
1010            language: lang.clone(),
1011            symbol: None,
1012        };
1013    }
1014
1015    ContentType::Text
1016}
1017
1018/// Build a Chunk from chunk output and embedding.
1019fn build_chunk(
1020    file_id: Uuid,
1021    file_path: &Path,
1022    root: &Path,
1023    chunk_index: u32,
1024    output: ChunkOutput,
1025    embedding: Vec<f32>,
1026    content_type: &ContentType,
1027    mime_type: &str,
1028    model_name: &str,
1029    now: chrono::DateTime<Utc>,
1030) -> Chunk {
1031    let scope = DirectoryScope::from_paths(file_path, Some(root));
1032    Chunk {
1033        id: Uuid::new_v4(),
1034        file_id,
1035        file_path: file_path.to_path_buf(),
1036        content: output.content,
1037        content_type: content_type.clone(),
1038        mime_type: Some(mime_type.to_string()),
1039        chunk_index,
1040        byte_range: output.byte_range,
1041        line_range: output.line_range,
1042        parent_chunk_id: None,
1043        depth: output.depth,
1044        embedding: Some(embedding),
1045        dir_path: scope.dir_path,
1046        dir_depth: scope.dir_depth,
1047        path_components: scope.path_components,
1048        metadata: ChunkMetadata {
1049            media: ragfs_core::MediaInfo {
1050                modality: if matches!(content_type, ContentType::ImageCaption) {
1051                    "image"
1052                } else {
1053                    "text"
1054                }
1055                .into(),
1056                ..Default::default()
1057            },
1058            embedding_model: Some(model_name.to_string()),
1059            indexed_at: Some(now),
1060            token_count: None,
1061            extra: Default::default(),
1062        },
1063    }
1064}
1065
1066#[async_trait::async_trait]
1067impl Indexer for IndexerService {
1068    async fn watch(&self, path: &Path) -> Result<()> {
1069        let mut w = self.watcher.write().await;
1070        if let Some(ref mut watcher) = *w {
1071            watcher
1072                .watch(path)
1073                .map_err(|e| Error::Other(format!("watch error: {e}")))?;
1074        }
1075        Ok(())
1076    }
1077
1078    async fn stop(&self) -> Result<()> {
1079        let mut running = self.running.write().await;
1080        *running = false;
1081        info!("Indexer stopped");
1082        Ok(())
1083    }
1084
1085    async fn index(&self, path: &Path, force: bool) -> Result<()> {
1086        if force {
1087            // Delete existing and reindex
1088            let _ = self.store.delete_by_file_path(path).await;
1089        }
1090
1091        self.pending.fetch_add(1, Ordering::SeqCst);
1092        if let Err(e) = self
1093            .event_tx
1094            .send(FileEvent::Modified(path.to_path_buf()))
1095            .await
1096        {
1097            self.pending.fetch_sub(1, Ordering::SeqCst);
1098            return Err(Error::Other(format!("send error: {e}")));
1099        }
1100        Ok(())
1101    }
1102
1103    async fn stats(&self) -> Result<IndexStats> {
1104        Ok(self.stats.read().await.clone())
1105    }
1106
1107    async fn needs_reindex(&self, path: &Path) -> Result<bool> {
1108        // Check if file exists in store and compare hash
1109        match self.store.get_file(path).await {
1110            Ok(Some(record)) => {
1111                let current_hash = compute_hash(path).await?;
1112                Ok(record.content_hash != current_hash)
1113            }
1114            Ok(None) => Ok(true),
1115            Err(e) => Err(Error::Store(e)),
1116        }
1117    }
1118}
1119
1120#[cfg(test)]
1121mod tests {
1122    use super::*;
1123    use ragfs_chunker::{ChunkerRegistry, FixedSizeChunker};
1124    use ragfs_core::{
1125        ContentMetadataInfo, EmbedError, Embedder, EmbeddingConfig, EmbeddingOutput, Modality,
1126        SearchQuery, SearchResult, StoreError, StoreStats,
1127    };
1128    use ragfs_embed::EmbedderPool;
1129    use ragfs_extract::ExtractorRegistry;
1130    use std::collections::HashMap;
1131    use tempfile::tempdir;
1132
1133    const TEST_DIM: usize = 384;
1134
1135    struct CaptionFixture {
1136        caption: Option<String>,
1137    }
1138
1139    #[async_trait::async_trait]
1140    impl ragfs_core::ContentExtractor for CaptionFixture {
1141        fn supported_types(&self) -> &[&str] {
1142            &["image/png", "application/pdf"]
1143        }
1144        async fn extract(
1145            &self,
1146            _: &Path,
1147        ) -> std::result::Result<ragfs_core::ExtractedContent, ragfs_core::ExtractError> {
1148            Ok(ragfs_core::ExtractedContent {
1149                text: "Image: sample.png (64x64, png)".into(),
1150                elements: vec![],
1151                images: vec![ragfs_core::ExtractedImage {
1152                    data: vec![],
1153                    mime_type: "image/png".into(),
1154                    caption: self.caption.clone(),
1155                    page: Some(1),
1156                }],
1157                metadata: Default::default(),
1158            })
1159        }
1160    }
1161
1162    #[tokio::test]
1163    async fn image_caption_and_metadata_reach_typed_chunks() {
1164        for caption in [Some("A vermilion lighthouse by the sea".to_string()), None] {
1165            let root = tempdir().unwrap();
1166            let path = root.path().join("sample.png");
1167            std::fs::write(&path, "fixture").unwrap();
1168            let store = Arc::new(MockStore::new());
1169            let mut indexer = create_test_indexer(store.clone(), root.path());
1170            let mut registry = ExtractorRegistry::new();
1171            registry.register(
1172                "image",
1173                CaptionFixture {
1174                    caption: caption.clone(),
1175                },
1176            );
1177            indexer.extractors = Arc::new(registry);
1178            assert!(indexer.process_single(&path).await.unwrap() > 0);
1179            let chunks = store.get_chunks_for_file(&path).await.unwrap();
1180            assert!(
1181                chunks
1182                    .iter()
1183                    .all(|c| matches!(c.content_type, ContentType::ImageCaption))
1184            );
1185            assert!(
1186                chunks
1187                    .iter()
1188                    .any(|c| c.content.contains(caption.as_deref().unwrap_or("64x64")))
1189            );
1190            assert!(
1191                chunks
1192                    .iter()
1193                    .all(|c| c.byte_range == (0..0) && c.line_range.is_none())
1194            );
1195        }
1196    }
1197
1198    // ==================== Mock Embedder ====================
1199
1200    struct MockEmbedder {
1201        dimension: usize,
1202    }
1203
1204    impl MockEmbedder {
1205        fn new(dimension: usize) -> Self {
1206            Self { dimension }
1207        }
1208    }
1209
1210    #[async_trait::async_trait]
1211    impl Embedder for MockEmbedder {
1212        fn model_name(&self) -> &str {
1213            "mock-embedder"
1214        }
1215
1216        fn dimension(&self) -> usize {
1217            self.dimension
1218        }
1219
1220        fn max_tokens(&self) -> usize {
1221            512
1222        }
1223
1224        fn modalities(&self) -> &[Modality] {
1225            &[Modality::Text]
1226        }
1227
1228        async fn embed_text(
1229            &self,
1230            texts: &[&str],
1231            _config: &EmbeddingConfig,
1232        ) -> std::result::Result<Vec<EmbeddingOutput>, EmbedError> {
1233            Ok(texts
1234                .iter()
1235                .map(|_| EmbeddingOutput {
1236                    embedding: vec![0.1; self.dimension],
1237                    token_count: 10,
1238                })
1239                .collect())
1240        }
1241
1242        async fn embed_query(
1243            &self,
1244            _query: &str,
1245            _config: &EmbeddingConfig,
1246        ) -> std::result::Result<EmbeddingOutput, EmbedError> {
1247            Ok(EmbeddingOutput {
1248                embedding: vec![0.1; self.dimension],
1249                token_count: 10,
1250            })
1251        }
1252    }
1253
1254    // ==================== Mock VectorStore ====================
1255
1256    struct MockStore {
1257        fail_delete: bool,
1258        chunks: Arc<RwLock<Vec<Chunk>>>,
1259        files: Arc<RwLock<HashMap<PathBuf, FileRecord>>>,
1260    }
1261
1262    impl MockStore {
1263        fn new() -> Self {
1264            Self {
1265                fail_delete: false,
1266                chunks: Arc::new(RwLock::new(Vec::new())),
1267                files: Arc::new(RwLock::new(HashMap::new())),
1268            }
1269        }
1270    }
1271
1272    #[async_trait::async_trait]
1273    impl VectorStore for MockStore {
1274        async fn init(&self) -> std::result::Result<(), StoreError> {
1275            Ok(())
1276        }
1277
1278        async fn upsert_chunks(&self, chunks: &[Chunk]) -> std::result::Result<(), StoreError> {
1279            let mut store = self.chunks.write().await;
1280            for chunk in chunks {
1281                store.push(chunk.clone());
1282            }
1283            Ok(())
1284        }
1285
1286        async fn search(
1287            &self,
1288            _query: SearchQuery,
1289        ) -> std::result::Result<Vec<SearchResult>, StoreError> {
1290            Ok(vec![])
1291        }
1292
1293        async fn hybrid_search(
1294            &self,
1295            _query: SearchQuery,
1296        ) -> std::result::Result<Vec<SearchResult>, StoreError> {
1297            Ok(vec![])
1298        }
1299
1300        async fn delete_by_file_path(&self, path: &Path) -> std::result::Result<u64, StoreError> {
1301            if self.fail_delete {
1302                return Err(StoreError::Init("injected delete failure".into()));
1303            }
1304            let mut chunks = self.chunks.write().await;
1305            let initial_len = chunks.len();
1306            chunks.retain(|c| c.file_path != path);
1307            let deleted = initial_len - chunks.len();
1308            let mut files = self.files.write().await;
1309            files.remove(path);
1310            Ok(deleted as u64)
1311        }
1312
1313        async fn get_file(
1314            &self,
1315            path: &Path,
1316        ) -> std::result::Result<Option<FileRecord>, StoreError> {
1317            let files = self.files.read().await;
1318            Ok(files.get(path).cloned())
1319        }
1320
1321        async fn upsert_file(&self, record: &FileRecord) -> std::result::Result<(), StoreError> {
1322            let mut files = self.files.write().await;
1323            files.insert(record.path.clone(), record.clone());
1324            Ok(())
1325        }
1326
1327        async fn stats(&self) -> std::result::Result<StoreStats, StoreError> {
1328            let chunks = self.chunks.read().await;
1329            let files = self.files.read().await;
1330            Ok(StoreStats {
1331                total_chunks: chunks.len() as u64,
1332                total_files: files.len() as u64,
1333                index_size_bytes: 0,
1334                last_updated: None,
1335                index_revision: 0,
1336            })
1337        }
1338
1339        async fn update_file_path(
1340            &self,
1341            _old_path: &Path,
1342            _new_path: &Path,
1343        ) -> std::result::Result<u64, StoreError> {
1344            Ok(0)
1345        }
1346
1347        async fn get_chunks_for_file(
1348            &self,
1349            path: &Path,
1350        ) -> std::result::Result<Vec<Chunk>, StoreError> {
1351            let chunks = self.chunks.read().await;
1352            Ok(chunks
1353                .iter()
1354                .filter(|c| c.file_path == path)
1355                .cloned()
1356                .collect())
1357        }
1358
1359        async fn get_all_chunks(&self) -> std::result::Result<Vec<Chunk>, StoreError> {
1360            let chunks = self.chunks.read().await;
1361            Ok(chunks.clone())
1362        }
1363
1364        async fn get_all_files(&self) -> std::result::Result<Vec<FileRecord>, StoreError> {
1365            let files = self.files.read().await;
1366            Ok(files.values().cloned().collect())
1367        }
1368    }
1369
1370    // ==================== Helper function tests ====================
1371
1372    #[test]
1373    fn test_determine_content_type_rust() {
1374        let path = PathBuf::from("/test/file.rs");
1375        let content = ragfs_core::ExtractedContent {
1376            text: "fn main() {}".to_string(),
1377            elements: vec![],
1378            images: vec![],
1379            metadata: ContentMetadataInfo::default(),
1380        };
1381
1382        let result = determine_content_type(&path, "text/x-rust", &content);
1383        match result {
1384            ContentType::Code { language, .. } => assert_eq!(language, "rust"),
1385            _ => panic!("Expected Code content type"),
1386        }
1387    }
1388
1389    #[test]
1390    fn test_determine_content_type_python() {
1391        let path = PathBuf::from("/test/script.py");
1392        let content = ragfs_core::ExtractedContent {
1393            text: "def main(): pass".to_string(),
1394            elements: vec![],
1395            images: vec![],
1396            metadata: ContentMetadataInfo::default(),
1397        };
1398
1399        let result = determine_content_type(&path, "text/x-python", &content);
1400        match result {
1401            ContentType::Code { language, .. } => assert_eq!(language, "python"),
1402            _ => panic!("Expected Code content type"),
1403        }
1404    }
1405
1406    #[test]
1407    fn test_determine_content_type_markdown() {
1408        let path = PathBuf::from("/test/readme.md");
1409        let content = ragfs_core::ExtractedContent {
1410            text: "# Hello".to_string(),
1411            elements: vec![],
1412            images: vec![],
1413            metadata: ContentMetadataInfo::default(),
1414        };
1415
1416        let result = determine_content_type(&path, "text/markdown", &content);
1417        assert!(matches!(result, ContentType::Markdown));
1418    }
1419
1420    #[test]
1421    fn test_determine_content_type_text() {
1422        let path = PathBuf::from("/test/notes.txt");
1423        let content = ragfs_core::ExtractedContent {
1424            text: "Some text content".to_string(),
1425            elements: vec![],
1426            images: vec![],
1427            metadata: ContentMetadataInfo::default(),
1428        };
1429
1430        let result = determine_content_type(&path, "text/plain", &content);
1431        assert!(matches!(result, ContentType::Text));
1432    }
1433
1434    #[test]
1435    fn test_determine_content_type_javascript() {
1436        let path = PathBuf::from("/test/app.js");
1437        let content = ragfs_core::ExtractedContent {
1438            text: "const x = 1;".to_string(),
1439            elements: vec![],
1440            images: vec![],
1441            metadata: ContentMetadataInfo::default(),
1442        };
1443
1444        let result = determine_content_type(&path, "application/javascript", &content);
1445        match result {
1446            ContentType::Code { language, .. } => assert_eq!(language, "javascript"),
1447            _ => panic!("Expected Code content type"),
1448        }
1449    }
1450
1451    #[tokio::test]
1452    async fn test_compute_hash() {
1453        let temp_dir = tempdir().unwrap();
1454        let file_path = temp_dir.path().join("test.txt");
1455        std::fs::write(&file_path, "test content").unwrap();
1456
1457        let hash = compute_hash(&file_path).await.unwrap();
1458        assert!(!hash.is_empty());
1459        assert_eq!(hash.len(), 64); // blake3 hex is 64 chars
1460
1461        // Same content should produce same hash
1462        let hash2 = compute_hash(&file_path).await.unwrap();
1463        assert_eq!(hash, hash2);
1464    }
1465
1466    #[tokio::test]
1467    async fn test_compute_hash_different_content() {
1468        let temp_dir = tempdir().unwrap();
1469
1470        let file1 = temp_dir.path().join("file1.txt");
1471        let file2 = temp_dir.path().join("file2.txt");
1472
1473        std::fs::write(&file1, "content 1").unwrap();
1474        std::fs::write(&file2, "content 2").unwrap();
1475
1476        let hash1 = compute_hash(&file1).await.unwrap();
1477        let hash2 = compute_hash(&file2).await.unwrap();
1478
1479        assert_ne!(hash1, hash2);
1480    }
1481
1482    #[test]
1483    fn test_build_chunk() {
1484        use ragfs_core::ChunkOutputMetadata;
1485
1486        let file_id = Uuid::new_v4();
1487        let root = PathBuf::from("/project");
1488        let file_path = PathBuf::from("/project/src/auth/login.rs");
1489        let chunk_output = ChunkOutput {
1490            content: "Test chunk content".to_string(),
1491            byte_range: 0..18,
1492            line_range: Some(0..1),
1493            parent_index: None,
1494            depth: 0,
1495            metadata: ChunkOutputMetadata::default(),
1496        };
1497        let embedding = vec![0.1; TEST_DIM];
1498        let content_type = ContentType::Text;
1499        let mime_type = "text/plain";
1500        let model_name = "test-model";
1501        let now = Utc::now();
1502
1503        let chunk = build_chunk(
1504            file_id,
1505            &file_path,
1506            &root,
1507            0,
1508            chunk_output,
1509            embedding.clone(),
1510            &content_type,
1511            mime_type,
1512            model_name,
1513            now,
1514        );
1515
1516        assert_eq!(chunk.file_id, file_id);
1517        assert_eq!(chunk.file_path, file_path);
1518        assert_eq!(chunk.chunk_index, 0);
1519        assert_eq!(chunk.content, "Test chunk content");
1520        assert_eq!(chunk.embedding, Some(embedding));
1521        assert_eq!(chunk.mime_type, Some("text/plain".to_string()));
1522        assert!(matches!(chunk.content_type, ContentType::Text));
1523        assert_eq!(chunk.dir_path, "src/auth");
1524        assert_eq!(chunk.dir_depth, 2);
1525        assert_eq!(chunk.path_components, "src,auth,login.rs");
1526        assert!(!chunk.dir_path.starts_with('/'));
1527    }
1528
1529    // ==================== IndexerService tests ====================
1530
1531    fn create_test_indexer(store: Arc<dyn VectorStore>, root: &Path) -> IndexerService {
1532        use ragfs_extract::TextExtractor;
1533
1534        let mut extractors = ExtractorRegistry::new();
1535        extractors.register("text", TextExtractor::new());
1536        let extractors = Arc::new(extractors);
1537
1538        let mut chunkers = ChunkerRegistry::new();
1539        chunkers.register("fixed", FixedSizeChunker::new());
1540        chunkers.set_default("fixed");
1541        let chunkers = Arc::new(chunkers);
1542
1543        let embedder = Arc::new(MockEmbedder::new(TEST_DIM));
1544        let embedder_pool = Arc::new(EmbedderPool::new(embedder, 1));
1545
1546        let config = IndexerConfig::default();
1547
1548        IndexerService::new(
1549            root.to_path_buf(),
1550            store,
1551            extractors,
1552            chunkers,
1553            embedder_pool,
1554            config,
1555        )
1556    }
1557
1558    #[tokio::test]
1559    async fn test_process_single_file() {
1560        let temp_dir = tempdir().unwrap();
1561        let file_path = temp_dir.path().join("test.txt");
1562        std::fs::write(&file_path, "This is test content for indexing.").unwrap();
1563
1564        let store = Arc::new(MockStore::new());
1565        let indexer =
1566            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1567
1568        let chunk_count = indexer.process_single(&file_path).await.unwrap();
1569
1570        assert!(chunk_count > 0, "Should have created at least one chunk");
1571
1572        // Verify chunks were stored
1573        let stored_chunks = store.chunks.read().await;
1574        assert!(!stored_chunks.is_empty());
1575        assert!(stored_chunks.iter().all(|c| c.file_path == file_path));
1576
1577        // Verify file record was stored
1578        let files = store.files.read().await;
1579        assert!(files.contains_key(&file_path));
1580        let file_record = files.get(&file_path).unwrap();
1581        assert_eq!(file_record.chunk_count, chunk_count);
1582        assert_eq!(file_record.status, FileStatus::Indexed);
1583    }
1584
1585    #[tokio::test]
1586    async fn test_process_single_skip_already_indexed() {
1587        let temp_dir = tempdir().unwrap();
1588        let file_path = temp_dir.path().join("test.txt");
1589        std::fs::write(&file_path, "Test content").unwrap();
1590
1591        let store = Arc::new(MockStore::new());
1592        let indexer =
1593            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1594
1595        // First indexing
1596        let chunk_count1 = indexer.process_single(&file_path).await.unwrap();
1597
1598        // Count chunks after first indexing
1599        let _chunks_after_first = store.chunks.read().await.len();
1600
1601        // Second indexing (should skip because content hasn't changed)
1602        let chunk_count2 = indexer.process_single(&file_path).await.unwrap();
1603
1604        assert_eq!(chunk_count1, chunk_count2);
1605
1606        // Chunk count should be same (old chunks deleted and new ones added if reindexed,
1607        // or no change if skipped)
1608        let chunks_after_second = store.chunks.read().await.len();
1609        // Note: process_file deletes old chunks before adding new ones, so count may vary
1610        assert!(chunks_after_second > 0);
1611    }
1612
1613    #[tokio::test]
1614    async fn test_needs_reindex_new_file() {
1615        let temp_dir = tempdir().unwrap();
1616        let file_path = temp_dir.path().join("new_file.txt");
1617        std::fs::write(&file_path, "New content").unwrap();
1618
1619        let store = Arc::new(MockStore::new());
1620        let indexer =
1621            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1622
1623        // File not in store should need reindex
1624        let needs = indexer.needs_reindex(&file_path).await.unwrap();
1625        assert!(needs);
1626    }
1627
1628    #[tokio::test]
1629    async fn test_needs_reindex_unchanged_file() {
1630        let temp_dir = tempdir().unwrap();
1631        let file_path = temp_dir.path().join("unchanged.txt");
1632        std::fs::write(&file_path, "Unchanged content").unwrap();
1633
1634        let store = Arc::new(MockStore::new());
1635        let indexer =
1636            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1637
1638        // Index the file first
1639        indexer.process_single(&file_path).await.unwrap();
1640
1641        // Same content should not need reindex
1642        let needs = indexer.needs_reindex(&file_path).await.unwrap();
1643        assert!(!needs);
1644    }
1645
1646    #[tokio::test]
1647    async fn test_needs_reindex_modified_file() {
1648        let temp_dir = tempdir().unwrap();
1649        let file_path = temp_dir.path().join("modified.txt");
1650        std::fs::write(&file_path, "Original content").unwrap();
1651
1652        let store = Arc::new(MockStore::new());
1653        let indexer =
1654            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1655
1656        // Index the file
1657        indexer.process_single(&file_path).await.unwrap();
1658
1659        // Modify the file
1660        std::fs::write(&file_path, "Modified content - different!").unwrap();
1661
1662        // Modified file should need reindex
1663        let needs = indexer.needs_reindex(&file_path).await.unwrap();
1664        assert!(needs);
1665    }
1666
1667    #[tokio::test]
1668    async fn test_reindex_path_file() {
1669        let temp_dir = tempdir().unwrap();
1670        let file_path = temp_dir.path().join("reindex_test.txt");
1671        std::fs::write(&file_path, "Original content for reindex test").unwrap();
1672
1673        let store = Arc::new(MockStore::new());
1674        let indexer =
1675            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1676
1677        // Index initially
1678        indexer.process_single(&file_path).await.unwrap();
1679
1680        let initial_chunks = store.chunks.read().await.len();
1681        assert!(initial_chunks > 0);
1682
1683        // Modify content
1684        std::fs::write(&file_path, "New content after modification").unwrap();
1685
1686        // Reindex
1687        indexer.reindex_path(&file_path).await.unwrap();
1688
1689        // Verify file was reindexed
1690        let files = store.files.read().await;
1691        assert!(files.contains_key(&file_path));
1692    }
1693
1694    #[tokio::test]
1695    async fn test_empty_file_returns_zero_chunks() {
1696        let temp_dir = tempdir().unwrap();
1697        let file_path = temp_dir.path().join("empty.txt");
1698        std::fs::write(&file_path, "").unwrap();
1699
1700        let store = Arc::new(MockStore::new());
1701        let indexer =
1702            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1703
1704        let chunk_count = indexer.process_single(&file_path).await.unwrap();
1705
1706        assert_eq!(chunk_count, 0, "Empty file should produce zero chunks");
1707    }
1708
1709    #[test]
1710    fn test_indexer_config_default() {
1711        let config = IndexerConfig::default();
1712
1713        assert!(!config.include_patterns.is_empty());
1714        assert!(config.include_patterns.contains(&"**/*".to_string()));
1715
1716        assert!(!config.exclude_patterns.is_empty());
1717        assert!(config.exclude_patterns.contains(&"**/.git/**".to_string()));
1718        assert!(
1719            config
1720                .exclude_patterns
1721                .contains(&"**/node_modules/**".to_string())
1722        );
1723        assert!(
1724            config
1725                .exclude_patterns
1726                .contains(&"**/target/**".to_string())
1727        );
1728        assert_eq!(
1729            config.exclude_patterns,
1730            crate::exclude::default_exclude_patterns()
1731        );
1732        assert!(!config.exclude_patterns.iter().any(|p| p == "**/.*"));
1733        assert_eq!(config.debounce_ms, 500);
1734        assert_eq!(config.max_file_size, 52_428_800);
1735        assert!(!config.force);
1736        assert!(!config.include_hidden);
1737        assert!(!config.include_secret_files);
1738        assert!(config.honor_gitignore);
1739        assert!(config.purge_excluded);
1740    }
1741
1742    #[test]
1743    fn test_path_matches_exclude_and_include_patterns() {
1744        assert!(path_matches_pattern("/proj/src/main.rs", "**/*"));
1745        assert!(path_matches_pattern(
1746            "/proj/node_modules/pkg/index.js",
1747            "**/node_modules/**"
1748        ));
1749        assert!(path_matches_pattern("/proj/.git/config", "**/.git/**"));
1750        assert!(path_matches_pattern("/proj/foo.pyc", "**/*.pyc"));
1751        assert!(path_matches_pattern("/proj/.env", "**/.env"));
1752        assert!(path_matches_pattern("/proj/.env", "**/.*"));
1753        assert!(
1754            !path_matches_pattern("/tmp/.tmpABC/file.txt", "**/.*"),
1755            "path_matches_pattern keeps the old **/.* basename shim; hidden dirs are ExclusionMatcher"
1756        );
1757        assert!(!path_matches_pattern(
1758            "/proj/src/main.rs",
1759            "**/node_modules/**"
1760        ));
1761        assert!(path_matches_pattern("/proj/src/main.rs", "**/*.rs"));
1762        assert!(!path_matches_pattern("/proj/readme.md", "**/*.rs"));
1763        assert!(
1764            path_matches_pattern("src/lib.rs", "src/**/*.rs"),
1765            "nested ** must match a file directly under the prefix"
1766        );
1767        assert!(path_matches_pattern("/proj/src/lib.rs", "src/**/*.rs"));
1768        assert!(path_matches_pattern(
1769            "/proj/src/nested/lib.rs",
1770            "src/**/*.rs"
1771        ));
1772        assert!(path_matches_pattern("test_unit.rs", "test_*.rs"));
1773        assert!(path_matches_pattern(
1774            "/proj/tests/test_unit.rs",
1775            "test_*.rs"
1776        ));
1777        assert!(!path_matches_pattern("/proj/src/lib.rs", "test_*.rs"));
1778
1779        let config = IndexerConfig {
1780            include_patterns: vec!["**/*.rs".to_string()],
1781            exclude_patterns: vec!["**/target/**".to_string()],
1782            ..Default::default()
1783        };
1784        assert!(config.should_process_path(Path::new("/proj/src/lib.rs")));
1785        assert!(!config.should_process_path(Path::new("/proj/src/lib.md")));
1786        assert!(!config.should_process_path(Path::new("/proj/target/debug/lib.rs")));
1787    }
1788
1789    fn create_test_indexer_with_config(
1790        store: Arc<dyn VectorStore>,
1791        config: IndexerConfig,
1792        root: &Path,
1793    ) -> IndexerService {
1794        use ragfs_extract::TextExtractor;
1795
1796        let mut extractors = ExtractorRegistry::new();
1797        extractors.register("text", TextExtractor::new());
1798        let extractors = Arc::new(extractors);
1799
1800        let mut chunkers = ChunkerRegistry::new();
1801        chunkers.register("fixed", FixedSizeChunker::new());
1802        chunkers.set_default("fixed");
1803        let chunkers = Arc::new(chunkers);
1804
1805        let embedder = Arc::new(MockEmbedder::new(TEST_DIM));
1806        let embedder_pool = Arc::new(EmbedderPool::new(embedder, 1));
1807
1808        IndexerService::new(
1809            root.to_path_buf(),
1810            store,
1811            extractors,
1812            chunkers,
1813            embedder_pool,
1814            config,
1815        )
1816    }
1817
1818    #[tokio::test]
1819    async fn test_max_file_size_skips_large_files() {
1820        let temp_dir = tempdir().unwrap();
1821        let file_path = temp_dir.path().join("big.txt");
1822        std::fs::write(&file_path, "this file is definitely larger than 8 bytes").unwrap();
1823
1824        let store = Arc::new(MockStore::new());
1825        let config = IndexerConfig {
1826            max_file_size: 8,
1827            ..Default::default()
1828        };
1829        let indexer = create_test_indexer_with_config(
1830            Arc::clone(&store) as Arc<dyn VectorStore>,
1831            config,
1832            temp_dir.path(),
1833        );
1834
1835        let chunk_count = indexer.process_single(&file_path).await.unwrap();
1836        assert_eq!(chunk_count, 0);
1837        assert!(store.files.read().await.is_empty());
1838        assert!(store.chunks.read().await.is_empty());
1839    }
1840
1841    #[tokio::test]
1842    async fn test_oversized_previously_indexed_file_is_removed() {
1843        let temp_dir = tempdir().unwrap();
1844        let file_path = temp_dir.path().join("grow.txt");
1845        std::fs::write(&file_path, "small").unwrap();
1846
1847        let store = Arc::new(MockStore::new());
1848        let indexer =
1849            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1850        let chunk_count = indexer.process_single(&file_path).await.unwrap();
1851        assert!(chunk_count > 0);
1852        assert!(store.files.read().await.contains_key(&file_path));
1853        assert!(!store.chunks.read().await.is_empty());
1854
1855        std::fs::write(&file_path, "this file is now much larger than eight bytes").unwrap();
1856
1857        let limited = IndexerConfig {
1858            max_file_size: 8,
1859            ..Default::default()
1860        };
1861        let limited_indexer = create_test_indexer_with_config(
1862            Arc::clone(&store) as Arc<dyn VectorStore>,
1863            limited,
1864            temp_dir.path(),
1865        );
1866        let skipped = limited_indexer.process_single(&file_path).await.unwrap();
1867        assert_eq!(skipped, 0);
1868        assert!(
1869            store.files.read().await.is_empty(),
1870            "growing past max_file_size must drop the file record"
1871        );
1872        assert!(
1873            store.chunks.read().await.is_empty(),
1874            "growing past max_file_size must drop indexed chunks"
1875        );
1876    }
1877
1878    #[tokio::test]
1879    async fn test_force_reindexes_unchanged_file() {
1880        let temp_dir = tempdir().unwrap();
1881        let file_path = temp_dir.path().join("stable.txt");
1882        std::fs::write(&file_path, "unchanged payload").unwrap();
1883
1884        let store = Arc::new(MockStore::new());
1885        let indexer =
1886            create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, temp_dir.path());
1887        indexer.process_single(&file_path).await.unwrap();
1888        let first_id = store.files.read().await.get(&file_path).unwrap().id;
1889
1890        // Incremental path skips when the hash matches.
1891        indexer.process_single(&file_path).await.unwrap();
1892        let skipped_id = store.files.read().await.get(&file_path).unwrap().id;
1893        assert_eq!(first_id, skipped_id);
1894
1895        let force_config = IndexerConfig {
1896            force: true,
1897            ..Default::default()
1898        };
1899        let force_indexer = create_test_indexer_with_config(
1900            Arc::clone(&store) as Arc<dyn VectorStore>,
1901            force_config,
1902            temp_dir.path(),
1903        );
1904        force_indexer.process_single(&file_path).await.unwrap();
1905        let forced_id = store.files.read().await.get(&file_path).unwrap().id;
1906        assert_ne!(
1907            first_id, forced_id,
1908            "--force must replace the existing file record"
1909        );
1910    }
1911
1912    #[tokio::test]
1913    async fn test_wait_until_idle_indexes_all_files() {
1914        let temp_dir = tempdir().unwrap();
1915        std::fs::write(temp_dir.path().join("a.txt"), "alpha file contents").unwrap();
1916        std::fs::write(temp_dir.path().join("b.txt"), "bravo file contents").unwrap();
1917        std::fs::create_dir(temp_dir.path().join("skip_me")).unwrap();
1918        std::fs::write(temp_dir.path().join("skip_me").join("c.bin"), "nope").unwrap();
1919
1920        let store = Arc::new(MockStore::new());
1921        let mut extractors = ExtractorRegistry::new();
1922        extractors.register("text", ragfs_extract::TextExtractor::new());
1923        let mut chunkers = ChunkerRegistry::new();
1924        chunkers.register("fixed", FixedSizeChunker::new());
1925        chunkers.set_default("fixed");
1926        let embedder_pool = Arc::new(EmbedderPool::new(Arc::new(MockEmbedder::new(TEST_DIM)), 1));
1927
1928        let config = IndexerConfig {
1929            include_patterns: vec!["**/*.txt".to_string()],
1930            exclude_patterns: vec!["**/skip_me/**".to_string()],
1931            debounce_ms: 50,
1932            ..Default::default()
1933        };
1934
1935        let indexer = IndexerService::new(
1936            temp_dir.path().to_path_buf(),
1937            Arc::clone(&store) as Arc<dyn VectorStore>,
1938            Arc::new(extractors),
1939            Arc::new(chunkers),
1940            embedder_pool,
1941            config,
1942        );
1943
1944        indexer.start().await.unwrap();
1945        tokio::time::timeout(
1946            std::time::Duration::from_secs(10),
1947            indexer.wait_until_idle(),
1948        )
1949        .await
1950        .expect("indexer should become idle");
1951
1952        let files = store.get_all_files().await.unwrap();
1953        assert_eq!(files.len(), 2, "only included .txt files should be indexed");
1954        indexer.stop().await.unwrap();
1955    }
1956
1957    #[tokio::test]
1958    async fn test_chunk_config_from_indexer_is_used() {
1959        let temp_dir = tempdir().unwrap();
1960        let file_path = temp_dir.path().join("chunky.txt");
1961        let body = "word ".repeat(80);
1962        std::fs::write(&file_path, body).unwrap();
1963
1964        let store = Arc::new(MockStore::new());
1965        let config = IndexerConfig {
1966            chunk_config: ChunkConfig {
1967                target_size: 8,
1968                max_size: 16,
1969                overlap: 0,
1970                ..Default::default()
1971            },
1972            ..Default::default()
1973        };
1974        let indexer = create_test_indexer_with_config(
1975            Arc::clone(&store) as Arc<dyn VectorStore>,
1976            config,
1977            temp_dir.path(),
1978        );
1979
1980        let chunk_count = indexer.process_single(&file_path).await.unwrap();
1981        assert!(
1982            chunk_count > 1,
1983            "small chunk target should produce multiple chunks, got {chunk_count}"
1984        );
1985    }
1986
1987    #[tokio::test]
1988    async fn test_subscribe_receives_updates() {
1989        let store = Arc::new(MockStore::new());
1990        let indexer = create_test_indexer(
1991            Arc::clone(&store) as Arc<dyn VectorStore>,
1992            Path::new("/tmp"),
1993        );
1994
1995        let mut receiver = indexer.subscribe();
1996
1997        // Note: This test is limited because we can't easily trigger updates
1998        // without starting the full indexer service. The subscribe mechanism
1999        // is tested indirectly through the update_tx.send() calls in process_file.
2000
2001        // Verify we can create a receiver without panicking
2002        assert!(receiver.try_recv().is_err()); // No messages yet
2003    }
2004
2005    #[test]
2006    fn test_index_update_variants() {
2007        // Test that all IndexUpdate variants can be created
2008        let _indexed = IndexUpdate::FileIndexed {
2009            path: PathBuf::from("/test"),
2010            chunk_count: 5,
2011        };
2012
2013        let _removed = IndexUpdate::FileRemoved {
2014            path: PathBuf::from("/test"),
2015        };
2016
2017        let _error = IndexUpdate::FileError {
2018            path: PathBuf::from("/test"),
2019            error: "test error".to_string(),
2020        };
2021
2022        let _started = IndexUpdate::IndexingStarted {
2023            path: PathBuf::from("/test"),
2024        };
2025    }
2026
2027    async fn seed_file(store: &MockStore, path: &Path, content: &str) {
2028        let now = Utc::now();
2029        let file_id = Uuid::new_v4();
2030        let record = FileRecord {
2031            id: file_id,
2032            path: path.to_path_buf(),
2033            size_bytes: content.len() as u64,
2034            mime_type: "text/plain".to_string(),
2035            content_hash: "seeded".to_string(),
2036            modified_at: now,
2037            indexed_at: Some(now),
2038            chunk_count: 1,
2039            status: FileStatus::Indexed,
2040            error_message: None,
2041        };
2042        let chunk = Chunk {
2043            id: Uuid::new_v4(),
2044            file_id,
2045            file_path: path.to_path_buf(),
2046            content: content.to_string(),
2047            content_type: ContentType::Text,
2048            mime_type: Some("text/plain".to_string()),
2049            chunk_index: 0,
2050            byte_range: 0..content.len() as u64,
2051            line_range: None,
2052            parent_chunk_id: None,
2053            depth: 0,
2054            embedding: Some(vec![0.1; TEST_DIM]),
2055            dir_path: String::new(),
2056            dir_depth: 0,
2057            path_components: path
2058                .file_name()
2059                .map(|n| n.to_string_lossy().into_owned())
2060                .unwrap_or_default(),
2061            metadata: ChunkMetadata::default(),
2062        };
2063        store.upsert_file(&record).await.unwrap();
2064        store.upsert_chunks(&[chunk]).await.unwrap();
2065    }
2066
2067    #[tokio::test]
2068    async fn reconcile_removes_missing_but_preserves_existing_and_external() {
2069        let root = tempdir().unwrap();
2070        let outside = tempdir().unwrap();
2071        let missing = root.path().join("removed.txt");
2072        let present = root.path().join("present.txt");
2073        let external = outside.path().join("external.txt");
2074        std::fs::write(&present, "still here").unwrap();
2075        let store = Arc::new(MockStore::new());
2076        for path in [&missing, &present, &external] {
2077            seed_file(&store, path, "indexed text").await;
2078        }
2079        let indexer = create_test_indexer(store.clone(), root.path());
2080        indexer.reconcile_missing_files(false).await.unwrap();
2081        assert!(store.get_file(&missing).await.unwrap().is_some());
2082        indexer.reconcile_missing_files(true).await.unwrap();
2083        assert!(store.get_file(&missing).await.unwrap().is_none());
2084        assert!(
2085            store
2086                .get_chunks_for_file(&missing)
2087                .await
2088                .unwrap()
2089                .is_empty()
2090        );
2091        assert!(store.get_file(&present).await.unwrap().is_some());
2092        assert!(store.get_file(&external).await.unwrap().is_some());
2093    }
2094
2095    #[tokio::test]
2096    async fn reconcile_preserves_records_when_root_is_unavailable() {
2097        let parent = tempdir().unwrap();
2098        let root = parent.path().join("unavailable");
2099        let path = root.join("file.txt");
2100        let store = Arc::new(MockStore::new());
2101        seed_file(&store, &path, "indexed text").await;
2102        create_test_indexer(store.clone(), &root)
2103            .reconcile_missing_files(true)
2104            .await
2105            .unwrap();
2106        assert!(store.get_file(&path).await.unwrap().is_some());
2107    }
2108
2109    #[cfg(unix)]
2110    #[test]
2111    fn reconcile_does_not_follow_symlink_ancestors() {
2112        let root = tempdir().unwrap();
2113        let external = tempdir().unwrap();
2114        std::os::unix::fs::symlink(external.path(), root.path().join("link")).unwrap();
2115        assert!(!confirmed_missing(
2116            root.path(),
2117            &root.path().join("link/missing.txt")
2118        ));
2119        assert!(!confirmed_missing(
2120            root.path(),
2121            &root.path().join("../missing.txt")
2122        ));
2123    }
2124
2125    #[tokio::test]
2126    async fn reconcile_propagates_store_failure() {
2127        let root = tempdir().unwrap();
2128        let store = Arc::new(MockStore {
2129            fail_delete: true,
2130            ..MockStore::new()
2131        });
2132        seed_file(&store, &root.path().join("missing.txt"), "indexed text").await;
2133        assert!(
2134            create_test_indexer(store, root.path())
2135                .reconcile_missing_files(true)
2136                .await
2137                .is_err()
2138        );
2139    }
2140
2141    #[tokio::test]
2142    async fn test_scan_excludes_hidden_secret_and_keeps_visible() {
2143        let temp_dir = tempdir().unwrap();
2144        let root = temp_dir.path();
2145        std::fs::write(root.join("keyboard.md"), "notes keyboard shortcuts").unwrap();
2146        std::fs::write(root.join("server.pem"), "SECRETPEM leaked cert").unwrap();
2147        std::fs::create_dir(root.join(".obsidian")).unwrap();
2148        std::fs::write(root.join(".obsidian").join("x.md"), "obsidian workspace").unwrap();
2149        std::fs::write(root.join(".hidden.md"), "hidden file token").unwrap();
2150        std::fs::create_dir(root.join(".ssh")).unwrap();
2151        std::fs::write(root.join(".ssh").join("id_rsa"), "ssh private key").unwrap();
2152
2153        let store = Arc::new(MockStore::new());
2154        let indexer = create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, root);
2155        indexer.start().await.unwrap();
2156        tokio::time::timeout(
2157            std::time::Duration::from_secs(10),
2158            indexer.wait_until_idle(),
2159        )
2160        .await
2161        .expect("indexer should become idle");
2162
2163        let files = store.get_all_files().await.unwrap();
2164        let paths: Vec<_> = files.iter().map(|f| f.path.clone()).collect();
2165        assert_eq!(files.len(), 1, "only the visible note: {paths:?}");
2166        assert!(paths[0].ends_with("keyboard.md"));
2167        indexer.stop().await.unwrap();
2168    }
2169
2170    #[tokio::test]
2171    async fn test_purge_excluded_on_every_index() {
2172        let temp_dir = tempdir().unwrap();
2173        let root = temp_dir.path();
2174        std::fs::write(root.join("note.md"), "visible note").unwrap();
2175        let secret = root.join("server.pem");
2176        std::fs::write(&secret, "SECRETPEM leaked cert").unwrap();
2177
2178        let store = Arc::new(MockStore::new());
2179        seed_file(&store, &secret, "SECRETPEM leaked cert").await;
2180        assert!(store.get_file(&secret).await.unwrap().is_some());
2181        assert!(!store.get_all_chunks().await.unwrap().is_empty());
2182
2183        let indexer = create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, root);
2184        indexer.start().await.unwrap();
2185        tokio::time::timeout(
2186            std::time::Duration::from_secs(10),
2187            indexer.wait_until_idle(),
2188        )
2189        .await
2190        .expect("indexer should become idle");
2191
2192        assert!(
2193            store.get_file(&secret).await.unwrap().is_none(),
2194            "excluded secret must be purged without --force"
2195        );
2196        assert!(
2197            store
2198                .get_all_chunks()
2199                .await
2200                .unwrap()
2201                .iter()
2202                .all(|c| c.file_path != secret),
2203            "purged secret chunks must be gone"
2204        );
2205        let files = store.get_all_files().await.unwrap();
2206        assert_eq!(files.len(), 1);
2207        assert!(files[0].path.ends_with("note.md"));
2208        indexer.stop().await.unwrap();
2209    }
2210
2211    #[tokio::test]
2212    async fn test_include_hidden_still_blocks_secrets() {
2213        let temp_dir = tempdir().unwrap();
2214        let root = temp_dir.path();
2215        std::fs::write(root.join(".notes.md"), "dotfile content").unwrap();
2216        std::fs::write(root.join("server.pem"), "SECRETPEM leaked cert").unwrap();
2217
2218        let store = Arc::new(MockStore::new());
2219        let config = IndexerConfig {
2220            include_hidden: true,
2221            ..Default::default()
2222        };
2223        let indexer = create_test_indexer_with_config(
2224            Arc::clone(&store) as Arc<dyn VectorStore>,
2225            config,
2226            root,
2227        );
2228        indexer.start().await.unwrap();
2229        tokio::time::timeout(
2230            std::time::Duration::from_secs(10),
2231            indexer.wait_until_idle(),
2232        )
2233        .await
2234        .expect("indexer should become idle");
2235
2236        let files = store.get_all_files().await.unwrap();
2237        let paths: Vec<_> = files.iter().map(|f| f.path.clone()).collect();
2238        assert_eq!(files.len(), 1, "dotfile in, pem out: {paths:?}");
2239        assert!(paths[0].ends_with(".notes.md"));
2240        indexer.stop().await.unwrap();
2241    }
2242
2243    #[tokio::test]
2244    async fn test_hidden_index_root_is_kept() {
2245        let parent = tempdir().unwrap();
2246        let root = parent.path().join(".notes");
2247        std::fs::create_dir(&root).unwrap();
2248        std::fs::write(root.join("todo.md"), "hidden root note").unwrap();
2249        std::fs::create_dir(root.join(".obsidian")).unwrap();
2250        std::fs::write(root.join(".obsidian").join("x.md"), "obsidian").unwrap();
2251
2252        let store = Arc::new(MockStore::new());
2253        let indexer = create_test_indexer(Arc::clone(&store) as Arc<dyn VectorStore>, &root);
2254        indexer.start().await.unwrap();
2255        tokio::time::timeout(
2256            std::time::Duration::from_secs(10),
2257            indexer.wait_until_idle(),
2258        )
2259        .await
2260        .expect("indexer should become idle");
2261
2262        let files = store.get_all_files().await.unwrap();
2263        assert_eq!(files.len(), 1, "hidden root keeps visible children");
2264        assert!(files[0].path.ends_with("todo.md"));
2265        indexer.stop().await.unwrap();
2266    }
2267    #[tokio::test]
2268    async fn failed_purge_aborts_start_before_watching() {
2269        let temp = tempdir().unwrap();
2270        let store = Arc::new(MockStore {
2271            fail_delete: true,
2272            ..MockStore::new()
2273        });
2274        seed_file(&store, &temp.path().join("secrets.md"), "private").await;
2275        let indexer = create_test_indexer(store.clone(), temp.path());
2276        assert!(indexer.start().await.is_err());
2277        assert!(!*indexer.running.read().await);
2278        assert!(indexer.watcher.read().await.is_none());
2279        assert_eq!(store.get_all_files().await.unwrap().len(), 1);
2280    }
2281    #[test]
2282    fn degenerate_chunks_use_unicode_letters_and_decimal_digits() {
2283        for text in ["---", "#", "  \n", "½Ⅷ²"] {
2284            assert!(!chunk_has_content(text, 3));
2285        }
2286        assert!(chunk_has_content("中文啊", 3));
2287        assert!(chunk_has_content("a١2", 3));
2288        assert!(chunk_has_content("", 0));
2289    }
2290    #[test]
2291    fn rootless_config_filter_accepts_relative_visible_paths() {
2292        let config = IndexerConfig::default();
2293        assert!(config.should_process_path(Path::new("notes/keyboard.md")));
2294        assert!(!config.should_process_path(Path::new("notes/server.pem")));
2295    }
2296}
2297
2298#[cfg(test)]
2299mod missing_parent_regression {
2300    #[test]
2301    fn file_replacing_directory_confirms_descendant_missing() {
2302        let root = tempfile::tempdir().unwrap();
2303        std::fs::write(root.path().join("parent"), "replacement").unwrap();
2304        assert!(super::confirmed_missing(
2305            root.path(),
2306            &root.path().join("parent/old.txt")
2307        ));
2308        assert!(!super::confirmed_missing(
2309            root.path(),
2310            &root.path().join("parent")
2311        ));
2312    }
2313}