frigg 0.9.2

Frigg gives AI agents local, source-backed code search and navigation without sending whole repositories through every prompt.
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
//! Search and exploration MCP wire types: text, hybrid, symbol, structural, and `explore` contracts.

use std::collections::BTreeMap;

use super::{
    MetadataObject, NextAction, ReadPresentationMode, RecoveryFields, ResponseMode,
    ResultCompleteness, SuggestedNext, ZeroHitReason, ZeroHitScope,
};
use crate::domain::{
    ChannelHealthStatus, EvidenceAnchor, PathClass, SourceClass, model::SymbolMatch,
    model::TextMatch,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Literal or safe-regex matching mode for text and explore queries.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SearchPatternType {
    Literal,
    Regex,
}

/// In-file explorer mode: scan, zoom to an anchor window, or refine within an anchor scope.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExploreOperation {
    Probe,
    Zoom,
    Refine,
}

/// 1-based source anchor bounding an explore zoom or refine window.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreAnchor {
    pub start_line: usize,
    pub start_column: usize,
    pub end_line: usize,
    pub end_column: usize,
}

/// 1-based continuation cursor for paginated explore probe or refine scans.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreCursor {
    pub line: usize,
    pub column: usize,
}

/// Inclusive 1-based line window inside one repository file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreLineWindow {
    pub start_line: usize,
    pub end_line: usize,
}

/// Bounded source excerpt returned by explore zoom or match windows.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreWindow {
    pub start_line: usize,
    pub end_line: usize,
    pub bytes: usize,
    pub content: String,
}

/// One explore match row with excerpt, anchor, and local context window.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreMatch {
    pub match_id: String,
    pub start_line: usize,
    pub start_column: usize,
    pub end_line: usize,
    pub end_column: usize,
    pub excerpt: String,
    pub window: ExploreWindow,
    pub anchor: ExploreAnchor,
}

/// Explorer execution metadata including effective limits and optional context-efficiency stats.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreMetadata {
    pub lossy_utf8: bool,
    pub effective_context_lines: usize,
    pub effective_max_matches: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_efficiency: Option<ContextEfficiencyMetadata>,
}

/// Parameters for the extended `explore` tool.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreParams {
    /// Canonical repository-relative path.
    pub path: String,
    /// Optional repository scope.
    pub repository_id: Option<String>,
    /// Explorer mode.
    pub operation: ExploreOperation,
    /// Search query for `probe` or `refine`.
    pub query: Option<String>,
    /// Match mode for `query`.
    pub pattern_type: Option<SearchPatternType>,
    /// Anchor used by `zoom` and `refine`.
    pub anchor: Option<ExploreAnchor>,
    /// Context lines around anchors and matches.
    pub context_lines: Option<usize>,
    /// Max match rows to return.
    pub max_matches: Option<usize>,
    /// Continuation cursor for `probe` or `refine`.
    pub resume_from: Option<ExploreCursor>,
    /// Opaque v2 continuation for `probe` or `refine`. Cannot be combined with `resume_from`.
    pub continuation: Option<String>,
    /// Read-surface presentation mode.
    pub presentation_mode: Option<ReadPresentationMode>,
    /// Include context-efficiency metadata; requires JSON presentation.
    pub include_context_efficiency: Option<bool>,
}

/// Response from the extended `explore` tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ExploreResponse {
    pub repository_id: String,
    pub path: String,
    pub operation: ExploreOperation,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern_type: Option<SearchPatternType>,
    pub total_lines: usize,
    pub scan_scope: ExploreLineWindow,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window: Option<ExploreWindow>,
    pub total_matches: usize,
    pub matches: Vec<ExploreMatch>,
    pub truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_from: Option<ExploreCursor>,
    /// Canonical cardinality and paging truth for match rows.
    pub completeness: super::ResultCompleteness,
    pub metadata: ExploreMetadata,
}

/// Parameters for `search_text`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SearchTextParams {
    /// Text query to match. Literal by default.
    #[serde(alias = "pattern")]
    pub query: String,
    /// Match mode for `query`.
    pub pattern_type: Option<SearchPatternType>,
    /// Optional repository scope.
    pub repository_id: Option<String>,
    /// Repository-relative path regex filter.
    pub path_regex: Option<String>,
    /// Max returned matches.
    pub limit: Option<usize>,
    /// Context lines around matches.
    pub context_lines: Option<usize>,
    /// Force case-sensitive matching.
    pub case_sensitive: Option<bool>,
    /// Force case-insensitive matching.
    pub ignore_case: Option<bool>,
    /// Match whole words.
    pub word: Option<bool>,
    /// Return at most one hit row per file.
    pub files_with_matches: Option<bool>,
    /// Return counts and omit match rows.
    pub count_only: Option<bool>,
    /// Repository-relative include glob.
    pub glob: Option<String>,
    /// Repository-relative exclude glob.
    pub exclude_glob: Option<String>,
    /// Include hidden path segments.
    pub include_hidden: Option<bool>,
    /// Max returned hits per file.
    pub max_count_per_file: Option<usize>,
    /// Collapse repeated paths.
    pub collapse_by_file: Option<bool>,
    /// Opaque v2 continuation returned by an earlier `search_text` page.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
    /// Include context-efficiency metadata.
    pub include_context_efficiency: Option<bool>,
}

/// Response from `search_text` with optional `result_handle` for `read_match`. Empty results may include flattened recovery fields.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchTextResponse {
    /// Exact raw eligible occurrence count when coverage is complete, retained for compatibility.
    pub total_matches: usize,
    pub matches: Vec<TextMatch>,
    /// Canonical cardinality and paging truth for the selected response row unit.
    pub completeness: super::ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    /// Short scope label for `match_id` values (for example `search`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_scope: Option<String>,
    /// Handle lifetime. Session-scoped handles use `"session"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_expires: Option<String>,
    /// Echo of `count_only` when the request asked for counts without match rows.
    /// When true, empty `matches[]` is intentional — read `total_matches`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count_only: Option<bool>,
    /// Approximate search latency class for agent tool-cost guidance.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency_class: Option<LatencyClass>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<SearchTextMetadata>,
    /// Shared recovery composer fields; omitted when empty so existing clients stay compatible.
    /// Applied scope echo lives on `recovery.scope` (`ZeroHitScope`) when path filters are set.
    #[serde(flatten, default)]
    pub recovery: RecoveryFields,
}

/// Coarse latency/cost class for compact search responses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LatencyClass {
    Hot,
    Warm,
    Cold,
}

/// Lexical search backend mix reported in text and hybrid metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SearchLexicalBackendMetadata {
    Native,
    Ripgrep,
    Mixed,
}

/// Optional metadata returned by `search_text`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchTextMetadata {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lexical_backend: Option<SearchLexicalBackendMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lexical_backend_note: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_efficiency: Option<ContextEfficiencyMetadata>,
}

/// Context-efficiency metadata returned when requested.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ContextEfficiencyMetadata {
    pub indexed_readable_files: usize,
    pub indexed_readable_bytes: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub indexed_min_mtime_ns: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub indexed_max_mtime_ns: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub candidate_input_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub candidate_output_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub returned_match_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub returned_unique_paths: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub returned_unique_file_bytes: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub returned_source_bytes_estimate: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matched_file_context_saved_bytes_estimate: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub matched_file_context_saved_percent_estimate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub corpus_context_saved_bytes_estimate: Option<i64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub corpus_context_saved_percent_estimate: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub corpus_narrowing_ratio_estimate: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_duration_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub narrowing_ratio_estimate: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stage_attribution: Option<ContextEfficiencyStageAttribution>,
}

/// Candidate narrowing counts attributed to one context-efficiency measurement stage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ContextEfficiencyStageAttribution {
    pub candidate_input_count: usize,
    pub candidate_output_count: usize,
}

/// Optional lexical, graph, and semantic weight overrides for `search_hybrid`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridChannelWeightsParams {
    pub lexical: Option<f32>,
    pub graph: Option<f32>,
    pub semantic: Option<f32>,
}

/// Parameters for `search_hybrid`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridParams {
    /// Discovery query.
    pub query: String,
    /// Optional repository scope.
    pub repository_id: Option<String>,
    /// Optional language filter.
    pub language: Option<String>,
    /// Optional max matches.
    pub limit: Option<usize>,
    /// Optional channel-weight overrides.
    pub weights: Option<SearchHybridChannelWeightsParams>,
    /// Optional semantic-channel toggle.
    pub semantic: Option<bool>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
    /// Include context-efficiency metadata.
    pub include_context_efficiency: Option<bool>,
}

/// One blended hybrid-search match with channel scores and navigation hints.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridMatch {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_ref: Option<super::TargetRef>,
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub excerpt: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor: Option<EvidenceAnchor>,
    pub blended_score: f32,
    pub lexical_score: f32,
    pub graph_score: f32,
    pub semantic_score: f32,
    pub lexical_sources: Vec<String>,
    pub graph_sources: Vec<String>,
    pub semantic_sources: Vec<String>,
    /// Hybrid graph pipeline when graph_score/sources contributed: projection | heuristic_symbol_graph | heuristic_implementation | unknown. Ranking signal only, not MCP nav precision.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub graph_mode: Option<String>,
    /// Path-class hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path_class: Option<PathClass>,
    /// Source-class hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_class: Option<SourceClass>,
    /// Surface-family hints.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub surface_families: Vec<String>,
    /// Live-navigation hint.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub navigation_hint: Option<SearchHybridNavigationHint>,
    /// Strongest rank signals.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rank_reasons: Vec<SearchHybridRankReason>,
}

/// Short explanation of the strongest signal that lifted a hybrid match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SearchHybridRankReason {
    ExactSymbolMatch,
    ExactTextMatch,
    StrongLexicalAnchor,
    GraphAdjacency,
    SemanticContribution,
    WitnessOnlyFallback,
}

/// Follow-up navigation affordances suggested for one hybrid match.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridNavigationHint {
    /// True when the match is a reasonable first pivot for `read_file` or symbol follow-up.
    pub pivotable: bool,
    /// True when `document_symbols` is expected to be useful on this path.
    pub document_symbols: bool,
    /// True when symbol/anchor follow-up is likely to support `go_to_definition`.
    pub go_to_definition: bool,
}

/// Discovery-to-navigation summary.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridUtilitySummary {
    /// Count of useful live-navigation pivots.
    pub pivotable_match_count: usize,
    /// One-based rank of the best pivot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_pivot_rank: Option<usize>,
    /// Canonical path of the best pivot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_pivot_path: Option<String>,
    /// Repository id for the best pivot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_pivot_repository_id: Option<String>,
    /// True when symbol follow-up is likely useful.
    pub symbol_navigation_ready: bool,
}

/// One structured diagnostic emitted by a hybrid search channel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridChannelDiagnostic {
    pub code: String,
    pub message: String,
}

/// Health and throughput metadata for one hybrid search channel.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridChannelMetadata {
    pub status: ChannelHealthStatus,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    pub candidate_count: usize,
    pub hit_count: usize,
    pub match_count: usize,
    pub diagnostic_count: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub diagnostics: Vec<SearchHybridChannelDiagnostic>,
    /// Present on the hybrid graph channel only: pipeline identity for honesty vs MCP nav.
    ///
    /// Value is always `hybrid_ephemeral` when set — ranking-time expansion, not `incoming_calls`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pipeline: Option<String>,
    /// Short dual-pipeline note for operators (full response_mode; stripped in compact).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pipeline_note: Option<String>,
}

/// Aggregate manifest walk and read diagnostic counts for hybrid search.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridDiagnosticsSummary {
    pub walk: usize,
    pub read: usize,
    pub total: usize,
}

/// Timing and candidate counts for one stage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridStageSample {
    pub elapsed_us: u64,
    pub input_count: usize,
    pub output_count: usize,
}

impl From<&crate::searcher::SearchStageSample> for SearchHybridStageSample {
    fn from(value: &crate::searcher::SearchStageSample) -> Self {
        Self {
            elapsed_us: value.elapsed_us,
            input_count: value.input_count,
            output_count: value.output_count,
        }
    }
}

/// Stage-by-stage execution counters.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridStageAttribution {
    pub candidate_intake: SearchHybridStageSample,
    pub freshness_validation: SearchHybridStageSample,
    pub scan: SearchHybridStageSample,
    pub witness_scoring: SearchHybridStageSample,
    pub graph_expansion: SearchHybridStageSample,
    pub semantic_retrieval: SearchHybridStageSample,
    pub anchor_blending: SearchHybridStageSample,
    pub document_aggregation: SearchHybridStageSample,
    pub final_diversification: SearchHybridStageSample,
}

impl From<&crate::searcher::SearchStageAttribution> for SearchHybridStageAttribution {
    fn from(value: &crate::searcher::SearchStageAttribution) -> Self {
        Self {
            candidate_intake: SearchHybridStageSample::from(&value.candidate_intake),
            freshness_validation: SearchHybridStageSample::from(&value.freshness_validation),
            scan: SearchHybridStageSample::from(&value.scan),
            witness_scoring: SearchHybridStageSample::from(&value.witness_scoring),
            graph_expansion: SearchHybridStageSample::from(&value.graph_expansion),
            semantic_retrieval: SearchHybridStageSample::from(&value.semantic_retrieval),
            anchor_blending: SearchHybridStageSample::from(&value.anchor_blending),
            document_aggregation: SearchHybridStageSample::from(&value.document_aggregation),
            final_diversification: SearchHybridStageSample::from(&value.final_diversification),
        }
    }
}

/// Per-repository freshness metadata.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ResponseFreshnessRepositoryMetadata {
    pub repository_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub snapshot_id: Option<String>,
    pub manifest: String,
    pub semantic: String,
    pub dirty_root: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cacheable_reason: Option<String>,
    pub candidate_source: String,
    pub using_live_walk: bool,
    pub refresh_in_progress: bool,
    #[serde(default)]
    pub active_index_tasks: Vec<Value>,
    pub recommended_client_behavior: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provider: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
}

/// Runtime cache freshness basis.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ResponseFreshnessBasisMetadata {
    pub mode: String,
    pub cacheable: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub repositories: Vec<ResponseFreshnessRepositoryMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runtime_cache_contract: Option<Value>,
}

/// Semantic accelerator health.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridSemanticAcceleratorMetadata {
    pub tier: String,
    pub state: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<ChannelHealthStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Language-specific semantic capabilities.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridLanguageCapabilityMetadata {
    pub requested_language: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    pub semantic_chunking: String,
    pub semantic_accelerator: SearchHybridSemanticAcceleratorMetadata,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub capabilities: BTreeMap<String, String>,
}

/// Classified query shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SearchHybridQueryShape {
    BroadNaturalLanguage,
    CodeShaped,
    Neutral,
}

/// Exact symbol or text pivot assistance.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridExactPivotAssistance {
    pub applied: bool,
    pub exact_symbol_hit_count: usize,
    pub exact_text_hit_count: usize,
    pub boosted_match_count: usize,
}

/// Diagnostics and optional telemetry for `search_hybrid`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridMetadata {
    pub channels: BTreeMap<String, SearchHybridChannelMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lexical_backend: Option<SearchLexicalBackendMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lexical_backend_note: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_requested: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_status: Option<ChannelHealthStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_reason: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_candidate_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_hit_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_match_count: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lexical_only_mode: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_shape: Option<SearchHybridQueryShape>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warning: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exact_pivot_assistance: Option<SearchHybridExactPivotAssistance>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub witness_demotion_applied: Option<bool>,
    pub diagnostics_count: usize,
    pub diagnostics: SearchHybridDiagnosticsSummary,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stage_attribution: Option<SearchHybridStageAttribution>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub semantic_capability: Option<SearchHybridLanguageCapabilityMetadata>,
    /// Discovery-to-navigation summary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub utility: Option<SearchHybridUtilitySummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_efficiency: Option<ContextEfficiencyMetadata>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_debug: Option<ResponseFreshnessBasisMetadata>,
}

/// Response from `search_hybrid`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchHybridResponse {
    pub matches: Vec<SearchHybridMatch>,
    /// Hybrid is ranked discovery, so its corpus total is deliberately unknown.
    pub completeness: super::ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    /// Short scope label for `match_id` values (for example `hybrid`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_scope: Option<String>,
    /// Handle lifetime. Session-scoped handles use `"session"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_expires: Option<String>,
    /// Always-on compact note: hybrid is discovery-only, not final proof.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ranking_note: Option<String>,
    /// Best live-navigation pivot path when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub best_pivot_path: Option<String>,
    /// Approximate search latency class for agent tool-cost guidance.
    /// Hybrid is typically `warm` or `cold` (discovery path; allowed slower than exact).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency_class: Option<LatencyClass>,
    /// Diagnostics metadata; compact mode omits it unless context-efficiency is requested.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<SearchHybridMetadata>,
    /// Flattened recovery fields (`suggested_next`, zero-hit) for compact re-planning
    ///.
    #[serde(flatten, default)]
    pub recovery: RecoveryFields,
}

/// Parameters for `search_symbol`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct SearchSymbolParams {
    /// Symbol name to search.
    pub query: String,
    /// Optional repository scope.
    pub repository_id: Option<String>,
    /// Optional path class filter.
    pub path_class: Option<SearchSymbolPathClass>,
    /// Repository-relative path regex filter.
    pub path_regex: Option<String>,
    /// Optional max matches.
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by an earlier exhaustive symbol page.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// Response from `search_symbol` with optional `result_handle` for `read_match`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchSymbolResponse {
    pub matches: Vec<SymbolMatch>,
    /// Canonical cardinality and paging truth for symbol rows.
    pub completeness: super::ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    /// Short scope label for `match_id` values (for example `symbols`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_scope: Option<String>,
    /// Handle lifetime. Session-scoped handles use `"session"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_expires: Option<String>,
    /// Approximate search latency class for agent tool-cost guidance.
    /// Known-name symbol lookup is typically `hot` when scoped/runtime-first.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency_class: Option<LatencyClass>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(schema_with = "super::metadata_object_field_schema")]
    pub metadata: Option<MetadataObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Flattened recovery fields on empty symbol results.
    #[serde(flatten, default)]
    pub recovery: RecoveryFields,
}

/// Path-class filter for runtime, project, support, or all symbol search.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SearchSymbolPathClass {
    Runtime,
    Project,
    Support,
    /// Opt-in: all path classes (runtime, project, and support/tests).
    Any,
}

impl SearchSymbolPathClass {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Runtime => "runtime",
            Self::Project => "project",
            Self::Support => "support",
            Self::Any => "any",
        }
    }

    /// True when this filter restricts to a single concrete path class.
    pub fn is_concrete_filter(self) -> bool {
        !matches!(self, Self::Any)
    }
}

/// Probe kind for multi-hypothesis `search_batch`.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum SearchBatchProbeKind {
    Text,
    Symbol,
    Hybrid,
}

impl SearchBatchProbeKind {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Text => "text",
            Self::Symbol => "symbol",
            Self::Hybrid => "hybrid",
        }
    }
}

/// Legacy input accepted during the two-minor-release `search_batch` compatibility window.
///
/// This is deliberately not part of the public request schema: batch merge is fixed to RRF.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum SearchBatchMergeMode {
    /// Historical spelling normalized to reciprocal-rank fusion.
    #[default]
    RankByProbeHitStrength,
}

/// Search substrate reported for one contributing batch probe.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum SearchBatchProbeTrust {
    LexicalText,
    IndexedSymbol,
    RankedHybrid,
}

/// One distinct probe's retained evidence for a merged batch coordinate.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema)]
pub struct SearchBatchEvidence {
    pub probe_id: String,
    pub kind: SearchBatchProbeKind,
    pub rank_one_based: usize,
    pub trust: SearchBatchProbeTrust,
}

/// Derived strength used only after consensus and reciprocal-rank fusion tie.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum SearchBatchMatchStrength {
    RankedHybrid,
    IndexedSymbol,
    ExactLiteral,
}

impl SearchBatchMatchStrength {
    pub const fn from_kind(kind: SearchBatchProbeKind) -> Self {
        match kind {
            SearchBatchProbeKind::Text => Self::ExactLiteral,
            SearchBatchProbeKind::Symbol => Self::IndexedSymbol,
            SearchBatchProbeKind::Hybrid => Self::RankedHybrid,
        }
    }
}

/// One typed probe inside a `search_batch` request.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchBatchProbe {
    /// Stable probe id echoed on matches and probe_summary rows.
    pub id: String,
    /// Which underlying search tool to invoke.
    pub kind: SearchBatchProbeKind,
    /// Query / symbol / hybrid question text.
    pub query: String,
    /// Optional repository scope (overrides batch-level when set).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repository_id: Option<String>,
    /// Optional path regex scope (text/symbol).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_regex: Option<String>,
    /// Optional include glob (text).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub glob: Option<String>,
    /// Optional path class (symbol; also echoed for text when set).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_class: Option<SearchSymbolPathClass>,
    /// Optional pattern type for text probes (default literal).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern_type: Option<SearchPatternType>,
}

/// Parameters for `search_batch` multi-probe search.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchBatchParams {
    /// 2..=8 typed probes. Each entry runs as its own text/symbol/hybrid search;
    /// results are merged after all complete (not one shared multi-query walk).
    pub probes: Vec<SearchBatchProbe>,
    /// Deprecated compatibility input. Only `rank_by_probe_hit_strength` is accepted and is
    /// normalized to the fixed reciprocal-rank-fusion merge; it is hidden from the public schema.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(skip)]
    pub merge: Option<SearchBatchMergeMode>,
    /// Max merged match rows to return.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<usize>,
    /// Optional shared repository scope for probes that omit `repository_id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repository_id: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub response_mode: Option<ResponseMode>,
    /// Continuation cursor for paginated batch results (match index).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resume_from: Option<usize>,
    /// Opaque v2 continuation for a previous identical batch request. Cannot be combined with
    /// `resume_from`; the token binds every child probe's scope and repository snapshots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub continuation: Option<String>,
}

/// One merged match row from `search_batch`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct SearchBatchMatch {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_ref: Option<super::TargetRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stable_symbol_id: Option<String>,
    /// Compatibility projection of `evidence` probe ids.
    pub probe_ids: Vec<String>,
    /// Representative contributor kind (the earliest request-order contributor).
    pub kind: SearchBatchProbeKind,
    /// One deterministic evidence record for every contributing probe.
    pub evidence: Vec<SearchBatchEvidence>,
    /// Number of distinct probes contributing retained evidence.
    pub consensus_count: usize,
    /// Equal-weight reciprocal-rank fusion: sum(1 / (60 + rank_one_based)).
    pub rrf_score: f64,
    /// Strength derived only from retained evidence, never backend scores.
    pub match_strength: SearchBatchMatchStrength,
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub column: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub excerpt: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path_class: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
}

/// Per-probe summary row for `search_batch`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchBatchProbeSummary {
    pub id: String,
    pub kind: SearchBatchProbeKind,
    /// Search substrate for this probe; it makes no completeness claim.
    pub trust: SearchBatchProbeTrust,
    pub hits: usize,
    /// Canonical child cardinality, coverage, and cap state. `hits` remains the legacy count
    /// projection; consumers must use this envelope when a child cannot prove an exact total.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zero_hit_reason: Option<ZeroHitReason>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub correction_hint: Option<String>,
    /// Canonical executable recovery actions. Deprecated suggestions are generated from this list.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub next_actions: Vec<NextAction>,
    /// Deprecated lossy projection retained for compatibility.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suggested_next: Vec<SuggestedNext>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<ZeroHitScope>,
}

impl SearchBatchProbeSummary {
    /// Build a child summary with compatibility rows owned exclusively by canonical actions.
    pub fn canonical(
        id: String,
        kind: SearchBatchProbeKind,
        hits: usize,
        completeness: ResultCompleteness,
        zero_hit_reason: Option<ZeroHitReason>,
        correction_hint: Option<String>,
        scope: Option<ZeroHitScope>,
    ) -> Self {
        Self {
            id,
            kind,
            trust: match kind {
                SearchBatchProbeKind::Text => SearchBatchProbeTrust::LexicalText,
                SearchBatchProbeKind::Symbol => SearchBatchProbeTrust::IndexedSymbol,
                SearchBatchProbeKind::Hybrid => SearchBatchProbeTrust::RankedHybrid,
            },
            hits,
            completeness,
            zero_hit_reason,
            correction_hint,
            next_actions: Vec::new(),
            suggested_next: Vec::new(),
            scope,
        }
    }

    /// Normalizes canonical actions and regenerates the deprecated compatibility projection.
    pub fn set_next_actions(&mut self, actions: impl IntoIterator<Item = NextAction>) {
        self.next_actions = super::normalize_next_actions(actions);
        self.suggested_next = self
            .next_actions
            .iter()
            .map(NextAction::to_legacy_suggestion)
            .collect();
    }
}

/// Response from `search_batch`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchBatchResponse {
    pub matches: Vec<SearchBatchMatch>,
    pub probe_summary: Vec<SearchBatchProbeSummary>,
    /// The sole batch merge strategy.
    pub merge_strategy: SearchBatchMergeStrategy,
    /// Source-owned version of the deterministic merge algorithm.
    pub merge_algorithm_version: String,
    /// Emitted only when the schema-hidden legacy `merge` input was used.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub compatibility_note: Option<String>,
    /// Canonical merged-row cardinality, child coverage, and v2 paging truth.
    pub completeness: ResultCompleteness,
    pub returned: usize,
    pub truncated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_from: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_scope: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub handle_expires: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency_class: Option<LatencyClass>,
    /// Flattened recovery on all-zero batches and batch-level next steps.
    #[serde(flatten, default)]
    pub recovery: RecoveryFields,
}

/// Fixed batch evidence merge strategy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SearchBatchMergeStrategy {
    ReciprocalRankFusion,
}

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

    #[test]
    fn context_efficiency_metadata_omits_unknown_optional_fields() {
        let value = serde_json::to_value(ContextEfficiencyMetadata {
            indexed_readable_files: 3,
            indexed_readable_bytes: 120,
            indexed_min_mtime_ns: None,
            indexed_max_mtime_ns: None,
            candidate_input_count: None,
            candidate_output_count: None,
            returned_match_count: Some(2),
            returned_unique_paths: Some(1),
            returned_unique_file_bytes: Some(80),
            returned_source_bytes_estimate: Some(20),
            matched_file_context_saved_bytes_estimate: Some(60),
            matched_file_context_saved_percent_estimate: Some(75.0),
            corpus_context_saved_bytes_estimate: Some(100),
            corpus_context_saved_percent_estimate: Some(83.33),
            corpus_narrowing_ratio_estimate: Some(6),
            query_duration_ms: Some(12),
            narrowing_ratio_estimate: Some(4),
            stage_attribution: None,
        })
        .expect("context-efficiency metadata should serialize");

        assert_eq!(
            value,
            json!({
                "indexed_readable_files": 3,
                "indexed_readable_bytes": 120,
                "returned_match_count": 2,
                "returned_unique_paths": 1,
                "returned_unique_file_bytes": 80,
                "returned_source_bytes_estimate": 20,
                "matched_file_context_saved_bytes_estimate": 60,
                "matched_file_context_saved_percent_estimate": 75.0,
                "corpus_context_saved_bytes_estimate": 100,
                "corpus_context_saved_percent_estimate": 83.33,
                "corpus_narrowing_ratio_estimate": 6,
                "query_duration_ms": 12,
                "narrowing_ratio_estimate": 4
            })
        );
    }

    #[test]
    fn context_efficiency_stage_attribution_is_typed() {
        let value = serde_json::to_value(ContextEfficiencyMetadata {
            indexed_readable_files: 1,
            indexed_readable_bytes: 10,
            indexed_min_mtime_ns: Some(100),
            indexed_max_mtime_ns: Some(200),
            candidate_input_count: Some(8),
            candidate_output_count: Some(3),
            returned_match_count: None,
            returned_unique_paths: None,
            returned_unique_file_bytes: None,
            returned_source_bytes_estimate: None,
            matched_file_context_saved_bytes_estimate: None,
            matched_file_context_saved_percent_estimate: None,
            corpus_context_saved_bytes_estimate: None,
            corpus_context_saved_percent_estimate: None,
            corpus_narrowing_ratio_estimate: None,
            query_duration_ms: None,
            narrowing_ratio_estimate: None,
            stage_attribution: Some(ContextEfficiencyStageAttribution {
                candidate_input_count: 8,
                candidate_output_count: 3,
            }),
        })
        .expect("context-efficiency metadata should serialize");

        assert_eq!(
            value["stage_attribution"]["candidate_input_count"],
            json!(8)
        );
        assert_eq!(
            value["stage_attribution"]["candidate_output_count"],
            json!(3)
        );
    }

    #[test]
    fn search_batch_legacy_merge_is_schema_hidden_and_strict() {
        let schema = schemars::schema_for!(SearchBatchParams);
        let schema = serde_json::to_value(schema).expect("search_batch schema serializes");
        assert!(
            schema["properties"].get("merge").is_none(),
            "the canonical request schema must not advertise a merge choice"
        );

        let legacy: SearchBatchParams = serde_json::from_value(json!({
            "probes": [],
            "merge": "rank_by_probe_hit_strength"
        }))
        .expect("the documented legacy spelling remains readable during its compatibility window");
        assert_eq!(
            legacy.merge,
            Some(SearchBatchMergeMode::RankByProbeHitStrength)
        );

        assert!(
            serde_json::from_value::<SearchBatchParams>(json!({
                "probes": [],
                "merge": "reciprocal_rank_fusion"
            }))
            .is_err(),
            "only the documented legacy spelling may be accepted"
        );
    }

    #[test]
    fn explore_params_accept_context_efficiency_opt_in() {
        let params: ExploreParams = serde_json::from_value(json!({
            "path": "src/lib.rs",
            "operation": "probe",
            "query": "needle",
            "include_context_efficiency": true
        }))
        .expect("explore params should accept include_context_efficiency");

        assert_eq!(params.include_context_efficiency, Some(true));
    }

    #[test]
    fn explore_metadata_omits_context_efficiency_by_default() {
        let value = serde_json::to_value(ExploreMetadata {
            lossy_utf8: false,
            effective_context_lines: 3,
            effective_max_matches: 8,
            context_efficiency: None,
        })
        .expect("explore metadata should serialize");

        assert!(value.get("context_efficiency").is_none());
    }

    #[test]
    fn response_freshness_basis_round_trips_runtime_metadata() {
        let value = json!({
            "mode": "manifest_only",
            "cacheable": false,
            "repositories": [{
                "repository_id": "repo-001",
                "snapshot_id": "snapshot-abc",
                "manifest": "ready",
                "semantic": "ready",
                "dirty_root": false,
                "cacheable_reason": "refresh in progress",
                "candidate_source": "manifest",
                "using_live_walk": false,
                "refresh_in_progress": true,
                "active_index_tasks": [{
                    "kind": "manifest",
                    "status": "running"
                }],
                "recommended_client_behavior": "prefer_current_response",
                "provider": "openai",
                "model": "text-embedding-3-small"
            }],
            "runtime_cache_contract": {
                "cacheable": false,
                "invalidation_basis": "snapshot"
            }
        });

        let metadata: ResponseFreshnessBasisMetadata =
            serde_json::from_value(value.clone()).expect("freshness metadata should deserialize");
        let serialized =
            serde_json::to_value(metadata).expect("freshness metadata should serialize");

        assert_eq!(serialized, value);
    }

    #[test]
    fn response_freshness_repository_keeps_empty_active_index_tasks() {
        let value = json!({
            "repository_id": "repo-001",
            "snapshot_id": "snapshot-abc",
            "manifest": "ready",
            "semantic": "ready",
            "dirty_root": false,
            "candidate_source": "manifest_snapshot",
            "using_live_walk": false,
            "refresh_in_progress": false,
            "active_index_tasks": [],
            "recommended_client_behavior": "use_cached_frigg_results"
        });

        let metadata: ResponseFreshnessRepositoryMetadata = serde_json::from_value(value.clone())
            .expect("repository freshness metadata should deserialize");
        let serialized =
            serde_json::to_value(metadata).expect("repository freshness metadata should serialize");

        assert_eq!(serialized, value);
    }
}