sqry-core 8.0.0

Core library for sqry - semantic code search engine
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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
//! `FileRegistry`: Path deduplication with `FileId` handles.
//!
//! This module implements `FileRegistry`, which provides efficient storage
//! of file paths by deduplicating identical canonical paths.
//!
//! # Design
//!
//! - **Path deduplication**: Same canonical path returns same `FileId`
//! - **Canonical normalization**: Paths are canonicalized before registration
//! - **Bi-directional lookup**: ID → path and path → ID
//!
//! # Thread Safety
//!
//! The registry uses `Arc<Path>` for path storage. However, the registry itself
//! requires external synchronization (e.g., `RwLock`) for concurrent access.

use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use super::super::file::id::FileId;
use super::super::string::id::StringId;
use crate::graph::node::Language;

/// Error returned when a file path cannot be registered.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryError {
    /// Path canonicalization failed.
    CanonicalizationFailed {
        /// The original path
        path: PathBuf,
        /// Error message
        message: String,
    },
    /// Registry capacity exhausted.
    CapacityExhausted,
}

impl fmt::Display for RegistryError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::CanonicalizationFailed { path, message } => {
                write!(
                    f,
                    "failed to canonicalize path '{}': {}",
                    path.display(),
                    message
                )
            }
            Self::CapacityExhausted => {
                write!(f, "file registry capacity exhausted (> 2^32 files)")
            }
        }
    }
}

impl std::error::Error for RegistryError {}

/// File entry storing path, language, and Phase 1 provenance.
///
/// This struct is **module-private**. External code reads provenance via
/// [`FileRegistry::file_provenance`], which returns a borrowed
/// [`FileProvenanceView`]. Phase 1 growth of this struct is an
/// implementation detail and does not affect the public API.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct FileEntry {
    /// The canonical file path.
    path: Arc<Path>,
    /// The language of this file (if known).
    language: Option<Language>,
    /// Whether this file originates from an external source (e.g., classpath JAR).
    #[serde(default)]
    is_external: bool,
    /// SHA-256 of the on-disk file bytes at the most recent indexing pass.
    ///
    /// Populated by the build pipeline (P1U08) via
    /// [`FileRegistry::set_content_hash`]. Defaulted to all-zero bytes for
    /// legacy V7 snapshots loaded through the backwards-read path, and for
    /// entries inserted before the hash is known.
    #[serde(default = "default_content_hash")]
    content_hash: [u8; 32],
    /// Unix-epoch seconds at which this file was registered in the most
    /// recent build. Equal to the snapshot's `fact_epoch` across every
    /// `FileEntry` in a single build.
    #[serde(default)]
    indexed_at: u64,
    /// Interned physical origin URI for external or synthetic files —
    /// e.g. `jar:file:///…/rt.jar!/java/lang/Object.class` for classpath
    /// entries. `Some` iff the physical path alone is insufficient to
    /// identify the origin.
    ///
    /// Invariant (eventual): once external registration is complete,
    /// `is_external == true` implies `source_uri.is_some()`. The
    /// two-phase path (`register_external` followed by `set_source_uri`)
    /// may temporarily leave `source_uri` unset until the URI is stamped.
    #[serde(default)]
    source_uri: Option<StringId>,
}

/// Default content hash for `FileEntry` fields deserialized from legacy
/// snapshots that predate Phase 1 or for entries inserted before the build
/// pipeline stamps a real hash.
#[inline]
fn default_content_hash() -> [u8; 32] {
    [0u8; 32]
}

/// Borrowed view of per-file provenance, returned by
/// [`FileRegistry::file_provenance`].
///
/// This is the stable public surface the Phase 1 accessor exposes. The
/// underlying [`FileEntry`] remains module-private; growing it is an
/// implementation detail of the registry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FileProvenanceView<'a> {
    /// Borrowed SHA-256 of the on-disk file bytes.
    pub content_hash: &'a [u8; 32],
    /// Unix-epoch seconds at which this file was registered.
    pub indexed_at: u64,
    /// Optional interned physical origin URI (see [`FileEntry::source_uri`]).
    pub source_uri: Option<StringId>,
    /// Whether this file originates from an external source.
    pub is_external: bool,
}

/// File registry for path deduplication.
///
/// `FileRegistry` stores file paths efficiently by maintaining a single
/// copy of each unique canonical path. When the same path is registered
/// multiple times (even with different formats), the same `FileId` is returned.
///
/// # Path Normalization
///
/// Paths are normalized before registration using a best-effort canonicalization:
/// - Relative paths are converted to absolute
/// - Symlinks are resolved (when possible)
/// - Path separators are normalized
///
/// # Language Tracking
///
/// Each file can optionally have an associated `Language` for filtering and
/// visualization purposes. Language can be set during registration or updated later.
///
/// # Example
///
/// ```rust,ignore
/// let mut registry = FileRegistry::new();
///
/// let id1 = registry.register(Path::new("src/lib.rs"))?;
/// let id2 = registry.register(Path::new("./src/../src/lib.rs"))?;
/// assert_eq!(id1, id2); // Same canonical path → same ID
///
/// // Set language
/// registry.set_language(id1, Language::Rust);
///
/// let path = registry.resolve(id1).unwrap();
/// assert!(path.ends_with("src/lib.rs"));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileRegistry {
    /// Storage of registered file entries, indexed by `FileId`.
    entries: Vec<Option<FileEntry>>,
    /// Reverse lookup from canonical path to index.
    lookup: HashMap<Arc<Path>, u32>,
    /// Free list of recycled slot indices.
    free_list: Vec<u32>,
}

impl FileRegistry {
    /// Creates a new empty file registry.
    #[must_use]
    pub fn new() -> Self {
        // Reserve index 0 for INVALID sentinel
        Self {
            entries: vec![None],
            lookup: HashMap::new(),
            free_list: Vec::new(),
        }
    }

    /// Creates a new registry with the specified capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        let mut entries = Vec::with_capacity(capacity + 1);
        entries.push(None); // Reserve index 0

        Self {
            entries,
            lookup: HashMap::with_capacity(capacity),
            free_list: Vec::new(),
        }
    }

    /// Returns the number of registered files (excluding INVALID slot).
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.lookup.len()
    }

    /// Returns true if no files are registered.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.lookup.is_empty()
    }

    /// Returns the total number of allocated slots (including vacant/recycled
    /// ones and the sentinel at index 0).
    ///
    /// This is the length of the underlying `entries` vector, not the count of
    /// live files. Use this to iterate every possible `FileId` index.
    #[inline]
    #[must_use]
    pub fn slot_count(&self) -> usize {
        self.entries.len()
    }

    /// Registers a file path and returns its `FileId`.
    ///
    /// The path is normalized using best-effort canonicalization before registration.
    /// If the canonical path was already registered, returns the existing ID.
    ///
    /// # Best-Effort Normalization
    ///
    /// This method uses fallback behavior when canonicalization fails:
    /// 1. Tries full canonicalization (resolve symlinks, make absolute)
    /// 2. Falls back to converting relative path to absolute using current directory
    /// 3. Falls back to using the path as-is
    ///
    /// This means non-existent or inaccessible paths are still registered, but
    /// may not be truly canonical. Use [`try_register_strict`] if you need to
    /// guarantee canonicalization succeeds.
    ///
    /// # Errors
    ///
    /// Returns `RegistryError::CapacityExhausted` if the registry has
    /// exhausted all available IDs (> 2^32 - 2 files).
    ///
    /// [`try_register_strict`]: Self::try_register_strict
    pub fn register(&mut self, path: &Path) -> Result<FileId, RegistryError> {
        self.register_with_language(path, None)
    }

    /// Registers a file path with an associated language.
    ///
    /// Similar to [`register`], but allows specifying the file's language.
    /// The language can be updated later using [`set_language`].
    ///
    /// # Errors
    ///
    /// Returns `RegistryError::CapacityExhausted` if the registry has
    /// exhausted all available IDs (> 2^32 - 2 files).
    ///
    /// [`register`]: Self::register
    /// [`set_language`]: Self::set_language
    pub fn register_with_language(
        &mut self,
        path: &Path,
        language: Option<Language>,
    ) -> Result<FileId, RegistryError> {
        // Normalize the path
        let canonical = Self::normalize_path(path);
        let arc_path: Arc<Path> = Arc::from(canonical.as_path());

        // Check if already registered
        if let Some(&index) = self.lookup.get(&arc_path) {
            // Update language if provided and entry exists
            if let Some(lang) = language
                && let Some(Some(entry)) = self.entries.get_mut(index as usize)
            {
                entry.language = Some(lang);
            }
            return Ok(FileId::new(index));
        }

        // Create new file entry
        let entry = FileEntry {
            path: Arc::clone(&arc_path),
            language,
            is_external: false,
            content_hash: default_content_hash(),
            indexed_at: 0,
            source_uri: None,
        };

        // Allocate new slot
        let index = if let Some(free_idx) = self.free_list.pop() {
            // Reuse a recycled slot
            self.entries[free_idx as usize] = Some(entry);
            free_idx
        } else {
            // Append new slot
            let idx = self.entries.len();
            if idx > u32::MAX as usize - 1 {
                return Err(RegistryError::CapacityExhausted);
            }
            self.entries.push(Some(entry));
            u32::try_from(idx).map_err(|_| RegistryError::CapacityExhausted)?
        };

        self.lookup.insert(arc_path, index);
        Ok(FileId::new(index))
    }

    /// Registers a file path with strict canonicalization.
    ///
    /// Unlike [`register`], this method returns an error if the path cannot
    /// be canonicalized. Use this when you need to guarantee that all registered
    /// paths are truly canonical.
    ///
    /// # Errors
    ///
    /// - [`RegistryError::CanonicalizationFailed`]: Path cannot be canonicalized
    ///   (e.g., file doesn't exist, permission denied, or symlink loop).
    /// - [`RegistryError::CapacityExhausted`]: Registry capacity exhausted.
    ///
    /// [`register`]: Self::register
    pub fn try_register_strict(&mut self, path: &Path) -> Result<FileId, RegistryError> {
        // Require successful canonicalization
        let canonical = path
            .canonicalize()
            .map_err(|e| RegistryError::CanonicalizationFailed {
                path: path.to_path_buf(),
                message: e.to_string(),
            })?;

        let arc_path: Arc<Path> = Arc::from(canonical.as_path());

        // Check if already registered
        if let Some(&index) = self.lookup.get(&arc_path) {
            return Ok(FileId::new(index));
        }

        // Create new file entry without language
        let entry = FileEntry {
            path: Arc::clone(&arc_path),
            language: None,
            is_external: false,
            content_hash: default_content_hash(),
            indexed_at: 0,
            source_uri: None,
        };

        // Allocate new slot
        let index = if let Some(free_idx) = self.free_list.pop() {
            self.entries[free_idx as usize] = Some(entry);
            free_idx
        } else {
            let idx = self.entries.len();
            if idx > u32::MAX as usize - 1 {
                return Err(RegistryError::CapacityExhausted);
            }
            self.entries.push(Some(entry));
            u32::try_from(idx).map_err(|_| RegistryError::CapacityExhausted)?
        };

        self.lookup.insert(arc_path, index);
        Ok(FileId::new(index))
    }

    /// Registers a path without normalization (for already-canonical paths).
    ///
    /// Use this when you know the path is already canonical (e.g., from
    /// file system enumeration).
    ///
    /// # Errors
    ///
    /// Returns an error if the registry is at capacity.
    pub fn register_canonical(&mut self, path: &Path) -> Result<FileId, RegistryError> {
        self.register_canonical_with_language(path, None)
    }

    /// Registers a canonical path with an associated language.
    ///
    /// # Errors
    ///
    /// Returns an error if the registry is at capacity.
    pub fn register_canonical_with_language(
        &mut self,
        path: &Path,
        language: Option<Language>,
    ) -> Result<FileId, RegistryError> {
        let arc_path: Arc<Path> = Arc::from(path);

        // Check if already registered
        if let Some(&index) = self.lookup.get(&arc_path) {
            // Update language if provided and entry exists
            if let Some(lang) = language
                && let Some(Some(entry)) = self.entries.get_mut(index as usize)
            {
                entry.language = Some(lang);
            }
            return Ok(FileId::new(index));
        }

        // Create new file entry
        let entry = FileEntry {
            path: Arc::clone(&arc_path),
            language,
            is_external: false,
            content_hash: default_content_hash(),
            indexed_at: 0,
            source_uri: None,
        };

        // Allocate new slot
        let index = if let Some(free_idx) = self.free_list.pop() {
            self.entries[free_idx as usize] = Some(entry);
            free_idx
        } else {
            let idx = self.entries.len();
            if idx > u32::MAX as usize - 1 {
                return Err(RegistryError::CapacityExhausted);
            }
            self.entries.push(Some(entry));
            u32::try_from(idx).map_err(|_| RegistryError::CapacityExhausted)?
        };

        self.lookup.insert(arc_path, index);
        Ok(FileId::new(index))
    }

    /// Resolves a `FileId` to its path.
    ///
    /// Returns `None` if the ID is invalid or has been unregistered.
    #[must_use]
    pub fn resolve(&self, id: FileId) -> Option<Arc<Path>> {
        if id.is_invalid() {
            return None;
        }

        let index = id.index() as usize;
        self.entries
            .get(index)
            .and_then(|opt| opt.as_ref().map(|entry| Arc::clone(&entry.path)))
    }

    /// Gets the language for a file.
    ///
    /// Returns `None` if the file ID is invalid, the file was unregistered,
    /// or no language has been set for this file.
    #[must_use]
    pub fn language_for_file(&self, file_id: FileId) -> Option<Language> {
        if file_id.is_invalid() {
            return None;
        }

        let index = file_id.index() as usize;
        self.entries
            .get(index)
            .and_then(|opt| opt.as_ref())
            .and_then(|entry| entry.language)
    }

    /// Sets or updates the language for a file.
    ///
    /// Returns `true` if the language was set successfully, `false` if the
    /// file ID is invalid or the file was unregistered.
    pub fn set_language(&mut self, file_id: FileId, language: Language) -> bool {
        if file_id.is_invalid() {
            return false;
        }

        let index = file_id.index() as usize;
        if let Some(Some(entry)) = self.entries.get_mut(index) {
            entry.language = Some(language);
            true
        } else {
            false
        }
    }

    /// Returns whether a file is external (e.g., from a classpath JAR).
    ///
    /// Returns `false` if the file ID is invalid or the file was unregistered.
    #[must_use]
    pub fn is_external(&self, id: FileId) -> bool {
        if id.is_invalid() {
            return false;
        }

        let index = id.index() as usize;
        self.entries
            .get(index)
            .and_then(|opt| opt.as_ref())
            .is_some_and(|entry| entry.is_external)
    }

    /// Registers an external file path and returns its `FileId`.
    ///
    /// External files originate from outside the project (e.g., classpath JARs).
    /// They are marked with `is_external = true` for filtering in queries and
    /// visualizations.
    ///
    /// The path is stored as-is (no normalization), since external files may
    /// reference virtual paths within JAR archives.
    ///
    /// # Errors
    ///
    /// Returns `RegistryError::CapacityExhausted` if the registry has
    /// exhausted all available IDs.
    pub fn register_external(
        &mut self,
        path: impl AsRef<Path>,
        language: Option<Language>,
    ) -> Result<FileId, RegistryError> {
        self.register_external_with_uri(path, language, None)
    }

    /// Registers an external file path with an associated language and source URI.
    ///
    /// Like [`register_external`], but also stamps the interned source URI at
    /// registration time when one is available. For classpath entries,
    /// `source_uri` should carry the JAR origin (e.g.
    /// `jar:file:///…/rt.jar!/java/lang/Object.class`).
    ///
    /// # Invariant
    ///
    /// Callers that cannot provide a URI yet should use [`register_external`]
    /// and stamp via [`set_source_uri`] later. This method does not assert on
    /// `source_uri` and accepts `None` for the two-phase registration flow.
    ///
    /// # Errors
    ///
    /// Returns `RegistryError::CapacityExhausted` if the registry has
    /// exhausted all available IDs.
    ///
    /// [`register_external`]: Self::register_external
    /// [`set_source_uri`]: Self::set_source_uri
    pub fn register_external_with_uri(
        &mut self,
        path: impl AsRef<Path>,
        language: Option<Language>,
        source_uri: Option<StringId>,
    ) -> Result<FileId, RegistryError> {
        let path = path.as_ref();
        let arc_path: Arc<Path> = Arc::from(path);

        // Check if already registered
        if let Some(&index) = self.lookup.get(&arc_path) {
            // Update external flag, language, and source_uri if entry exists
            if let Some(Some(entry)) = self.entries.get_mut(index as usize) {
                entry.is_external = true;
                if let Some(lang) = language {
                    entry.language = Some(lang);
                }
                if source_uri.is_some() {
                    entry.source_uri = source_uri;
                }
            }
            return Ok(FileId::new(index));
        }

        // Create new external file entry
        let entry = FileEntry {
            path: Arc::clone(&arc_path),
            language,
            is_external: true,
            content_hash: default_content_hash(),
            indexed_at: 0,
            source_uri,
        };

        // Allocate new slot
        let index = if let Some(free_idx) = self.free_list.pop() {
            self.entries[free_idx as usize] = Some(entry);
            free_idx
        } else {
            let idx = self.entries.len();
            if idx > u32::MAX as usize - 1 {
                return Err(RegistryError::CapacityExhausted);
            }
            self.entries.push(Some(entry));
            u32::try_from(idx).map_err(|_| RegistryError::CapacityExhausted)?
        };

        self.lookup.insert(arc_path, index);
        Ok(FileId::new(index))
    }

    /// Gets all files that match the specified language.
    ///
    /// Returns a vector of `(FileId, Arc<Path>)` pairs for all files
    /// that have been assigned the given language.
    #[must_use]
    pub fn files_by_language(&self, language: Language) -> Vec<(FileId, Arc<Path>)> {
        self.entries
            .iter()
            .enumerate()
            .skip(1) // Skip INVALID slot
            .filter_map(|(idx, opt)| {
                opt.as_ref().and_then(|entry| {
                    if entry.language == Some(language) {
                        let idx_u32 = u32::try_from(idx).ok()?;
                        Some((FileId::new(idx_u32), Arc::clone(&entry.path)))
                    } else {
                        None
                    }
                })
            })
            .collect()
    }

    /// Unregisters a file, freeing its slot for reuse.
    ///
    /// Returns the path that was unregistered, or `None` if the ID was invalid.
    pub fn unregister(&mut self, id: FileId) -> Option<Arc<Path>> {
        if id.is_invalid() {
            return None;
        }

        let index = id.index() as usize;
        if index >= self.entries.len() {
            return None;
        }

        if let Some(entry) = self.entries[index].take() {
            self.lookup.remove(&entry.path);
            if let Ok(index_u32) = u32::try_from(index) {
                self.free_list.push(index_u32);
            } else {
                log::warn!("File registry index overflow when recycling slot {index}");
            }
            Some(entry.path)
        } else {
            None
        }
    }

    /// Checks if a path is registered.
    #[must_use]
    pub fn contains(&self, path: &Path) -> bool {
        let canonical = Self::normalize_path(path);
        self.lookup.contains_key(canonical.as_path())
    }

    /// Checks if a path is registered without normalization.
    #[must_use]
    pub fn contains_canonical(&self, path: &Path) -> bool {
        self.lookup.contains_key(path)
    }

    /// Gets the `FileId` for a path if it's registered.
    ///
    /// Unlike `register()`, this does not create a new entry.
    #[must_use]
    pub fn get(&self, path: &Path) -> Option<FileId> {
        let canonical = Self::normalize_path(path);
        self.lookup
            .get(canonical.as_path())
            .map(|&idx| FileId::new(idx))
    }

    /// Gets the `FileId` for a canonical path if it's registered.
    #[must_use]
    pub fn get_canonical(&self, path: &Path) -> Option<FileId> {
        self.lookup.get(path).map(|&idx| FileId::new(idx))
    }

    /// Returns an iterator over all registered files with their IDs.
    pub fn iter(&self) -> impl Iterator<Item = (FileId, &Arc<Path>)> {
        self.entries
            .iter()
            .enumerate()
            .skip(1) // Skip INVALID slot
            .filter_map(|(idx, opt)| {
                opt.as_ref().and_then(|entry| {
                    u32::try_from(idx)
                        .ok()
                        .map(|idx_u32| (FileId::new(idx_u32), &entry.path))
                })
            })
    }

    /// Returns an iterator over all registered files with their IDs and languages.
    pub fn iter_with_language(
        &self,
    ) -> impl Iterator<Item = (FileId, &Arc<Path>, Option<Language>)> {
        self.entries
            .iter()
            .enumerate()
            .skip(1) // Skip INVALID slot
            .filter_map(|(idx, opt)| {
                opt.as_ref().and_then(|entry| {
                    u32::try_from(idx)
                        .ok()
                        .map(|idx_u32| (FileId::new(idx_u32), &entry.path, entry.language))
                })
            })
    }

    /// Registers multiple file paths in a single batch operation.
    ///
    /// Each file is registered with its optional language using
    /// [`register_with_language`]. Duplicate paths within the batch (or
    /// already registered) receive the same `FileId`, matching the
    /// existing deduplication behavior.
    ///
    /// # Errors
    ///
    /// Returns `RegistryError::CapacityExhausted` if the registry
    /// exhausts all available IDs during the batch.  On error, files
    /// registered before the failure remain in the registry.
    ///
    /// [`register_with_language`]: Self::register_with_language
    pub fn register_batch(
        &mut self,
        files: &[(PathBuf, Option<Language>)],
    ) -> Result<Vec<FileId>, RegistryError> {
        let mut ids = Vec::with_capacity(files.len());
        for (path, language) in files {
            let id = self.register_with_language(path, *language)?;
            ids.push(id);
        }
        Ok(ids)
    }

    /// Clears all registered files.
    pub fn clear(&mut self) {
        self.entries.truncate(1); // Keep INVALID slot
        self.entries[0] = None;
        self.lookup.clear();
        self.free_list.clear();
    }

    /// Reserves capacity for at least `additional` more files.
    pub fn reserve(&mut self, additional: usize) {
        self.entries.reserve(additional);
        self.lookup.reserve(additional);
    }

    // ------------------------------------------------------------------
    // Phase 1 fact-layer provenance accessors and setters (P1U05).
    // ------------------------------------------------------------------

    /// Returns a borrowed provenance view for `id`.
    ///
    /// Returns `None` for the invalid sentinel, unregistered IDs, and
    /// recycled (vacant) slots.
    #[must_use]
    pub fn file_provenance(&self, id: FileId) -> Option<FileProvenanceView<'_>> {
        if id.is_invalid() {
            return None;
        }
        let entry = self.entries.get(id.index() as usize)?.as_ref()?;
        Some(FileProvenanceView {
            content_hash: &entry.content_hash,
            indexed_at: entry.indexed_at,
            source_uri: entry.source_uri,
            is_external: entry.is_external,
        })
    }

    /// Stamps the content hash on a registered file entry.
    ///
    /// Intended for use by the build pipeline (P1U08) after the file bytes
    /// have been read for tree-sitter but before the extraction pass starts.
    /// Returns `false` if the ID is invalid or the slot is vacant.
    pub fn set_content_hash(&mut self, id: FileId, hash: [u8; 32]) -> bool {
        if id.is_invalid() {
            return false;
        }
        if let Some(Some(entry)) = self.entries.get_mut(id.index() as usize) {
            entry.content_hash = hash;
            true
        } else {
            false
        }
    }

    /// Stamps the indexed-at epoch on a registered file entry.
    ///
    /// In Phase 1, every `FileEntry` in a single build shares the same
    /// `indexed_at` value, equal to the snapshot's `fact_epoch`.
    /// Returns `false` if the ID is invalid or the slot is vacant.
    pub fn set_indexed_at(&mut self, id: FileId, epoch: u64) -> bool {
        if id.is_invalid() {
            return false;
        }
        if let Some(Some(entry)) = self.entries.get_mut(id.index() as usize) {
            entry.indexed_at = epoch;
            true
        } else {
            false
        }
    }

    /// Stamps the interned source URI on a registered file entry.
    ///
    /// Should only be called for external or synthetic files. The caller is
    /// responsible for interning the URI through the `StringInterner` before
    /// passing the resulting `StringId` here.
    ///
    /// # Debug assertion
    ///
    /// In debug builds, asserts that if `is_external` is `true` on this
    /// entry and `source_uri` is `Some`, the invariant `is_external ⇒
    /// source_uri.is_some()` was already met or is met by this call. This
    /// catches the converse case: calling `set_source_uri(None)` on an
    /// external entry would violate the invariant.
    ///
    /// Returns `false` if the ID is invalid or the slot is vacant.
    pub fn set_source_uri(&mut self, id: FileId, uri: Option<StringId>) -> bool {
        if id.is_invalid() {
            return false;
        }
        if let Some(Some(entry)) = self.entries.get_mut(id.index() as usize) {
            debug_assert!(
                !(entry.is_external && uri.is_none()),
                "set_source_uri(None) on an external file violates is_external => source_uri.is_some()"
            );
            entry.source_uri = uri;
            true
        } else {
            false
        }
    }

    /// Returns statistics about the registry.
    #[must_use]
    pub fn stats(&self) -> RegistryStats {
        RegistryStats {
            file_count: self.len(),
            free_slots: self.free_list.len(),
            capacity: self.entries.capacity(),
        }
    }

    /// Normalizes a path for consistent lookup.
    ///
    /// This performs best-effort canonicalization:
    /// - Tries to canonicalize (resolve symlinks, absolute path)
    /// - Falls back to converting to absolute path
    /// - Falls back to using the path as-is if it's already absolute
    fn normalize_path(path: &Path) -> PathBuf {
        // Try full canonicalization first
        if let Ok(canonical) = path.canonicalize() {
            return canonical;
        }

        // Fall back to just making it absolute
        if path.is_relative()
            && let Ok(cwd) = std::env::current_dir()
        {
            return cwd.join(path);
        }

        // Last resort: return as-is (converted to PathBuf)
        path.to_path_buf()
    }
}

impl Default for FileRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for FileRegistry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "FileRegistry(files={}, free={})",
            self.len(),
            self.free_list.len()
        )
    }
}

/// Statistics about a `FileRegistry`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegistryStats {
    /// Number of registered files.
    pub file_count: usize,
    /// Number of free (recyclable) slots.
    pub free_slots: usize,
    /// Allocated capacity.
    pub capacity: usize,
}

impl crate::graph::unified::memory::GraphMemorySize for FileRegistry {
    fn heap_bytes(&self) -> usize {
        use crate::graph::unified::memory::HASHMAP_ENTRY_OVERHEAD;

        let entries_vec = self.entries.capacity() * std::mem::size_of::<Option<FileEntry>>();
        let lookup = self.lookup.capacity()
            * (std::mem::size_of::<Arc<Path>>()
                + std::mem::size_of::<u32>()
                + HASHMAP_ENTRY_OVERHEAD);
        let free_list = self.free_list.capacity() * std::mem::size_of::<u32>();
        entries_vec + lookup + free_list
    }
}

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

    #[test]
    fn test_new() {
        let registry = FileRegistry::new();
        assert_eq!(registry.len(), 0);
        assert!(registry.is_empty());
    }

    #[test]
    fn test_with_capacity() {
        let registry = FileRegistry::with_capacity(100);
        assert_eq!(registry.len(), 0);
        assert!(registry.entries.capacity() >= 101); // +1 for INVALID slot
    }

    #[test]
    fn test_register_and_resolve() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("test.rs");
        fs::write(&file_path, "fn main() {}").unwrap();

        let mut registry = FileRegistry::new();
        let id = registry.register(&file_path).unwrap();

        assert!(!id.is_invalid());
        assert_eq!(registry.len(), 1);

        let resolved = registry.resolve(id).unwrap();
        // Both should resolve to the same canonical path
        assert_eq!(resolved.canonicalize().ok(), file_path.canonicalize().ok());
    }

    #[test]
    fn test_register_duplicate() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("test.rs");
        fs::write(&file_path, "").unwrap();

        let mut registry = FileRegistry::new();
        let id1 = registry.register(&file_path).unwrap();
        let id2 = registry.register(&file_path).unwrap();

        assert_eq!(id1, id2);
        assert_eq!(registry.len(), 1);
    }

    #[test]
    fn test_register_different() {
        let tmp = TempDir::new().unwrap();
        let file1 = tmp.path().join("a.rs");
        let file2 = tmp.path().join("b.rs");
        fs::write(&file1, "").unwrap();
        fs::write(&file2, "").unwrap();

        let mut registry = FileRegistry::new();
        let id1 = registry.register(&file1).unwrap();
        let id2 = registry.register(&file2).unwrap();

        assert_ne!(id1, id2);
        assert_eq!(registry.len(), 2);
    }

    #[test]
    fn test_register_canonical() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/canonical/path/file.rs");
        let id = registry.register_canonical(path).unwrap();

        assert!(!id.is_invalid());
        assert_eq!(registry.resolve(id).unwrap().as_ref(), path);
    }

    #[test]
    fn test_resolve_invalid() {
        let registry = FileRegistry::new();
        assert!(registry.resolve(FileId::INVALID).is_none());
    }

    #[test]
    fn test_resolve_out_of_bounds() {
        let registry = FileRegistry::new();
        assert!(registry.resolve(FileId::new(999)).is_none());
    }

    #[test]
    fn test_unregister() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/test/file.rs");
        let id = registry.register_canonical(path).unwrap();

        assert_eq!(registry.len(), 1);

        let removed = registry.unregister(id);
        assert!(removed.is_some());
        assert_eq!(registry.len(), 0);
        assert!(registry.resolve(id).is_none());
    }

    #[test]
    fn test_unregister_invalid() {
        let mut registry = FileRegistry::new();
        assert!(registry.unregister(FileId::INVALID).is_none());
    }

    #[test]
    fn test_free_list_reuse() {
        let mut registry = FileRegistry::new();
        let path1 = Path::new("/test/a.rs");
        let path2 = Path::new("/test/b.rs");

        let id1 = registry.register_canonical(path1).unwrap();
        registry.unregister(id1);

        let id2 = registry.register_canonical(path2).unwrap();
        assert_eq!(id1.index(), id2.index()); // Same slot reused
    }

    #[test]
    fn test_contains() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("test.rs");
        fs::write(&file_path, "").unwrap();

        let mut registry = FileRegistry::new();
        registry.register(&file_path).unwrap();

        assert!(registry.contains(&file_path));
        assert!(!registry.contains(Path::new("/nonexistent/path.rs")));
    }

    #[test]
    fn test_contains_canonical() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/canonical/test.rs");
        registry.register_canonical(path).unwrap();

        assert!(registry.contains_canonical(path));
        assert!(!registry.contains_canonical(Path::new("/other/path.rs")));
    }

    #[test]
    fn test_get() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("test.rs");
        fs::write(&file_path, "").unwrap();

        let mut registry = FileRegistry::new();
        let id = registry.register(&file_path).unwrap();

        assert_eq!(registry.get(&file_path), Some(id));
        assert_eq!(registry.get(Path::new("/nonexistent.rs")), None);
    }

    #[test]
    fn test_get_canonical() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/canonical/test.rs");
        let id = registry.register_canonical(path).unwrap();

        assert_eq!(registry.get_canonical(path), Some(id));
        assert_eq!(registry.get_canonical(Path::new("/other.rs")), None);
    }

    #[test]
    fn test_iter() {
        let mut registry = FileRegistry::new();
        registry.register_canonical(Path::new("/a.rs")).unwrap();
        registry.register_canonical(Path::new("/b.rs")).unwrap();
        registry.register_canonical(Path::new("/c.rs")).unwrap();

        let paths: Vec<_> = registry.iter().map(|(_, p)| p.to_path_buf()).collect();
        assert_eq!(paths.len(), 3);
        assert!(paths.contains(&PathBuf::from("/a.rs")));
        assert!(paths.contains(&PathBuf::from("/b.rs")));
        assert!(paths.contains(&PathBuf::from("/c.rs")));
    }

    #[test]
    fn test_clear() {
        let mut registry = FileRegistry::new();
        registry.register_canonical(Path::new("/a.rs")).unwrap();
        registry.register_canonical(Path::new("/b.rs")).unwrap();

        assert_eq!(registry.len(), 2);
        registry.clear();
        assert_eq!(registry.len(), 0);
        assert!(registry.is_empty());
    }

    #[test]
    fn test_reserve() {
        let mut registry = FileRegistry::new();
        registry.reserve(1000);
        assert!(registry.entries.capacity() >= 1001);
    }

    #[test]
    fn test_display() {
        let mut registry = FileRegistry::new();
        registry.register_canonical(Path::new("/test.rs")).unwrap();

        let display = format!("{registry}");
        assert!(display.contains("FileRegistry"));
        assert!(display.contains("files=1"));
    }

    #[test]
    fn test_stats() {
        let mut registry = FileRegistry::new();
        registry.register_canonical(Path::new("/a.rs")).unwrap();
        registry.register_canonical(Path::new("/b.rs")).unwrap();

        let stats = registry.stats();
        assert_eq!(stats.file_count, 2);
        assert_eq!(stats.free_slots, 0);
    }

    #[test]
    fn test_default() {
        let registry: FileRegistry = FileRegistry::default();
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_registry_error_display() {
        let err = RegistryError::CanonicalizationFailed {
            path: PathBuf::from("/test/path"),
            message: "not found".to_string(),
        };
        let display = format!("{err}");
        assert!(display.contains("/test/path"));
        assert!(display.contains("not found"));

        let err2 = RegistryError::CapacityExhausted;
        let display2 = format!("{err2}");
        assert!(display2.contains("capacity exhausted"));
    }

    #[test]
    fn test_unicode_path() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/日本語/ファイル.rs");
        let id = registry.register_canonical(path).unwrap();

        let resolved = registry.resolve(id).unwrap();
        assert_eq!(resolved.as_ref(), path);
    }

    #[test]
    fn test_try_register_strict_success() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("test.rs");
        fs::write(&file_path, "fn main() {}").unwrap();

        let mut registry = FileRegistry::new();
        let id = registry.try_register_strict(&file_path).unwrap();

        assert!(!id.is_invalid());
        assert_eq!(registry.len(), 1);

        // Verify it returns canonical path
        let resolved = registry.resolve(id).unwrap();
        assert_eq!(resolved.as_ref(), file_path.canonicalize().unwrap());
    }

    #[test]
    fn test_try_register_strict_nonexistent() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/nonexistent/path/that/does/not/exist.rs");

        let result = registry.try_register_strict(path);
        assert!(result.is_err());

        match result.unwrap_err() {
            RegistryError::CanonicalizationFailed {
                path: err_path,
                message,
            } => {
                assert_eq!(err_path, path);
                assert!(!message.is_empty());
            }
            RegistryError::CapacityExhausted => {
                panic!("Expected CanonicalizationFailed, got CapacityExhausted")
            }
        }
    }

    #[test]
    fn test_register_fallback_nonexistent() {
        // Verify that register() uses fallback for non-existent paths
        let mut registry = FileRegistry::new();
        let path = Path::new("/nonexistent/path/file.rs");

        // register() should succeed with fallback behavior
        let result = registry.register(path);
        assert!(result.is_ok());

        let id = result.unwrap();
        let resolved = registry.resolve(id).unwrap();

        // The path should be stored (as-is since it can't be canonicalized)
        // and should contain the original path components
        assert!(resolved.to_string_lossy().contains("file.rs"));
    }

    #[test]
    fn test_try_register_strict_duplicate() {
        let tmp = TempDir::new().unwrap();
        let file_path = tmp.path().join("test.rs");
        fs::write(&file_path, "").unwrap();

        let mut registry = FileRegistry::new();
        let id1 = registry.try_register_strict(&file_path).unwrap();
        let id2 = registry.try_register_strict(&file_path).unwrap();

        assert_eq!(id1, id2);
        assert_eq!(registry.len(), 1);
    }

    #[test]
    fn test_language_tracking_basic() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/test/file.rs");
        let id = registry.register_canonical(path).unwrap();

        // Initially no language
        assert_eq!(registry.language_for_file(id), None);

        // Set language
        assert!(registry.set_language(id, Language::Rust));
        assert_eq!(registry.language_for_file(id), Some(Language::Rust));

        // Update language
        assert!(registry.set_language(id, Language::JavaScript));
        assert_eq!(registry.language_for_file(id), Some(Language::JavaScript));
    }

    #[test]
    fn test_language_tracking_invalid_id() {
        let mut registry = FileRegistry::new();

        // Invalid ID should return None
        assert_eq!(registry.language_for_file(FileId::INVALID), None);

        // Setting language on invalid ID should fail
        assert!(!registry.set_language(FileId::INVALID, Language::Rust));
    }

    #[test]
    fn test_register_with_language() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/test/main.py");

        let id = registry
            .register_canonical_with_language(path, Some(Language::Python))
            .unwrap();

        assert_eq!(registry.language_for_file(id), Some(Language::Python));
        assert_eq!(registry.resolve(id).unwrap().as_ref(), path);
    }

    #[test]
    fn test_register_with_language_duplicate_updates() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/test/script.js");

        // Register with JavaScript
        let id1 = registry
            .register_canonical_with_language(path, Some(Language::JavaScript))
            .unwrap();
        assert_eq!(registry.language_for_file(id1), Some(Language::JavaScript));

        // Re-register same path with TypeScript updates language
        let id2 = registry
            .register_canonical_with_language(path, Some(Language::TypeScript))
            .unwrap();

        assert_eq!(id1, id2, "Should return same ID for duplicate path");
        assert_eq!(registry.language_for_file(id2), Some(Language::TypeScript));
    }

    #[test]
    fn test_files_by_language_empty() {
        let registry = FileRegistry::new();
        let files = registry.files_by_language(Language::Rust);
        assert!(files.is_empty());
    }

    #[test]
    fn test_files_by_language_single() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/src/main.rs");
        let id = registry
            .register_canonical_with_language(path, Some(Language::Rust))
            .unwrap();

        let files = registry.files_by_language(Language::Rust);
        assert_eq!(files.len(), 1);
        assert_eq!(files[0].0, id);
        assert_eq!(files[0].1.as_ref(), path);

        // Different language should return empty
        let js_files = registry.files_by_language(Language::JavaScript);
        assert!(js_files.is_empty());
    }

    #[test]
    fn test_files_by_language_multiple() {
        let mut registry = FileRegistry::new();

        // Register Rust files
        let rs1 = Path::new("/src/main.rs");
        let rs2 = Path::new("/src/lib.rs");
        let id1 = registry
            .register_canonical_with_language(rs1, Some(Language::Rust))
            .unwrap();
        let id2 = registry
            .register_canonical_with_language(rs2, Some(Language::Rust))
            .unwrap();

        // Register Python file
        let py1 = Path::new("/scripts/test.py");
        let id3 = registry
            .register_canonical_with_language(py1, Some(Language::Python))
            .unwrap();

        // Register file without language
        let _ = registry
            .register_canonical(Path::new("/data/config.json"))
            .unwrap();

        // Query Rust files
        let rust_files = registry.files_by_language(Language::Rust);
        assert_eq!(rust_files.len(), 2);
        let rust_ids: Vec<_> = rust_files.iter().map(|(id, _)| *id).collect();
        assert!(rust_ids.contains(&id1));
        assert!(rust_ids.contains(&id2));

        // Query Python files
        let python_files = registry.files_by_language(Language::Python);
        assert_eq!(python_files.len(), 1);
        assert_eq!(python_files[0].0, id3);

        // Query JavaScript files (none registered)
        let js_files = registry.files_by_language(Language::JavaScript);
        assert!(js_files.is_empty());
    }

    #[test]
    fn test_iter_with_language() {
        let mut registry = FileRegistry::new();

        let rs_path = Path::new("/src/main.rs");
        let py_path = Path::new("/scripts/test.py");
        let no_lang_path = Path::new("/config.json");

        let id1 = registry
            .register_canonical_with_language(rs_path, Some(Language::Rust))
            .unwrap();
        let id2 = registry
            .register_canonical_with_language(py_path, Some(Language::Python))
            .unwrap();
        let id3 = registry.register_canonical(no_lang_path).unwrap();

        let entries: Vec<_> = registry.iter_with_language().collect();
        assert_eq!(entries.len(), 3);

        // Find each entry and verify
        let rs_entry = entries.iter().find(|(id, _, _)| *id == id1).unwrap();
        assert_eq!(rs_entry.1.as_ref(), rs_path);
        assert_eq!(rs_entry.2, Some(Language::Rust));

        let py_entry = entries.iter().find(|(id, _, _)| *id == id2).unwrap();
        assert_eq!(py_entry.1.as_ref(), py_path);
        assert_eq!(py_entry.2, Some(Language::Python));

        let no_lang_entry = entries.iter().find(|(id, _, _)| *id == id3).unwrap();
        assert_eq!(no_lang_entry.1.as_ref(), no_lang_path);
        assert_eq!(no_lang_entry.2, None);
    }

    #[test]
    fn test_unregister_with_language() {
        let mut registry = FileRegistry::new();
        let path = Path::new("/test/file.rs");
        let id = registry
            .register_canonical_with_language(path, Some(Language::Rust))
            .unwrap();

        assert_eq!(registry.language_for_file(id), Some(Language::Rust));
        assert_eq!(registry.files_by_language(Language::Rust).len(), 1);

        // Unregister
        let removed = registry.unregister(id);
        assert!(removed.is_some());

        // Language should be gone
        assert_eq!(registry.language_for_file(id), None);
        assert_eq!(registry.files_by_language(Language::Rust).len(), 0);
    }

    #[test]
    fn test_language_serialization() {
        let mut registry = FileRegistry::new();
        let path1 = Path::new("/src/main.rs");
        let path2 = Path::new("/src/lib.py");

        registry
            .register_canonical_with_language(path1, Some(Language::Rust))
            .unwrap();
        registry
            .register_canonical_with_language(path2, Some(Language::Python))
            .unwrap();

        // Serialize to JSON
        let json = serde_json::to_string(&registry).unwrap();

        // Deserialize
        let deserialized: FileRegistry = serde_json::from_str(&json).unwrap();

        // Verify languages are preserved
        let rust_files = deserialized.files_by_language(Language::Rust);
        assert_eq!(rust_files.len(), 1);

        let python_files = deserialized.files_by_language(Language::Python);
        assert_eq!(python_files.len(), 1);
    }

    #[test]
    fn test_language_with_best_effort_register() {
        let mut registry = FileRegistry::new();
        // Non-existent path (uses fallback normalization)
        let path = Path::new("/nonexistent/file.rs");

        let id = registry
            .register_with_language(path, Some(Language::Rust))
            .unwrap();

        assert_eq!(registry.language_for_file(id), Some(Language::Rust));
    }

    #[test]
    #[allow(clippy::similar_names)] // file1/file2/file3 vs files: intentional test variable names
    fn test_register_batch() {
        let tmp = TempDir::new().unwrap();
        let file1 = tmp.path().join("alpha.rs");
        let file2 = tmp.path().join("beta.py");
        let file3 = tmp.path().join("gamma.js");
        fs::write(&file1, "fn main() {}").unwrap();
        fs::write(&file2, "print('hello')").unwrap();
        fs::write(&file3, "console.log('hi')").unwrap();

        let mut registry = FileRegistry::new();
        let files: Vec<(PathBuf, Option<Language>)> = vec![
            (file1.clone(), Some(Language::Rust)),
            (file2.clone(), Some(Language::Python)),
            (file3.clone(), Some(Language::JavaScript)),
        ];

        let ids = registry.register_batch(&files).unwrap();

        // Should return 3 unique IDs
        assert_eq!(ids.len(), 3);
        assert_ne!(ids[0], ids[1]);
        assert_ne!(ids[1], ids[2]);
        assert_ne!(ids[0], ids[2]);

        // All IDs should be resolvable
        for (i, id) in ids.iter().enumerate() {
            let resolved = registry.resolve(*id).unwrap();
            let expected_canonical = files[i].0.canonicalize().unwrap();
            assert_eq!(resolved.as_ref(), expected_canonical.as_path());
        }

        // Languages should be set
        assert_eq!(registry.language_for_file(ids[0]), Some(Language::Rust));
        assert_eq!(registry.language_for_file(ids[1]), Some(Language::Python));
        assert_eq!(
            registry.language_for_file(ids[2]),
            Some(Language::JavaScript)
        );

        // Registry should have 3 files
        assert_eq!(registry.len(), 3);
    }

    #[test]
    fn test_register_batch_empty() {
        let mut registry = FileRegistry::new();
        let files: Vec<(PathBuf, Option<Language>)> = vec![];

        let ids = registry.register_batch(&files).unwrap();

        assert!(ids.is_empty());
        assert_eq!(registry.len(), 0);
    }

    #[test]
    fn test_register_batch_duplicate_paths() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("dup.rs");
        fs::write(&file, "fn main() {}").unwrap();

        let mut registry = FileRegistry::new();
        let files: Vec<(PathBuf, Option<Language>)> = vec![
            (file.clone(), Some(Language::Rust)),
            (file.clone(), Some(Language::Rust)),
        ];

        let ids = registry.register_batch(&files).unwrap();

        // Duplicate path returns same FileId (deduplication behavior)
        assert_eq!(ids.len(), 2);
        assert_eq!(ids[0], ids[1]);

        // Only 1 unique file registered
        assert_eq!(registry.len(), 1);
    }

    #[test]
    fn test_register_batch_duplicate_paths_different_languages() {
        let tmp = TempDir::new().unwrap();
        let file = tmp.path().join("polyglot.rs");
        fs::write(&file, "fn main() {}").unwrap();

        let mut registry = FileRegistry::new();
        let files: Vec<(PathBuf, Option<Language>)> = vec![
            (file.clone(), Some(Language::Rust)),
            (file.clone(), Some(Language::Python)),
        ];

        let ids = registry.register_batch(&files).unwrap();

        // Same FileId for same path
        assert_eq!(ids[0], ids[1]);
        assert_eq!(registry.len(), 1);

        // Last language wins (matches register_with_language dedup behavior)
        assert_eq!(registry.language_for_file(ids[0]), Some(Language::Python));
    }

    // ------------------------------------------------------------------
    // Phase 1 P1U05: file provenance accessors
    // ------------------------------------------------------------------

    #[test]
    fn phase1_file_provenance_defaults_to_zero_hash_and_zero_epoch() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("test.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let mut reg = FileRegistry::new();
        let id = reg.register(&path).unwrap();

        let view = reg.file_provenance(id).expect("provenance present");
        assert_eq!(view.content_hash, &[0u8; 32]);
        assert_eq!(view.indexed_at, 0);
        assert_eq!(view.source_uri, None);
        assert!(!view.is_external);
    }

    #[test]
    fn phase1_set_content_hash_round_trip() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("test.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let mut reg = FileRegistry::new();
        let id = reg.register(&path).unwrap();

        let hash = [0xAB; 32];
        assert!(reg.set_content_hash(id, hash));

        let view = reg.file_provenance(id).unwrap();
        assert_eq!(view.content_hash, &hash);
    }

    #[test]
    fn phase1_set_indexed_at_round_trip() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("test.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let mut reg = FileRegistry::new();
        let id = reg.register(&path).unwrap();
        assert!(reg.set_indexed_at(id, 42_000));

        let view = reg.file_provenance(id).unwrap();
        assert_eq!(view.indexed_at, 42_000);
    }

    #[test]
    fn phase1_set_source_uri_round_trip() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("test.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let mut reg = FileRegistry::new();
        let id = reg.register(&path).unwrap();
        let uri = StringId::new(7);
        assert!(reg.set_source_uri(id, Some(uri)));

        let view = reg.file_provenance(id).unwrap();
        assert_eq!(view.source_uri, Some(uri));
    }

    #[test]
    fn phase1_file_provenance_invalid_sentinel_returns_none() {
        let reg = FileRegistry::new();
        assert!(reg.file_provenance(FileId::INVALID).is_none());
    }

    #[test]
    fn phase1_file_provenance_survives_postcard_round_trip() {
        let tmp = TempDir::new().unwrap();
        let path = tmp.path().join("test.rs");
        fs::write(&path, "fn main() {}").unwrap();

        let mut reg = FileRegistry::new();
        let id = reg.register(&path).unwrap();
        reg.set_content_hash(id, [0xCD; 32]);
        reg.set_indexed_at(id, 12_345);
        reg.set_source_uri(id, Some(StringId::new(99)));

        let encoded = postcard::to_allocvec(&reg).expect("encode");
        let decoded: FileRegistry = postcard::from_bytes(&encoded).expect("decode");

        let view = decoded
            .file_provenance(id)
            .expect("provenance after decode");
        assert_eq!(view.content_hash, &[0xCD; 32]);
        assert_eq!(view.indexed_at, 12_345);
        assert_eq!(view.source_uri, Some(StringId::new(99)));
    }

    #[test]
    fn phase1_external_entry_exposes_is_external_true() {
        let mut reg = FileRegistry::new();
        let uri = StringId::new(42);
        let id = reg
            .register_external_with_uri("/virtual/path/Foo.class", Some(Language::Java), Some(uri))
            .unwrap();

        let view = reg.file_provenance(id).unwrap();
        assert!(view.is_external);
        assert_eq!(view.source_uri, Some(uri));
    }

    #[test]
    fn phase1_register_external_then_set_source_uri_round_trip() {
        let mut reg = FileRegistry::new();
        let id = reg
            .register_external("/virtual/path/Foo.class", Some(Language::Java))
            .unwrap();

        let initial_view = reg.file_provenance(id).unwrap();
        assert!(initial_view.is_external);
        assert_eq!(initial_view.source_uri, None);

        let uri = StringId::new(84);
        assert!(reg.set_source_uri(id, Some(uri)));

        let updated_view = reg.file_provenance(id).unwrap();
        assert!(updated_view.is_external);
        assert_eq!(updated_view.source_uri, Some(uri));
    }

    #[test]
    fn phase1_register_external_with_uri_accepts_none_and_records_externality() {
        let mut reg = FileRegistry::new();
        let id = reg
            .register_external_with_uri("/virtual/path/Foo.class", Some(Language::Java), None)
            .unwrap();

        let view = reg.file_provenance(id).unwrap();
        assert!(view.is_external);
        assert_eq!(view.source_uri, None);
    }

    #[test]
    fn phase1_setters_return_false_for_invalid_id() {
        let mut reg = FileRegistry::new();
        assert!(!reg.set_content_hash(FileId::INVALID, [0; 32]));
        assert!(!reg.set_indexed_at(FileId::INVALID, 1));
        assert!(!reg.set_source_uri(FileId::INVALID, None));
    }
}