pleme-codesearch 0.1.142

Fast, local semantic code search powered by Rust — BM25, vector embeddings, tree-sitter AST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::time::SystemTime;

use crate::constants::FILE_META_DB_NAME;

/// Normalize a file path for consistent HashMap lookups.
///
/// On Windows, `Path::canonicalize()` and some APIs add a UNC extended-length
/// prefix (`\\?\C:\...`). Notify (FSW) events may use standard paths (`C:\...`).
/// This function strips the UNC prefix and converts backslashes to forward slashes
/// so that paths from different sources all map to the same key.
pub fn normalize_path(path: &Path) -> String {
    let s = path.to_string_lossy();
    s.trim_start_matches(r"\\?\").replace('\\', "/")
}

/// Normalize a path string (same logic as `normalize_path` but for `&str` input).
pub fn normalize_path_str(path: &str) -> String {
    path.trim_start_matches(r"\\?\").replace('\\', "/")
}

/// Metadata for a single indexed file
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileMeta {
    /// SHA256 hash of file content
    pub hash: String,
    /// File modification time (for quick change detection)
    pub mtime: u64,
    /// File size in bytes
    pub size: u64,
    /// Number of chunks extracted from this file
    pub chunk_count: usize,
    /// Chunk IDs in the vector store (for deletion on update)
    pub chunk_ids: Vec<u32>,
}

/// Persistent store for file metadata - enables incremental indexing
///
/// Improvements over osgrep:
/// 1. Two-level check: mtime first (fast), hash only if mtime changed
/// 2. Tracks chunk IDs for efficient deletion on file update
/// 3. Stores chunk count for statistics
#[derive(Debug, Serialize, Deserialize)]
pub struct FileMetaStore {
    /// Map of absolute file path -> metadata
    files: HashMap<String, FileMeta>,
    /// Model used for indexing (invalidate if model changes)
    pub model_name: String,
    /// Dimensions of embeddings
    pub dimensions: usize,
    /// Last full index timestamp
    pub last_full_index: Option<u64>,
    /// Version for format compatibility
    version: u32,
}

impl FileMetaStore {
    const CURRENT_VERSION: u32 = 1;
    const FILENAME: &'static str = FILE_META_DB_NAME;

    /// Create a new empty store
    pub fn new(model_name: String, dimensions: usize) -> Self {
        Self {
            files: HashMap::new(),
            model_name,
            dimensions,
            last_full_index: None,
            version: Self::CURRENT_VERSION,
        }
    }

    /// Load from database directory, or create new if doesn't exist
    pub fn load_or_create(db_path: &Path, model_name: &str, dimensions: usize) -> Result<Self> {
        let meta_path = db_path.join(Self::FILENAME);

        if meta_path.exists() {
            let content = fs::read_to_string(&meta_path)?;
            let mut store: FileMetaStore = serde_json::from_str(&content)
                .map_err(|e| anyhow!("Failed to parse file metadata: {}", e))?;

            // Check if model changed - if so, invalidate everything
            if store.model_name != model_name || store.dimensions != dimensions {
                println!(
                    "⚠️  Model changed ({} -> {}), full re-index required",
                    store.model_name, model_name
                );
                store = Self::new(model_name.to_string(), dimensions);
            }

            // Migrate stored paths to normalized format (strip UNC prefix, forward slashes).
            // Existing stores may have Windows backslash paths or \\?\ prefixed paths.
            store.migrate_paths();

            Ok(store)
        } else {
            Ok(Self::new(model_name.to_string(), dimensions))
        }
    }

    /// Save to database directory
    pub fn save(&self, db_path: &Path) -> Result<()> {
        let meta_path = db_path.join(Self::FILENAME);
        let content = serde_json::to_string_pretty(self)?;
        fs::write(meta_path, content)?;
        Ok(())
    }

    /// Migrate stored paths to normalized format.
    ///
    /// Existing stores may have Windows backslash paths (`C:\foo\bar.rs`) or
    /// UNC prefixed paths (`\\?\C:\foo\bar.rs`). This re-keys the HashMap
    /// to use the canonical normalized form (forward slashes, no UNC prefix).
    fn migrate_paths(&mut self) {
        let old_files = std::mem::take(&mut self.files);
        let capacity = old_files.len();
        let mut new_files = HashMap::with_capacity(capacity);
        let mut migrated = 0;

        for (old_key, meta) in old_files {
            let new_key = normalize_path_str(&old_key);
            if new_key != old_key {
                migrated += 1;
            }
            new_files.insert(new_key, meta);
        }

        self.files = new_files;

        if migrated > 0 {
            tracing::info!("🔄 Migrated {} file paths to normalized format", migrated);
        }
    }

    /// Compute SHA256 hash of file content
    pub fn compute_hash(path: &Path) -> Result<String> {
        let content = fs::read(path)?;
        let mut hasher = Sha256::new();
        hasher.update(&content);
        Ok(format!("{:x}", hasher.finalize()))
    }

    /// Get file modification time as unix timestamp
    fn get_mtime(path: &Path) -> Result<u64> {
        let metadata = fs::metadata(path)?;
        let mtime = metadata.modified()?;
        Ok(mtime.duration_since(SystemTime::UNIX_EPOCH)?.as_secs())
    }

    /// Check if a file needs re-indexing
    /// Returns: (needs_reindex, existing_chunk_ids_to_delete)
    pub fn check_file(&self, path: &Path) -> Result<(bool, Vec<u32>)> {
        let path_str = normalize_path(path);

        // Get current file stats
        let current_mtime = Self::get_mtime(path)?;
        let current_size = fs::metadata(path)?.len();

        if let Some(meta) = self.files.get(&path_str) {
            // Quick check: if mtime and size unchanged, file is unchanged
            if meta.mtime == current_mtime && meta.size == current_size {
                return Ok((false, vec![]));
            }

            // Mtime changed - compute hash to be sure
            let current_hash = Self::compute_hash(path)?;
            if meta.hash == current_hash {
                // Content same, just update mtime
                return Ok((false, vec![]));
            }

            // File changed - return old chunk IDs for deletion
            Ok((true, meta.chunk_ids.clone()))
        } else {
            // New file
            Ok((true, vec![]))
        }
    }

    /// Update metadata for a file after indexing
    pub fn update_file(&mut self, path: &Path, chunk_ids: Vec<u32>) -> Result<()> {
        let path_str = normalize_path(path);
        let hash = Self::compute_hash(path)?;
        let mtime = Self::get_mtime(path)?;
        let size = fs::metadata(path)?.len();

        self.files.insert(
            path_str,
            FileMeta {
                hash,
                mtime,
                size,
                chunk_count: chunk_ids.len(),
                chunk_ids,
            },
        );

        Ok(())
    }

    /// Mark a file as deleted
    pub fn remove_file(&mut self, path: &Path) -> Option<FileMeta> {
        let path_str = normalize_path(path);
        self.files.remove(&path_str)
    }

    /// Get all tracked files
    #[allow(dead_code)] // Reserved for file listing feature
    pub fn tracked_files(&self) -> impl Iterator<Item = &String> {
        self.files.keys()
    }

    /// Find files that were deleted (exist in store but not on disk)
    pub fn find_deleted_files(&self) -> Vec<(String, Vec<u32>)> {
        self.files
            .iter()
            .filter(|(path, _)| !Path::new(path).exists())
            .map(|(path, meta)| (path.clone(), meta.chunk_ids.clone()))
            .collect()
    }

    /// Get statistics
    #[allow(dead_code)] // Reserved for stats display
    pub fn stats(&self) -> FileMetaStats {
        let total_chunks: usize = self.files.values().map(|m| m.chunk_count).sum();
        let total_size: u64 = self.files.values().map(|m| m.size).sum();

        FileMetaStats {
            total_files: self.files.len(),
            total_chunks,
            total_size_bytes: total_size,
        }
    }

    /// Clear all entries (for full re-index)
    #[allow(dead_code)] // Reserved for index reset
    pub fn clear(&mut self) {
        self.files.clear();
        self.last_full_index = None;
    }

    /// Set last full index time
    pub fn mark_full_index(&mut self) {
        self.last_full_index = Some(
            SystemTime::now()
                .duration_since(SystemTime::UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        );
    }
}

#[derive(Debug)]
#[allow(dead_code)] // Used with stats() method
pub struct FileMetaStats {
    pub total_files: usize,
    pub total_chunks: usize,
    pub total_size_bytes: u64,
}

impl FileMetaStats {
    #[allow(dead_code)] // Reserved for stats display
    pub fn total_size_mb(&self) -> f64 {
        self.total_size_bytes as f64 / (1024.0 * 1024.0)
    }
}

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

    #[test]
    fn test_normalize_path_strips_unc_prefix() {
        let path = Path::new(r"\\?\C:\WorkArea\AI\codesearch\src\main.rs");
        assert_eq!(
            normalize_path(path),
            "C:/WorkArea/AI/codesearch/src/main.rs"
        );
    }

    #[test]
    fn test_normalize_path_converts_backslashes() {
        let path = Path::new(r"C:\WorkArea\AI\codesearch\src\main.rs");
        assert_eq!(
            normalize_path(path),
            "C:/WorkArea/AI/codesearch/src/main.rs"
        );
    }

    #[test]
    fn test_normalize_path_forward_slashes_unchanged() {
        let path = Path::new("C:/WorkArea/AI/codesearch/src/main.rs");
        let result = normalize_path(path);
        // On Windows, Path::new with forward slashes may or may not convert them
        // The important thing is the result is consistent
        assert!(!result.contains('\\'));
        assert!(!result.starts_with(r"\\?\"));
    }

    #[test]
    fn test_normalize_path_str_strips_unc() {
        assert_eq!(normalize_path_str(r"\\?\C:\foo\bar.rs"), "C:/foo/bar.rs");
    }

    #[test]
    fn test_normalize_path_unix_style() {
        // Unix/Linux/macOS paths should remain unchanged
        let path = Path::new("/home/user/project/src/main.rs");
        assert_eq!(normalize_path(path), "/home/user/project/src/main.rs");
    }

    #[test]
    fn test_normalize_path_mixed_separators() {
        // Mixed separators should be normalized to forward slashes
        let path = Path::new(r"C:\Users\project/src/lib.rs");
        assert_eq!(normalize_path(path), "C:/Users/project/src/lib.rs");
    }

    #[test]
    fn test_normalize_path_str_mixed_separators() {
        assert_eq!(
            normalize_path_str(r"C:\Users\project/src/lib.rs"),
            "C:/Users/project/src/lib.rs"
        );
    }

    #[test]
    fn test_normalize_path_already_normalized() {
        // Already normalized paths should remain unchanged
        let path = Path::new("C:/WorkArea/AI/codesearch/src/main.rs");
        assert_eq!(
            normalize_path(path),
            "C:/WorkArea/AI/codesearch/src/main.rs"
        );
    }

    #[test]
    fn test_normalize_path_deeply_nested() {
        // Deeply nested paths
        let path = Path::new(r"\\?\C:\Very\Deep\Nested\Path\To\Some\File.rs");
        assert_eq!(
            normalize_path(path),
            "C:/Very/Deep/Nested/Path/To/Some/File.rs"
        );
    }

    #[test]
    fn test_normalize_path_consecutive_backslashes() {
        // Consecutive backslashes (edge case from file systems)
        let path = Path::new(r"C:\\Double\\Backslashes\\file.rs");
        assert_eq!(normalize_path(path), "C://Double//Backslashes//file.rs");
    }

    #[test]
    fn test_migrate_paths_normalizes_keys() {
        let mut store = FileMetaStore::new("test-model".to_string(), 384);
        // Insert with non-normalized key (simulating old format)
        store.files.insert(
            r"C:\WorkArea\src\main.rs".to_string(),
            FileMeta {
                hash: "abc123".to_string(),
                mtime: 1000,
                size: 100,
                chunk_count: 2,
                chunk_ids: vec![1, 2],
            },
        );
        store.files.insert(
            r"\\?\C:\WorkArea\src\lib.rs".to_string(),
            FileMeta {
                hash: "def456".to_string(),
                mtime: 2000,
                size: 200,
                chunk_count: 3,
                chunk_ids: vec![3, 4, 5],
            },
        );

        store.migrate_paths();

        // Both should be normalized
        assert!(store.files.contains_key("C:/WorkArea/src/main.rs"));
        assert!(store.files.contains_key("C:/WorkArea/src/lib.rs"));
        // Old keys should be gone
        assert!(!store.files.contains_key(r"C:\WorkArea\src\main.rs"));
        assert!(!store.files.contains_key(r"\\?\C:\WorkArea\src\lib.rs"));
    }

    #[test]
    fn test_file_meta_store() {
        let dir = tempdir().unwrap();
        let db_path = dir.path();

        let mut store = FileMetaStore::new("test-model".to_string(), 384);

        // Create a test file
        let test_file = dir.path().join("test.txt");
        fs::write(&test_file, "hello world").unwrap();

        // Check new file
        let (needs_reindex, old_chunks) = store.check_file(&test_file).unwrap();
        assert!(needs_reindex);
        assert!(old_chunks.is_empty());

        // Update metadata
        store.update_file(&test_file, vec![1, 2, 3]).unwrap();

        // Check again - should not need reindex
        let (needs_reindex, _) = store.check_file(&test_file).unwrap();
        assert!(!needs_reindex);

        // Modify file
        fs::write(&test_file, "hello world modified").unwrap();

        // Now should need reindex
        let (needs_reindex, old_chunks) = store.check_file(&test_file).unwrap();
        assert!(needs_reindex);
        assert_eq!(old_chunks, vec![1, 2, 3]);

        // Save and load
        store.save(db_path).unwrap();
        let loaded = FileMetaStore::load_or_create(db_path, "test-model", 384).unwrap();
        assert_eq!(loaded.files.len(), 1);
    }
}