claudix 0.2.0

Local semantic search plugin for Claude Code
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
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
mod input;
mod install;
mod watch;

use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use serde::Serialize;

use crate::config;
use crate::error::{ClaudixError, RecoveryHint, Result};
use crate::hooks::HookEvent;
use crate::prompts::hints;
use crate::search::SearchQuery;
use crate::search::duplicates::{self, LabeledChunk};
pub use crate::search::duplicates::{DuplicateChunk, DuplicatePair};
use crate::store::{IndexLockGuard, Store};
use crate::types::{RelativePath, path_prefix_matches};
use crate::{Claudix, IndexFileStatus, IndexProgress};

use input::{
    parse_language_filter, parse_path_prefix, validate_search_query, validate_search_top_k,
};

/// Maximum number of top identifiers surfaced per directory in `OverviewOutput`.
const TOP_IDENTIFIERS_CAP: usize = 8;

/// Default cosine-similarity floor for [`run_find_duplicates`]. Higher = stricter / fewer pairs.
pub(crate) const DEFAULT_MIN_SIMILARITY: f32 = 0.85;
/// Default maximum number of duplicate pairs returned by [`run_find_duplicates`].
pub(crate) const DEFAULT_DUPLICATE_LIMIT: usize = 50;
/// Hard ceiling on the combined chunk count fed to the O(n²) duplicate scan.
/// `limit` caps only the output heap, not the input, so a caller pointing at
/// many large repos could drive an unbounded pairwise scan (≈ n²/2 comparisons).
/// Beyond this the scan is skipped and a notice is surfaced instead.
pub(crate) const MAX_DUPLICATE_CORPUS_CHUNKS: usize = 50_000;

pub use install::{run_install, setup_state};
pub use watch::run_watch;

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SearchHit {
    /// Canonical path of the repo this hit came from.
    pub repo: String,
    pub file_path: String,
    pub language: String,
    pub kind: String,
    pub name: Option<String>,
    pub line_start: u32,
    pub line_end: u32,
    pub score: f32,
    pub stale: bool,
    pub snippet: String,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DirectoryGroup {
    /// Canonical repo path the directory belongs to. Same-named directories in
    /// different repos do not merge — the group key is `(repo, directory)`.
    pub repo: String,
    pub directory: String,
    pub hits: Vec<SearchHit>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SearchOutput {
    pub groups: Vec<DirectoryGroup>,
    /// Repos that could not be searched (unindexed, mismatched, missing).
    /// Empty for single-repo searches.
    pub repo_errors: Vec<RepoError>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IndexOutput {
    pub file_count: usize,
    pub chunk_count: usize,
}

pub struct StderrIndexProgress;

impl IndexProgress for StderrIndexProgress {
    fn file(&mut self, path: &RelativePath, status: IndexFileStatus) -> Result<()> {
        let mut stderr = io::stderr().lock();
        match status {
            IndexFileStatus::Indexed => writeln!(stderr, "indexed {}", path.as_str())?,
            IndexFileStatus::Verified => writeln!(stderr, "verified {}", path.as_str())?,
            IndexFileStatus::Skipped(reason) => {
                writeln!(stderr, "skipped {}: {reason}", path.as_str())?
            }
        }
        stderr.flush()?;
        Ok(())
    }
}

struct FileIndexProgress {
    writer: io::BufWriter<fs::File>,
}

impl FileIndexProgress {
    fn try_open(log_dir: &Path) -> Option<Self> {
        fs::create_dir_all(log_dir).ok()?;
        fs::File::create(log_dir.join("index.log"))
            .ok()
            .map(|f| Self {
                writer: io::BufWriter::new(f),
            })
    }
}

impl IndexProgress for FileIndexProgress {
    fn file(&mut self, path: &RelativePath, status: IndexFileStatus) -> Result<()> {
        match status {
            IndexFileStatus::Indexed => writeln!(self.writer, "indexed {}", path.as_str())?,
            IndexFileStatus::Verified => writeln!(self.writer, "verified {}", path.as_str())?,
            IndexFileStatus::Skipped(reason) => {
                writeln!(self.writer, "skipped {}: {reason}", path.as_str())?
            }
        }
        self.writer.flush()?;
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ClearOutput {
    pub cleared: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StatusOutput {
    pub chunk_count: usize,
    pub file_count: usize,
    pub model: Option<String>,
    pub dimensions: Option<u16>,
    pub last_full_index_at: Option<String>,
    pub last_incremental_at: Option<String>,
    /// True when the index is missing or older than `reindex_after_hours`.
    pub stale: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DoctorOutput {
    pub project_root: String,
    pub index_present: bool,
    pub chunk_count: usize,
    pub file_count: usize,
    pub model: Option<String>,
    pub dimensions: Option<u16>,
    pub embedding_provider: String,
    pub embedding_healthy: bool,
    /// Why the embedding check failed, when `embedding_healthy` is false and the
    /// cause is not a model mismatch — auth, timeout, unreachable, HTTP status.
    pub embedding_error: Option<String>,
    /// True when the stored index model differs from the active config model.
    /// Distinct from `embedding_healthy = false` caused by the server being unreachable.
    pub embedding_model_mismatch: bool,
    /// Dev-only flag from config: when on, `bin/claudix-bootstrap.js` runs the
    /// `cargo install` binary instead of the downloaded release.
    pub development_mode: bool,
    /// Absolute path of the binary serving this command, so it is unambiguous
    /// which build is running (cargo vs. cached release) during development.
    pub binary_path: String,
    /// Last `error:` line the node bootstrap recorded in install.log when a binary
    /// download/verify failed, so a permanently-dead MCP has a visible cause instead
    /// of failing silently across sessions. None when no install.log or no error.
    pub install_error: Option<String>,
    /// Absolute path to the bootstrap's install.log, if resolvable, for the agent
    /// to open and inspect. None when `CLAUDE_PLUGIN_DATA` is unset (manual shell run).
    pub install_log_path: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct InstallOutput {
    pub plugin_root: String,
    pub binary_path: String,
    pub config_path: String,
    pub wrote_config: bool,
    pub embedding_healthy: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SetupState {
    Ready,
    Missing(Vec<&'static str>),
}

/// Per-language chunk count within a directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct LanguageCount {
    pub language: String,
    pub chunk_count: usize,
}

/// Aggregated stats for one immediate parent directory in the index.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DirectoryRollup {
    /// Repo-relative directory path, or `"."` for root-level files.
    pub path: String,
    pub file_count: usize,
    pub chunk_count: usize,
    /// Languages present in this directory, sorted by chunk count desc then name asc.
    pub languages: Vec<LanguageCount>,
    /// Most frequent non-empty chunk names, capped at [`TOP_IDENTIFIERS_CAP`], sorted by
    /// frequency desc then name asc.
    pub top_identifiers: Vec<String>,
}

/// Structural map of the indexed repo, grouped by immediate parent directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct OverviewOutput {
    /// One entry per directory, sorted by path ascending.
    pub directories: Vec<DirectoryRollup>,
    /// Distinct files in the filtered view.
    pub file_count: usize,
    /// Total chunks in the filtered view.
    pub chunk_count: usize,
}

/// A repo that could not contribute to the duplicate scan, with a reason.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RepoError {
    pub repo: String,
    pub error: String,
}

/// Result of [`run_find_duplicates`].
///
/// Partial success is intentional: indexed repos produce pairs even when
/// some listed repos errored.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DuplicatesOutput {
    pub pairs: Vec<DuplicatePair>,
    pub repo_errors: Vec<RepoError>,
}

pub async fn run_overview(
    project_root: impl AsRef<Path>,
    path_prefix: Option<String>,
) -> Result<OverviewOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;

    // Validate and normalize the path prefix the same way search does.
    let prefix: Option<RelativePath> = parse_path_prefix(path_prefix)?;

    // Metadata projection — skips embedding vectors; only file_path, file_hash,
    // language, and name are needed for the directory rollup.
    let metadata = store.read_chunk_metadata().await?;

    // Group chunks by the immediate parent directory of their file_path.
    // Splitting on `/` is sound because file_path comes from RelativePath,
    // which forward-slash-normalizes on construction on every platform.
    // Aggregation is light counting over an already-loaded Vec — no spawn_blocking needed.
    //
    // One aggregate per directory keeps the key clone count to at most one per
    // chunk (on the `entry().or_insert_with` path for new dirs, zero for existing).
    struct DirAggregate {
        files: std::collections::HashSet<String>,
        chunk_count: usize,
        languages: HashMap<String, usize>,
        names: HashMap<String, usize>,
    }

    let mut dir_map: HashMap<String, DirAggregate> = HashMap::new();

    for chunk in &metadata {
        // Apply path-prefix filter, consistent with `apply_filters` in search.
        if let Some(ref prefix) = prefix
            && !path_prefix_matches(&chunk.file_path, prefix.as_str())
        {
            continue;
        }

        let dir = immediate_parent_dir(&chunk.file_path);
        let agg = dir_map.entry(dir).or_insert_with(|| DirAggregate {
            files: std::collections::HashSet::new(),
            chunk_count: 0,
            languages: HashMap::new(),
            names: HashMap::new(),
        });
        agg.files.insert(chunk.file_path.clone());
        agg.chunk_count += 1;
        *agg.languages.entry(chunk.language.clone()).or_insert(0) += 1;
        if let Some(ref name) = chunk.name
            && !name.is_empty()
        {
            *agg.names.entry(name.clone()).or_insert(0) += 1;
        }
    }

    let mut directories: Vec<DirectoryRollup> = dir_map
        .into_iter()
        .map(|(dir, agg)| {
            let mut languages: Vec<LanguageCount> = agg
                .languages
                .into_iter()
                .map(|(language, chunk_count)| LanguageCount {
                    language,
                    chunk_count,
                })
                .collect();
            // Sort by chunk count desc, then language name asc for determinism.
            languages.sort_by(|a, b| {
                b.chunk_count
                    .cmp(&a.chunk_count)
                    .then_with(|| a.language.cmp(&b.language))
            });

            let top_identifiers: Vec<String> = {
                let mut pairs: Vec<(String, usize)> = agg.names.into_iter().collect();
                // Frequency desc, then name asc for determinism, then cap.
                pairs.sort_by(|(a_name, a_count), (b_name, b_count)| {
                    b_count.cmp(a_count).then_with(|| a_name.cmp(b_name))
                });
                pairs.truncate(TOP_IDENTIFIERS_CAP);
                pairs.into_iter().map(|(name, _)| name).collect()
            };

            DirectoryRollup {
                path: dir,
                file_count: agg.files.len(),
                chunk_count: agg.chunk_count,
                languages,
                top_identifiers,
            }
        })
        .collect();

    // Sort directories by path ascending for deterministic, navigable output.
    directories.sort_by(|a, b| a.path.cmp(&b.path));

    let file_count: usize = directories.iter().map(|d| d.file_count).sum();
    let chunk_count: usize = directories.iter().map(|d| d.chunk_count).sum();

    Ok(OverviewOutput {
        directories,
        file_count,
        chunk_count,
    })
}

/// Read the manifest JSON sidecar directly from a repo path without opening a
/// Store (no LanceDB connection machinery). Derives the manifest path from the
/// repo's config the same way `Store::new` would, but avoids a second Store
/// construction in the `load_repo_chunks_readonly` call that always follows.
///
/// The manifest file name and location logic must stay in sync with
/// `Store::new` + `store::manifest::MANIFEST_FILE_NAME`.
fn read_manifest_at_repo(
    repo_path: &str,
) -> std::result::Result<Option<crate::store::Manifest>, RepoError> {
    let config = config::load(std::path::Path::new(repo_path)).map_err(|e| RepoError {
        repo: repo_path.to_owned(),
        error: e.to_string(),
    })?;

    // Replicate `Store::new` path derivation: canonicalize root, join the
    // config-relative index_dir (validated at config-load time to not escape),
    // take its parent as state_dir, append the manifest file name.
    let root = std::path::Path::new(repo_path)
        .canonicalize()
        .map_err(|e| RepoError {
            repo: repo_path.to_owned(),
            error: e.to_string(),
        })?;

    let index_dir = root.join(&config.paths.index_dir);

    let state_dir = index_dir.parent().ok_or_else(|| RepoError {
        repo: repo_path.to_owned(),
        error: "index path has no parent directory".to_owned(),
    })?;

    let manifest_path = state_dir.join(crate::store::manifest::MANIFEST_FILE_NAME);

    if !manifest_path.exists() {
        return Ok(None);
    }

    let text = fs::read_to_string(&manifest_path).map_err(|e| RepoError {
        repo: repo_path.to_owned(),
        error: e.to_string(),
    })?;

    let manifest: crate::store::Manifest = serde_json::from_str(&text).map_err(|e| RepoError {
        repo: repo_path.to_owned(),
        error: e.to_string(),
    })?;

    Ok(Some(manifest))
}

/// Read the embedding identity (model, dimensions) from a repo's manifest without
/// validating against any reference. Used to bootstrap the reference for the first
/// repo in a multi-repo scan.
fn peek_manifest_identity(repo_path: &str) -> std::result::Result<(String, u16), RepoError> {
    match read_manifest_at_repo(repo_path)? {
        Some(m) if m.chunk_count > 0 => Ok((m.embedding_model, m.dimensions)),
        _ => Err(RepoError {
            repo: repo_path.to_owned(),
            error: "not indexed".to_owned(),
        }),
    }
}

/// Open a repo read-only, confirm it is indexed and dimension-compatible,
/// and return its chunks labeled with the canonical repo path.
///
/// This helper is intentionally read-only: it calls only `Store::new`,
/// `read_manifest`, and `read_chunks` — never `ensure_layout` or `write_manifest`.
/// Feature 6 (cross-repo search) reuses this to load remote repos without writing.
///
/// Returns `Err(RepoError)` when the repo path is invalid, the index is absent,
/// the chunk count is zero, or the embedding identity (model + dimensions) does
/// not match `ref_model`/`ref_dims`.
pub(crate) async fn load_repo_chunks_readonly(
    repo_path: &str,
    ref_model: &str,
    ref_dims: u16,
) -> std::result::Result<(String, Vec<crate::store::StoredChunk>), RepoError> {
    let config = config::load(std::path::Path::new(repo_path)).map_err(|e| RepoError {
        repo: repo_path.to_owned(),
        error: e.to_string(),
    })?;

    let store = Store::new(repo_path, &config).map_err(|e| RepoError {
        repo: repo_path.to_owned(),
        error: e.to_string(),
    })?;

    // Use the canonical path the store resolved to as the stable repo key.
    let canonical_repo = store.project_root().display().to_string();

    let manifest = store
        .validate_manifest_compatibility(ref_model, ref_dims)
        .map_err(|e| RepoError {
            repo: canonical_repo.clone(),
            error: e.to_string(),
        })?;

    let Some(manifest) = manifest else {
        return Err(RepoError {
            repo: canonical_repo,
            error: "not indexed".to_owned(),
        });
    };

    if manifest.chunk_count == 0 {
        return Err(RepoError {
            repo: canonical_repo,
            error: "not indexed".to_owned(),
        });
    }

    let chunks = store.read_chunks().await.map_err(|e| RepoError {
        repo: canonical_repo.clone(),
        error: e.to_string(),
    })?;

    if chunks.is_empty() {
        return Err(RepoError {
            repo: canonical_repo,
            error: "index chunks missing".to_owned(),
        });
    }

    Ok((canonical_repo, chunks))
}

/// Find near-duplicate code chunks within the active repo or across an explicit list of repos.
///
/// When `repos` is `None` or empty, only `project_root` is scanned.
/// When `repos` is non-empty, EXACTLY those paths are used — `project_root` is NOT
/// auto-added; the caller decides what to include.
///
/// The reference embedding identity (model + dimensions) is established from the
/// manifest of the first repo that loads successfully. All subsequent repos must
/// match that identity or they become `RepoError`s.
///
/// The O(n²) detection scan runs inside `tokio::task::spawn_blocking`.
pub async fn run_find_duplicates(
    project_root: impl AsRef<Path>,
    min_similarity: Option<f32>,
    limit: Option<usize>,
    repos: Option<Vec<String>>,
) -> Result<DuplicatesOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let min_similarity = min_similarity.unwrap_or(DEFAULT_MIN_SIMILARITY);
    if !min_similarity.is_finite() || !(0.0..=1.0).contains(&min_similarity) {
        return Err(ClaudixError::ConfigInvalid {
            message: "min_similarity must be between 0 and 1".to_owned(),
            recovery: RecoveryHint(hints::FINITE_MIN_SIMILARITY),
        });
    }
    let limit = limit.unwrap_or(DEFAULT_DUPLICATE_LIMIT);
    if limit == 0 {
        return Err(ClaudixError::ConfigInvalid {
            message: "limit must be at least 1".to_owned(),
            recovery: RecoveryHint(hints::POSITIVE_LIMIT),
        });
    }

    // Determine which repo paths to scan.
    let repo_paths: Vec<String> = match repos {
        Some(list) if !list.is_empty() => list,
        _ => vec![project_root.display().to_string()],
    };

    let mut all_chunks: Vec<crate::store::StoredChunk> = Vec::new();
    let mut repo_labels: Vec<Arc<str>> = Vec::new();
    let mut repo_errors: Vec<RepoError> = Vec::new();

    // The reference embedding identity is taken from the first repo whose manifest
    // loads successfully. Subsequent repos must match or they become RepoErrors.
    let mut ref_identity: Option<(String, u16)> = None;

    for path in &repo_paths {
        // Resolve reference identity lazily from the first successful manifest.
        if ref_identity.is_none() {
            match peek_manifest_identity(path) {
                Ok(identity) => ref_identity = Some(identity),
                Err(err) => {
                    repo_errors.push(err);
                    continue;
                }
            }
        }

        let Some((ref_model, ref_dims)) = ref_identity.as_ref() else {
            continue;
        };
        match load_repo_chunks_readonly(path, ref_model, *ref_dims).await {
            Ok((canonical, chunks)) => {
                let label: Arc<str> = Arc::from(canonical.as_str());
                for _ in &chunks {
                    repo_labels.push(Arc::clone(&label));
                }
                all_chunks.extend(chunks);
            }
            Err(err) => {
                repo_errors.push(err);
            }
        }
    }

    if all_chunks.is_empty() {
        return Ok(DuplicatesOutput {
            pairs: Vec::new(),
            repo_errors,
        });
    }

    // Cap the combined corpus before the O(n²) scan: `limit` bounds only the
    // output, so a large multi-repo input is a CPU/memory amplifier. Skip the
    // scan and surface a notice rather than churning through millions of pairs.
    if all_chunks.len() > MAX_DUPLICATE_CORPUS_CHUNKS {
        repo_errors.push(RepoError {
            repo: project_root.display().to_string(),
            error: format!(
                "duplicate scan skipped: {} chunks exceeds the {MAX_DUPLICATE_CORPUS_CHUNKS} cap; \
                 narrow the repo list",
                all_chunks.len()
            ),
        });
        return Ok(DuplicatesOutput {
            pairs: Vec::new(),
            repo_errors,
        });
    }

    // Build the labeled slice for the detection scan.
    // `spawn_blocking` keeps the O(n²) work off the async executor.
    let pairs = tokio::task::spawn_blocking(move || {
        let labeled: Vec<LabeledChunk<'_>> = all_chunks
            .iter()
            .zip(repo_labels.iter())
            .map(|(chunk, repo)| LabeledChunk {
                repo: repo.as_ref(),
                chunk,
            })
            .collect();
        duplicates::find_duplicates(&labeled, min_similarity, limit)
    })
    .await
    .map_err(|e| ClaudixError::Store(format!("duplicate scan task failed: {e}")))?;

    Ok(DuplicatesOutput { pairs, repo_errors })
}

/// Returns the immediate parent directory of a repo-relative file path,
/// normalized to forward slashes. Root-level files (no `/`) return `"."`.
///
/// Used by `run_overview` for directory grouping. Feature 5 can reuse this
/// for grouping search results.
pub(crate) fn immediate_parent_dir(file_path: &str) -> String {
    match file_path.rfind('/') {
        Some(pos) => file_path[..pos].to_owned(),
        None => ".".to_owned(),
    }
}

pub async fn run_search(
    project_root: impl AsRef<Path>,
    query: String,
    top_k: Option<usize>,
    language_filter: Option<Vec<String>>,
    path_prefix: Option<String>,
    repos: Option<Vec<String>>,
) -> Result<SearchOutput> {
    validate_search_query(&query)?;
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let top_k = top_k.unwrap_or(config.search.top_k);
    validate_search_top_k(top_k)?;
    // Active project is always in scope; union the config cross_repos with the
    // per-call repos, deduped at search time by canonical path.
    let repos = effective_cross_repos(&config.search.cross_repos, repos);
    let claudix = Claudix::new(project_root, Arc::new(config)).await?;

    run_search_with_claudix(&claudix, query, top_k, language_filter, path_prefix, repos).await
}

/// Union the configured `cross_repos` with the per-call `repos`, preserving
/// order and dropping exact-string duplicates. Canonical-path dedup happens
/// later in the searcher (it needs to resolve each path through the store).
fn effective_cross_repos(cross_repos: &[String], repos: Option<Vec<String>>) -> Vec<String> {
    let mut seen = HashSet::new();
    cross_repos
        .iter()
        .cloned()
        .chain(repos.into_iter().flatten())
        .filter(|repo| seen.insert(repo.clone()))
        .collect()
}

pub async fn run_index(project_root: impl AsRef<Path>, progress: bool) -> Result<IndexOutput> {
    let session = IndexSession::new(project_root).await?;
    let log_dir = session
        .claudix
        .project_root()
        .join(&session.claudix.config().paths.log_dir);
    let mut stderr_progress = StderrIndexProgress;
    let mut file_progress = (!progress)
        .then(|| FileIndexProgress::try_open(&log_dir))
        .flatten();
    let progress: &mut dyn IndexProgress = if progress {
        &mut stderr_progress
    } else if let Some(ref mut fp) = file_progress {
        fp
    } else {
        &mut ()
    };
    let stats = match session.claudix.index_full(progress).await {
        Ok(stats) => stats,
        Err(error) => {
            // The background index runs with stderr → null, so its terminal
            // error would otherwise vanish. Leave a breadcrumb in index.log so
            // the failure notice can surface the cause.
            append_index_log_error(&log_dir, &error);
            return Err(error);
        }
    };

    Ok(IndexOutput {
        file_count: stats.file_count,
        chunk_count: stats.chunk_count,
    })
}

/// Append a terminal error line to `index.log` so a failed background index
/// leaves a debuggable trace. Best-effort: a logging failure must never mask
/// the real indexing error.
fn append_index_log_error(log_dir: &Path, error: &ClaudixError) {
    if fs::create_dir_all(log_dir).is_err() {
        return;
    }
    let Ok(mut file) = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(log_dir.join("index.log"))
    else {
        return;
    };
    let _ = writeln!(file, "error: {error}");
}

struct IndexSession {
    claudix: Claudix,
    _lock: IndexLockGuard,
}

impl IndexSession {
    async fn new(project_root: impl AsRef<Path>) -> Result<Self> {
        let project_root = canonical_project_root(project_root.as_ref())?;
        require_git_repo(&project_root)?;
        let config = config::load(&project_root)?;
        let store = Store::new(&project_root, &config)?;
        let lock = store
            .acquire_index_lock()
            .ok_or_else(|| crate::error::ClaudixError::Store("index already running".to_owned()))?;
        let claudix = match Claudix::new(project_root.clone(), Arc::new(config.clone())).await {
            Ok(claudix) => claudix,
            Err(error) if requires_clean_reindex(&error) => {
                store.clear_chunks(&config).await?;
                Claudix::new(project_root, Arc::new(config)).await?
            }
            Err(error) => return Err(error),
        };

        Ok(Self {
            claudix,
            _lock: lock,
        })
    }
}

pub async fn run_status(project_root: impl AsRef<Path>) -> Result<StatusOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;
    status_from_store(&store, &config).await
}

pub async fn run_reindex_file(
    project_root: impl AsRef<Path>,
    path: impl AsRef<Path>,
) -> Result<IndexOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;

    // Block on the shared chunk-writer lock instead of short-circuiting on a
    // running full index: bailing here loses the user's edit until they save
    // again, since the reindex-file child returns 0 with no retry path.
    let _reindex_lock = store.acquire_reindex_lock()?;
    let claudix = Claudix::new(project_root, Arc::new(config)).await?;
    let stats = claudix.reindex_file(path.as_ref()).await?;

    Ok(IndexOutput {
        file_count: stats.file_count,
        chunk_count: stats.chunk_count,
    })
}

pub async fn run_doctor(project_root: impl AsRef<Path>) -> Result<DoctorOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;
    let status = status_from_store(&store, &config).await?;

    let claudix = Claudix::new(project_root.clone(), Arc::new(config.clone())).await;
    let (embedding_healthy, embedding_model_mismatch, embedding_error) = match claudix {
        Ok(claudix) => match claudix.embedder_health_check().await {
            Ok(()) => (true, false, None),
            Err(error) => (false, false, Some(error.to_string())),
        },
        Err(ClaudixError::EmbeddingModelMismatch { .. }) => (false, true, None),
        Err(error) => (false, false, Some(error.to_string())),
    };

    let install_log = install_data_dir().map(|dir| dir.join("install.log"));
    let install_error = install_log
        .as_ref()
        .and_then(|path| crate::util::last_error_line(path));

    Ok(DoctorOutput {
        project_root: project_root.display().to_string(),
        index_present: status.chunk_count > 0 || status.model.is_some(),
        chunk_count: status.chunk_count,
        file_count: status.file_count,
        model: status.model,
        dimensions: status.dimensions,
        embedding_provider: match config.embedding.provider {
            config::EmbeddingProvider::Bundled => "bundled".to_owned(),
            config::EmbeddingProvider::Http => "http".to_owned(),
        },
        embedding_healthy,
        embedding_error,
        embedding_model_mismatch,
        development_mode: config.development_mode,
        binary_path: std::env::current_exe()
            .map(|path| path.display().to_string())
            .unwrap_or_else(|_| "<unknown>".to_owned()),
        install_error,
        install_log_path: install_log.map(|path| path.display().to_string()),
    })
}

/// Resolve the claudix binary cache dir from the environment, mirroring
/// `bin/claudix-bootstrap.js`'s resolution so `/doctor` reads the same
/// `install.log` the bootstrap writes. `None` when no env hints a cache dir
/// (e.g. `claudix doctor` run manually from a shell).
fn install_data_dir() -> Option<PathBuf> {
    if let Some(dir) = std::env::var_os("CLAUDE_PLUGIN_DATA").map(PathBuf::from) {
        return Some(dir);
    }
    if let Some(dir) = std::env::var_os("CLAUDIX_HOME").map(PathBuf::from) {
        return Some(dir);
    }
    let base = std::env::var_os("XDG_DATA_HOME").map(PathBuf::from);
    let base = match base {
        Some(base) => base,
        None => dirs::home_dir()?.join(".local").join("share"),
    };
    Some(base.join("claudix"))
}

pub async fn run_clear_index(project_root: impl AsRef<Path>) -> Result<ClearOutput> {
    let project_root = canonical_project_root(project_root.as_ref())?;
    let config = config::load(&project_root)?;
    let store = Store::new(&project_root, &config)?;
    store.clear_chunks(&config).await?;

    Ok(ClearOutput { cleared: true })
}

fn requires_clean_reindex(error: &ClaudixError) -> bool {
    matches!(
        error,
        ClaudixError::SchemaMismatch { .. }
            | ClaudixError::EmbeddingModelMismatch { .. }
            | ClaudixError::DimensionMismatch { .. }
    )
}

pub fn parse_hook_event(value: &str) -> Result<HookEvent> {
    match value {
        "SessionStart" => Ok(HookEvent::SessionStart),
        "PostToolUse" => Ok(HookEvent::PostToolUse),
        "PreToolUse" => Ok(HookEvent::PreToolUse),
        "UserPromptSubmit" => Ok(HookEvent::UserPromptSubmit),
        _ => Err(ClaudixError::ConfigInvalid {
            message: format!("unknown hook event: {value}"),
            recovery: RecoveryHint(hints::VALID_HOOK_EVENTS),
        }),
    }
}

async fn run_search_with_claudix(
    claudix: &Claudix,
    query: String,
    top_k: usize,
    language_filter: Option<Vec<String>>,
    path_prefix: Option<String>,
    repos: Vec<String>,
) -> Result<SearchOutput> {
    let query = SearchQuery {
        query,
        top_k,
        language_filter: parse_language_filter(language_filter)?,
        path_prefix: parse_path_prefix(path_prefix)?,
        repos,
    };
    let found = claudix.search(query).await?;

    // Walk hits in score order (results is already score-desc from search).
    // Bucket by (repo, directory) preserving first-seen order so the first key
    // encountered owns the top hit — groups naturally ordered by best score.
    // Keying on repo too keeps same-named directories in different repos apart.
    let mut group_index: Vec<(String, String)> = Vec::new();
    let mut grouped: HashMap<(String, String), Vec<SearchHit>> = HashMap::new();

    for result in found.results {
        let dir = immediate_parent_dir(result.chunk.file_path.as_str());
        let key = (result.repo.clone(), dir);
        let hit = SearchHit {
            repo: result.repo,
            file_path: result.chunk.file_path.to_string(),
            language: result.chunk.language.to_string(),
            kind: result.chunk.kind.to_string(),
            name: result.chunk.name,
            line_start: result.chunk.line_range.start,
            line_end: result.chunk.line_range.end,
            score: result.score,
            stale: result.stale,
            snippet: result.chunk.content,
        };
        if !grouped.contains_key(&key) {
            group_index.push(key.clone());
        }
        grouped.entry(key).or_default().push(hit);
    }

    let groups = group_index
        .into_iter()
        .filter_map(|key| {
            let hits = grouped.remove(&key)?;
            let (repo, directory) = key;
            Some(DirectoryGroup {
                repo,
                directory,
                hits,
            })
        })
        .collect();

    Ok(SearchOutput {
        groups,
        repo_errors: found.repo_errors,
    })
}

async fn status_from_store(store: &Store, config: &crate::config::Config) -> Result<StatusOutput> {
    let manifest = store.read_manifest()?;
    let chunk_count = manifest
        .as_ref()
        .map(|m| m.chunk_count as usize)
        .unwrap_or(0);
    let file_count = manifest
        .as_ref()
        .map(|m| m.file_count as usize)
        .unwrap_or(0);

    let stale = manifest
        .as_ref()
        .map(|m| m.is_stale(config))
        .unwrap_or(true);

    Ok(StatusOutput {
        chunk_count,
        file_count,
        model: manifest
            .as_ref()
            .map(|manifest| manifest.embedding_model.clone()),
        dimensions: manifest.as_ref().map(|manifest| manifest.dimensions),
        last_full_index_at: manifest
            .as_ref()
            .and_then(|manifest| manifest.last_full_index_at.clone()),
        last_incremental_at: manifest
            .as_ref()
            .and_then(|manifest| manifest.last_incremental_at.clone()),
        stale,
    })
}

fn require_git_repo(project_root: &Path) -> Result<()> {
    if !crate::enumeration::is_git_repo(project_root) {
        return Err(ClaudixError::NotAGitRepository {
            path: project_root.to_path_buf(),
            recovery: RecoveryHint(hints::GIT_REPO_REQUIRED),
        });
    }
    Ok(())
}

pub(super) fn canonical_project_root(project_root: &Path) -> Result<PathBuf> {
    project_root.canonicalize().map_err(ClaudixError::from)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::embedding::{Provider, StubProvider};
    use crate::store::{Manifest, Store};
    use crate::types::Dimension;

    mod fixture {
        include!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/common/fixture.rs"
        ));
    }

    mod test_support {
        use crate as claudix;

        include!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/common/test_support.rs"
        ));
    }

    use fixture::TestFixture;
    use test_support::{index_fixture, stub_config};

    struct CliHarness {
        // Some when the harness owns its fixture (private harness); None when
        // the fixture is shared and owned by SHARED_FIXTURE_DIR.
        _fixture: Option<TestFixture>,
        claudix: Claudix,
        store: Store,
    }

    fn test_claudix(project_root: PathBuf, config: Config) -> Result<Claudix> {
        let store = Store::new(&project_root, &config)?;
        let config = Arc::new(config);
        let embedder: Arc<dyn Provider> = Arc::new(StubProvider::with_model_id(
            config.embedding.model.clone(),
            Dimension(config.embedding.dimensions),
        ));

        Ok(Claudix::from_parts(project_root, config, embedder, store))
    }

    // Shared indexed fixture directory — built once per test process.
    // The TempDir is stored here to keep the path alive for the process lifetime.
    static SHARED_FIXTURE_DIR: std::sync::OnceLock<(tempfile::TempDir, PathBuf)> =
        std::sync::OnceLock::new();

    fn shared_fixture_dir() -> &'static (tempfile::TempDir, PathBuf) {
        SHARED_FIXTURE_DIR.get_or_init(|| {
            // Spawn a fresh OS thread so `block_on` isn't called from within
            // an existing tokio runtime (which `#[tokio::test]` provides).
            // `TestFixture::new` initialises a real git repo so `FileEnumerator`
            // (called inside `index_fixture`) can enumerate files via git ls-files.
            // The git cost is paid once here for the entire test process.
            std::thread::spawn(|| {
                let fixture = TestFixture::new("small_rust").expect("shared fixture copy failed");
                let config = stub_config();
                let root = fixture.root().to_path_buf();
                let claudix =
                    test_claudix(root.clone(), config.clone()).expect("shared claudix init failed");

                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .expect("shared fixture tokio runtime")
                    .block_on(async {
                        index_fixture(
                            &claudix.store,
                            claudix.embedder.as_ref(),
                            claudix.project_root(),
                            &config,
                        )
                        .await
                        .expect("shared fixture indexing failed");
                    });

                fixture.into_parts()
            })
            .join()
            .expect("shared fixture init thread panicked")
        })
    }

    /// Harness for read-only tests: opens a fresh Store/Claudix against the
    /// shared pre-indexed fixture — no copy, no git, no indexing per test.
    async fn cli_harness() -> Result<CliHarness> {
        let (_, root) = shared_fixture_dir();
        let config = stub_config();
        let claudix = test_claudix(root.clone(), config.clone())?;
        let store = Store::new(root, &config)?;
        Ok(CliHarness {
            _fixture: None,
            claudix,
            store,
        })
    }

    /// Harness for tests that mutate fixture state (write files, delete the
    /// index dir, etc.) — each call gets its own isolated copy.
    async fn cli_harness_private() -> Result<CliHarness> {
        let fixture = TestFixture::new("small_rust")?;
        let config = stub_config();
        let claudix = test_claudix(fixture.root().to_path_buf(), config.clone())?;
        index_fixture(
            &claudix.store,
            claudix.embedder.as_ref(),
            claudix.project_root(),
            &config,
        )
        .await?;
        let store = Store::new(fixture.root(), &config)?;

        Ok(CliHarness {
            _fixture: Some(fixture),
            claudix,
            store,
        })
    }

    #[test]
    fn parse_hook_event_accepts_known_values() {
        let event = parse_hook_event("SessionStart");
        assert!(matches!(event, Ok(HookEvent::SessionStart)));

        let event = parse_hook_event("PostToolUse");
        assert!(matches!(event, Ok(HookEvent::PostToolUse)));

        let event = parse_hook_event("PreToolUse");
        assert!(matches!(event, Ok(HookEvent::PreToolUse)));

        let event = parse_hook_event("UserPromptSubmit");
        assert!(matches!(event, Ok(HookEvent::UserPromptSubmit)));
    }

    #[test]
    fn parse_hook_event_rejects_unknown_values() {
        let result = parse_hook_event("Unknown");
        assert!(matches!(result, Err(ClaudixError::ConfigInvalid { .. })));
    }

    #[tokio::test]
    async fn run_search_returns_ranked_hits() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_search_with_claudix(
            &harness.claudix,
            "add".to_owned(),
            5,
            None,
            None,
            Vec::new(),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(!output.groups.is_empty());
        let top_hit = &output.groups[0].hits[0];
        assert_eq!(top_hit.name.as_deref(), Some("add"));
        assert_eq!(top_hit.file_path, "src/math.rs");
    }

    #[tokio::test]
    async fn run_search_applies_filters() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_search_with_claudix(
            &harness.claudix,
            "add".to_owned(),
            5,
            Some(vec!["rust".to_owned()]),
            Some(RelativePath::new("src/math").to_string()),
            Vec::new(),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert_eq!(output.groups.len(), 1);
        assert_eq!(output.groups[0].hits.len(), 1);
        assert_eq!(output.groups[0].hits[0].file_path, "src/math.rs");
    }

    #[test]
    fn clean_reindex_required_for_manifest_compatibility_errors() {
        assert!(requires_clean_reindex(&ClaudixError::SchemaMismatch {
            store: 0,
            binary: 1,
            recovery: RecoveryHint(hints::RUN_REINDEX),
        }));
        assert!(requires_clean_reindex(
            &ClaudixError::EmbeddingModelMismatch {
                store_model: "old".to_owned(),
                active_model: "new".to_owned(),
                recovery: RecoveryHint(hints::RUN_REINDEX),
            }
        ));
        assert!(requires_clean_reindex(&ClaudixError::DimensionMismatch {
            store_dim: 384,
            model_dim: 768,
            recovery: RecoveryHint(hints::RUN_REINDEX),
        }));
        assert!(!requires_clean_reindex(&ClaudixError::Store(
            "index already running".to_owned()
        )));
    }

    #[test]
    fn append_index_log_error_writes_error_line() {
        let dir = tempfile::tempdir().unwrap_or_else(|_| unreachable!());
        let log_dir = dir.path().join("logs");
        append_index_log_error(&log_dir, &ClaudixError::Store("boom".to_owned()));
        let text =
            std::fs::read_to_string(log_dir.join("index.log")).unwrap_or_else(|_| unreachable!());
        assert!(
            text.starts_with("error:") && text.contains("boom"),
            "log must capture the terminal error so the failure notice can quote it, got: {text}"
        );
    }

    #[tokio::test]
    async fn run_index_clears_model_mismatch_and_reindexes() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let config = stub_config();
        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(&config);
        assert!(config_text.is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default(),
            )
            .is_ok()
        );

        let store = Store::new(fixture.root(), &config);
        assert!(store.is_ok());
        let store = store.ok().unwrap_or_else(|| unreachable!());
        let old_manifest = Manifest::new("old-model", config.embedding.dimensions);
        assert!(store.write_manifest(&old_manifest).is_ok());

        let output = run_index(fixture.root(), false).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());
        assert!(output.chunk_count > 0);

        let manifest = store.read_manifest();
        assert!(manifest.is_ok());
        let manifest = manifest.ok().unwrap_or_else(|| unreachable!());
        let manifest = manifest.unwrap_or_else(|| unreachable!());
        assert_eq!(manifest.embedding_model, config.embedding.model);
        assert_eq!(manifest.dimensions, config.embedding.dimensions);
        assert_eq!(manifest.chunk_count as usize, output.chunk_count);
    }

    #[tokio::test]
    async fn run_index_clears_dimension_mismatch_and_reindexes() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());
        let config = stub_config();
        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(&config);
        assert!(config_text.is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default(),
            )
            .is_ok()
        );

        let store = Store::new(fixture.root(), &config);
        assert!(store.is_ok());
        let store = store.ok().unwrap_or_else(|| unreachable!());
        // Same model, wrong dimensions: only the dimension check fires.
        let stale_manifest =
            Manifest::new(&config.embedding.model, config.embedding.dimensions * 2);
        assert!(store.write_manifest(&stale_manifest).is_ok());

        let output = run_index(fixture.root(), false).await;
        assert!(
            output.is_ok(),
            "run_index must auto-clear and reindex on dimension mismatch: {:?}",
            output.err()
        );
        let output = output.ok().unwrap_or_else(|| unreachable!());
        assert!(output.chunk_count > 0);

        let manifest = store.read_manifest();
        assert!(manifest.is_ok());
        let manifest = manifest.ok().unwrap_or_else(|| unreachable!());
        let manifest = manifest.unwrap_or_else(|| unreachable!());
        assert_eq!(
            manifest.dimensions, config.embedding.dimensions,
            "dimensions must match config after the clean reindex"
        );
    }

    #[tokio::test]
    async fn run_status_reports_manifest_and_counts() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let config = stub_config();
        let status = status_from_store(&harness.store, &config).await;
        assert!(status.is_ok());
        let status = status.ok().unwrap_or_else(|| unreachable!());

        assert_eq!(status.chunk_count, 3);
        assert_eq!(status.file_count, 2);
        assert_eq!(status.model.as_deref(), Some("stub-v1"));
        assert_eq!(status.dimensions, Some(8));
        assert!(!status.stale, "freshly indexed should not be stale");
    }

    #[tokio::test]
    async fn run_doctor_reports_index_and_embedding_health() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let config = stub_config();
        let claude_dir = harness.claudix.project_root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(&config);
        assert!(config_text.is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default(),
            )
            .is_ok()
        );

        let output = run_doctor(harness.claudix.project_root()).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(output.index_present);
        assert_eq!(output.chunk_count, 3);
        assert_eq!(output.file_count, 2);
        assert_eq!(output.model.as_deref(), Some("stub-v1"));
        assert_eq!(output.embedding_provider, "bundled");
        assert!(output.embedding_healthy);
    }

    #[tokio::test]
    async fn run_overview_returns_src_directory_rollup() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_overview(harness.claudix.project_root(), None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        // The small_rust fixture has files under src/ only.
        let src = output.directories.iter().find(|d| d.path == "src");
        assert!(src.is_some(), "expected a 'src' directory in the rollup");
        let src = src.unwrap_or_else(|| unreachable!());

        // src/ has src/math.rs and src/lib.rs — 2 files, 3 chunks total.
        assert_eq!(src.file_count, 2);
        assert_eq!(src.chunk_count, 3);

        // The fixture is Rust source — rust must appear in languages.
        assert!(
            src.languages.iter().any(|l| l.language == "rust"),
            "expected 'rust' among languages in src/"
        );
    }

    #[tokio::test]
    async fn run_overview_top_identifiers_include_known_fixture_name() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_overview(harness.claudix.project_root(), None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        let src = output.directories.iter().find(|d| d.path == "src");
        assert!(src.is_some());
        let src = src.unwrap_or_else(|| unreachable!());

        // src/math.rs defines `add` — it must appear in top identifiers.
        assert!(
            src.top_identifiers.iter().any(|name| name == "add"),
            "expected 'add' in top_identifiers for src/; got: {:?}",
            src.top_identifiers,
        );
    }

    #[tokio::test]
    async fn run_overview_path_prefix_narrows_to_subtree() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        // Prefix "src/math" should match only src/math.rs.
        let output =
            run_overview(harness.claudix.project_root(), Some("src/math".to_owned())).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        // Only chunks from src/math.rs pass the filter; src/lib.rs is excluded.
        assert!(output.file_count < 2, "prefix should exclude src/lib.rs");
        assert!(
            output.chunk_count > 0,
            "at least one chunk from src/math.rs"
        );

        // Every directory in the result must have files that match the prefix.
        for dir in &output.directories {
            assert!(
                path_prefix_matches(&format!("{}/file.rs", dir.path), "src/math")
                    || dir.path == "src",
                "unexpected directory outside prefix: {}",
                dir.path,
            );
        }
    }

    #[tokio::test]
    async fn run_overview_directories_sorted_ascending() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_overview(harness.claudix.project_root(), None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        let paths: Vec<&str> = output.directories.iter().map(|d| d.path.as_str()).collect();
        let mut sorted = paths.clone();
        sorted.sort();
        assert_eq!(
            paths, sorted,
            "directories must be sorted ascending by path"
        );
    }

    #[test]
    fn immediate_parent_dir_returns_dot_for_root_level_file() {
        assert_eq!(immediate_parent_dir("Cargo.toml"), ".");
        assert_eq!(immediate_parent_dir("lib.rs"), ".");
    }

    #[test]
    fn immediate_parent_dir_extracts_parent_segment() {
        assert_eq!(immediate_parent_dir("src/math.rs"), "src");
        assert_eq!(immediate_parent_dir("src/hooks/mod.rs"), "src/hooks");
    }

    #[tokio::test]
    async fn run_doctor_surfaces_specific_embedding_failure() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        // Point at a dead port with a non-bundled model so no fallback masks the
        // failure; doctor must report the actual reason, not a flat "unreachable".
        let mut config = stub_config();
        config.embedding.provider = config::EmbeddingProvider::Http;
        config.embedding.endpoint = "http://127.0.0.1:1".to_owned();
        config.embedding.model = "no-fallback-model".to_owned();
        config.embedding.timeout_ms = 100;

        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        let config_text = toml::to_string(&config);
        assert!(config_text.is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                config_text.ok().unwrap_or_default(),
            )
            .is_ok()
        );

        let output = run_doctor(fixture.root()).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(!output.embedding_healthy);
        assert!(!output.embedding_model_mismatch);
        assert!(
            output
                .embedding_error
                .is_some_and(|reason| reason.contains("http://127.0.0.1:1"))
        );
    }

    #[tokio::test]
    async fn search_groups_hits_by_directory_ordered_by_best_score() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        // "greet add" spans both src/lib.rs and src/math.rs — two directories
        // are both under "src", so we expect exactly one group named "src".
        // The small_rust fixture has all files under src/, so one group.
        let output = run_search_with_claudix(
            &harness.claudix,
            "add greet".to_owned(),
            10,
            None,
            None,
            Vec::new(),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(!output.groups.is_empty(), "expected at least one group");

        // Every group's directory must equal immediate_parent_dir of its hits.
        for group in &output.groups {
            for hit in &group.hits {
                assert_eq!(
                    immediate_parent_dir(&hit.file_path),
                    group.directory,
                    "hit {} belongs in wrong group",
                    hit.file_path,
                );
            }
        }

        // Hits within each group must be in score-descending order.
        for group in &output.groups {
            let scores: Vec<f32> = group.hits.iter().map(|h| h.score).collect();
            let mut sorted = scores.clone();
            sorted.sort_by(|a, b| b.partial_cmp(a).unwrap_or(std::cmp::Ordering::Equal));
            assert_eq!(
                scores, sorted,
                "hits in group '{}' not score-desc",
                group.directory
            );
        }
    }

    #[tokio::test]
    async fn search_grouping_preserves_top_hit_ranking() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_search_with_claudix(
            &harness.claudix,
            "add".to_owned(),
            5,
            None,
            None,
            Vec::new(),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(!output.groups.is_empty());

        // The globally top-ranked hit must be groups[0].hits[0] — grouping must
        // not reorder the flat ranking, only reshape its presentation.
        let top = &output.groups[0].hits[0];
        let all_scores: Vec<f32> = output
            .groups
            .iter()
            .flat_map(|g| g.hits.iter().map(|h| h.score))
            .collect();
        let global_max = all_scores.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        assert_eq!(
            top.score, global_max,
            "top hit in groups[0] must have the globally highest score"
        );
    }

    // ── find_duplicates tests ────────────────────────────────────────────────

    /// Build a temporary fixture with two Rust source files having identical content,
    /// index them with the stub provider, and return (fixture, store) so tests can
    /// call `run_find_duplicates`.
    async fn dup_harness() -> Result<(TestFixture, Store)> {
        let fixture = TestFixture::new("small_rust")?;
        // Write a second file whose content is byte-identical to src/math.rs so
        // the StubProvider (content-hash seed) emits the same vector → cosine = 1.0.
        let dup_content = std::fs::read_to_string(fixture.root().join("src").join("math.rs"))
            .map_err(ClaudixError::from)?;
        std::fs::write(fixture.root().join("src").join("math_copy.rs"), dup_content)
            .map_err(ClaudixError::from)?;

        let config = stub_config();
        let claudix = test_claudix(fixture.root().to_path_buf(), config.clone())?;
        index_fixture(
            &claudix.store,
            claudix.embedder.as_ref(),
            claudix.project_root(),
            &config,
        )
        .await?;
        let store = Store::new(fixture.root(), &config)?;
        Ok((fixture, store))
    }

    #[tokio::test]
    async fn find_duplicates_returns_pair_for_identical_content() {
        let result = dup_harness().await;
        assert!(result.is_ok());
        let (fixture, _store) = result.ok().unwrap_or_else(|| unreachable!());

        let output = run_find_duplicates(fixture.root(), None, None, None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        // math.rs and math_copy.rs share identical content → identical vectors → cosine 1.0.
        assert!(
            !output.pairs.is_empty(),
            "expected at least one pair from identical file content"
        );
        // Both chunks name the right files.
        let pair = &output.pairs[0];
        let paths = [pair.a.file_path.as_str(), pair.b.file_path.as_str()];
        assert!(
            paths.iter().any(|p| p.contains("math.rs")),
            "expected math.rs in the pair; got {:?}",
            paths
        );
        assert!(
            paths.iter().any(|p| p.contains("math_copy.rs")),
            "expected math_copy.rs in the pair; got {:?}",
            paths
        );
        assert!(
            pair.similarity > 0.99,
            "similarity should be ~1.0 for identical content"
        );
    }

    #[tokio::test]
    async fn find_duplicates_returns_empty_for_unique_repo() {
        // small_rust has lib.rs and math.rs with distinct content → no duplicates.
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let output = run_find_duplicates(harness.claudix.project_root(), None, None, None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(
            output.pairs.is_empty(),
            "distinct-content repo should have no duplicates"
        );
    }

    #[tokio::test]
    async fn find_duplicates_threshold_sensitivity() {
        let result = dup_harness().await;
        assert!(result.is_ok());
        let (fixture, _store) = result.ok().unwrap_or_else(|| unreachable!());

        // At threshold 0.99 the identical pair still shows.
        let high = run_find_duplicates(fixture.root(), Some(0.99), None, None).await;
        assert!(high.is_ok());
        let high = high.ok().unwrap_or_else(|| unreachable!());
        assert!(
            !high.pairs.is_empty(),
            "threshold 0.99 should still find identical pair"
        );

        let ceiling = run_find_duplicates(fixture.root(), Some(1.01), None, None).await;
        assert!(
            ceiling.is_err(),
            "threshold > 1.0 must be rejected before scanning"
        );
    }

    #[tokio::test]
    async fn find_duplicates_rejects_invalid_threshold_and_limit() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let nan =
            run_find_duplicates(harness.claudix.project_root(), Some(f32::NAN), None, None).await;
        assert!(nan.is_err(), "NaN threshold must be rejected");

        let negative =
            run_find_duplicates(harness.claudix.project_root(), Some(-0.1), None, None).await;
        assert!(negative.is_err(), "negative threshold must be rejected");

        let zero_limit =
            run_find_duplicates(harness.claudix.project_root(), None, Some(0), None).await;
        assert!(zero_limit.is_err(), "zero limit must be rejected");
    }

    #[tokio::test]
    async fn find_duplicates_same_file_not_reported() {
        // Even when identical chunks come from the same file, only cross-file pairs
        // should appear. The dup_harness fixture has math.rs AND math_copy.rs (different
        // files), so the pair is expected — but confirm no entry has a.file_path == b.file_path.
        let result = dup_harness().await;
        assert!(result.is_ok());
        let (fixture, _store) = result.ok().unwrap_or_else(|| unreachable!());

        let output = run_find_duplicates(fixture.root(), Some(0.0), None, None).await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        for pair in &output.pairs {
            assert!(
                pair.a.file_path != pair.b.file_path || pair.a.repo != pair.b.repo,
                "same-file pair must not be reported: {} == {}",
                pair.a.file_path,
                pair.b.file_path,
            );
        }
    }

    #[tokio::test]
    async fn find_duplicates_partial_success_on_unindexed_path() {
        let result = dup_harness().await;
        assert!(result.is_ok());
        let (fixture, _store) = result.ok().unwrap_or_else(|| unreachable!());

        let indexed = fixture.root().display().to_string();
        let unindexed = "/tmp/nonexistent-claudix-test-repo-12345".to_owned();

        let output = run_find_duplicates(
            fixture.root(),
            None,
            None,
            Some(vec![indexed, unindexed.clone()]),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        // The unindexed path must produce a RepoError.
        assert!(
            output.repo_errors.iter().any(|e| e.repo == unindexed
                || e.error.contains("not indexed")
                || e.error.contains("No such")),
            "expected a repo_error for the unindexed path; got: {:?}",
            output.repo_errors,
        );
        // Pairs from the indexed repo are still returned.
        assert!(
            !output.pairs.is_empty(),
            "indexed repo should still produce pairs despite the error"
        );
    }

    #[tokio::test]
    async fn load_repo_chunks_readonly_rejects_dimension_mismatch() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let root = harness.claudix.project_root().display().to_string();
        // Manifest has dimensions=8 (stub_config). Asking with wrong dims triggers mismatch.
        let result = load_repo_chunks_readonly(&root, "stub-v1", 999).await;
        assert!(
            result.is_err(),
            "mismatched dimensions must produce a RepoError"
        );
        let err = result.err().unwrap_or_else(|| unreachable!());
        assert!(
            err.error.contains("mismatch"),
            "error should mention mismatch; got: {}",
            err.error,
        );
    }

    #[tokio::test]
    async fn load_repo_chunks_readonly_rejects_model_mismatch() {
        let harness = cli_harness().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let root = harness.claudix.project_root().display().to_string();
        let result = load_repo_chunks_readonly(&root, "different-model", 8).await;
        assert!(result.is_err(), "mismatched model must produce a RepoError");
        let err = result.err().unwrap_or_else(|| unreachable!());
        assert!(
            err.error.contains("mismatch"),
            "error should mention mismatch; got: {}",
            err.error,
        );
    }

    #[tokio::test]
    async fn load_repo_chunks_readonly_rejects_missing_chunk_table() {
        let harness = cli_harness_private().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());

        let index_dir = harness.claudix.store.state_dir_path().join("index");
        let remove = std::fs::remove_dir_all(&index_dir);
        assert!(remove.is_ok());

        let root = harness.claudix.project_root().display().to_string();
        let result = load_repo_chunks_readonly(&root, "stub-v1", 8).await;
        assert!(
            result.is_err(),
            "manifest claiming chunks without a chunks table must produce a RepoError"
        );
        let err = result.err().unwrap_or_else(|| unreachable!());
        assert!(
            err.error.contains("chunks missing"),
            "error should mention missing chunks; got: {}",
            err.error,
        );
    }

    #[tokio::test]
    async fn find_duplicates_multi_repo_detects_cross_repo_pair() {
        // Build two separate repos with an identical file, index each, then scan both.
        let fixture_a = TestFixture::new("small_rust");
        assert!(fixture_a.is_ok());
        let fixture_a = fixture_a.ok().unwrap_or_else(|| unreachable!());

        let fixture_b = TestFixture::new("small_rust");
        assert!(fixture_b.is_ok());
        let fixture_b = fixture_b.ok().unwrap_or_else(|| unreachable!());

        let config = stub_config();

        // Index repo A.
        let claudix_a = test_claudix(fixture_a.root().to_path_buf(), config.clone());
        assert!(claudix_a.is_ok());
        let claudix_a = claudix_a.ok().unwrap_or_else(|| unreachable!());
        let index_a = index_fixture(
            &claudix_a.store,
            claudix_a.embedder.as_ref(),
            claudix_a.project_root(),
            &config,
        )
        .await;
        assert!(index_a.is_ok());

        // Index repo B.
        let claudix_b = test_claudix(fixture_b.root().to_path_buf(), config.clone());
        assert!(claudix_b.is_ok());
        let claudix_b = claudix_b.ok().unwrap_or_else(|| unreachable!());
        let index_b = index_fixture(
            &claudix_b.store,
            claudix_b.embedder.as_ref(),
            claudix_b.project_root(),
            &config,
        )
        .await;
        assert!(index_b.is_ok());

        let repo_a = fixture_a.root().display().to_string();
        let repo_b = fixture_b.root().display().to_string();

        // Provide both repos explicitly — active project is NOT auto-added.
        let output = run_find_duplicates(
            fixture_a.root(),
            Some(0.99),
            None,
            Some(vec![repo_a.clone(), repo_b.clone()]),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(
            output.repo_errors.is_empty(),
            "both repos are indexed; no errors expected"
        );

        // Both repos contain the same fixture content → at least one cross-repo pair.
        assert!(
            !output.pairs.is_empty(),
            "identical fixture content across repos must produce cross-repo pairs"
        );

        // At least one pair must have a.repo != b.repo.
        let has_cross_repo = output.pairs.iter().any(|p| p.a.repo != p.b.repo);
        assert!(
            has_cross_repo,
            "at least one pair must span two different repos"
        );
    }

    // ── cross-repo search tests (Feature 6) ─────────────────────────────────

    /// Write `.claude/claudix.toml` into a fixture so `config::load` doesn't
    /// fall through to the user's global config (which on dev machines may
    /// point at a real embedding model that doesn't match the stub index).
    fn write_fixture_config(project_root: &Path, config: &Config) -> Result<()> {
        let claude_dir = project_root.join(".claude");
        fs::create_dir_all(&claude_dir).map_err(ClaudixError::from)?;
        let text = toml::to_string(config)
            .map_err(|e| ClaudixError::Store(format!("serialize stub config: {e}")))?;
        fs::write(claude_dir.join("claudix.toml"), text).map_err(ClaudixError::from)?;
        Ok(())
    }

    /// Set up two repos backed by the small_rust fixture and indexed with the
    /// same stub model so their vectors are comparable. Returns the canonical
    /// path of each. Caller passes one as `project_root`, the other as `repos`.
    async fn dual_repo_harness() -> Result<(TestFixture, TestFixture, String, String)> {
        let fixture_a = TestFixture::new("small_rust")?;
        let fixture_b = TestFixture::new("small_rust")?;
        let config = stub_config();

        let claudix_a = test_claudix(fixture_a.root().to_path_buf(), config.clone())?;
        index_fixture(
            &claudix_a.store,
            claudix_a.embedder.as_ref(),
            claudix_a.project_root(),
            &config,
        )
        .await?;
        write_fixture_config(fixture_a.root(), &config)?;

        let claudix_b = test_claudix(fixture_b.root().to_path_buf(), config.clone())?;
        index_fixture(
            &claudix_b.store,
            claudix_b.embedder.as_ref(),
            claudix_b.project_root(),
            &config,
        )
        .await?;
        write_fixture_config(fixture_b.root(), &config)?;

        let repo_a = fixture_a.root().display().to_string();
        let repo_b = fixture_b.root().display().to_string();
        Ok((fixture_a, fixture_b, repo_a, repo_b))
    }

    #[tokio::test]
    async fn search_spans_active_and_listed_repo_with_correct_labels() {
        let setup = dual_repo_harness().await;
        assert!(setup.is_ok());
        let (fixture_a, _fixture_b, repo_a, repo_b) = setup.ok().unwrap_or_else(|| unreachable!());

        let output = run_search(
            fixture_a.root(),
            "add".to_owned(),
            Some(10),
            None,
            None,
            Some(vec![repo_b.clone()]),
        )
        .await;
        assert!(output.is_ok(), "cross-repo search failed: {output:?}");
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(output.repo_errors.is_empty(), "no errors expected");

        // Hits surface from both repos, each correctly labeled.
        let from_a = output
            .groups
            .iter()
            .flat_map(|g| g.hits.iter())
            .any(|h| h.repo == repo_a);
        let from_b = output
            .groups
            .iter()
            .flat_map(|g| g.hits.iter())
            .any(|h| h.repo == repo_b);
        assert!(
            from_a,
            "expected at least one hit from active repo {repo_a}"
        );
        assert!(from_b, "expected at least one hit from extra repo {repo_b}");

        // Every hit's repo equals its group's repo.
        for group in &output.groups {
            for hit in &group.hits {
                assert_eq!(
                    hit.repo, group.repo,
                    "hit/group repo mismatch in directory {}",
                    group.directory
                );
            }
        }
    }

    #[tokio::test]
    async fn search_partial_success_on_unindexed_repo() {
        let harness = cli_harness_private().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());
        let write = write_fixture_config(harness.claudix.project_root(), &stub_config());
        assert!(write.is_ok());

        let unindexed = "/tmp/nonexistent-claudix-cross-repo-search-9999".to_owned();
        let output = run_search(
            harness.claudix.project_root(),
            "add".to_owned(),
            Some(10),
            None,
            None,
            Some(vec![unindexed.clone()]),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        // Unindexed path surfaces as a RepoError; the active repo still returns hits.
        assert!(
            output.repo_errors.iter().any(|e| e.repo == unindexed
                || e.error.contains("not indexed")
                || e.error.contains("No such")),
            "expected RepoError for unindexed path; got: {:?}",
            output.repo_errors,
        );
        assert!(
            !output.groups.is_empty(),
            "active repo must still produce hits despite the error"
        );
    }

    #[tokio::test]
    async fn search_partial_success_on_model_mismatch() {
        let fixture_a = TestFixture::new("small_rust");
        assert!(fixture_a.is_ok());
        let fixture_a = fixture_a.ok().unwrap_or_else(|| unreachable!());
        let fixture_b = TestFixture::new("small_rust");
        assert!(fixture_b.is_ok());
        let fixture_b = fixture_b.ok().unwrap_or_else(|| unreachable!());

        // Active repo uses stub-v1; extra repo uses stub-v2 → mismatch.
        let config_a = stub_config();
        let config_b = {
            let mut c = stub_config();
            c.embedding.model = "stub-v2".to_owned();
            c
        };

        let claudix_a = test_claudix(fixture_a.root().to_path_buf(), config_a.clone());
        assert!(claudix_a.is_ok());
        let claudix_a = claudix_a.ok().unwrap_or_else(|| unreachable!());
        let _ = index_fixture(
            &claudix_a.store,
            claudix_a.embedder.as_ref(),
            claudix_a.project_root(),
            &config_a,
        )
        .await;
        let write_a = write_fixture_config(fixture_a.root(), &config_a);
        assert!(write_a.is_ok());

        let claudix_b = test_claudix(fixture_b.root().to_path_buf(), config_b.clone());
        assert!(claudix_b.is_ok());
        let claudix_b = claudix_b.ok().unwrap_or_else(|| unreachable!());
        let _ = index_fixture(
            &claudix_b.store,
            claudix_b.embedder.as_ref(),
            claudix_b.project_root(),
            &config_b,
        )
        .await;
        let write_b = write_fixture_config(fixture_b.root(), &config_b);
        assert!(write_b.is_ok());

        let repo_b = fixture_b.root().display().to_string();
        let output = run_search(
            fixture_a.root(),
            "add".to_owned(),
            Some(10),
            None,
            None,
            Some(vec![repo_b.clone()]),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(
            output
                .repo_errors
                .iter()
                .any(|e| e.error.contains("mismatch")),
            "expected mismatch error for extra repo; got: {:?}",
            output.repo_errors,
        );
        // Active repo still returns hits.
        assert!(
            !output.groups.is_empty(),
            "active repo hits must survive a sibling repo's mismatch"
        );
    }

    #[tokio::test]
    async fn search_dedupes_active_when_listed_in_repos() {
        let harness = cli_harness_private().await;
        assert!(harness.is_ok());
        let harness = harness.ok().unwrap_or_else(|| unreachable!());
        let write = write_fixture_config(harness.claudix.project_root(), &stub_config());
        assert!(write.is_ok());

        // Baseline: no extra repos.
        let baseline = run_search(
            harness.claudix.project_root(),
            "add".to_owned(),
            Some(10),
            None,
            None,
            None,
        )
        .await;
        assert!(baseline.is_ok());
        let baseline = baseline.ok().unwrap_or_else(|| unreachable!());
        let baseline_hits: usize = baseline.groups.iter().map(|g| g.hits.len()).sum();

        // List the active repo path explicitly — must not double-count.
        let active_path = harness.claudix.project_root().display().to_string();
        let echoed = run_search(
            harness.claudix.project_root(),
            "add".to_owned(),
            Some(10),
            None,
            None,
            Some(vec![active_path]),
        )
        .await;
        assert!(echoed.is_ok());
        let echoed = echoed.ok().unwrap_or_else(|| unreachable!());
        let echoed_hits: usize = echoed.groups.iter().map(|g| g.hits.len()).sum();

        assert_eq!(
            baseline_hits, echoed_hits,
            "listing active path must not duplicate hits"
        );
        assert!(echoed.repo_errors.is_empty());
    }

    #[tokio::test]
    async fn search_groups_separate_same_named_dirs_per_repo() {
        let setup = dual_repo_harness().await;
        assert!(setup.is_ok());
        let (fixture_a, _fixture_b, _repo_a, repo_b) = setup.ok().unwrap_or_else(|| unreachable!());

        let output = run_search(
            fixture_a.root(),
            "add".to_owned(),
            Some(20),
            None,
            None,
            Some(vec![repo_b]),
        )
        .await;
        assert!(output.is_ok());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        // Both repos have a "src" directory; the grouping must keep them apart.
        let src_groups: Vec<&DirectoryGroup> = output
            .groups
            .iter()
            .filter(|g| g.directory == "src")
            .collect();
        assert!(
            src_groups.len() >= 2,
            "expected two distinct 'src' groups (one per repo), got {}",
            src_groups.len(),
        );
        let repos: HashSet<&str> = src_groups.iter().map(|g| g.repo.as_str()).collect();
        assert!(
            repos.len() >= 2,
            "src groups must come from distinct repos, got: {:?}",
            repos,
        );
    }

    #[tokio::test]
    async fn search_does_not_write_into_extra_repo() {
        let setup = dual_repo_harness().await;
        assert!(setup.is_ok());
        let (fixture_a, fixture_b, _repo_a, repo_b) = setup.ok().unwrap_or_else(|| unreachable!());

        // Snapshot the extra repo's .claudix state-dir tree before the search.
        let state_dir = fixture_b.root().join(".claudix");
        let before = snapshot_paths(&state_dir);

        let output = run_search(
            fixture_a.root(),
            "add".to_owned(),
            Some(10),
            None,
            None,
            Some(vec![repo_b]),
        )
        .await;
        assert!(output.is_ok());

        let after = snapshot_paths(&state_dir);
        assert_eq!(
            before, after,
            "cross-repo search must not write into the extra repo's .claudix dir",
        );
    }

    /// Snapshot every file path and its byte length under `dir` (recursive).
    /// Used to assert read-only behavior: nothing in the snapshot changes.
    fn snapshot_paths(dir: &Path) -> std::collections::BTreeSet<(PathBuf, u64)> {
        fn walk(dir: &Path, into: &mut std::collections::BTreeSet<(PathBuf, u64)>) {
            let Ok(entries) = std::fs::read_dir(dir) else {
                return;
            };
            for entry in entries.flatten() {
                let path = entry.path();
                let Ok(metadata) = entry.metadata() else {
                    continue;
                };
                if metadata.is_dir() {
                    walk(&path, into);
                } else {
                    into.insert((path, metadata.len()));
                }
            }
        }
        let mut set = std::collections::BTreeSet::new();
        walk(dir, &mut set);
        set
    }

    #[test]
    fn effective_cross_repos_orders_config_then_call_args() {
        let cfg = vec!["/cfg/a".to_owned(), "/cfg/b".to_owned()];
        let call = Some(vec!["/cfg/b".to_owned(), "/call/c".to_owned()]);
        let merged = effective_cross_repos(&cfg, call);
        // Config first, call second, exact-string duplicates dropped.
        assert_eq!(merged, vec!["/cfg/a", "/cfg/b", "/call/c"]);
    }

    #[test]
    fn effective_cross_repos_empty_when_both_empty() {
        let merged = effective_cross_repos(&[], None);
        assert!(merged.is_empty());
    }

    /// `run_doctor` must surface `development_mode` from config and `binary_path`
    /// from the running process. The default config has `development_mode = false`;
    /// a project config with `development_mode = true` must flip the field.
    #[tokio::test]
    async fn run_doctor_surfaces_development_mode_and_binary_path() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        // `development_mode` is a top-level key — must precede any section header.
        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                "development_mode = true\n\n[embedding]\nmodel = \"stub-v1\"\ndimensions = 8\n",
            )
            .is_ok()
        );

        let output = run_doctor(fixture.root()).await;
        assert!(output.is_ok(), "run_doctor failed: {:?}", output.err());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(
            output.development_mode,
            "development_mode must be true when set in project config"
        );
        assert!(
            !output.binary_path.is_empty(),
            "binary_path must be a non-empty string"
        );
        assert!(
            output.binary_path != "<unknown>" || std::env::current_exe().is_err(),
            "binary_path must resolve to the current exe path when available"
        );
    }

    /// `run_doctor` must surface `development_mode = false` when the project config
    /// explicitly sets it to false, overriding any global setting.
    #[tokio::test]
    async fn run_doctor_development_mode_false_when_project_config_disables_it() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        // `development_mode` is a top-level key — must appear before any
        // section header so the TOML parser does not assign it to [embedding].
        // This ensures the project layer wins over any global config the test
        // host may have (e.g. ~/.claude/claudix.toml with development_mode = true).
        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                "development_mode = false\n\n[embedding]\nmodel = \"stub-v1\"\ndimensions = 8\n",
            )
            .is_ok()
        );

        let output = run_doctor(fixture.root()).await;
        assert!(output.is_ok(), "run_doctor failed: {:?}", output.err());
        let output = output.ok().unwrap_or_else(|| unreachable!());

        assert!(
            !output.development_mode,
            "development_mode must be false when project config explicitly disables it"
        );
    }

    /// `run_index` must clear the store and produce a working index when
    /// `validate_manifest_compatibility` returns `SchemaMismatch` (future schema
    /// bump). This exercises the `requires_clean_reindex` → `clear_chunks` →
    /// `Claudix::new` retry path inside `IndexSession::new`.
    #[tokio::test]
    async fn run_index_clears_schema_mismatch_and_reindexes() {
        let fixture = TestFixture::new("small_rust");
        assert!(fixture.is_ok());
        let fixture = fixture.ok().unwrap_or_else(|| unreachable!());

        // Write a project config so run_index can load it.
        let claude_dir = fixture.root().join(".claude");
        assert!(std::fs::create_dir_all(&claude_dir).is_ok());
        assert!(
            std::fs::write(
                claude_dir.join("claudix.toml"),
                "[embedding]\nmodel = \"stub-v1\"\ndimensions = 8\n",
            )
            .is_ok()
        );

        let config = stub_config();
        let store = Store::new(fixture.root(), &config);
        assert!(store.is_ok());
        let store = store.ok().unwrap_or_else(|| unreachable!());

        // Inject a manifest with a future schema_version to trigger SchemaMismatch.
        let mut stale_manifest =
            Manifest::new(&config.embedding.model, config.embedding.dimensions);
        stale_manifest.schema_version = crate::store::SCHEMA_VERSION + 1;
        assert!(store.write_manifest(&stale_manifest).is_ok());

        // run_index must detect SchemaMismatch, clear, and reindex successfully.
        let output = run_index(fixture.root(), false).await;
        assert!(
            output.is_ok(),
            "run_index must succeed after schema mismatch: {:?}",
            output.err()
        );
        let output = output.ok().unwrap_or_else(|| unreachable!());
        assert!(
            output.chunk_count > 0,
            "reindex after schema mismatch must produce chunks"
        );

        // The manifest written after the reindex must carry the current schema version.
        let manifest = store.read_manifest();
        assert!(manifest.is_ok());
        let manifest = manifest.ok().unwrap_or_else(|| unreachable!());
        assert!(manifest.is_some());
        let manifest = manifest.unwrap_or_else(|| unreachable!());
        assert_eq!(
            manifest.schema_version,
            crate::store::SCHEMA_VERSION,
            "schema_version must match binary after clean reindex"
        );
    }
}