maproom 0.1.0

Semantic code search powered by embeddings and SQLite
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
//! Final search result structures with complete metadata.
//!
//! This module defines the final output format for hybrid search queries,
//! including complete chunk details, metadata, and timing information.

use crate::search::executor_types::SearchSource;
use crate::search::types::SearchMode;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Complete search results with ranked chunks and metadata.
///
/// This is the top-level structure returned by the SearchPipeline,
/// containing everything needed to display and analyze search results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FinalSearchResults {
    /// Original query string
    pub query: String,

    /// Ranked search results with full chunk details
    pub results: Vec<ChunkSearchResult>,

    /// Search execution metadata and statistics
    pub metadata: SearchMetadata,
}

impl FinalSearchResults {
    /// Create new FinalSearchResults.
    pub fn new(query: String, results: Vec<ChunkSearchResult>, metadata: SearchMetadata) -> Self {
        Self {
            query,
            results,
            metadata,
        }
    }

    /// Check if there are any results.
    pub fn is_empty(&self) -> bool {
        self.results.is_empty()
    }

    /// Get the number of results.
    pub fn len(&self) -> usize {
        self.results.len()
    }

    /// Get the top N results.
    pub fn top_n(&self, n: usize) -> &[ChunkSearchResult] {
        let end = n.min(self.results.len());
        &self.results[..end]
    }
}

/// A single search result with complete chunk details and scores.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChunkSearchResult {
    /// Chunk ID from maproom.chunks table
    pub chunk_id: i64,

    /// File ID from maproom.files table
    pub file_id: i64,

    /// Relative path to the file
    pub relpath: String,

    /// Optional symbol name (function, class, etc.)
    pub symbol_name: Option<String>,

    /// Chunk kind (function, class, interface, etc.)
    pub kind: String,

    /// Starting line number (1-based)
    pub start_line: i32,

    /// Ending line number (1-based)
    pub end_line: i32,

    /// Preview text from the chunk
    pub preview: String,

    /// Final fused score (0.0-1.0)
    pub score: f32,

    /// Individual scores from each search source
    pub source_scores: HashMap<SearchSource, f32>,

    /// Confidence signals for result quality assessment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<ConfidenceSignals>,

    /// Related chunks discovered via graph traversal.
    ///
    /// Only populated when include_related=true and confidence criteria are met.
    /// Empty result semantics:
    /// - None: Expansion did not run (low confidence, disabled, or error)
    /// - Some([]): Expansion ran but found no relationships
    #[serde(skip_serializing_if = "Option::is_none")]
    pub related: Option<Vec<RelatedChunkResult>>,
}

impl ChunkSearchResult {
    /// Create a new ChunkSearchResult.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        chunk_id: i64,
        file_id: i64,
        relpath: String,
        symbol_name: Option<String>,
        kind: String,
        start_line: i32,
        end_line: i32,
        preview: String,
        score: f32,
        source_scores: HashMap<SearchSource, f32>,
    ) -> Self {
        Self {
            chunk_id,
            file_id,
            relpath,
            symbol_name,
            kind,
            start_line,
            end_line,
            preview,
            score,
            source_scores,
            confidence: None,
            related: None,
        }
    }

    /// Get the line range as a formatted string.
    pub fn line_range(&self) -> String {
        format!("{}-{}", self.start_line, self.end_line)
    }

    /// Get the number of lines in this chunk.
    pub fn line_count(&self) -> i32 {
        self.end_line - self.start_line + 1
    }
}

/// Query understanding metadata for successful searches (Phase 2).
///
/// This structure provides transparency about how the query was interpreted,
/// what filters were applied, and timing breakdown. All data is assembled from
/// existing in-memory structures - no new computation is performed.
///
/// TYPE_SYNC: packages/daemon-client/src/client.ts::QueryUnderstanding
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryUnderstanding {
    /// Detected search mode
    pub mode: SearchMode,

    /// Tokenized query terms
    pub tokens: Vec<String>,

    /// Expanded query terms (synonyms, variations)
    pub expanded_terms: Vec<String>,

    /// Applied filters
    pub filters: QueryFilters,

    /// Fusion strategy name (e.g., "reciprocal_rank_fusion", "basic_weighted")
    pub fusion_strategy: String,

    /// Timing breakdown for search stages
    pub timing: TimingBreakdown,
}

impl QueryUnderstanding {
    /// Create from processed query data and timing information.
    ///
    /// This is a convenience constructor that assembles QueryUnderstanding from
    /// data already available in the search pipeline.
    pub fn from_query_data(
        mode: SearchMode,
        tokens: Vec<String>,
        expanded_terms: Vec<String>,
        filters: QueryFilters,
        fusion_strategy: String,
        timing: TimingBreakdown,
    ) -> Self {
        Self {
            mode,
            tokens,
            expanded_terms,
            filters,
            fusion_strategy,
            timing,
        }
    }
}

/// Filters applied to the search query.
///
/// TYPE_SYNC: packages/daemon-client/src/client.ts::QueryFilters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryFilters {
    /// Repository ID being searched
    pub repo_id: i64,

    /// Optional worktree ID filter
    pub worktree_id: Option<i64>,

    /// File type filters (e.g., ["ts", "tsx", "js"])
    pub file_types: Vec<String>,

    /// Recency threshold filter (e.g., "7 days", "1 month")
    pub recency_threshold: Option<String>,
}

/// Timing breakdown for search execution stages.
///
/// TYPE_SYNC: packages/daemon-client/src/client.ts::TimingBreakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimingBreakdown {
    /// Time spent processing the query (ms)
    pub query_processing_ms: f64,

    /// Time spent executing searches (ms)
    pub search_execution_ms: f64,

    /// Time spent fusing scores (ms)
    pub score_fusion_ms: f64,

    /// Time spent assembling final results (ms)
    pub result_assembly_ms: f64,

    /// Total time across all stages (ms)
    pub total_ms: f64,
}

impl TimingBreakdown {
    /// Create a new TimingBreakdown with automatic total calculation.
    ///
    /// The total_ms field is calculated as the sum of all individual timings.
    pub fn new(
        query_processing_ms: f64,
        search_execution_ms: f64,
        score_fusion_ms: f64,
        result_assembly_ms: f64,
    ) -> Self {
        let total_ms =
            query_processing_ms + search_execution_ms + score_fusion_ms + result_assembly_ms;

        Self {
            query_processing_ms,
            search_execution_ms,
            score_fusion_ms,
            result_assembly_ms,
            total_ms,
        }
    }
}

/// Metadata about search execution and results.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchMetadata {
    /// Query processing details
    pub query_processing: QueryProcessingDetails,

    /// Result counts from each search strategy
    pub result_counts: HashMap<SearchSource, usize>,

    /// Timing breakdown for each stage
    pub timing: SearchTiming,

    /// Total number of unique chunks found before fusion
    pub total_unique_chunks: usize,

    /// Number of results returned after fusion and limit
    pub returned_results: usize,

    /// Query understanding metadata (added in Phase 2)
    ///
    /// This field provides transparency about query interpretation, filters,
    /// and timing. It's optional for backward compatibility and is omitted
    /// from JSON when None.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub understanding: Option<QueryUnderstanding>,
}

impl SearchMetadata {
    /// Create new SearchMetadata.
    pub fn new(
        query_processing: QueryProcessingDetails,
        result_counts: HashMap<SearchSource, usize>,
        timing: SearchTiming,
        total_unique_chunks: usize,
        returned_results: usize,
    ) -> Self {
        Self {
            query_processing,
            result_counts,
            timing,
            total_unique_chunks,
            returned_results,
            understanding: None,
        }
    }

    /// Create new SearchMetadata with query understanding.
    pub fn with_understanding(
        query_processing: QueryProcessingDetails,
        result_counts: HashMap<SearchSource, usize>,
        timing: SearchTiming,
        total_unique_chunks: usize,
        returned_results: usize,
        understanding: QueryUnderstanding,
    ) -> Self {
        Self {
            query_processing,
            result_counts,
            timing,
            total_unique_chunks,
            returned_results,
            understanding: Some(understanding),
        }
    }

    /// Get total execution time in milliseconds.
    pub fn total_time_ms(&self) -> f64 {
        self.timing.query_processing_ms
            + self.timing.search_execution_ms
            + self.timing.fusion_ms
            + self.timing.assembly_ms
    }

    /// Check if search met the performance target (< 50ms total).
    pub fn met_performance_target(&self) -> bool {
        self.total_time_ms() < 50.0
    }
}

/// Details about query processing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryProcessingDetails {
    /// Original query string
    pub original: String,

    /// Detected search mode
    pub mode: SearchMode,

    /// Number of tokens extracted
    pub token_count: usize,

    /// Number of expanded terms added
    pub expanded_term_count: usize,

    /// FTS query string generated
    pub fts_query: String,

    /// Whether embedding was generated successfully
    pub has_embedding: bool,
}

impl QueryProcessingDetails {
    /// Create new QueryProcessingDetails.
    pub fn new(
        original: String,
        mode: SearchMode,
        token_count: usize,
        expanded_term_count: usize,
        fts_query: String,
        has_embedding: bool,
    ) -> Self {
        Self {
            original,
            mode,
            token_count,
            expanded_term_count,
            fts_query,
            has_embedding,
        }
    }
}

/// Timing breakdown for search execution stages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchTiming {
    /// Time spent processing the query (ms)
    pub query_processing_ms: f64,

    /// Time spent executing parallel searches (ms)
    pub search_execution_ms: f64,

    /// Time spent fusing scores (ms)
    pub fusion_ms: f64,

    /// Time spent assembling final results with chunk details (ms)
    pub assembly_ms: f64,

    /// Optional reranking time (ms) - unused in Phase 2
    pub reranking_ms: Option<f64>,
}

impl SearchTiming {
    /// Create new SearchTiming.
    pub fn new(
        query_processing_ms: f64,
        search_execution_ms: f64,
        fusion_ms: f64,
        assembly_ms: f64,
    ) -> Self {
        Self {
            query_processing_ms,
            search_execution_ms,
            fusion_ms,
            assembly_ms,
            reranking_ms: None,
        }
    }

    /// Create SearchTiming with all stages at 0.0.
    pub fn zero() -> Self {
        Self {
            query_processing_ms: 0.0,
            search_execution_ms: 0.0,
            fusion_ms: 0.0,
            assembly_ms: 0.0,
            reranking_ms: None,
        }
    }
}

/// Options for configuring search execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchOptions {
    /// Repository ID to search within
    pub repo_id: i64,

    /// Optional worktree ID for filtering
    pub worktree_id: Option<i64>,

    /// Maximum number of results to return
    pub limit: usize,

    /// Fusion weights for combining scores
    pub fusion_weights: Option<crate::search::fusion::FusionWeights>,

    /// Whether to skip vector search (faster, text-only)
    pub skip_vector: bool,

    /// Whether to skip graph search
    pub skip_graph: bool,

    /// Whether to skip signal search
    pub skip_signals: bool,

    /// Whether to deduplicate results across worktrees.
    ///
    /// When enabled (default), results with the same identity
    /// (relpath, symbol_name, start_line) are grouped, and only
    /// the highest-scoring instance is returned.
    ///
    /// Default: `true`
    #[serde(default = "default_deduplicate")]
    pub deduplicate: bool,

    /// File type filters (e.g., ["ts", "tsx", "js"])
    #[serde(default)]
    pub file_types: Vec<String>,

    /// Recency threshold filter (e.g., "7 days", "1 month")
    #[serde(default)]
    pub recency_threshold: Option<String>,

    /// Whether to include confidence signals in search results.
    ///
    /// When true, each result will include confidence field with quality signals.
    /// When false (default), confidence is None for backward compatibility.
    ///
    /// Default: `false`
    #[serde(default)]
    pub include_confidence: bool,

    /// Whether to include related chunks via graph traversal.
    ///
    /// When true, high-confidence results will include related chunks discovered
    /// through graph traversal. Auto-enables confidence scoring.
    /// When false (default), related field is None for backward compatibility.
    ///
    /// Default: `false`
    #[serde(default)]
    pub include_related: bool,
}

fn default_deduplicate() -> bool {
    true
}

/// Confidence signals for search result quality assessment.
///
/// This structure provides transparency about result quality through three
/// core signals computed from existing search pipeline data. All fields are
/// derived from in-memory structures with O(1) computation per result.
///
/// TYPE_SYNC: packages/daemon-client/src/types.ts::ConfidenceSignals
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfidenceSignals {
    /// Number of search sources that found this result (FTS, vector, graph, signals).
    /// Higher values indicate stronger cross-strategy agreement.
    pub source_count: usize,

    /// Score difference between this result and the next result.
    /// Larger gaps indicate clearer quality separation. 0.0 for the last result.
    pub score_gap: f32,

    /// Whether this result received an exact match boost during scoring.
    /// Exact matches (exact_match_multiplier >= 2.9) have higher confidence.
    pub is_exact_match: bool,
}

/// Lightweight metadata for a related chunk discovered via graph traversal.
///
/// Contains only metadata (no file content) to keep responses small and fast.
/// Users can invoke context tool to retrieve full content for specific chunks.
///
/// Empty Result Semantics:
/// - `Option::None`: Expansion did not run (confidence too low or disabled)
/// - `Option::Some(vec![])`: Expansion ran but found no relationships
///
/// TYPE_SYNC: packages/daemon-client/src/types.ts::RelatedChunkResult
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RelatedChunkResult {
    /// Chunk ID for requesting full context via context tool
    pub chunk_id: i64,

    /// File path relative to repository root
    pub relpath: String,

    /// Symbol name (function, class, etc.)
    pub symbol_name: Option<String>,

    /// Symbol kind (function, class, interface, etc.)
    pub kind: String,

    /// Start line in file (1-based)
    pub start_line: i32,

    /// End line in file (1-based)
    pub end_line: i32,

    /// Content preview (first 100 characters)
    pub preview: String,

    /// Graph traversal depth from source chunk (1 or 2)
    pub depth: i32,

    /// Decay-adjusted relevance score (0.0-1.0)
    ///
    /// Computed as: base_decay × edge_weight × module_boost
    /// - base_decay: 0.7^depth (depth 1: 0.7, depth 2: 0.49)
    /// - edge_weight: 0.5-1.1 based on edge type and target kind
    /// - module_boost: 1.2 if same module, else 1.0
    pub relevance: f32,

    /// Relationship type: "import", "call", "extends", "implements"
    pub relationship_type: String,
}

impl SearchOptions {
    /// Create new SearchOptions with required parameters.
    pub fn new(repo_id: i64, worktree_id: Option<i64>, limit: usize) -> Self {
        Self {
            repo_id,
            worktree_id,
            limit,
            fusion_weights: None,
            skip_vector: false,
            skip_graph: false,
            skip_signals: false,
            deduplicate: true,
            file_types: vec![],
            recency_threshold: None,
            include_confidence: false,
            include_related: false,
        }
    }

    /// Builder method to set fusion weights.
    pub fn with_fusion_weights(mut self, weights: crate::search::fusion::FusionWeights) -> Self {
        self.fusion_weights = Some(weights);
        self
    }

    /// Builder method to skip vector search.
    pub fn with_skip_vector(mut self, skip: bool) -> Self {
        self.skip_vector = skip;
        self
    }

    /// Builder method to skip graph search.
    pub fn with_skip_graph(mut self, skip: bool) -> Self {
        self.skip_graph = skip;
        self
    }

    /// Builder method to skip signal search.
    pub fn with_skip_signals(mut self, skip: bool) -> Self {
        self.skip_signals = skip;
        self
    }

    /// Builder method to disable deduplication.
    pub fn without_dedup(mut self) -> Self {
        self.deduplicate = false;
        self
    }

    /// Builder method to set deduplication explicitly.
    pub fn with_deduplicate(mut self, deduplicate: bool) -> Self {
        self.deduplicate = deduplicate;
        self
    }

    /// Get the fusion weights, using defaults if not specified.
    pub fn get_fusion_weights(&self) -> crate::search::fusion::FusionWeights {
        self.fusion_weights.clone().unwrap_or_default()
    }
}

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

    #[test]
    fn test_final_search_results_empty() {
        let results = FinalSearchResults::new(
            "test query".to_string(),
            vec![],
            SearchMetadata::new(
                QueryProcessingDetails::new(
                    "test query".to_string(),
                    SearchMode::Auto,
                    2,
                    0,
                    "test & query".to_string(),
                    true,
                ),
                HashMap::new(),
                SearchTiming::zero(),
                0,
                0,
            ),
        );

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

    #[test]
    fn test_chunk_search_result_line_range() {
        let result = ChunkSearchResult::new(
            1,
            1,
            "src/main.rs".to_string(),
            Some("main".to_string()),
            "function".to_string(),
            10,
            25,
            "fn main() {".to_string(),
            0.95,
            HashMap::new(),
        );

        assert_eq!(result.line_range(), "10-25");
        assert_eq!(result.line_count(), 16);
    }

    #[test]
    fn test_search_metadata_total_time() {
        let timing = SearchTiming::new(5.0, 30.0, 2.0, 8.0);
        let metadata = SearchMetadata::new(
            QueryProcessingDetails::new(
                "test".to_string(),
                SearchMode::Auto,
                1,
                0,
                "test".to_string(),
                true,
            ),
            HashMap::new(),
            timing,
            50,
            10,
        );

        assert_eq!(metadata.total_time_ms(), 45.0);
        assert!(metadata.met_performance_target());
    }

    #[test]
    fn test_search_metadata_performance_target_exceeded() {
        let timing = SearchTiming::new(15.0, 40.0, 5.0, 10.0);
        let metadata = SearchMetadata::new(
            QueryProcessingDetails::new(
                "test".to_string(),
                SearchMode::Auto,
                1,
                0,
                "test".to_string(),
                true,
            ),
            HashMap::new(),
            timing,
            50,
            10,
        );

        assert_eq!(metadata.total_time_ms(), 70.0);
        assert!(!metadata.met_performance_target());
    }

    #[test]
    fn test_search_options_builder() {
        let options = SearchOptions::new(1, Some(2), 10)
            .with_skip_vector(true)
            .with_skip_graph(false);

        assert_eq!(options.repo_id, 1);
        assert_eq!(options.worktree_id, Some(2));
        assert_eq!(options.limit, 10);
        assert!(options.skip_vector);
        assert!(!options.skip_graph);
    }

    #[test]
    fn test_search_options_default_weights() {
        let options = SearchOptions::new(1, None, 10);
        let weights = options.get_fusion_weights();

        assert_eq!(weights.fts, 0.4);
        assert_eq!(weights.vector, 0.35);
        assert_eq!(weights.graph, 0.1);
        assert_eq!(weights.recency, 0.1);
        assert_eq!(weights.churn, 0.05);
    }

    #[test]
    fn test_search_options_deduplicate_default() {
        let options = SearchOptions::new(1, None, 10);
        assert!(
            options.deduplicate,
            "Deduplication should be enabled by default"
        );
    }

    #[test]
    fn test_search_options_without_dedup() {
        let options = SearchOptions::new(1, None, 10).without_dedup();
        assert!(
            !options.deduplicate,
            "without_dedup should disable deduplication"
        );
    }

    #[test]
    fn test_search_options_with_deduplicate() {
        let options = SearchOptions::new(1, None, 10)
            .without_dedup()
            .with_deduplicate(true);
        assert!(
            options.deduplicate,
            "with_deduplicate(true) should enable deduplication"
        );

        let options = SearchOptions::new(1, None, 10).with_deduplicate(false);
        assert!(
            !options.deduplicate,
            "with_deduplicate(false) should disable deduplication"
        );
    }

    #[test]
    fn test_timing_breakdown_total_calculation() {
        let timing = TimingBreakdown::new(4.2, 35.8, 2.1, 6.4);

        assert_eq!(timing.total_ms, 48.5);
        assert_eq!(timing.query_processing_ms, 4.2);
        assert_eq!(timing.search_execution_ms, 35.8);
        assert_eq!(timing.score_fusion_ms, 2.1);
        assert_eq!(timing.result_assembly_ms, 6.4);
    }

    #[test]
    fn test_query_understanding_serialization() {
        let understanding = QueryUnderstanding {
            mode: SearchMode::Auto,
            tokens: vec!["authenticate".to_string(), "user".to_string()],
            expanded_terms: vec!["auth".to_string(), "login".to_string()],
            filters: QueryFilters {
                repo_id: 1,
                worktree_id: Some(2),
                file_types: vec![],
                recency_threshold: None,
            },
            fusion_strategy: "reciprocal_rank_fusion".to_string(),
            timing: TimingBreakdown::new(4.2, 35.8, 2.1, 6.4),
        };

        let json = serde_json::to_string(&understanding).unwrap();
        assert!(json.contains("authenticate"));
        assert!(json.contains("reciprocal_rank_fusion"));
        assert!(json.contains("\"total_ms\":48.5"));
    }

    #[test]
    fn test_optional_understanding_field_serialization() {
        let metadata = SearchMetadata {
            query_processing: QueryProcessingDetails::new(
                "test query".to_string(),
                SearchMode::Auto,
                2,
                0,
                "test & query".to_string(),
                true,
            ),
            result_counts: HashMap::new(),
            timing: SearchTiming::zero(),
            total_unique_chunks: 0,
            returned_results: 0,
            understanding: None,
        };

        let json = serde_json::to_value(&metadata).unwrap();
        // When None, field should be omitted (skip_serializing_if)
        assert!(json.get("understanding").is_none());

        let metadata_with_understanding = SearchMetadata {
            query_processing: QueryProcessingDetails::new(
                "test query".to_string(),
                SearchMode::Auto,
                2,
                0,
                "test & query".to_string(),
                true,
            ),
            result_counts: HashMap::new(),
            timing: SearchTiming::zero(),
            total_unique_chunks: 0,
            returned_results: 0,
            understanding: Some(QueryUnderstanding {
                mode: SearchMode::Code,
                tokens: vec!["test".to_string()],
                expanded_terms: vec![],
                filters: QueryFilters {
                    repo_id: 1,
                    worktree_id: None,
                    file_types: vec![],
                    recency_threshold: None,
                },
                fusion_strategy: "basic_weighted".to_string(),
                timing: TimingBreakdown::new(1.0, 2.0, 3.0, 4.0),
            }),
        };

        let json = serde_json::to_value(&metadata_with_understanding).unwrap();
        assert!(json.get("understanding").is_some());
        let understanding = json.get("understanding").unwrap();
        assert_eq!(understanding.get("mode").unwrap(), "code");
        assert_eq!(
            understanding.get("fusion_strategy").unwrap(),
            "basic_weighted"
        );
    }

    #[test]
    fn test_query_filters_serialization() {
        let filters = QueryFilters {
            repo_id: 42,
            worktree_id: Some(123),
            file_types: vec!["ts".to_string(), "tsx".to_string()],
            recency_threshold: Some("7 days".to_string()),
        };

        let json = serde_json::to_value(&filters).unwrap();
        assert_eq!(json.get("repo_id").unwrap(), 42);
        assert_eq!(json.get("worktree_id").unwrap(), 123);

        let file_types = json.get("file_types").unwrap().as_array().unwrap();
        assert_eq!(file_types.len(), 2);
        assert_eq!(file_types[0], "ts");
        assert_eq!(file_types[1], "tsx");

        assert_eq!(json.get("recency_threshold").unwrap(), "7 days");
    }

    #[test]
    fn test_query_understanding_from_query_data() {
        let timing = TimingBreakdown::new(5.0, 10.0, 2.0, 3.0);
        let filters = QueryFilters {
            repo_id: 1,
            worktree_id: None,
            file_types: vec!["rs".to_string()],
            recency_threshold: None,
        };

        let understanding = QueryUnderstanding::from_query_data(
            SearchMode::Code,
            vec!["search".to_string(), "query".to_string()],
            vec!["find".to_string()],
            filters,
            "reciprocal_rank_fusion".to_string(),
            timing,
        );

        assert_eq!(understanding.mode, SearchMode::Code);
        assert_eq!(understanding.tokens.len(), 2);
        assert_eq!(understanding.expanded_terms.len(), 1);
        assert_eq!(understanding.fusion_strategy, "reciprocal_rank_fusion");
        assert_eq!(understanding.timing.total_ms, 20.0);
    }
}