Skip to main content

ragfs_core/
types.rs

1//! Core types for RAGFS.
2//!
3//! This module contains all shared data structures used across RAGFS:
4//!
5//! ## File Management
6//! - [`FileRecord`]: Metadata about an indexed file
7//! - [`FileStatus`]: Current indexing state of a file
8//! - [`FileEvent`]: File system events for the watcher
9//!
10//! ## Content Chunks
11//! - [`Chunk`]: A segment of content with its embedding
12//! - [`ContentType`]: Type classification for chunk content
13//! - [`ChunkConfig`]: Configuration for chunking behavior
14//!
15//! ## Extraction
16//! - [`ExtractedContent`]: Content extracted from a file
17//! - [`ContentElement`]: Structural elements (headings, paragraphs, etc.)
18//!
19//! ## Embeddings
20//! - [`Modality`]: Supported embedding modalities (text, image, audio)
21//! - [`EmbeddingConfig`]: Configuration for embedding generation
22//! - [`EmbeddingOutput`]: Result of embedding a text
23//!
24//! ## Search
25//! - [`SearchQuery`]: Parameters for a vector search
26//! - [`SearchResult`]: A matching chunk with similarity score
27//! - [`SearchFilter`]: Filters to narrow search results
28//! - [`DirectoryScope`]: Relative directory metadata for scoped search
29//! - [`DistanceMetric`]: Vector distance calculation method
30
31use chrono::{DateTime, Utc};
32use serde::{Deserialize, Serialize};
33use std::collections::HashMap;
34use std::ops::Range;
35use std::path::PathBuf;
36use uuid::Uuid;
37
38// ============================================================================
39// File Records
40// ============================================================================
41
42/// Metadata about an indexed file.
43#[derive(Debug, Clone, Serialize, Deserialize)]
44pub struct FileRecord {
45    /// Unique file identifier
46    pub id: Uuid,
47    /// Absolute path to the file
48    pub path: PathBuf,
49    /// File size in bytes
50    pub size_bytes: u64,
51    /// MIME type
52    pub mime_type: String,
53    /// Content hash for change detection (blake3)
54    pub content_hash: String,
55    /// Last modification time
56    pub modified_at: DateTime<Utc>,
57    /// When the file was indexed (None if not yet indexed)
58    pub indexed_at: Option<DateTime<Utc>>,
59    /// Number of chunks produced
60    pub chunk_count: u32,
61    /// Current indexing status
62    pub status: FileStatus,
63    /// Error message if status is Error
64    pub error_message: Option<String>,
65}
66
67/// File indexing status.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "lowercase")]
70pub enum FileStatus {
71    /// Waiting to be indexed
72    Pending,
73    /// Currently being indexed
74    Indexing,
75    /// Successfully indexed
76    Indexed,
77    /// Indexing failed
78    Error,
79    /// File was deleted
80    Deleted,
81}
82
83// ============================================================================
84// Chunks
85// ============================================================================
86
87/// A chunk of content from a file.
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Chunk {
90    /// Unique chunk identifier
91    pub id: Uuid,
92    /// Parent file identifier
93    pub file_id: Uuid,
94    /// Path to the source file
95    pub file_path: PathBuf,
96    /// The actual content
97    pub content: String,
98    /// Type of content
99    pub content_type: ContentType,
100    /// MIME type of the source file
101    pub mime_type: Option<String>,
102    /// Position in file (0-indexed)
103    pub chunk_index: u32,
104    /// Byte range in source file
105    pub byte_range: Range<u64>,
106    /// Line range (if applicable)
107    pub line_range: Option<Range<u32>>,
108    /// Parent chunk ID (for hierarchical chunking)
109    pub parent_chunk_id: Option<Uuid>,
110    /// Depth in hierarchy (0 = root)
111    pub depth: u8,
112    /// Embedding vector (if computed)
113    pub embedding: Option<Vec<f32>>,
114    /// Relative directory of the source file (e.g. `src/auth`). Empty at the index root.
115    pub dir_path: String,
116    /// Number of directory components in `dir_path`.
117    pub dir_depth: u16,
118    /// Comma-separated relative path components, including the filename.
119    pub path_components: String,
120    /// Additional metadata
121    pub metadata: ChunkMetadata,
122}
123
124/// Directory-scope metadata stored on each indexed chunk.
125///
126/// This is a path prefix, not a trie. Search uses exact `dir_path` or a
127/// subdirectory (`src/auth` matches `src/auth` and `src/auth/oauth`).
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
129pub struct DirectoryScope {
130    /// Relative directory containing the file (e.g. `src/auth`).
131    pub dir_path: String,
132    /// Number of directory components in `dir_path`.
133    pub dir_depth: u16,
134    /// Comma-separated relative path components including the filename.
135    pub path_components: String,
136}
137
138impl DirectoryScope {
139    /// Derive scope fields from `file_path`, optionally relative to an index `root`.
140    #[must_use]
141    pub fn from_paths(file_path: &std::path::Path, root: Option<&std::path::Path>) -> Self {
142        let rel = root
143            .and_then(|r| file_path.strip_prefix(r).ok())
144            .unwrap_or(file_path);
145        let parts: Vec<String> = rel
146            .components()
147            .filter_map(|c| match c {
148                std::path::Component::Normal(s) => Some(s.to_string_lossy().into_owned()),
149                _ => None,
150            })
151            .collect();
152
153        let dir_parts = parts.get(..parts.len().saturating_sub(1)).unwrap_or(&[]);
154        let dir_path = dir_parts.join("/");
155        let dir_depth = dir_parts.len() as u16;
156        let path_components = parts.join(",");
157
158        Self {
159            dir_path,
160            dir_depth,
161            path_components,
162        }
163    }
164
165    /// Derive scope from an already-relative or absolute file path (no index root).
166    #[must_use]
167    pub fn from_file_path(file_path: &std::path::Path) -> Self {
168        Self::from_paths(file_path, None)
169    }
170
171    /// Normalize a CLI/query scope (`src/auth/`, `src\\auth` → `src/auth`).
172    #[must_use]
173    pub fn normalize_prefix(scope: &str) -> String {
174        scope.replace('\\', "/").trim_matches('/').to_string()
175    }
176
177    /// Whether this directory is `scope` or a subdirectory of it.
178    #[must_use]
179    pub fn matches_prefix(&self, scope: &str) -> bool {
180        dir_path_matches_scope(&self.dir_path, scope)
181    }
182
183    /// Infer the index root from an absolute file path and its stored relative `dir_path`.
184    #[must_use]
185    pub fn infer_root(file_path: &std::path::Path, dir_path: &str) -> Option<std::path::PathBuf> {
186        let parent = file_path.parent()?;
187        let dir = Self::normalize_prefix(dir_path);
188        if dir.is_empty() {
189            return Some(parent.to_path_buf());
190        }
191        let parent_norm = parent.to_string_lossy().replace('\\', "/");
192        parent_norm
193            .strip_suffix(&dir)
194            .map(|root| std::path::PathBuf::from(root.trim_end_matches('/')))
195    }
196}
197
198/// Match a stored `dir_path` against a scope prefix.
199///
200/// Empty / `.` scope matches everything (no restriction).
201///
202/// Besides an exact directory or a subdirectory (`src/auth` matches
203/// `src/auth/oauth`), a path-component-aligned suffix also matches. That
204/// covers schema-v1 indexes whose `dir_path` was backfilled from an
205/// absolute `file_path` (`project/src/auth` still matches `--scope src/auth`).
206#[must_use]
207pub fn dir_path_matches_scope(dir_path: &str, scope: &str) -> bool {
208    let scope = DirectoryScope::normalize_prefix(scope);
209    if scope.is_empty() || scope == "." {
210        return true;
211    }
212    let dir = DirectoryScope::normalize_prefix(dir_path);
213    dir == scope
214        || dir.starts_with(&format!("{scope}/"))
215        || dir.ends_with(&format!("/{scope}"))
216        || dir.contains(&format!("/{scope}/"))
217}
218
219/// Type of chunk content.
220#[derive(Debug, Clone, Serialize, Deserialize)]
221#[serde(tag = "type", rename_all = "snake_case")]
222pub enum ContentType {
223    /// Plain text content
224    Text,
225    /// Source code
226    Code {
227        /// Programming language
228        language: String,
229        /// Code symbol information
230        symbol: Option<CodeSymbol>,
231    },
232    /// Caption for an image
233    ImageCaption,
234    /// Content from a PDF page
235    PdfPage {
236        /// Page number (1-indexed)
237        page_num: u32,
238    },
239    /// Markdown content
240    Markdown,
241}
242
243/// Code symbol information.
244#[derive(Debug, Clone, Serialize, Deserialize)]
245pub struct CodeSymbol {
246    /// Type of symbol
247    pub kind: SymbolKind,
248    /// Symbol name
249    pub name: String,
250}
251
252/// Types of code symbols.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
254#[serde(rename_all = "snake_case")]
255pub enum SymbolKind {
256    Function,
257    Method,
258    Class,
259    Struct,
260    Enum,
261    Module,
262    Constant,
263    Variable,
264    Interface,
265    Trait,
266}
267
268/// Metadata associated with a chunk.
269#[derive(Debug, Clone, Default, Serialize, Deserialize)]
270pub struct ChunkMetadata {
271    /// Source modality and optional timestamp range. Legacy chunks default to text.
272    #[serde(default)]
273    pub media: MediaInfo,
274    /// Embedding model used
275    pub embedding_model: Option<String>,
276    /// When chunk was indexed
277    pub indexed_at: Option<DateTime<Utc>>,
278    /// Token count (approximate)
279    pub token_count: Option<usize>,
280    /// Additional key-value metadata
281    #[serde(flatten)]
282    pub extra: HashMap<String, String>,
283}
284
285// ============================================================================
286// Extraction
287// ============================================================================
288
289/// Content extracted from a file.
290#[derive(Debug, Clone)]
291pub struct ExtractedContent {
292    /// Main text content
293    pub text: String,
294    /// Structured elements
295    pub elements: Vec<ContentElement>,
296    /// Extracted images
297    pub images: Vec<ExtractedImage>,
298    /// File-level metadata
299    pub metadata: ContentMetadataInfo,
300}
301
302/// A structural element in extracted content.
303#[derive(Debug, Clone)]
304pub enum ContentElement {
305    Heading {
306        level: u8,
307        text: String,
308        byte_offset: u64,
309    },
310    Paragraph {
311        text: String,
312        byte_offset: u64,
313    },
314    CodeBlock {
315        language: Option<String>,
316        code: String,
317        byte_offset: u64,
318    },
319    List {
320        items: Vec<String>,
321        ordered: bool,
322        byte_offset: u64,
323    },
324    Table {
325        headers: Vec<String>,
326        rows: Vec<Vec<String>>,
327        byte_offset: u64,
328    },
329}
330
331/// An image extracted from a document.
332#[derive(Debug, Clone)]
333pub struct ExtractedImage {
334    /// Raw image data
335    pub data: Vec<u8>,
336    /// MIME type
337    pub mime_type: String,
338    /// Caption if available
339    pub caption: Option<String>,
340    /// Page number (for PDFs)
341    pub page: Option<u32>,
342}
343
344/// Metadata extracted from file content.
345#[derive(Debug, Clone, Default)]
346pub struct ContentMetadataInfo {
347    /// Document title
348    pub title: Option<String>,
349    /// Author
350    pub author: Option<String>,
351    /// Language
352    pub language: Option<String>,
353    /// Page count (for PDFs)
354    pub page_count: Option<u32>,
355    /// Creation date
356    pub created_at: Option<DateTime<Utc>>,
357}
358
359// ============================================================================
360// Chunking
361// ============================================================================
362
363/// Configuration for chunking.
364#[derive(Debug, Clone, Serialize, Deserialize)]
365pub struct ChunkConfig {
366    /// Target chunk size in tokens
367    pub target_size: usize,
368    /// Maximum chunk size in tokens
369    pub max_size: usize,
370    /// Overlap between chunks in tokens
371    pub overlap: usize,
372    /// Enable hierarchical chunking
373    pub hierarchical: bool,
374    /// Maximum hierarchy depth
375    pub max_depth: u8,
376}
377
378impl Default for ChunkConfig {
379    fn default() -> Self {
380        Self {
381            target_size: 512,
382            max_size: 1024,
383            overlap: 64,
384            hierarchical: true,
385            max_depth: 2,
386        }
387    }
388}
389
390/// Output from a chunker.
391#[derive(Debug, Clone)]
392pub struct ChunkOutput {
393    /// Chunk content
394    pub content: String,
395    /// Byte range in source
396    pub byte_range: Range<u64>,
397    /// Line range if applicable
398    pub line_range: Option<Range<u32>>,
399    /// Index of parent chunk (in output array)
400    pub parent_index: Option<usize>,
401    /// Depth in hierarchy
402    pub depth: u8,
403    /// Additional metadata
404    pub metadata: ChunkOutputMetadata,
405}
406
407/// Metadata for chunk output.
408#[derive(Debug, Clone, Default)]
409pub struct ChunkOutputMetadata {
410    /// Symbol type (for code)
411    pub symbol_type: Option<String>,
412    /// Symbol name (for code)
413    pub symbol_name: Option<String>,
414    /// Programming language
415    pub language: Option<String>,
416}
417
418// ============================================================================
419// Embedding
420// ============================================================================
421
422/// Supported modalities for embedding.
423#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
424#[serde(rename_all = "lowercase")]
425pub enum Modality {
426    Text,
427    Image,
428    Audio,
429}
430
431/// Source-media location, independent of the embedding modality (all caption,
432/// OCR and transcript chunks still use the text embedding space).
433#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
434#[serde(default)]
435pub struct MediaInfo {
436    pub modality: String,
437    pub start_ms: Option<u64>,
438    pub end_ms: Option<u64>,
439}
440
441impl Default for MediaInfo {
442    fn default() -> Self {
443        Self {
444            modality: "text".into(),
445            start_ms: None,
446            end_ms: None,
447        }
448    }
449}
450
451impl MediaInfo {
452    pub fn validate(&self) -> std::result::Result<(), String> {
453        if !matches!(self.modality.as_str(), "text" | "image" | "audio" | "video") {
454            return Err("Unsupported source modality".into());
455        }
456        match (self.start_ms, self.end_ms) {
457            (None, None) => Ok(()),
458            (Some(start), Some(end)) if end >= start => Ok(()),
459            _ => Err("Media range requires start_ms <= end_ms, or both null".into()),
460        }
461    }
462
463    pub fn from_metadata(metadata: &HashMap<String, String>) -> std::result::Result<Self, String> {
464        let time = |key: &str| {
465            metadata
466                .get(key)
467                .map(|v| v.parse::<u64>().map_err(|_| format!("Invalid {key}")))
468                .transpose()
469        };
470        let media = Self {
471            modality: metadata
472                .get("modality")
473                .cloned()
474                .unwrap_or_else(|| "text".into()),
475            start_ms: time("start_ms")?,
476            end_ms: time("end_ms")?,
477        };
478        media.validate()?;
479        Ok(media)
480    }
481
482    pub fn write_metadata(&self, metadata: &mut HashMap<String, String>) {
483        metadata.remove("start_ms");
484        metadata.remove("end_ms");
485        metadata.insert("modality".into(), self.modality.clone());
486        if let (Some(start), Some(end)) = (self.start_ms, self.end_ms) {
487            metadata.insert("start_ms".into(), start.to_string());
488            metadata.insert("end_ms".into(), end.to_string());
489        }
490    }
491}
492
493/// Configuration for embedding.
494#[derive(Debug, Clone, Serialize, Deserialize)]
495pub struct EmbeddingConfig {
496    /// Normalize embeddings to unit length
497    pub normalize: bool,
498    /// Instruction prefix for models that support it
499    pub instruction: Option<String>,
500    /// Batch size for processing
501    pub batch_size: usize,
502}
503
504impl Default for EmbeddingConfig {
505    fn default() -> Self {
506        Self {
507            normalize: true,
508            instruction: None,
509            batch_size: 32,
510        }
511    }
512}
513
514/// Output from embedding.
515#[derive(Debug, Clone)]
516pub struct EmbeddingOutput {
517    /// The embedding vector
518    pub embedding: Vec<f32>,
519    /// Number of tokens in input
520    pub token_count: usize,
521}
522
523// ============================================================================
524// Search
525// ============================================================================
526
527/// A search query.
528#[derive(Debug, Clone)]
529pub struct SearchQuery {
530    /// Query embedding
531    pub embedding: Vec<f32>,
532    /// Optional text for hybrid search
533    pub text: Option<String>,
534    /// Maximum results to return
535    pub limit: usize,
536    /// Search filters
537    pub filters: Vec<SearchFilter>,
538    /// Distance metric
539    pub metric: DistanceMetric,
540    /// Optional directory scope, relative to the index root.
541    ///
542    /// When set, only chunks whose `dir_path` is this directory or a
543    /// subdirectory are considered. Applied as a filter alongside ANN.
544    pub scope_prefix: Option<String>,
545}
546
547/// Search filters.
548#[derive(Debug, Clone)]
549pub enum SearchFilter {
550    /// Match files with path prefix
551    PathPrefix(String),
552    /// Match files by glob pattern
553    PathGlob(String),
554    /// Match by MIME type
555    MimeType(String),
556    /// Match by programming language
557    Language(String),
558    /// Files modified after date
559    ModifiedAfter(DateTime<Utc>),
560    /// Files modified before date
561    ModifiedBefore(DateTime<Utc>),
562    /// Minimum hierarchy depth
563    MinDepth(u8),
564    /// Maximum hierarchy depth
565    MaxDepth(u8),
566}
567
568/// Distance metric for vector search.
569#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
570#[serde(rename_all = "lowercase")]
571pub enum DistanceMetric {
572    #[default]
573    Cosine,
574    L2,
575    Dot,
576}
577
578/// A search result.
579#[derive(Debug, Clone, Serialize, Deserialize)]
580pub struct SearchResult {
581    /// Additive media location; defaults to text for legacy results.
582    #[serde(default, flatten)]
583    pub media: MediaInfo,
584    /// Chunk ID
585    pub chunk_id: Uuid,
586    /// File path
587    pub file_path: PathBuf,
588    /// Chunk content
589    pub content: String,
590    /// Similarity score
591    pub score: f32,
592    /// Byte range in file
593    pub byte_range: Range<u64>,
594    /// Line range if available
595    pub line_range: Option<Range<u32>>,
596    /// Additional metadata
597    pub metadata: HashMap<String, String>,
598}
599
600/// Vector store statistics.
601#[derive(Debug, Clone, Serialize, Deserialize)]
602pub struct StoreStats {
603    /// Total number of chunks
604    pub total_chunks: u64,
605    /// Total number of files
606    pub total_files: u64,
607    /// Index size in bytes
608    pub index_size_bytes: u64,
609    /// Last update time
610    pub last_updated: Option<DateTime<Utc>>,
611    /// Monotonic index revision. Changes on add/update/delete/reindex, not on reads.
612    ///
613    /// `0` only appears on backends that have not assigned a revision yet.
614    #[serde(default)]
615    pub index_revision: u64,
616}
617
618// ============================================================================
619// Index Status
620// ============================================================================
621
622/// Overall index statistics.
623#[derive(Debug, Clone, Default, Serialize, Deserialize)]
624pub struct IndexStats {
625    /// Total files tracked
626    pub total_files: u64,
627    /// Successfully indexed files
628    pub indexed_files: u64,
629    /// Files pending indexing
630    pub pending_files: u64,
631    /// Files with errors
632    pub error_files: u64,
633    /// Total chunks stored
634    pub total_chunks: u64,
635    /// Last update time
636    pub last_update: Option<DateTime<Utc>>,
637}
638
639// ============================================================================
640// File Events
641// ============================================================================
642
643/// File system event for indexing.
644#[derive(Debug, Clone)]
645pub enum FileEvent {
646    Created(PathBuf),
647    Modified(PathBuf),
648    Deleted(PathBuf),
649    Renamed { from: PathBuf, to: PathBuf },
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    // ==================== FileRecord Tests ====================
657
658    #[test]
659    fn test_file_record_serialization() {
660        let record = FileRecord {
661            id: Uuid::new_v4(),
662            path: PathBuf::from("/test/file.txt"),
663            size_bytes: 1024,
664            mime_type: "text/plain".to_string(),
665            content_hash: "abc123".to_string(),
666            modified_at: Utc::now(),
667            indexed_at: Some(Utc::now()),
668            chunk_count: 5,
669            status: FileStatus::Indexed,
670            error_message: None,
671        };
672
673        let json = serde_json::to_string(&record).unwrap();
674        let deserialized: FileRecord = serde_json::from_str(&json).unwrap();
675
676        assert_eq!(record.id, deserialized.id);
677        assert_eq!(record.path, deserialized.path);
678        assert_eq!(record.size_bytes, deserialized.size_bytes);
679        assert_eq!(record.status, deserialized.status);
680    }
681
682    #[test]
683    fn test_file_status_serialization() {
684        assert_eq!(
685            serde_json::to_string(&FileStatus::Pending).unwrap(),
686            "\"pending\""
687        );
688        assert_eq!(
689            serde_json::to_string(&FileStatus::Indexed).unwrap(),
690            "\"indexed\""
691        );
692        assert_eq!(
693            serde_json::to_string(&FileStatus::Error).unwrap(),
694            "\"error\""
695        );
696    }
697
698    #[test]
699    fn test_file_status_equality() {
700        assert_eq!(FileStatus::Pending, FileStatus::Pending);
701        assert_ne!(FileStatus::Pending, FileStatus::Indexed);
702    }
703
704    // ==================== Chunk Tests ====================
705
706    #[test]
707    fn test_chunk_serialization() {
708        let chunk = Chunk {
709            id: Uuid::new_v4(),
710            file_id: Uuid::new_v4(),
711            file_path: PathBuf::from("/test/file.rs"),
712            content: "fn main() {}".to_string(),
713            content_type: ContentType::Code {
714                language: "rust".to_string(),
715                symbol: Some(CodeSymbol {
716                    kind: SymbolKind::Function,
717                    name: "main".to_string(),
718                }),
719            },
720            mime_type: Some("text/x-rust".to_string()),
721            chunk_index: 0,
722            byte_range: 0..12,
723            line_range: Some(0..1),
724            parent_chunk_id: None,
725            depth: 0,
726            embedding: None,
727            dir_path: "test".to_string(),
728            dir_depth: 1,
729            path_components: "test,file.rs".to_string(),
730            metadata: ChunkMetadata::default(),
731        };
732
733        let json = serde_json::to_string(&chunk).unwrap();
734        let deserialized: Chunk = serde_json::from_str(&json).unwrap();
735
736        assert_eq!(chunk.id, deserialized.id);
737        assert_eq!(chunk.content, deserialized.content);
738    }
739
740    #[test]
741    fn test_content_type_text() {
742        let ct = ContentType::Text;
743        let json = serde_json::to_string(&ct).unwrap();
744        assert!(json.contains("\"type\":\"text\""));
745    }
746
747    #[test]
748    fn test_content_type_code() {
749        let ct = ContentType::Code {
750            language: "python".to_string(),
751            symbol: None,
752        };
753        let json = serde_json::to_string(&ct).unwrap();
754        assert!(json.contains("\"type\":\"code\""));
755        assert!(json.contains("\"language\":\"python\""));
756    }
757
758    #[test]
759    fn test_content_type_pdf_page() {
760        let ct = ContentType::PdfPage { page_num: 5 };
761        let json = serde_json::to_string(&ct).unwrap();
762        assert!(json.contains("\"type\":\"pdf_page\""));
763        assert!(json.contains("\"page_num\":5"));
764    }
765
766    #[test]
767    fn test_content_type_markdown() {
768        let ct = ContentType::Markdown;
769        let json = serde_json::to_string(&ct).unwrap();
770        assert!(json.contains("\"type\":\"markdown\""));
771    }
772
773    #[test]
774    fn test_symbol_kind_serialization() {
775        assert_eq!(
776            serde_json::to_string(&SymbolKind::Function).unwrap(),
777            "\"function\""
778        );
779        assert_eq!(
780            serde_json::to_string(&SymbolKind::Struct).unwrap(),
781            "\"struct\""
782        );
783        assert_eq!(
784            serde_json::to_string(&SymbolKind::Trait).unwrap(),
785            "\"trait\""
786        );
787    }
788
789    // ==================== ChunkConfig Tests ====================
790
791    #[test]
792    fn test_chunk_config_default() {
793        let config = ChunkConfig::default();
794        assert_eq!(config.target_size, 512);
795        assert_eq!(config.max_size, 1024);
796        assert_eq!(config.overlap, 64);
797        assert!(config.hierarchical);
798        assert_eq!(config.max_depth, 2);
799    }
800
801    #[test]
802    fn test_chunk_config_serialization() {
803        let config = ChunkConfig::default();
804        let json = serde_json::to_string(&config).unwrap();
805        let deserialized: ChunkConfig = serde_json::from_str(&json).unwrap();
806
807        assert_eq!(config.target_size, deserialized.target_size);
808        assert_eq!(config.max_size, deserialized.max_size);
809    }
810
811    // ==================== EmbeddingConfig Tests ====================
812
813    #[test]
814    fn test_embedding_config_default() {
815        let config = EmbeddingConfig::default();
816        assert!(config.normalize);
817        assert!(config.instruction.is_none());
818        assert_eq!(config.batch_size, 32);
819    }
820
821    #[test]
822    fn test_embedding_config_serialization() {
823        let config = EmbeddingConfig {
824            normalize: false,
825            instruction: Some("Search: ".to_string()),
826            batch_size: 16,
827        };
828        let json = serde_json::to_string(&config).unwrap();
829        let deserialized: EmbeddingConfig = serde_json::from_str(&json).unwrap();
830
831        assert_eq!(config.normalize, deserialized.normalize);
832        assert_eq!(config.instruction, deserialized.instruction);
833        assert_eq!(config.batch_size, deserialized.batch_size);
834    }
835
836    // ==================== Modality Tests ====================
837
838    #[test]
839    fn test_modality_serialization() {
840        assert_eq!(serde_json::to_string(&Modality::Text).unwrap(), "\"text\"");
841        assert_eq!(
842            serde_json::to_string(&Modality::Image).unwrap(),
843            "\"image\""
844        );
845        assert_eq!(
846            serde_json::to_string(&Modality::Audio).unwrap(),
847            "\"audio\""
848        );
849    }
850
851    #[test]
852    fn test_modality_equality() {
853        assert_eq!(Modality::Text, Modality::Text);
854        assert_ne!(Modality::Text, Modality::Image);
855    }
856
857    // ==================== DistanceMetric Tests ====================
858
859    #[test]
860    fn test_distance_metric_default() {
861        let metric = DistanceMetric::default();
862        assert_eq!(metric, DistanceMetric::Cosine);
863    }
864
865    #[test]
866    fn test_distance_metric_serialization() {
867        assert_eq!(
868            serde_json::to_string(&DistanceMetric::Cosine).unwrap(),
869            "\"cosine\""
870        );
871        assert_eq!(
872            serde_json::to_string(&DistanceMetric::L2).unwrap(),
873            "\"l2\""
874        );
875        assert_eq!(
876            serde_json::to_string(&DistanceMetric::Dot).unwrap(),
877            "\"dot\""
878        );
879    }
880
881    // ==================== SearchResult Tests ====================
882
883    #[test]
884    fn test_search_result_serialization() {
885        let result = SearchResult {
886            media: Default::default(),
887            chunk_id: Uuid::new_v4(),
888            file_path: PathBuf::from("/test/file.txt"),
889            content: "Test content".to_string(),
890            score: 0.95,
891            byte_range: 0..12,
892            line_range: Some(0..1),
893            metadata: HashMap::new(),
894        };
895
896        let json = serde_json::to_string(&result).unwrap();
897        let deserialized: SearchResult = serde_json::from_str(&json).unwrap();
898
899        assert_eq!(result.chunk_id, deserialized.chunk_id);
900        assert_eq!(result.score, deserialized.score);
901        assert_eq!(result.content, deserialized.content);
902    }
903
904    // ==================== StoreStats Tests ====================
905
906    #[test]
907    fn test_store_stats_serialization() {
908        let stats = StoreStats {
909            total_chunks: 100,
910            total_files: 10,
911            index_size_bytes: 1024 * 1024,
912            last_updated: Some(Utc::now()),
913            index_revision: 4,
914        };
915
916        let json = serde_json::to_string(&stats).unwrap();
917        let deserialized: StoreStats = serde_json::from_str(&json).unwrap();
918
919        assert_eq!(stats.total_chunks, deserialized.total_chunks);
920        assert_eq!(stats.total_files, deserialized.total_files);
921        assert_eq!(stats.index_revision, deserialized.index_revision);
922    }
923
924    #[test]
925    fn old_store_stats_json_defaults_revision() {
926        let deserialized: StoreStats = serde_json::from_str(
927            r#"{"total_chunks":1,"total_files":1,"index_size_bytes":0,"last_updated":null}"#,
928        )
929        .unwrap();
930        assert_eq!(deserialized.index_revision, 0);
931    }
932
933    // ==================== IndexStats Tests ====================
934
935    #[test]
936    fn test_index_stats_default() {
937        let stats = IndexStats::default();
938        assert_eq!(stats.total_files, 0);
939        assert_eq!(stats.indexed_files, 0);
940        assert_eq!(stats.pending_files, 0);
941        assert_eq!(stats.error_files, 0);
942        assert_eq!(stats.total_chunks, 0);
943        assert!(stats.last_update.is_none());
944    }
945
946    #[test]
947    fn test_index_stats_serialization() {
948        let stats = IndexStats {
949            total_files: 50,
950            indexed_files: 45,
951            pending_files: 3,
952            error_files: 2,
953            total_chunks: 500,
954            last_update: Some(Utc::now()),
955        };
956
957        let json = serde_json::to_string(&stats).unwrap();
958        let deserialized: IndexStats = serde_json::from_str(&json).unwrap();
959
960        assert_eq!(stats.total_files, deserialized.total_files);
961        assert_eq!(stats.indexed_files, deserialized.indexed_files);
962    }
963
964    // ==================== ChunkMetadata Tests ====================
965
966    #[test]
967    fn test_chunk_metadata_default() {
968        let meta = ChunkMetadata::default();
969        assert!(meta.embedding_model.is_none());
970        assert!(meta.indexed_at.is_none());
971        assert!(meta.token_count.is_none());
972        assert!(meta.extra.is_empty());
973    }
974
975    // ==================== ChunkOutput Tests ====================
976
977    #[test]
978    fn test_chunk_output_metadata_default() {
979        let meta = ChunkOutputMetadata::default();
980        assert!(meta.symbol_type.is_none());
981        assert!(meta.symbol_name.is_none());
982        assert!(meta.language.is_none());
983    }
984
985    // ==================== ContentMetadataInfo Tests ====================
986
987    #[test]
988    fn test_content_metadata_info_default() {
989        let meta = ContentMetadataInfo::default();
990        assert!(meta.title.is_none());
991        assert!(meta.author.is_none());
992        assert!(meta.language.is_none());
993        assert!(meta.page_count.is_none());
994        assert!(meta.created_at.is_none());
995    }
996
997    // ==================== DirectoryScope Tests ====================
998
999    #[test]
1000    fn test_directory_scope_is_relative_to_root() {
1001        let root = PathBuf::from("/project");
1002        let file = PathBuf::from("/project/src/auth/login.rs");
1003        let scope = DirectoryScope::from_paths(&file, Some(&root));
1004
1005        assert_eq!(scope.dir_path, "src/auth");
1006        assert_eq!(scope.dir_depth, 2);
1007        assert_eq!(scope.path_components, "src,auth,login.rs");
1008    }
1009
1010    #[test]
1011    fn test_directory_scope_index_root_file() {
1012        let root = PathBuf::from("/project");
1013        let file = PathBuf::from("/project/README.md");
1014        let scope = DirectoryScope::from_paths(&file, Some(&root));
1015
1016        assert_eq!(scope.dir_path, "");
1017        assert_eq!(scope.dir_depth, 0);
1018        assert_eq!(scope.path_components, "README.md");
1019    }
1020
1021    #[test]
1022    fn test_directory_scope_without_root_strips_only_prefix_components() {
1023        let file = PathBuf::from("/test/file.rs");
1024        let scope = DirectoryScope::from_file_path(&file);
1025        assert_eq!(scope.dir_path, "test");
1026        assert_eq!(scope.path_components, "test,file.rs");
1027    }
1028
1029    #[test]
1030    fn test_dir_path_matches_scope_exact_and_subdirectory() {
1031        assert!(dir_path_matches_scope("src/auth", "src/auth"));
1032        assert!(dir_path_matches_scope("src/auth/oauth", "src/auth"));
1033        assert!(dir_path_matches_scope("src/auth", "src/auth/"));
1034        assert!(!dir_path_matches_scope("src/other", "src/auth"));
1035        assert!(!dir_path_matches_scope("src/auth-backup", "src/auth"));
1036        assert!(dir_path_matches_scope("src", ""));
1037        assert!(dir_path_matches_scope("src", "."));
1038    }
1039
1040    #[test]
1041    fn test_dir_path_matches_scope_migrated_absolute_suffix() {
1042        // from_file_path("/project/src/auth/login.rs") → "project/src/auth"
1043        assert!(dir_path_matches_scope("project/src/auth", "src/auth"));
1044        assert!(dir_path_matches_scope("project/src/auth/oauth", "src/auth"));
1045        assert!(dir_path_matches_scope("project/src", "src"));
1046        assert!(dir_path_matches_scope("project/src/auth", "src"));
1047        assert!(!dir_path_matches_scope("project/src-backup", "src"));
1048        assert!(!dir_path_matches_scope("project/other", "src/auth"));
1049        assert!(!dir_path_matches_scope("project/author/notes", "auth"));
1050    }
1051
1052    // ==================== FileEvent Tests ====================
1053
1054    #[test]
1055    fn test_file_event_created() {
1056        let event = FileEvent::Created(PathBuf::from("/test/new.txt"));
1057        match event {
1058            FileEvent::Created(path) => assert_eq!(path, PathBuf::from("/test/new.txt")),
1059            _ => panic!("Expected Created event"),
1060        }
1061    }
1062
1063    #[test]
1064    fn test_file_event_modified() {
1065        let event = FileEvent::Modified(PathBuf::from("/test/changed.txt"));
1066        match event {
1067            FileEvent::Modified(path) => assert_eq!(path, PathBuf::from("/test/changed.txt")),
1068            _ => panic!("Expected Modified event"),
1069        }
1070    }
1071
1072    #[test]
1073    fn test_file_event_deleted() {
1074        let event = FileEvent::Deleted(PathBuf::from("/test/removed.txt"));
1075        match event {
1076            FileEvent::Deleted(path) => assert_eq!(path, PathBuf::from("/test/removed.txt")),
1077            _ => panic!("Expected Deleted event"),
1078        }
1079    }
1080
1081    #[test]
1082    fn test_file_event_renamed() {
1083        let event = FileEvent::Renamed {
1084            from: PathBuf::from("/test/old.txt"),
1085            to: PathBuf::from("/test/new.txt"),
1086        };
1087        match event {
1088            FileEvent::Renamed { from, to } => {
1089                assert_eq!(from, PathBuf::from("/test/old.txt"));
1090                assert_eq!(to, PathBuf::from("/test/new.txt"));
1091            }
1092            _ => panic!("Expected Renamed event"),
1093        }
1094    }
1095}
1096
1097#[cfg(test)]
1098mod media_tests {
1099    use super::*;
1100    #[test]
1101    fn legacy_media_defaults_and_ranges_are_validated() {
1102        assert_eq!(
1103            serde_json::from_str::<MediaInfo>("{}").unwrap(),
1104            MediaInfo::default()
1105        );
1106        let mut metadata = HashMap::from([
1107            ("modality".into(), "audio".into()),
1108            ("start_ms".into(), "10".into()),
1109            ("end_ms".into(), "20".into()),
1110        ]);
1111        let media = MediaInfo::from_metadata(&metadata).unwrap();
1112        assert_eq!(media.start_ms, Some(10));
1113        metadata.insert("end_ms".into(), "9".into());
1114        assert!(MediaInfo::from_metadata(&metadata).is_err());
1115        metadata.remove("end_ms");
1116        assert!(MediaInfo::from_metadata(&metadata).is_err());
1117        MediaInfo::default().write_metadata(&mut metadata);
1118        assert_eq!(
1119            MediaInfo::from_metadata(&metadata).unwrap(),
1120            MediaInfo::default()
1121        );
1122    }
1123}