leindex 1.6.1

LeIndex MCP and semantic code search engine for AI tools and large codebases
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! Unique Project Identification
//!
//! *L'Identifiant Unique* (Unique ID) - Deterministic project identification using BLAKE3 path hashing

use blake3;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Unique project identifier with conflict resolution via instance counter
///
/// Each project gets a deterministic ID based on:
/// - `base_name`: The directory name of the project
/// - `path_hash`: First 8 hex characters of BLAKE3 hash of canonical path
/// - `instance`: Counter starting at 0, incremented for path conflicts
///
/// Format: `<base_name>_<path_hash[:8]>_<instance>`
///
/// # Example
///
/// ```
/// use leindex::storage::UniqueProjectId;
/// use std::path::Path;
///
/// // Original project
/// let path = Path::new("/home/user/projects/leindex");
/// let id = UniqueProjectId::generate(&path, &[]);
/// assert!(id.as_unique_string().starts_with("leindex_"));
/// assert!(id.as_unique_string().ends_with("_0"));
///
/// // Clone at different path (different base_name due to directory name)
/// let clone_path = Path::new("/home/user/projects/leindex-copy");
/// let clone_id = UniqueProjectId::generate(&clone_path, &[id.clone()]);
/// assert!(clone_id.as_unique_string().starts_with("leindex-copy_"));
/// assert!(clone_id.instance == 0); // different base_name means no conflict
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UniqueProjectId {
    /// Base name extracted from project directory name
    pub base_name: String,

    /// First 8 hex characters of BLAKE3 hash of canonical path
    pub path_hash: String,

    /// Instance counter (0 for original, incremented for clones)
    pub instance: u32,
}

impl UniqueProjectId {
    /// Character length of path hash (BLAKE3 is 256-bit = 64 hex chars, we use first 8)
    const HASH_LEN: usize = 8;

    /// Create a new UniqueProjectId from components
    ///
    /// # Arguments
    ///
    /// * `base_name` - Project directory name
    /// * `path_hash` - First 8 hex chars of BLAKE3 hash
    /// * `instance` - Instance counter (0 for original)
    #[must_use]
    pub fn new(base_name: String, path_hash: String, instance: u32) -> Self {
        Self {
            base_name,
            path_hash,
            instance,
        }
    }

    /// Generate a unique project ID for the given path
    ///
    /// This method:
    /// 1. Extracts base_name from directory name
    /// 2. Computes BLAKE3 hash of canonical path
    /// 3. Checks for conflicts with existing IDs
    /// 4. Returns appropriate instance number
    ///
    /// # Arguments
    ///
    /// * `project_path` - Path to the project directory
    /// * `existing_ids` - List of existing project IDs to check for conflicts
    ///
    /// # Returns
    ///
    /// A new `UniqueProjectId` with appropriate instance number
    ///
    /// # Example
    ///
    /// ```
    /// use leindex::storage::UniqueProjectId;
    /// use std::path::Path;
    ///
    /// let path = Path::new("/home/user/projects/leindex");
    /// let id = UniqueProjectId::generate(&path, &[]);
    /// assert_eq!(id.instance, 0);
    /// assert_eq!(id.base_name, "leindex");
    /// ```
    #[must_use]
    pub fn generate(project_path: &Path, existing_ids: &[UniqueProjectId]) -> Self {
        // Extract base name from directory
        let base_name = project_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown")
            .to_string();

        // Get canonical path for hashing
        let canonical_path = project_path
            .canonicalize()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|_| project_path.to_string_lossy().to_string());

        // Compute BLAKE3 hash
        let path_hash = Self::hash_path(&canonical_path);

        // Check for conflicts (same base_name + path_hash combination)
        // In practice, path_hash should be unique due to canonical path,
        // but we handle edge cases like symlinks to same directory
        let instance = Self::find_next_instance(&base_name, existing_ids);

        Self {
            base_name,
            path_hash,
            instance,
        }
    }

    /// Compute BLAKE3 hash of path and return first 8 hex characters
    ///
    /// # Arguments
    ///
    /// * `path` - Path string to hash
    ///
    /// # Returns
    ///
    /// First 8 hex characters of BLAKE3 hash
    #[must_use]
    fn hash_path(path: &str) -> String {
        let hash = blake3::hash(path.as_bytes());
        hash.to_hex()[..Self::HASH_LEN].to_string()
    }

    /// Find the next available instance number for a given base_name
    ///
    /// Scans existing IDs with same base_name and returns max(instance) + 1
    ///
    /// # Arguments
    ///
    /// * `base_name` - Base name to check for conflicts
    /// * `existing_ids` - List of existing project IDs
    ///
    /// # Returns
    ///
    /// Next available instance number (0 if no conflicts)
    #[must_use]
    fn find_next_instance(base_name: &str, existing_ids: &[UniqueProjectId]) -> u32 {
        existing_ids
            .iter()
            .filter(|id| id.base_name == base_name)
            .map(|id| id.instance)
            .max()
            .map(|max| max + 1)
            .unwrap_or(0)
    }

    /// Convert to full string representation
    ///
    /// Format: `<base_name>_<path_hash[:8]>_<instance>`
    ///
    /// # Example
    ///
    /// ```
    /// use leindex::storage::UniqueProjectId;
    ///
    /// let id = UniqueProjectId::new(
    ///     "leindex".to_string(),
    ///     "a3f7d9e2".to_string(),
    ///     0
    /// );
    /// assert_eq!(id.as_unique_string(), "leindex_a3f7d9e2_0");
    /// ```
    #[must_use]
    pub fn as_unique_string(&self) -> String {
        format!("{}_{}_{}", self.base_name, self.path_hash, self.instance)
    }

    /// User-friendly display name with clone indicator
    ///
    /// Format:
    /// - Original (instance=0): `<base_name>`
    /// - Clone (instance>0): `<base_name> (clone #<instance>)`
    ///
    /// # Example
    ///
    /// ```
    /// use leindex::storage::UniqueProjectId;
    ///
    /// let original = UniqueProjectId::new(
    ///     "leindex".to_string(),
    ///     "a3f7d9e2".to_string(),
    ///     0
    /// );
    /// assert_eq!(original.display(), "leindex");
    ///
    /// let clone = UniqueProjectId::new(
    ///     "leindex".to_string(),
    ///     "b4e8f1a3".to_string(),
    ///     1
    /// );
    /// assert_eq!(clone.display(), "leindex (clone #1)");
    /// ```
    #[must_use]
    pub fn display(&self) -> String {
        if self.instance == 0 {
            self.base_name.clone()
        } else {
            format!("{} (clone #{})", self.base_name, self.instance)
        }
    }

    /// Parse a unique project ID from its string representation
    ///
    /// # Arguments
    ///
    /// * `s` - String in format `<base_name>_<path_hash>_<instance>`
    ///
    /// # Returns
    ///
    /// `Option<UniqueProjectId>` - None if format is invalid
    ///
    /// # Example
    ///
    /// ```
    /// use leindex::storage::UniqueProjectId;
    ///
    /// let id = UniqueProjectId::parse_id("leindex_a3f7d9e2_0");
    /// assert!(id.is_some());
    /// assert_eq!(id.unwrap().base_name, "leindex");
    /// ```
    #[must_use]
    pub fn parse_id(s: &str) -> Option<Self> {
        let parts: Vec<&str> = s.rsplitn(3, '_').collect();
        if parts.len() != 3 {
            return None;
        }

        let instance = parts[0].parse().ok()?;
        let path_hash = parts[1].to_string();
        let base_name = parts[2].to_string();

        // Validate hash is 8 hex chars
        if path_hash.len() != Self::HASH_LEN || !path_hash.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }

        Some(Self {
            base_name,
            path_hash,
            instance,
        })
    }

    /// Parse a unique project ID from its string representation (compatibility alias)
    ///
    /// This method is a compatibility shim for the 1.x API. It delegates to `parse_id`.
    ///
    /// # Arguments
    ///
    /// * `s` - String in format `<base_name>_<path_hash>_<instance>`
    ///
    /// # Returns
    ///
    /// `Option<UniqueProjectId>` - None if format is invalid
    ///
    /// # Example
    ///
    /// ```
    /// use leindex::storage::UniqueProjectId;
    ///
    /// let id = UniqueProjectId::from_str_compat("leindex_a3f7d9e2_0");
    /// assert!(id.is_some());
    /// assert_eq!(id.unwrap().base_name, "leindex");
    /// ```
    #[must_use]
    #[inline(always)]
    pub fn from_str_compat(s: &str) -> Option<Self> {
        Self::parse_id(s)
    }

    /// Parse a unique project ID from its string representation (backward compatibility)
    ///
    /// This is an alias for `from_str_compat` to preserve the 1.x API surface.
    /// Downstream crates using `UniqueProjectId::from_str()` will continue to work.
    ///
    /// # Deprecated
    ///
    /// This method is deprecated in favor of `parse_id`. Use `parse_id` for new code.
    ///
    /// # Arguments
    ///
    /// * `s` - String in format `<base_name>_<path_hash>_<instance>`
    ///
    /// # Returns
    ///
    /// `Option<UniqueProjectId>` - None if format is invalid
    #[deprecated(since = "1.6.0", note = "Use `parse_id` instead")]
    #[must_use]
    #[inline(always)]
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(s: &str) -> Option<Self> {
        Self::parse_id(s)
    }

    /// Check if this ID represents a clone (instance > 0)
    ///
    /// # Returns
    ///
    /// true if instance > 0, false otherwise
    #[must_use]
    pub fn is_clone(&self) -> bool {
        self.instance > 0
    }

    /// Get the unique project ID string (alias for to_string)
    #[must_use]
    pub fn as_unique_id(&self) -> String {
        self.to_string()
    }
}

impl std::fmt::Display for UniqueProjectId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_unique_string())
    }
}

impl From<&UniqueProjectId> for String {
    fn from(id: &UniqueProjectId) -> Self {
        id.as_unique_string()
    }
}

impl From<UniqueProjectId> for String {
    fn from(id: UniqueProjectId) -> Self {
        id.as_unique_string()
    }
}

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

    #[test]
    fn test_generate_creates_valid_id() {
        let path = Path::new("/home/user/projects/leindex");
        let id = UniqueProjectId::generate(path, &[]);

        assert_eq!(id.base_name, "leindex");
        assert_eq!(id.path_hash.len(), 8);
        assert_eq!(id.instance, 0);
    }

    #[test]
    fn test_hash_path_returns_8_chars() {
        let hash = UniqueProjectId::hash_path("/test/path");
        assert_eq!(hash.len(), 8);
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn test_hash_path_is_deterministic() {
        let path = "/test/path/to/project";
        let hash1 = UniqueProjectId::hash_path(path);
        let hash2 = UniqueProjectId::hash_path(path);
        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_hash_path_is_different_for_different_paths() {
        let hash1 = UniqueProjectId::hash_path("/path/one");
        let hash2 = UniqueProjectId::hash_path("/path/two");
        assert_ne!(hash1, hash2);
    }

    #[test]
    fn test_instance_starts_at_zero() {
        let path = Path::new("/home/user/projects/leindex");
        let id = UniqueProjectId::generate(path, &[]);
        assert_eq!(id.instance, 0);
    }

    #[test]
    fn test_instance_increments_for_same_base_name() {
        let path1 = Path::new("/home/user/projects/leindex");
        let id1 = UniqueProjectId::generate(path1, &[]);

        let path2 = Path::new("/different/path/leindex");
        let id2 = UniqueProjectId::generate(path2, &[id1.clone()]);

        assert_eq!(id1.instance, 0);
        assert_eq!(id2.instance, 1);
    }

    #[test]
    fn test_instance_counts_correctly() {
        let base_name = "myproject";

        let id1 = UniqueProjectId::new(base_name.to_string(), "hash1".to_string(), 0);
        let id2 = UniqueProjectId::new(base_name.to_string(), "hash2".to_string(), 1);
        let id3 = UniqueProjectId::new(base_name.to_string(), "hash3".to_string(), 2);

        let next = UniqueProjectId::find_next_instance(base_name, &[id1, id2, id3]);
        assert_eq!(next, 3);
    }

    #[test]
    fn test_to_string_format() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 0);
        assert_eq!(id.as_unique_string(), "leindex_a3f7d9e2_0");
    }

    #[test]
    fn test_to_string_with_instance() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 2);
        assert_eq!(id.as_unique_string(), "leindex_a3f7d9e2_2");
    }

    #[test]
    fn test_display_original() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 0);
        assert_eq!(id.display(), "leindex");
    }

    #[test]
    fn test_display_clone() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 1);
        assert_eq!(id.display(), "leindex (clone #1)");

        let id2 = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 5);
        assert_eq!(id2.display(), "leindex (clone #5)");
    }

    #[test]
    fn test_parse_id_valid() {
        let id = UniqueProjectId::parse_id("leindex_a3f7d9e2_0");
        assert!(id.is_some());
        let id = id.unwrap();
        assert_eq!(id.base_name, "leindex");
        assert_eq!(id.path_hash, "a3f7d9e2");
        assert_eq!(id.instance, 0);
    }

    #[test]
    fn test_parse_id_invalid_format() {
        assert!(UniqueProjectId::parse_id("invalid").is_none());
        assert!(UniqueProjectId::parse_id("only_two_parts").is_none());
    }

    #[test]
    fn test_parse_id_invalid_hash() {
        // Wrong hash length
        assert!(UniqueProjectId::parse_id("leindex_a3f7_0").is_none());
        // Non-hex characters
        assert!(UniqueProjectId::parse_id("leindex_xyzxyz9_0").is_none());
    }

    #[test]
    fn test_parse_id_roundtrip() {
        let original = UniqueProjectId::new("myproject".to_string(), "b4e8f1a3".to_string(), 3);
        let s = original.as_unique_string();
        let parsed = UniqueProjectId::parse_id(&s).unwrap();
        assert_eq!(parsed, original);
    }

    #[test]
    fn test_is_clone() {
        let original = UniqueProjectId::new("leindex".to_string(), "hash1".to_string(), 0);
        assert!(!original.is_clone());

        let clone = UniqueProjectId::new("leindex".to_string(), "hash2".to_string(), 1);
        assert!(clone.is_clone());
    }

    #[test]
    fn test_as_unique_id() {
        let id = UniqueProjectId::new("test".to_string(), "abcd1234".to_string(), 0);
        assert_eq!(id.as_unique_id(), "test_abcd1234_0");
    }

    #[test]
    fn test_display_trait() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 0);
        assert_eq!(format!("{}", id), "leindex_a3f7d9e2_0");
    }

    #[test]
    fn test_from_string_trait() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 0);
        let s: String = (&id).into();
        assert_eq!(s, "leindex_a3f7d9e2_0");

        let s2: String = id.clone().into();
        assert_eq!(s2, "leindex_a3f7d9e2_0");
    }

    #[test]
    fn test_handle_unicode_directory_name() {
        // Test with unicode characters
        let path = Path::new("/home/user/projects/été");
        let id = UniqueProjectId::generate(path, &[]);
        assert_eq!(id.base_name, "été");
        assert_eq!(id.path_hash.len(), 8);
    }

    #[test]
    fn test_handle_special_characters() {
        let path = Path::new("/home/user/projects/my-project_v2.0");
        let id = UniqueProjectId::generate(path, &[]);
        assert_eq!(id.base_name, "my-project_v2.0");
        assert_eq!(id.path_hash.len(), 8);
    }

    #[test]
    fn test_unknown_fallback_for_invalid_path() {
        // Current directory doesn't have a file name
        let path = Path::new(".");
        let id = UniqueProjectId::generate(path, &[]);
        // When there's no file name, should use "unknown" fallback
        // or the path itself if it can be represented
        assert!(!id.base_name.is_empty());
    }

    #[test]
    fn test_serialization() {
        let id = UniqueProjectId::new("leindex".to_string(), "a3f7d9e2".to_string(), 2);
        let json = serde_json::to_string(&id).unwrap();
        let deserialized: UniqueProjectId = serde_json::from_str(&json).unwrap();
        assert_eq!(id, deserialized);
    }

    #[test]
    fn test_generate_with_conflicting_names() {
        let path1 = Path::new("/path/to/project");
        let id1 = UniqueProjectId::generate(path1, &[]);

        let path2 = Path::new("/different/path/project");
        let id2 = UniqueProjectId::generate(path2, &[id1.clone()]);

        let path3 = Path::new("/another/path/project");
        let id3 = UniqueProjectId::generate(path3, &[id1.clone(), id2.clone()]);

        assert_eq!(id1.instance, 0);
        assert_eq!(id2.instance, 1);
        assert_eq!(id3.instance, 2);
    }
}