memd 0.51.0

Local memory CLI for AI agents with hybrid retrieval
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
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
//! Hybrid search coordinator
//!
//! Combines dense (semantic) and sparse (keyword) search with RRF fusion
//! and feature-based reranking for comprehensive retrieval.
//! Supports tiered search with cache/hot/warm fallback when enabled.
//! Includes query routing for intent classification and structural search blending.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use parking_lot::RwLock;
use tracing::debug;

use super::dense::DenseSearcher;
use crate::error::Result;
use crate::index::{Bm25Index, SearchResult, SparseIndex};
use crate::metrics::TieredQueryMetrics;
use crate::retrieval::packer::{ContextPacker, PackerConfig};
use crate::retrieval::{
    ChunkWithMeta, FusionCandidate, FusionSource, RerankerConfig, RerankerContext, RerankerEngine,
    RerankerMode, RrfConfig, RrfFusion,
};
use crate::structural::{
    CallerInfo, ErrorResult, ImportInfo, QueryIntent, QueryRouter, RouteResult, SymbolLocation,
    SymbolQueryService, ToolCallResult, TraceQueryService,
};
use crate::text::TextProcessor;
use crate::tiered::{
    AccessTracker, AccessTrackerConfig, HotTier, HotTierConfig, SemanticCache, SemanticCacheConfig,
    TieredSearcher, TieredSearcherConfig, TieredTiming, WarmTierSearch,
};
use crate::types::{ChunkId, ChunkType, TenantId};

/// Configuration for hybrid search
#[derive(Debug, Clone)]
pub struct HybridConfig {
    /// Number of candidates to fetch from dense search
    pub dense_k: usize,
    /// Number of candidates to fetch from sparse search
    pub sparse_k: usize,
    /// RRF configuration
    pub rrf: RrfConfig,
    /// Reranker configuration
    pub reranker: RerankerConfig,
    /// Packer configuration
    pub packer: PackerConfig,
    /// Enable sparse search (can be disabled for dense-only fallback)
    pub enable_sparse: bool,
    /// Enable tiered search with cache/hot/warm fallback
    pub enable_tiered: bool,
    /// Tiered search configuration (if enable_tiered is true)
    pub tiered_config: Option<TieredSearcherConfig>,
}

impl Default for HybridConfig {
    fn default() -> Self {
        Self {
            dense_k: 100,
            sparse_k: 100,
            rrf: RrfConfig::default(),
            reranker: RerankerConfig::default(),
            packer: PackerConfig::default(),
            enable_sparse: true,
            enable_tiered: true,
            tiered_config: None,
        }
    }
}

/// Result from hybrid search (before packing)
#[derive(Debug, Clone)]
pub struct HybridSearchResult {
    pub chunk_id: ChunkId,
    pub final_score: f32,
    pub dense_rank: Option<usize>,
    pub sparse_rank: Option<usize>,
}

/// Context for search (project, preferences)
#[derive(Debug, Clone, Default)]
pub struct SearchContext {
    pub current_project: Option<String>,
    pub preferred_types: Vec<ChunkType>,
}

/// Timing breakdown for hybrid search
#[derive(Debug, Clone, Default)]
pub struct HybridTiming {
    pub dense_time: Duration,
    pub sparse_time: Duration,
    pub fusion_time: Duration,
    pub rerank_time: Duration,
    pub total_time: Duration,
    /// Tiered timing breakdown (if tiered search was used)
    pub tiered: Option<TieredTiming>,
}

/// Chunk metadata for reranking
pub struct ChunkMetaForRerank {
    pub chunk_id: ChunkId,
    pub rrf_score: f32,
    pub timestamp_created: i64,
    pub project_id: Option<String>,
    pub chunk_type: ChunkType,
    pub text: Option<String>,
}

// ============================================================================
// Query Routing Types
// ============================================================================

/// Result from search_with_routing, supporting different result types.
#[derive(Debug)]
pub enum SearchWithRoutingResult {
    /// Pure hybrid/semantic search results.
    Hybrid(Vec<HybridSearchResult>),

    /// Structural results only (no semantic context).
    Structural(StructuralSearchResult),

    /// Structural primary + semantic context (STRUCT-14 blending).
    Blended(BlendedSearchResult),

    /// Trace/debug results (tool calls, stack traces).
    Trace(TraceSearchResult),
}

/// Result from structural search.
#[derive(Debug)]
pub struct StructuralSearchResult {
    /// The classified intent.
    pub intent: QueryIntent,
    /// Symbol locations found.
    pub symbols: Vec<SymbolLocation>,
    /// Caller information (if callers query).
    pub callers: Vec<CallerInfo>,
    /// Import information (if imports query).
    pub imports: Vec<ImportInfo>,
    /// Whether we fell back to semantic search.
    pub fell_back_to_semantic: bool,
}

impl Default for StructuralSearchResult {
    fn default() -> Self {
        Self {
            intent: QueryIntent::SemanticSearch,
            symbols: Vec::new(),
            callers: Vec::new(),
            imports: Vec::new(),
            fell_back_to_semantic: false,
        }
    }
}

/// Blended result with structural primary and semantic context (STRUCT-14).
#[derive(Debug)]
pub struct BlendedSearchResult {
    /// The classified intent.
    pub intent: QueryIntent,
    /// Primary results from structural search.
    pub structural: StructuralSearchResult,
    /// Supplementary context from semantic search.
    pub semantic_context: Vec<HybridSearchResult>,
    /// How results were blended.
    pub blend_strategy: BlendStrategy,
}

/// Strategy for blending structural and semantic results.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BlendStrategy {
    /// Structural results first (100%), semantic for context only.
    StructuralPrimary,
    /// Weighted blend (structural_weight determines proportion).
    Weighted {
        /// Weight for structural results (0.0-1.0).
        structural_weight: f32,
    },
}

impl Default for BlendStrategy {
    fn default() -> Self {
        Self::StructuralPrimary
    }
}

/// Result from trace/debug search.
#[derive(Debug, Default)]
pub struct TraceSearchResult {
    /// The classified intent.
    pub intent: QueryIntent,
    /// Tool call results.
    pub tool_calls: Vec<ToolCallResult>,
    /// Error/stack trace results.
    pub errors: Vec<ErrorResult>,
}

/// Adapter to expose DenseSearcher as a warm tier for TieredSearcher
///
/// This adapter bridges the DenseSearcher (which handles embedding + HNSW)
/// to the WarmTierSearch trait required by TieredSearcher.
pub struct WarmTierAdapter {
    /// Reference to the dense searcher
    dense: Arc<DenseSearcher>,
    /// Tenant for scoped searches
    tenant_id: TenantId,
    /// Version counter for cache invalidation
    version: AtomicU64,
    /// Cached embeddings for hot tier promotion (chunk_id -> embedding)
    embedding_cache: RwLock<std::collections::HashMap<ChunkId, Vec<f32>>>,
}

impl WarmTierAdapter {
    /// Create a new warm tier adapter for a tenant
    pub fn new(dense: Arc<DenseSearcher>, tenant_id: TenantId) -> Self {
        Self {
            dense,
            tenant_id,
            version: AtomicU64::new(1),
            embedding_cache: RwLock::new(std::collections::HashMap::new()),
        }
    }

    /// Cache an embedding for later hot tier promotion
    pub fn cache_embedding(&self, chunk_id: ChunkId, embedding: Vec<f32>) {
        let mut cache = self.embedding_cache.write();
        cache.insert(chunk_id, embedding);
    }

    /// Increment version (call on chunk add/delete)
    pub fn increment_version(&self) {
        self.version.fetch_add(1, Ordering::SeqCst);
    }
}

impl WarmTierSearch for WarmTierAdapter {
    fn search(&self, query_embedding: &[f32], k: usize) -> Result<Vec<SearchResult>> {
        // Use the dense searcher's search with pre-computed embedding
        let results = self
            .dense
            .search_with_embedding(&self.tenant_id, query_embedding, k)?;

        // Convert DenseSearchResult to SearchResult
        Ok(results
            .into_iter()
            .map(|r| SearchResult {
                chunk_id: r.chunk_id,
                score: r.score,
            })
            .collect())
    }

    fn get_embedding(&self, chunk_id: &ChunkId) -> Option<Vec<f32>> {
        let cache = self.embedding_cache.read();
        cache.get(chunk_id).cloned()
    }

    fn get_version(&self) -> u64 {
        self.version.load(Ordering::SeqCst)
    }

    fn len(&self) -> usize {
        self.dense.index_len(&self.tenant_id)
    }
}

/// Hybrid search coordinator
///
/// Combines dense (embedding-based) and sparse (BM25) search, fuses results
/// with RRF, and applies feature-based reranking. Supports tiered search
/// with cache/hot/warm fallback when enabled.
///
/// Also integrates query routing for intent classification and structural search.
pub struct HybridSearcher {
    dense: Arc<DenseSearcher>,
    sparse: Option<Arc<Bm25Index>>,
    text_processor: TextProcessor,
    fusion: RrfFusion,
    reranker: RerankerEngine,
    #[allow(dead_code)]
    packer: ContextPacker,
    config: HybridConfig,
    /// Per-tenant tiered searchers (only populated if enable_tiered is true)
    tiered_searchers:
        RwLock<std::collections::HashMap<String, Arc<TieredSearcher<WarmTierAdapter>>>>,
    /// Shared semantic cache (across tenants)
    semantic_cache: Option<Arc<SemanticCache>>,
    /// Access tracker config for creating per-tenant access trackers
    access_tracker_config: AccessTrackerConfig,
    /// Hot tier config for creating per-tenant hot tiers
    hot_tier_config: HotTierConfig,
    /// Query router for intent classification.
    router: QueryRouter,
    /// Optional symbol query service for structural search.
    symbol_query_service: Option<Arc<SymbolQueryService>>,
    /// Optional trace query service for debug/trace search.
    trace_query_service: Option<Arc<TraceQueryService>>,
}

impl HybridSearcher {
    /// Borrow the sparse index if BM25 is enabled.
    pub fn sparse_index(&self) -> Option<&Arc<Bm25Index>> {
        self.sparse.as_ref()
    }

    /// Create a new hybrid searcher
    pub fn new(
        dense: Arc<DenseSearcher>,
        sparse: Option<Arc<Bm25Index>>,
        config: HybridConfig,
    ) -> Self {
        let fusion = RrfFusion::new(config.rrf.clone());
        let reranker = RerankerEngine::new(config.reranker.clone());
        let packer = ContextPacker::new(config.packer.clone());

        // Create shared semantic cache if tiered search is enabled
        let semantic_cache = if config.enable_tiered {
            Some(Arc::new(SemanticCache::new(SemanticCacheConfig::default())))
        } else {
            None
        };

        // Create hot tier config based on dense dimension
        let dimension = dense.dimension();
        let hot_tier_config = HotTierConfig {
            hnsw_config: crate::index::HnswConfig {
                dimension,
                max_elements: 50_000,
                max_connections: 16,
                ef_construction: 200,
                ef_search: 30, // Lower than warm tier for faster queries
                persist_graph_dump: true,
            },
            ..Default::default()
        };

        Self {
            dense,
            sparse,
            text_processor: TextProcessor::new(),
            fusion,
            reranker,
            packer,
            config,
            tiered_searchers: RwLock::new(std::collections::HashMap::new()),
            semantic_cache,
            access_tracker_config: AccessTrackerConfig::default(),
            hot_tier_config,
            router: QueryRouter::new(),
            symbol_query_service: None,
            trace_query_service: None,
        }
    }

    /// Create a hybrid searcher with structural query services.
    pub fn with_query_services(
        dense: Arc<DenseSearcher>,
        sparse: Option<Arc<Bm25Index>>,
        config: HybridConfig,
        symbol_query_service: Option<Arc<SymbolQueryService>>,
        trace_query_service: Option<Arc<TraceQueryService>>,
    ) -> Self {
        let mut searcher = Self::new(dense, sparse, config);
        searcher.symbol_query_service = symbol_query_service;
        searcher.trace_query_service = trace_query_service;
        searcher
    }

    /// Effective reranker mode in use (after fallback handling).
    pub fn reranker_mode(&self) -> RerankerMode {
        self.reranker.mode()
    }

    /// Set the symbol query service for structural search.
    pub fn set_symbol_query_service(&mut self, service: Arc<SymbolQueryService>) {
        self.symbol_query_service = Some(service);
    }

    /// Set the trace query service for debug/trace search.
    pub fn set_trace_query_service(&mut self, service: Arc<TraceQueryService>) {
        self.trace_query_service = Some(service);
    }

    /// Get reference to the query router.
    pub fn router(&self) -> &QueryRouter {
        &self.router
    }

    /// Get or create tiered searcher for a tenant
    fn get_or_create_tiered_searcher(
        &self,
        tenant_id: &TenantId,
    ) -> Option<Arc<TieredSearcher<WarmTierAdapter>>> {
        if !self.config.enable_tiered {
            return None;
        }

        let tenant_str = tenant_id.to_string();

        // Fast path: read lock
        {
            let tiered_searchers = self.tiered_searchers.read();
            if let Some(searcher) = tiered_searchers.get(&tenant_str) {
                return Some(Arc::clone(searcher));
            }
        }

        // Slow path: write lock + create
        let mut tiered_searchers = self.tiered_searchers.write();

        // Double-check
        if let Some(searcher) = tiered_searchers.get(&tenant_str) {
            return Some(Arc::clone(searcher));
        }

        // Create components for this tenant
        let warm_tier = Arc::new(WarmTierAdapter::new(
            Arc::clone(&self.dense),
            tenant_id.clone(),
        ));

        let access_tracker = Arc::new(RwLock::new(AccessTracker::new(
            self.access_tracker_config.clone(),
        )));

        let hot_tier = Arc::new(RwLock::new(HotTier::with_access_tracker(
            self.hot_tier_config.clone(),
            Arc::clone(&access_tracker),
        )));

        let tiered_config = self.config.tiered_config.clone().unwrap_or_default();

        let tiered_searcher = TieredSearcher::new(
            Arc::clone(self.semantic_cache.as_ref()?),
            hot_tier,
            access_tracker,
            warm_tier,
            tiered_config,
        );

        let tiered_searcher = Arc::new(tiered_searcher);
        tiered_searchers.insert(tenant_str, Arc::clone(&tiered_searcher));

        Some(tiered_searcher)
    }

    /// Index a chunk in both dense and sparse indexes
    pub async fn index_chunk(
        &self,
        tenant_id: &TenantId,
        chunk_id: &ChunkId,
        text: &str,
    ) -> Result<()> {
        self.index_batch(tenant_id, &[(chunk_id.clone(), text.to_string())])
            .await
    }

    /// Index multiple chunks in dense+sparse indexes with batched operations.
    pub async fn index_batch(
        &self,
        tenant_id: &TenantId,
        chunks: &[(ChunkId, String)],
    ) -> Result<()> {
        if chunks.is_empty() {
            return Ok(());
        }

        self.dense.index_batch(tenant_id, chunks).await?;

        if self.config.enable_sparse {
            if let Some(ref sparse) = self.sparse {
                let sparse_items: Vec<(TenantId, ChunkId, Vec<String>)> = chunks
                    .iter()
                    .filter_map(|(chunk_id, text)| {
                        let processed = self.text_processor.process_chunk(text);
                        let sentences: Vec<String> =
                            processed.into_iter().map(|p| p.text).collect();
                        if sentences.is_empty() {
                            return None;
                        }
                        Some((tenant_id.clone(), chunk_id.clone(), sentences))
                    })
                    .collect();
                if !sparse_items.is_empty() {
                    sparse.insert_batch(&sparse_items)?;
                }
            }
        }

        // Phase 3.5: bump the per-tenant memory version so the
        // semantic cache invalidates any entry whose snapshot predates
        // this write. Previously the version was only advertised via
        // `WarmTierAdapter::get_version` but never incremented, so the
        // cache never invalidated on add.
        self.bump_tenant_memory_version(tenant_id);

        debug!(
            tenant_id = %tenant_id,
            chunk_count = chunks.len(),
            sparse_enabled = self.config.enable_sparse,
            "indexed batch in hybrid searcher"
        );
        Ok(())
    }

    /// Bump the per-tenant `memory_version` on the warm tier so cache
    /// consumers can detect stale entries. Exposed on HybridSearcher
    /// rather than inlined so the storage layer can call it from any
    /// mutation path without reaching into private state.
    pub fn bump_tenant_memory_version(&self, tenant_id: &TenantId) {
        if let Some(searcher) = self.get_or_create_tiered_searcher(tenant_id) {
            searcher.warm_tier().increment_version();
        }
    }

    /// Current per-tenant `memory_version` from the warm tier.
    /// Returns `None` when no tiered searcher has been created for
    /// this tenant (e.g., tiered search disabled). Exposed primarily
    /// for tests and diagnostics — production code should rely on the
    /// cache's own staleness logic.
    pub fn tenant_memory_version(&self, tenant_id: &TenantId) -> Option<u64> {
        use crate::tiered::tiered_searcher::WarmTierSearch;
        let searchers = self.tiered_searchers.read();
        searchers
            .get(tenant_id.as_str())
            .map(|searcher| searcher.warm_tier().get_version())
    }

    /// Remove chunk from indexes
    pub fn delete_chunk(&self, tenant_id: &TenantId, chunk_id: &ChunkId) -> Result<()> {
        // Delete from sparse if enabled
        if self.config.enable_sparse {
            if let Some(ref sparse) = self.sparse {
                sparse.delete(tenant_id, chunk_id)?;
            }
        }

        // Invalidate in semantic cache (if tiered enabled)
        self.invalidate_chunk_in_cache(chunk_id);

        // Demote from hot tier if present
        if self.get_or_create_tiered_searcher(tenant_id).is_some() {
            // Access the hot tier through the searcher is not directly possible,
            // but invalidation is handled through cache and the chunk will be
            // filtered out on next search since metadata marks it deleted.
            debug!(
                tenant_id = %tenant_id,
                chunk_id = %chunk_id,
                "invalidated chunk in tiered cache"
            );
        }

        // Note: Dense index deletion is not currently supported by HnswIndex
        // The chunk will be orphaned but won't appear in results after
        // metadata is updated

        // Phase 3.5: bump the per-tenant memory version so cache
        // entries that predate this delete are invalidated.
        self.bump_tenant_memory_version(tenant_id);

        debug!(
            tenant_id = %tenant_id,
            chunk_id = %chunk_id,
            "deleted chunk from hybrid searcher"
        );

        Ok(())
    }

    /// Perform hybrid search with fusion and reranking
    pub async fn search(
        &self,
        tenant_id: &TenantId,
        query: &str,
        k: usize,
        context: Option<SearchContext>,
    ) -> Result<Vec<HybridSearchResult>> {
        let (results, _timing) = self
            .search_with_timing(tenant_id, query, k, context)
            .await?;
        Ok(results)
    }

    /// Search with timing information for metrics
    ///
    /// If tiered search is enabled, uses cache/hot/warm fallback.
    /// Otherwise falls back to standard dense+sparse fusion.
    pub async fn search_with_timing(
        &self,
        tenant_id: &TenantId,
        query: &str,
        k: usize,
        context: Option<SearchContext>,
    ) -> Result<(Vec<HybridSearchResult>, HybridTiming)> {
        // Try tiered search first if enabled
        if let Some(tiered_searcher) = self.get_or_create_tiered_searcher(tenant_id) {
            return self
                .search_tiered(tenant_id, query, k, context.as_ref(), &tiered_searcher)
                .await;
        }

        // Fall back to standard dense+sparse fusion
        self.search_standard(tenant_id, query, k).await
    }

    /// Internal tiered search path
    async fn search_tiered(
        &self,
        tenant_id: &TenantId,
        query: &str,
        k: usize,
        context: Option<&SearchContext>,
        tiered_searcher: &TieredSearcher<WarmTierAdapter>,
    ) -> Result<(Vec<HybridSearchResult>, HybridTiming)> {
        let total_start = Instant::now();
        let mut timing = HybridTiming::default();

        // Step 1: Embed query
        let embed_start = Instant::now();
        let query_embedding = self.dense.embed_query(query).await?;
        timing.dense_time = embed_start.elapsed(); // Embed time tracked as dense_time

        // Step 2: Tiered search (cache -> hot -> warm)
        let project_id = context.and_then(|c| c.current_project.as_deref());
        let tiered_result = tiered_searcher.search(&query_embedding, tenant_id, project_id, k)?;

        // Convert TieredTiming
        let tiered_timing = tiered_result.timing;
        timing.tiered = Some(tiered_timing.clone());

        // Step 3: If cache miss and sparse enabled, merge with sparse results
        let sparse_start = Instant::now();
        let sparse_results = if !tiered_result.cache_hit && self.config.enable_sparse {
            if let Some(ref sparse) = self.sparse {
                sparse.search(tenant_id, query, self.config.sparse_k)?
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };
        timing.sparse_time = sparse_start.elapsed();

        // Step 4: Build results
        // For cache hits, return directly; for non-cache, fuse with sparse
        let results: Vec<HybridSearchResult> =
            if tiered_result.cache_hit || sparse_results.is_empty() {
                // Direct conversion from tiered results
                tiered_result
                    .results
                    .into_iter()
                    .map(|r| HybridSearchResult {
                        chunk_id: r.chunk_id,
                        final_score: r.score,
                        dense_rank: None, // Tier doesn't track separate ranks
                        sparse_rank: None,
                    })
                    .collect()
            } else {
                // Fuse tiered (dense) results with sparse
                let fusion_start = Instant::now();
                let mut candidates: Vec<FusionCandidate> = Vec::new();

                // Tiered results as dense candidates
                for (rank, result) in tiered_result.results.iter().enumerate() {
                    candidates.push(FusionCandidate {
                        chunk_id: result.chunk_id.clone(),
                        source: FusionSource::Dense,
                        rank: rank + 1,
                        source_score: result.score,
                    });
                }

                // Sparse candidates
                for (rank, result) in sparse_results.iter().enumerate() {
                    candidates.push(FusionCandidate {
                        chunk_id: result.chunk_id.clone(),
                        source: FusionSource::Sparse,
                        rank: rank + 1,
                        source_score: result.score,
                    });
                }

                let fused = self.fusion.fuse(candidates);
                timing.fusion_time = fusion_start.elapsed();

                fused
                    .into_iter()
                    .take(k)
                    .map(|f| HybridSearchResult {
                        chunk_id: f.chunk_id,
                        final_score: f.rrf_score,
                        dense_rank: f.dense_rank,
                        sparse_rank: f.sparse_rank,
                    })
                    .collect()
            };

        timing.total_time = total_start.elapsed();

        debug!(
            tenant_id = %tenant_id,
            query_len = query.len(),
            cache_hit = tiered_result.cache_hit,
            hot_tier_hit = tiered_result.hot_tier_hit,
            source_tier = ?tiered_result.source_tier,
            result_count = results.len(),
            total_ms = timing.total_time.as_millis(),
            "tiered hybrid search completed"
        );

        Ok((results, timing))
    }

    /// Standard dense+sparse fusion path (when tiered is disabled)
    async fn search_standard(
        &self,
        tenant_id: &TenantId,
        query: &str,
        k: usize,
    ) -> Result<(Vec<HybridSearchResult>, HybridTiming)> {
        let total_start = Instant::now();
        let mut timing = HybridTiming::default();

        // Step 1: Dense search
        let dense_start = Instant::now();
        let (dense_results, _embed_time, _search_time) = self
            .dense
            .search_with_timing(tenant_id, query, self.config.dense_k)
            .await?;
        timing.dense_time = dense_start.elapsed();

        // Step 2: Sparse search (if enabled)
        let sparse_start = Instant::now();
        let sparse_results = if self.config.enable_sparse {
            if let Some(ref sparse) = self.sparse {
                sparse.search(tenant_id, query, self.config.sparse_k)?
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };
        timing.sparse_time = sparse_start.elapsed();

        // Step 3: Build fusion candidates
        let fusion_start = Instant::now();
        let mut candidates: Vec<FusionCandidate> = Vec::new();

        // Dense candidates
        for (rank, result) in dense_results.iter().enumerate() {
            candidates.push(FusionCandidate {
                chunk_id: result.chunk_id.clone(),
                source: FusionSource::Dense,
                rank: rank + 1, // 1-indexed
                source_score: result.score,
            });
        }

        // Sparse candidates
        for (rank, result) in sparse_results.iter().enumerate() {
            candidates.push(FusionCandidate {
                chunk_id: result.chunk_id.clone(),
                source: FusionSource::Sparse,
                rank: rank + 1, // 1-indexed
                source_score: result.score,
            });
        }

        // Fuse with RRF
        let fused = self.fusion.fuse(candidates);
        timing.fusion_time = fusion_start.elapsed();

        // Step 4: Rerank (simplified - without full metadata)
        // Full reranking with metadata requires store access, which is done at PersistentStore level
        let rerank_start = Instant::now();

        // Build results from fused
        let results: Vec<HybridSearchResult> = fused
            .into_iter()
            .take(k)
            .map(|f| HybridSearchResult {
                chunk_id: f.chunk_id,
                final_score: f.rrf_score,
                dense_rank: f.dense_rank,
                sparse_rank: f.sparse_rank,
            })
            .collect();

        timing.rerank_time = rerank_start.elapsed();
        timing.total_time = total_start.elapsed();

        debug!(
            tenant_id = %tenant_id,
            query_len = query.len(),
            dense_count = dense_results.len(),
            sparse_count = sparse_results.len(),
            result_count = results.len(),
            dense_ms = timing.dense_time.as_millis(),
            sparse_ms = timing.sparse_time.as_millis(),
            fusion_ms = timing.fusion_time.as_millis(),
            total_ms = timing.total_time.as_millis(),
            "hybrid search completed"
        );

        Ok((results, timing))
    }

    /// Rerank results with full metadata (called by PersistentStore)
    pub fn rerank_with_metadata(
        &self,
        results: Vec<HybridSearchResult>,
        chunks_meta: Vec<ChunkMetaForRerank>,
        context: Option<SearchContext>,
    ) -> Vec<HybridSearchResult> {
        self.rerank_with_metadata_for_query("", results, chunks_meta, context)
    }

    /// Rerank results with full metadata and query context.
    pub fn rerank_with_metadata_for_query(
        &self,
        query: &str,
        results: Vec<HybridSearchResult>,
        chunks_meta: Vec<ChunkMetaForRerank>,
        context: Option<SearchContext>,
    ) -> Vec<HybridSearchResult> {
        if chunks_meta.is_empty() {
            return results;
        }

        let mut reranker_context = match context {
            Some(ctx) => {
                let base = RerankerContext::now().with_preferred_types(ctx.preferred_types);
                if let Some(project) = ctx.current_project {
                    base.with_project(project)
                } else {
                    base
                }
            }
            None => RerankerContext::now(),
        };
        if !query.trim().is_empty() {
            reranker_context = reranker_context.with_query(query);
        }

        let chunks_with_meta: Vec<ChunkWithMeta> = chunks_meta
            .into_iter()
            .map(|meta| ChunkWithMeta {
                chunk_id: meta.chunk_id,
                rrf_score: meta.rrf_score,
                timestamp_created: meta.timestamp_created,
                project_id: meta.project_id,
                chunk_type: meta.chunk_type,
                text: meta.text,
            })
            .collect();

        let ranked = self.reranker.rerank(chunks_with_meta, &reranker_context);

        ranked
            .into_iter()
            .map(|r| {
                let original = results.iter().find(|orig| orig.chunk_id == r.chunk_id);

                HybridSearchResult {
                    chunk_id: r.chunk_id,
                    final_score: r.final_score,
                    dense_rank: original.and_then(|o| o.dense_rank),
                    sparse_rank: original.and_then(|o| o.sparse_rank),
                }
            })
            .collect()
    }

    // ========================================================================
    // Query Routing Methods
    // ========================================================================

    /// Search with intent-based routing.
    ///
    /// Classifies the query intent and routes to the appropriate search backend:
    /// - Structural queries (symbol definition, callers, references, imports) go to SymbolQueryService
    /// - Trace queries (tool calls, errors) go to TraceQueryService
    /// - Semantic queries fall back to hybrid search
    ///
    /// For code-intent queries (STRUCT-14), blends structural results with semantic context.
    pub async fn search_with_routing(
        &self,
        tenant_id: &TenantId,
        query: &str,
        k: usize,
        project_id: Option<&str>,
    ) -> Result<SearchWithRoutingResult> {
        let route = self.router.classify(query);

        debug!(
            tenant_id = %tenant_id,
            query = query,
            intent = ?route.intent,
            confidence = route.confidence,
            blend = route.blend_semantic_context,
            "query routed"
        );

        match route.intent {
            QueryIntent::SemanticSearch => {
                // Fall back to standard hybrid search
                let context = project_id.map(|p| SearchContext {
                    current_project: Some(p.to_string()),
                    preferred_types: Vec::new(),
                });
                let results = self.search(tenant_id, query, k, context).await?;
                Ok(SearchWithRoutingResult::Hybrid(results))
            }

            QueryIntent::SymbolDefinition(ref name) => {
                self.route_symbol_definition(tenant_id, name, k, project_id, &route)
                    .await
            }

            QueryIntent::SymbolCallers(ref name) => {
                self.route_symbol_callers(tenant_id, name, k, project_id, &route)
                    .await
            }

            QueryIntent::SymbolReferences(ref name) => {
                self.route_symbol_references(tenant_id, name, k, project_id, &route)
                    .await
            }

            QueryIntent::ModuleImports(ref module) => {
                self.route_module_imports(tenant_id, module, k, project_id, &route)
                    .await
            }

            QueryIntent::FileSymbols(ref file) => {
                self.route_file_symbols(tenant_id, file, k, project_id, &route)
                    .await
            }

            QueryIntent::ToolCalls(ref tool_name) => {
                self.route_tool_calls(tenant_id, tool_name.as_deref(), k)
            }

            QueryIntent::ErrorSearch(ref signature) => {
                self.route_error_search(tenant_id, signature.as_deref(), k)
            }

            // Document queries fall back to semantic
            QueryIntent::DocQa | QueryIntent::DecisionWhy(_) | QueryIntent::PlanNext => {
                let context = project_id.map(|p| SearchContext {
                    current_project: Some(p.to_string()),
                    preferred_types: Vec::new(),
                });
                let results = self.search(tenant_id, query, k, context).await?;
                Ok(SearchWithRoutingResult::Hybrid(results))
            }
        }
    }

    /// Route symbol definition query.
    async fn route_symbol_definition(
        &self,
        tenant_id: &TenantId,
        name: &str,
        k: usize,
        project_id: Option<&str>,
        route: &RouteResult,
    ) -> Result<SearchWithRoutingResult> {
        let symbols = if let Some(ref svc) = self.symbol_query_service {
            svc.find_symbol_definition(tenant_id, name, project_id)?
        } else {
            Vec::new()
        };

        let structural = StructuralSearchResult {
            intent: QueryIntent::SymbolDefinition(name.to_string()),
            symbols,
            callers: Vec::new(),
            imports: Vec::new(),
            fell_back_to_semantic: false,
        };

        self.maybe_blend_or_fallback(tenant_id, name, k, project_id, structural, route)
            .await
    }

    /// Route symbol callers query.
    async fn route_symbol_callers(
        &self,
        tenant_id: &TenantId,
        name: &str,
        k: usize,
        project_id: Option<&str>,
        route: &RouteResult,
    ) -> Result<SearchWithRoutingResult> {
        let callers = if let Some(ref svc) = self.symbol_query_service {
            svc.find_callers(tenant_id, name, 1, project_id)?
        } else {
            Vec::new()
        };

        let structural = StructuralSearchResult {
            intent: QueryIntent::SymbolCallers(name.to_string()),
            symbols: Vec::new(),
            callers,
            imports: Vec::new(),
            fell_back_to_semantic: false,
        };

        self.maybe_blend_or_fallback(tenant_id, name, k, project_id, structural, route)
            .await
    }

    /// Route symbol references query.
    async fn route_symbol_references(
        &self,
        tenant_id: &TenantId,
        name: &str,
        k: usize,
        project_id: Option<&str>,
        route: &RouteResult,
    ) -> Result<SearchWithRoutingResult> {
        let symbols = if let Some(ref svc) = self.symbol_query_service {
            svc.find_references(tenant_id, name, project_id)?
        } else {
            Vec::new()
        };

        let structural = StructuralSearchResult {
            intent: QueryIntent::SymbolReferences(name.to_string()),
            symbols,
            callers: Vec::new(),
            imports: Vec::new(),
            fell_back_to_semantic: false,
        };

        self.maybe_blend_or_fallback(tenant_id, name, k, project_id, structural, route)
            .await
    }

    /// Route module imports query.
    async fn route_module_imports(
        &self,
        tenant_id: &TenantId,
        module: &str,
        k: usize,
        project_id: Option<&str>,
        route: &RouteResult,
    ) -> Result<SearchWithRoutingResult> {
        let imports = if let Some(ref svc) = self.symbol_query_service {
            svc.find_imports(tenant_id, module, project_id)?
        } else {
            Vec::new()
        };

        let structural = StructuralSearchResult {
            intent: QueryIntent::ModuleImports(module.to_string()),
            symbols: Vec::new(),
            callers: Vec::new(),
            imports,
            fell_back_to_semantic: false,
        };

        self.maybe_blend_or_fallback(tenant_id, module, k, project_id, structural, route)
            .await
    }

    /// Route file symbols query.
    async fn route_file_symbols(
        &self,
        tenant_id: &TenantId,
        file: &str,
        k: usize,
        project_id: Option<&str>,
        route: &RouteResult,
    ) -> Result<SearchWithRoutingResult> {
        // File symbols not directly supported by SymbolQueryService yet
        // Fall back to semantic search for the file name
        let structural = StructuralSearchResult {
            intent: QueryIntent::FileSymbols(file.to_string()),
            symbols: Vec::new(),
            callers: Vec::new(),
            imports: Vec::new(),
            fell_back_to_semantic: false,
        };

        self.maybe_blend_or_fallback(tenant_id, file, k, project_id, structural, route)
            .await
    }

    /// Route tool calls query.
    fn route_tool_calls(
        &self,
        tenant_id: &TenantId,
        tool_name: Option<&str>,
        k: usize,
    ) -> Result<SearchWithRoutingResult> {
        let tool_calls = if let Some(ref svc) = self.trace_query_service {
            svc.find_tool_calls(tenant_id, tool_name, None, None, k)?
        } else {
            Vec::new()
        };

        Ok(SearchWithRoutingResult::Trace(TraceSearchResult {
            intent: QueryIntent::ToolCalls(tool_name.map(String::from)),
            tool_calls,
            errors: Vec::new(),
        }))
    }

    /// Route error search query.
    fn route_error_search(
        &self,
        tenant_id: &TenantId,
        signature: Option<&str>,
        k: usize,
    ) -> Result<SearchWithRoutingResult> {
        let errors = if let Some(ref svc) = self.trace_query_service {
            svc.find_errors(
                tenant_id, signature, None, // function_name
                None, // file_path
                None, // time_range
                k,
            )?
        } else {
            Vec::new()
        };

        Ok(SearchWithRoutingResult::Trace(TraceSearchResult {
            intent: QueryIntent::ErrorSearch(signature.map(String::from)),
            tool_calls: Vec::new(),
            errors,
        }))
    }

    /// Maybe blend structural results with semantic context, or fall back to semantic.
    ///
    /// Implements STRUCT-14: code-intent queries blend structural (primary) with semantic (context).
    async fn maybe_blend_or_fallback(
        &self,
        tenant_id: &TenantId,
        query_term: &str,
        k: usize,
        project_id: Option<&str>,
        structural: StructuralSearchResult,
        route: &RouteResult,
    ) -> Result<SearchWithRoutingResult> {
        let has_results = !structural.symbols.is_empty()
            || !structural.callers.is_empty()
            || !structural.imports.is_empty();

        // If no structural results and fallback enabled, use semantic search only
        if !has_results && route.fallback_to_semantic {
            let context = project_id.map(|p| SearchContext {
                current_project: Some(p.to_string()),
                preferred_types: Vec::new(),
            });
            // Trigger semantic search (result not used for structural return, but ensures fallback behavior)
            let _results = self.search(tenant_id, query_term, k, context).await?;

            return Ok(SearchWithRoutingResult::Structural(
                StructuralSearchResult {
                    fell_back_to_semantic: true,
                    ..structural
                },
            ));
        }

        // If blending is enabled and we have structural results, add semantic context
        if has_results && route.blend_semantic_context {
            let context = project_id.map(|p| SearchContext {
                current_project: Some(p.to_string()),
                preferred_types: Vec::new(),
            });

            // Get fewer semantic results since they're supplementary
            let semantic_k = (k / 2).max(3);
            let semantic_context = self
                .search(tenant_id, query_term, semantic_k, context)
                .await?;

            return Ok(SearchWithRoutingResult::Blended(BlendedSearchResult {
                intent: structural.intent.clone(),
                structural,
                semantic_context,
                blend_strategy: BlendStrategy::StructuralPrimary,
            }));
        }

        // Return structural results only
        Ok(SearchWithRoutingResult::Structural(structural))
    }

    /// Classify a query intent without executing the search.
    pub fn classify_query(&self, query: &str) -> RouteResult {
        self.router.classify(query)
    }

    /// Check if structural search is available.
    pub fn structural_enabled(&self) -> bool {
        self.symbol_query_service.is_some()
    }

    /// Check if trace search is available.
    pub fn trace_enabled(&self) -> bool {
        self.trace_query_service.is_some()
    }

    /// Check if sparse search is enabled
    pub fn sparse_enabled(&self) -> bool {
        self.config.enable_sparse && self.sparse.is_some()
    }

    /// Check if tiered search is enabled
    pub fn tiered_enabled(&self) -> bool {
        self.config.enable_tiered
    }

    /// Get reference to text processor
    pub fn text_processor(&self) -> &TextProcessor {
        &self.text_processor
    }

    /// Run tiered maintenance for a tenant (promotions, demotions, evictions)
    ///
    /// Should be called periodically (e.g., every 60 seconds).
    pub fn run_tiered_maintenance(
        &self,
        tenant_id: &TenantId,
    ) -> Option<crate::tiered::MaintenanceResult> {
        let tiered_searcher = self.get_or_create_tiered_searcher(tenant_id)?;
        Some(tiered_searcher.run_maintenance(tenant_id))
    }

    /// Get tiered metrics for recording
    ///
    /// Returns a TieredQueryMetrics for the given timing and cache/hot tier hit info.
    pub fn create_tiered_metrics(
        timing: &HybridTiming,
        cache_hit: bool,
        hot_tier_hit: bool,
    ) -> TieredQueryMetrics {
        let tiered = timing.tiered.as_ref();
        let source_tier = if cache_hit {
            "cache"
        } else if hot_tier_hit {
            "hot"
        } else {
            "warm"
        };

        TieredQueryMetrics {
            source_tier: source_tier.to_string(),
            cache_lookup_ms: tiered.map(|t| t.cache_lookup_ms).unwrap_or(0),
            hot_tier_ms: tiered.map(|t| t.hot_tier_ms).unwrap_or(0),
            warm_tier_ms: tiered.map(|t| t.warm_tier_ms).unwrap_or(0),
            cache_hit,
            hot_tier_hit,
        }
    }

    /// Invalidate cache entries containing a specific chunk
    ///
    /// Called when a chunk is deleted to ensure cache consistency.
    pub fn invalidate_chunk_in_cache(&self, chunk_id: &ChunkId) {
        if let Some(ref cache) = self.semantic_cache {
            cache.invalidate_chunks(&[chunk_id.clone()]);
        }
    }

    /// Get semantic cache statistics (if tiered search enabled)
    pub fn get_cache_stats(&self) -> Option<crate::tiered::CacheStats> {
        self.semantic_cache.as_ref().map(|c| c.get_stats())
    }

    /// Get reference to semantic cache for compaction
    ///
    /// Returns None if tiered search is not enabled.
    pub fn get_semantic_cache(&self) -> Option<&SemanticCache> {
        self.semantic_cache.as_ref().map(|c| c.as_ref())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::embeddings::MockEmbedder;
    use crate::store::DenseSearchConfig;

    fn make_test_hybrid_searcher(enable_sparse: bool) -> HybridSearcher {
        let embedder = Arc::new(MockEmbedder::new()); // Uses default config (1024 dims)
        let dense_config = DenseSearchConfig {
            persist: false,
            ..Default::default()
        };
        let dense = Arc::new(DenseSearcher::with_embedder(embedder, dense_config));

        let sparse = if enable_sparse {
            Some(Arc::new(Bm25Index::new().unwrap()))
        } else {
            None
        };

        let config = HybridConfig {
            enable_sparse,
            enable_tiered: false, // Disable tiered for tests (MockEmbedder has different dimension)
            ..Default::default()
        };

        HybridSearcher::new(dense, sparse, config)
    }

    fn make_tenant() -> TenantId {
        TenantId::new("test_tenant").unwrap()
    }

    #[tokio::test]
    async fn test_hybrid_search_basic() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();
        let chunk_id = ChunkId::new();

        // Index a chunk
        searcher
            .index_chunk(
                &tenant,
                &chunk_id,
                "The getUserById function returns user data",
            )
            .await
            .unwrap();

        // Search should find it
        let results = searcher
            .search(&tenant, "getUserById", 10, None)
            .await
            .unwrap();

        // Should have results (at least from sparse)
        assert!(!results.is_empty());
        assert_eq!(results[0].chunk_id, chunk_id);
    }

    #[tokio::test]
    async fn test_index_batch_and_search() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();
        let chunk_a = ChunkId::new();
        let chunk_b = ChunkId::new();
        let chunks = vec![
            (
                chunk_a.clone(),
                "The alpha parser handles config and json".to_string(),
            ),
            (
                chunk_b.clone(),
                "The beta formatter emits markdown output".to_string(),
            ),
        ];

        searcher.index_batch(&tenant, &chunks).await.unwrap();

        let alpha = searcher
            .search(&tenant, "alpha parser", 10, None)
            .await
            .unwrap();
        assert!(!alpha.is_empty());
        assert_eq!(alpha[0].chunk_id, chunk_a);

        let beta = searcher
            .search(&tenant, "beta formatter", 10, None)
            .await
            .unwrap();
        assert!(!beta.is_empty());
        assert_eq!(beta[0].chunk_id, chunk_b);
    }

    #[tokio::test]
    async fn test_keyword_match_improvement() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();
        let chunk_id = ChunkId::new();

        // Add chunk with unique identifier
        searcher
            .index_chunk(
                &tenant,
                &chunk_id,
                "The XyzSpecialFunctionName handles edge cases in processing",
            )
            .await
            .unwrap();

        // Search for the unique identifier
        let results = searcher
            .search(&tenant, "XyzSpecialFunctionName", 10, None)
            .await
            .unwrap();

        // Hybrid should find it via sparse (keyword) search
        assert!(
            !results.is_empty(),
            "Should find unique identifier via sparse search"
        );
        assert_eq!(results[0].chunk_id, chunk_id);
    }

    #[tokio::test]
    async fn test_index_and_delete() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();
        let chunk_id = ChunkId::new();

        // Index a chunk
        searcher
            .index_chunk(&tenant, &chunk_id, "deletable content here")
            .await
            .unwrap();

        // Verify searchable
        let results = searcher
            .search(&tenant, "deletable", 10, None)
            .await
            .unwrap();
        assert!(!results.is_empty(), "Should be searchable after indexing");

        // Delete from sparse
        searcher.delete_chunk(&tenant, &chunk_id).unwrap();

        // Should not be findable in sparse anymore
        // (dense may still have it until full deletion support is added)
        if let Some(ref sparse) = searcher.sparse {
            let sparse_results = sparse.search(&tenant, "deletable", 10).unwrap();
            assert!(
                sparse_results.is_empty(),
                "Should not be in sparse after delete"
            );
        }
    }

    #[tokio::test]
    async fn test_timing_breakdown() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();

        // Search with timing
        let (results, timing) = searcher
            .search_with_timing(&tenant, "test query", 10, None)
            .await
            .unwrap();

        // All timing components should be populated (even if zero)
        assert!(timing.total_time >= timing.dense_time);
        assert!(results.len() <= 10);
    }

    #[tokio::test]
    async fn test_sparse_disabled() {
        let searcher = make_test_hybrid_searcher(false);
        let tenant = make_tenant();
        let chunk_id = ChunkId::new();

        // Index
        searcher
            .index_chunk(&tenant, &chunk_id, "some content")
            .await
            .unwrap();

        // Search should work (dense only)
        let results = searcher.search(&tenant, "content", 10, None).await.unwrap();

        // Verify sparse is disabled
        assert!(!searcher.sparse_enabled());

        // Should still get results from dense
        // (MockEmbedder produces deterministic embeddings)
        assert!(results.is_empty() || results[0].sparse_rank.is_none());
    }

    #[tokio::test]
    async fn test_rerank_with_metadata() {
        let searcher = make_test_hybrid_searcher(true);
        let chunk_id1 = ChunkId::new();
        let chunk_id2 = ChunkId::new();

        let results = vec![
            HybridSearchResult {
                chunk_id: chunk_id1.clone(),
                final_score: 0.5,
                dense_rank: Some(1),
                sparse_rank: Some(2),
            },
            HybridSearchResult {
                chunk_id: chunk_id2.clone(),
                final_score: 0.4,
                dense_rank: Some(2),
                sparse_rank: Some(1),
            },
        ];

        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as i64)
            .unwrap_or(0);

        // chunk2 is newer and in current project
        let chunks_meta = vec![
            ChunkMetaForRerank {
                chunk_id: chunk_id1.clone(),
                rrf_score: 0.5,
                timestamp_created: now_ms - 7 * 24 * 60 * 60 * 1000, // 7 days old
                project_id: None,
                chunk_type: ChunkType::Doc,
                text: None,
            },
            ChunkMetaForRerank {
                chunk_id: chunk_id2.clone(),
                rrf_score: 0.4,
                timestamp_created: now_ms, // just created
                project_id: Some("current_project".to_string()),
                chunk_type: ChunkType::Code,
                text: None,
            },
        ];

        let context = Some(SearchContext {
            current_project: Some("current_project".to_string()),
            preferred_types: vec![ChunkType::Code],
        });

        let reranked = searcher.rerank_with_metadata(results, chunks_meta, context);

        // chunk2 should be boosted due to recency, project match, and type preference
        assert_eq!(reranked.len(), 2);
        // The reranker may reorder based on bonuses
    }

    #[tokio::test]
    async fn test_rerank_with_metadata_cross_encoder_prefers_query_match() {
        let embedder = Arc::new(MockEmbedder::new());
        let dense_config = DenseSearchConfig {
            persist: false,
            ..Default::default()
        };
        let dense = Arc::new(DenseSearcher::with_embedder(embedder, dense_config));
        let config = HybridConfig {
            enable_sparse: false,
            enable_tiered: false,
            reranker: RerankerConfig {
                mode: RerankerMode::CrossEncoder,
                rrf_weight: 0.2,
                recency_weight: 0.0,
                recency_half_life_days: 7.0,
                project_weight: 0.0,
                type_weight: 0.0,
                query_text_weight: 0.0,
                cross_encoder_weight: 1.0,
            },
            ..Default::default()
        };
        let searcher = HybridSearcher::new(dense, None, config);

        let chunk_id1 = ChunkId::new();
        let chunk_id2 = ChunkId::new();
        let results = vec![
            HybridSearchResult {
                chunk_id: chunk_id1.clone(),
                final_score: 0.5,
                dense_rank: Some(1),
                sparse_rank: None,
            },
            HybridSearchResult {
                chunk_id: chunk_id2.clone(),
                final_score: 0.5,
                dense_rank: Some(2),
                sparse_rank: None,
            },
        ];
        let chunks_meta = vec![
            ChunkMetaForRerank {
                chunk_id: chunk_id1.clone(),
                rrf_score: 0.5,
                timestamp_created: 0,
                project_id: None,
                chunk_type: ChunkType::Doc,
                text: Some("hybrid retrieval with query-aware ranking".to_string()),
            },
            ChunkMetaForRerank {
                chunk_id: chunk_id2.clone(),
                rrf_score: 0.5,
                timestamp_created: 0,
                project_id: None,
                chunk_type: ChunkType::Doc,
                text: Some("totally unrelated text".to_string()),
            },
        ];

        let reranked = searcher.rerank_with_metadata_for_query(
            "query aware retrieval",
            results,
            chunks_meta,
            None,
        );

        assert_eq!(reranked.len(), 2);
        #[cfg(feature = "cross-encoder-reranker")]
        assert_eq!(reranked[0].chunk_id, chunk_id1);
        #[cfg(not(feature = "cross-encoder-reranker"))]
        assert_eq!(searcher.reranker_mode(), RerankerMode::Feature);
    }

    #[tokio::test]
    async fn test_multiple_chunks_fusion() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();

        // Add multiple chunks with different content
        let chunk_id1 = ChunkId::new();
        let chunk_id2 = ChunkId::new();
        let chunk_id3 = ChunkId::new();

        searcher
            .index_chunk(
                &tenant,
                &chunk_id1,
                "The parseConfig function reads configuration files",
            )
            .await
            .unwrap();
        searcher
            .index_chunk(
                &tenant,
                &chunk_id2,
                "Configuration parsing is handled by parseConfig",
            )
            .await
            .unwrap();
        searcher
            .index_chunk(
                &tenant,
                &chunk_id3,
                "This module handles user authentication",
            )
            .await
            .unwrap();

        // Search for parseConfig - should find chunks 1 and 2
        let results = searcher
            .search(&tenant, "parseConfig", 10, None)
            .await
            .unwrap();

        // Should find the relevant chunks
        assert!(
            !results.is_empty(),
            "Should find chunks matching parseConfig"
        );

        // Results should include chunks with parseConfig
        let result_ids: Vec<ChunkId> = results.iter().map(|r| r.chunk_id.clone()).collect();
        assert!(
            result_ids.contains(&chunk_id1) || result_ids.contains(&chunk_id2),
            "Should include parseConfig chunks"
        );
    }

    #[tokio::test]
    async fn test_tenant_isolation() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant_a = TenantId::new("tenant_a").unwrap();
        let tenant_b = TenantId::new("tenant_b").unwrap();
        let chunk_id = ChunkId::new();

        // Index chunk for tenant_a
        searcher
            .index_chunk(&tenant_a, &chunk_id, "secret data for tenant A only")
            .await
            .unwrap();

        // Tenant A should find it
        let results_a = searcher
            .search(&tenant_a, "secret", 10, None)
            .await
            .unwrap();
        assert!(!results_a.is_empty(), "Tenant A should find their data");

        // Tenant B should not find it
        let results_b = searcher
            .search(&tenant_b, "secret", 10, None)
            .await
            .unwrap();
        // Sparse index enforces tenant isolation
        let sparse_found_b = results_b.iter().any(|r| r.sparse_rank.is_some());
        assert!(
            !sparse_found_b,
            "Tenant B should not find tenant A's data in sparse"
        );
    }

    #[tokio::test]
    async fn test_empty_query() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();
        let chunk_id = ChunkId::new();

        searcher
            .index_chunk(&tenant, &chunk_id, "some content here")
            .await
            .unwrap();

        // Empty query should not crash
        let results = searcher.search(&tenant, "", 10, None).await;
        // May return error or empty results depending on sparse index behavior
        assert!(results.is_ok() || results.is_err());
    }

    #[tokio::test]
    async fn test_config_defaults() {
        let config = HybridConfig::default();

        assert_eq!(config.dense_k, 100);
        assert_eq!(config.sparse_k, 100);
        assert!(config.enable_sparse);
    }

    // ========================================================================
    // Query Routing Tests
    // ========================================================================

    #[tokio::test]
    async fn test_route_to_semantic_search() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();
        let chunk_id = ChunkId::new();

        // Index some content
        searcher
            .index_chunk(
                &tenant,
                &chunk_id,
                "How does authentication work in our system",
            )
            .await
            .unwrap();

        // Generic question should route to semantic/hybrid search
        let result = searcher
            .search_with_routing(&tenant, "how does authentication work", 10, None)
            .await
            .unwrap();

        assert!(matches!(result, SearchWithRoutingResult::Hybrid(_)));
    }

    #[tokio::test]
    async fn test_route_to_structural_search_no_service() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();

        // Structural query without symbol service should return empty structural result
        let result = searcher
            .search_with_routing(&tenant, "where is UserService defined", 10, None)
            .await
            .unwrap();

        // Should return structural result (empty, possibly with fallback)
        match result {
            SearchWithRoutingResult::Structural(s) => {
                assert!(matches!(s.intent, QueryIntent::SymbolDefinition(_)));
                assert!(s.symbols.is_empty());
            }
            SearchWithRoutingResult::Blended(b) => {
                assert!(matches!(b.intent, QueryIntent::SymbolDefinition(_)));
            }
            _ => panic!("Expected structural or blended result"),
        }
    }

    #[tokio::test]
    async fn test_route_to_trace_search_no_service() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();

        // Tool calls query without trace service should return empty trace result
        let result = searcher
            .search_with_routing(&tenant, "recent tool calls", 10, None)
            .await
            .unwrap();

        assert!(matches!(result, SearchWithRoutingResult::Trace(ref t) if t.tool_calls.is_empty()));
    }

    #[tokio::test]
    async fn test_classify_query_intent() {
        let searcher = make_test_hybrid_searcher(true);

        // Test various query classifications
        let route = searcher.classify_query("where is Config defined");
        assert!(matches!(route.intent, QueryIntent::SymbolDefinition(_)));
        assert!(route.blend_semantic_context);

        let route = searcher.classify_query("who calls process_data");
        assert!(matches!(route.intent, QueryIntent::SymbolCallers(_)));
        assert!(route.blend_semantic_context);

        let route = searcher.classify_query("recent errors");
        assert!(matches!(route.intent, QueryIntent::ErrorSearch(None)));
        assert!(!route.blend_semantic_context);

        let route = searcher.classify_query("how does caching work");
        assert!(matches!(route.intent, QueryIntent::SemanticSearch));
        assert!(!route.blend_semantic_context);
    }

    #[test]
    fn test_blend_strategy_default() {
        assert_eq!(BlendStrategy::default(), BlendStrategy::StructuralPrimary);
    }

    #[test]
    fn test_structural_result_default() {
        let result = StructuralSearchResult::default();
        assert!(matches!(result.intent, QueryIntent::SemanticSearch));
        assert!(result.symbols.is_empty());
        assert!(result.callers.is_empty());
        assert!(result.imports.is_empty());
        assert!(!result.fell_back_to_semantic);
    }

    #[test]
    fn test_searcher_service_flags() {
        let searcher = make_test_hybrid_searcher(true);

        // No services attached
        assert!(!searcher.structural_enabled());
        assert!(!searcher.trace_enabled());

        // Router should be available
        let _ = searcher.router();
    }

    #[tokio::test]
    async fn test_route_error_search() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();

        let result = searcher
            .search_with_routing(&tenant, "errors: TypeError", 10, None)
            .await
            .unwrap();

        match result {
            SearchWithRoutingResult::Trace(t) => {
                assert!(
                    matches!(t.intent, QueryIntent::ErrorSearch(Some(ref s)) if s == "TypeError")
                );
            }
            _ => panic!("Expected trace result"),
        }
    }

    #[tokio::test]
    async fn test_route_tool_calls() {
        let searcher = make_test_hybrid_searcher(true);
        let tenant = make_tenant();

        let result = searcher
            .search_with_routing(&tenant, "calls to read_file", 10, None)
            .await
            .unwrap();

        match result {
            SearchWithRoutingResult::Trace(t) => {
                assert!(
                    matches!(t.intent, QueryIntent::ToolCalls(Some(ref s)) if s == "read_file")
                );
            }
            _ => panic!("Expected trace result"),
        }
    }
}