frigg 0.10.0

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
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
//! Navigation MCP wire types: references, definitions, declarations, implementations, and call hierarchy.

use super::{MetadataObject, ResponseMode, ResultCompleteness, TargetRef};
use crate::domain::model::{GeneratedStructuralFollowUp, ReferenceMatch};
use schemars::{JsonSchema, Schema, SchemaGenerator};
use serde::{Deserialize, Serialize};
use std::borrow::Cow;

/// Parameters for `find_references`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct FindReferencesParams {
    pub target: Option<TargetRef>,
    /// Symbol query.
    pub symbol: Option<String>,
    pub repository_id: Option<String>,
    /// Source path for location-aware resolution.
    pub path: Option<String>,
    /// 1-based source line.
    pub line: Option<usize>,
    /// 1-based source column.
    pub column: Option<usize>,
    /// Include definition rows.
    pub include_definition: Option<bool>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by a prior identical request.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// Precision mode reported by navigation tools for the resolved target and match set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NavigationMode {
    Precise,
    PrecisePartial,
    HeuristicNoPrecise,
    UnavailableNoPrecise,
}

/// Whether navigation target resolution produced one symbol or requires disambiguation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NavigationTargetSelectionStatus {
    Resolved,
    DisambiguationRequired,
}

/// Closed public category describing how the selected navigation target was resolved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NavigationResolutionSource {
    ResultMatch,
    StableSymbol,
    DirectSymbol,
    DirectLocation,
}

/// Target-resolution summary shared by navigation tool responses.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct NavigationTargetSelectionSummary {
    pub status: NavigationTargetSelectionStatus,
    pub resolution_source: NavigationResolutionSource,
    pub symbol_query: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub selected_stable_symbol_id: Option<String>,
    pub candidate_count: usize,
    pub same_rank_candidate_count: usize,
    pub ambiguous_query: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidates: Vec<crate::domain::model::SymbolMatch>,
}

/// Response from `find_references` with navigation mode and optional target-selection notes.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FindReferencesResponse {
    pub total_matches: usize,
    pub matches: Vec<ReferenceMatch>,
    /// Canonical cardinality, coverage, and paging truth for reference rows.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    /// Short scope label for `match_id` values (for example `nav`).
    #[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>,
    pub mode: NavigationMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    #[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 reference results.
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

/// Parameters for `go_to_definition` (default agent route for definition/body anchors).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct GoToDefinitionParams {
    pub target: Option<TargetRef>,
    /// Recommended: symbol name to resolve. Prefer this over path+line alone on dense lines.
    pub symbol: Option<String>,
    pub repository_id: Option<String>,
    pub path: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by a prior identical request.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// One resolved navigation location with optional structural follow-up suggestions.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct NavigationLocation {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_ref: Option<TargetRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stable_symbol_id: Option<String>,
    pub symbol: String,
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub kind: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    pub precision: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub follow_up_structural: Vec<GeneratedStructuralFollowUp>,
}

/// Response from `go_to_definition`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GoToDefinitionResponse {
    pub matches: Vec<NavigationLocation>,
    /// Canonical cardinality, coverage, and paging truth for definition rows.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    /// Short scope label for `match_id` values (for example `nav`).
    #[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>,
    pub mode: NavigationMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    #[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>,
    /// Soft warning when path+line was used without `symbol` (generic or density-specific copy).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location_warning: Option<String>,
    /// True when path+line without symbol may be wrong. Check this or location_warning before edits; prefer symbol= from search_symbol.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ambiguous_location: Option<bool>,
    /// Flattened recovery fields on empty definition results (and soft re-plan on ambiguous hits).
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

/// Parameters for `find_declarations` (secondary to go_to_definition; use when decl vs def matters).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct FindDeclarationsParams {
    pub target: Option<TargetRef>,
    /// Preferred when the name is known (same as go_to_definition).
    pub symbol: Option<String>,
    pub repository_id: Option<String>,
    pub path: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by a prior identical request.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// Response from `find_declarations`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FindDeclarationsResponse {
    pub matches: Vec<NavigationLocation>,
    /// Canonical cardinality, coverage, and paging truth for declaration rows.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    pub mode: NavigationMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    #[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 declaration results.
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

/// Parameters for `find_implementations`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct FindImplementationsParams {
    pub target: Option<TargetRef>,
    pub symbol: Option<String>,
    pub repository_id: Option<String>,
    pub path: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by a prior identical request.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// One implementation or override location for a resolved symbol target.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ImplementationMatch {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_ref: Option<TargetRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stable_symbol_id: Option<String>,
    pub symbol: String,
    pub kind: Option<String>,
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub relation: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    pub precision: Option<String>,
    pub fallback_reason: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub follow_up_structural: Vec<GeneratedStructuralFollowUp>,
}

/// Response from `find_implementations`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct FindImplementationsResponse {
    pub matches: Vec<ImplementationMatch>,
    /// Canonical cardinality, coverage, and paging truth for implementation rows.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    pub mode: NavigationMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    #[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 implementation results.
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

/// Parameters for `incoming_calls`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct IncomingCallsParams {
    pub target: Option<TargetRef>,
    pub symbol: Option<String>,
    pub repository_id: Option<String>,
    pub path: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by a prior identical request.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// Parameters for `outgoing_calls`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct OutgoingCallsParams {
    pub target: Option<TargetRef>,
    pub symbol: Option<String>,
    pub repository_id: Option<String>,
    pub path: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    pub limit: Option<usize>,
    /// Opaque v2 continuation returned by a prior identical request.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// One incoming or outgoing call edge in the call hierarchy.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CallHierarchyMatch {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_ref: Option<TargetRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_stable_symbol_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_stable_symbol_id: Option<String>,
    pub source_symbol: String,
    pub target_symbol: String,
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub relation: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_signature: Option<String>,
    pub precision: Option<String>,
    pub call_path: Option<String>,
    pub call_line: Option<usize>,
    pub call_column: Option<usize>,
    pub call_end_line: Option<usize>,
    pub call_end_column: Option<usize>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub follow_up_structural: Vec<GeneratedStructuralFollowUp>,
}

/// Response from `incoming_calls`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct IncomingCallsResponse {
    pub matches: Vec<CallHierarchyMatch>,
    /// Canonical cardinality, coverage, and paging truth for incoming call rows.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    pub mode: NavigationMode,
    pub availability: Option<NavigationAvailability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    #[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 caller results.
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

/// Trust tier for nav edges. Outgoing_calls is always provisional today; do not invent verified.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum NavigationEdgeTrust {
    Provisional,
    Verified,
}

/// Always-on compact honesty copy for `outgoing_calls` (EXP-nav-outgoing-honesty B).
pub const OUTGOING_CALLS_TRUST_NOTE: &str = "Callee edges are provisional; confirm with read_file, find_references, or search_structural before asserting blast radius.";

/// Response from `outgoing_calls`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct OutgoingCallsResponse {
    pub matches: Vec<CallHierarchyMatch>,
    /// Canonical cardinality, coverage, and paging truth for outgoing call rows.
    pub completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    pub mode: NavigationMode,
    pub availability: Option<NavigationAvailability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(schema_with = "super::metadata_object_field_schema")]
    pub metadata: Option<MetadataObject>,
    /// Full-mode diagnostic note only (stripped in compact). Prefer `trust` / `trust_note`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
    /// Machine-obvious trust tier. Outgoing callees are always `provisional` today.
    pub trust: NavigationEdgeTrust,
    /// Always-on compact honesty (not stripped in compact mode; skill-less hosts still see it).
    pub trust_note: String,
    /// Flattened recovery fields on empty callee results.
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

impl OutgoingCallsResponse {
    /// Default provisional honesty applied to every outgoing_calls response path.
    pub fn with_provisional_honesty(mut self) -> Self {
        self.trust = NavigationEdgeTrust::Provisional;
        self.trust_note = OUTGOING_CALLS_TRUST_NOTE.to_owned();
        self
    }
}

/// Availability note when call-hierarchy results depend on precise coverage.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct NavigationAvailability {
    pub status: String,
    pub reason: Option<String>,
    pub precise_required_for_complete_results: bool,
}

/// Parameters for `document_symbols`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct DocumentSymbolsParams {
    pub target: Option<TargetRef>,
    pub path: String,
    pub repository_id: Option<String>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    /// Return only top-level symbols when true. Defaults to `true` when omitted.
    pub top_level_only: Option<bool>,
    /// Max outline rows to return. Omit for the default bounded page.
    pub limit: Option<usize>,
    /// Continuation offset returned as `resume_from` when the outline is truncated.
    pub resume_from: Option<usize>,
    /// Opaque v2 continuation. Cannot be combined with `resume_from`.
    pub continuation: Option<String>,
    /// Response detail profile. Omit to default to `compact`.
    pub response_mode: Option<ResponseMode>,
}

/// One document symbol row with optional nested children.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentSymbolItem {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    /// Opaque executable identity for this handle-bound symbol.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_ref: Option<TargetRef>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stable_symbol_id: Option<String>,
    pub symbol: String,
    pub kind: String,
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub end_line: Option<usize>,
    pub end_column: Option<usize>,
    pub container: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub follow_up_structural: Vec<GeneratedStructuralFollowUp>,
    pub children: Vec<DocumentSymbolItem>,
}

/// Response from `document_symbols`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DocumentSymbolsResponse {
    pub symbols: Vec<DocumentSymbolItem>,
    /// Total outline symbols before pagination (after top_level_only filtering).
    pub total_symbols: usize,
    /// Number of symbols returned in this page.
    pub returned: usize,
    /// True when more outline rows remain after this page.
    pub truncated: bool,
    /// Continuation offset for the next page when `truncated` is true.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resume_from: Option<usize>,
    /// Canonical cardinality and paging truth for outline rows.
    pub completeness: super::ResultCompleteness,
    /// Echo of the effective top_level_only setting.
    pub top_level_only: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    #[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>,
}

/// Parameters for `inspect_syntax_tree`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InspectSyntaxTreeParams {
    pub path: String,
    pub repository_id: Option<String>,
    pub line: Option<usize>,
    pub column: Option<usize>,
    pub max_ancestors: Option<usize>,
    pub max_children: Option<usize>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
}

/// One syntax-tree node with source span and excerpt.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SyntaxTreeNodeItem {
    pub kind: String,
    pub named: bool,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub end_line: usize,
    pub end_column: usize,
    pub excerpt: String,
}

/// Response from `inspect_syntax_tree` around a focused AST node.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct InspectSyntaxTreeResponse {
    pub repository_id: String,
    pub path: String,
    pub language: String,
    pub focus: SyntaxTreeNodeItem,
    pub ancestors: Vec<SyntaxTreeNodeItem>,
    pub children: Vec<SyntaxTreeNodeItem>,
    /// Independent completeness for the bounded ancestor collection.
    pub ancestors_completeness: super::ResultCompleteness,
    /// Independent completeness for the bounded child collection.
    pub children_completeness: super::ResultCompleteness,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub follow_up_structural: Vec<GeneratedStructuralFollowUp>,
    #[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>,
}

/// Parameters for optional `impact_bundle` convenience composition.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ImpactBundleParams {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<TargetRef>,
    /// Legacy symbol name to resolve impact for. Either this non-empty value or `target` is
    /// required; both together are rejected so an issued target can never be overridden.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub symbol: String,
    /// Path class for the initial symbol lookup. Defaults to `runtime`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path_class: Option<crate::mcp::types::SearchSymbolPathClass>,
    /// Optional repository scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repository_id: Option<String>,
    /// Force include implementations even when kind is not trait/interface.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_implementations: Option<bool>,
    /// Include exact literal mentions under `test` and `tests` directories. Omit or pass `false`
    /// to keep test evidence out of the impact bundle.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include_test_mentions: Option<bool>,
    /// Response detail profile. Omit to default to `compact`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_mode: Option<ResponseMode>,
}

impl JsonSchema for ImpactBundleParams {
    fn schema_name() -> Cow<'static, str> {
        "ImpactBundleParams".into()
    }

    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
        let target = serde_json::to_value(generator.subschema_for::<TargetRef>())
            .expect("target schema must serialize");
        let path_class = serde_json::to_value(
            generator.subschema_for::<crate::mcp::types::SearchSymbolPathClass>(),
        )
        .expect("path-class schema must serialize");
        let response_mode = serde_json::to_value(generator.subschema_for::<ResponseMode>())
            .expect("response-mode schema must serialize");
        Schema::try_from(serde_json::json!({
            "type": "object",
            "properties": {
                "target": target,
                "symbol": { "type": "string", "minLength": 1 },
                "path_class": path_class,
                "repository_id": { "type": "string" },
                "include_implementations": { "type": "boolean" },
                "include_test_mentions": { "type": "boolean", "default": false },
                "response_mode": response_mode
            },
            "oneOf": [
                { "required": ["target"], "not": { "required": ["symbol"] } },
                { "required": ["symbol"], "not": { "required": ["target"] } }
            ]
        }))
        .expect("impact bundle schema must be valid")
    }
}

impl ImpactBundleParams {
    /// Whether the opt-in test-mention section should execute.
    pub fn includes_test_mentions(&self) -> bool {
        self.include_test_mentions.unwrap_or(false)
    }
}

/// Closed evidence section vocabulary for `impact_bundle`.
///
/// Outgoing calls are intentionally not an impact section.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ImpactSection {
    Symbol,
    Reference,
    IncomingCall,
    Implementation,
    TestMention,
}

/// Whether an impact section ran, was intentionally omitted, or could not run because target
/// resolution failed. This is independent from pagination completeness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ImpactSectionExecution {
    Included,
    OmittedByPolicy,
    NotRunTargetUnresolved,
}

/// Semantic trust for an impact section. It deliberately does not encode pagination or coverage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum ImpactSectionTrust {
    ResolvedTarget {
        resolution_source: NavigationResolutionSource,
    },
    ExactLiteralText,
    Navigation {
        mode: NavigationMode,
    },
}

/// Rows owned by one typed impact section.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(
    tag = "row_kind",
    content = "rows",
    rename_all = "snake_case",
    deny_unknown_fields
)]
pub enum ImpactSectionRows {
    Symbol(Vec<crate::domain::model::SymbolMatch>),
    Reference(Vec<crate::domain::model::ReferenceMatch>),
    IncomingCall(Vec<CallHierarchyMatch>),
    Implementation(Vec<ImplementationMatch>),
    TestMention(Vec<crate::domain::model::TextMatch>),
}

impl ImpactSectionRows {
    fn section(&self) -> ImpactSection {
        match self {
            Self::Symbol(_) => ImpactSection::Symbol,
            Self::Reference(_) => ImpactSection::Reference,
            Self::IncomingCall(_) => ImpactSection::IncomingCall,
            Self::Implementation(_) => ImpactSection::Implementation,
            Self::TestMention(_) => ImpactSection::TestMention,
        }
    }

    fn has_bound_row(&self, target: &ImpactProofRowTarget) -> bool {
        let target_ref = target.as_target_ref();
        let matches = |match_id: &Option<String>, row_target: &Option<TargetRef>| {
            match_id.as_deref() == Some(target.match_id.as_str())
                && row_target.as_ref() == Some(&target_ref)
        };
        match self {
            Self::Symbol(rows) => rows
                .iter()
                .any(|row| matches(&row.match_id, &row.target_ref)),
            Self::Reference(rows) => rows
                .iter()
                .any(|row| matches(&row.match_id, &row.target_ref)),
            Self::IncomingCall(rows) => rows
                .iter()
                .any(|row| matches(&row.match_id, &row.target_ref)),
            Self::Implementation(rows) => rows
                .iter()
                .any(|row| matches(&row.match_id, &row.target_ref)),
            Self::TestMention(rows) => rows
                .iter()
                .any(|row| matches(&row.match_id, &row.target_ref)),
        }
    }

    /// Every returned row that carries a spec-011 result target is proofable.
    fn bound_row_targets(&self) -> Vec<ImpactProofRowTarget> {
        let collect = |rows: Vec<(&Option<String>, &Option<TargetRef>)>| {
            rows.into_iter()
                .filter_map(|(match_id, target_ref)| match (match_id, target_ref) {
                    (
                        Some(match_id),
                        Some(TargetRef::ResultMatch {
                            result_handle,
                            match_id: target_match_id,
                            target_scope,
                        }),
                    ) if match_id == target_match_id => ImpactProofRowTarget::new(
                        result_handle.clone(),
                        match_id.clone(),
                        target_scope.clone(),
                    ),
                    _ => None,
                })
                .collect()
        };
        match self {
            Self::Symbol(rows) => collect(
                rows.iter()
                    .map(|row| (&row.match_id, &row.target_ref))
                    .collect(),
            ),
            Self::Reference(rows) => collect(
                rows.iter()
                    .map(|row| (&row.match_id, &row.target_ref))
                    .collect(),
            ),
            Self::IncomingCall(rows) => collect(
                rows.iter()
                    .map(|row| (&row.match_id, &row.target_ref))
                    .collect(),
            ),
            Self::Implementation(rows) => collect(
                rows.iter()
                    .map(|row| (&row.match_id, &row.target_ref))
                    .collect(),
            ),
            Self::TestMention(rows) => collect(
                rows.iter()
                    .map(|row| (&row.match_id, &row.target_ref))
                    .collect(),
            ),
        }
    }
}

/// Authoritative execution, trust, completeness, rows, and proofs for one impact section.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ImpactSectionResult {
    pub section: ImpactSection,
    pub execution: ImpactSectionExecution,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trust: Option<ImpactSectionTrust>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completeness: Option<ResultCompleteness>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
    pub rows: ImpactSectionRows,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub proof_targets: Vec<ImpactProofTarget>,
}

impl ImpactSectionResult {
    /// Build a section result only when its execution state and evidence agree.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        section: ImpactSection,
        execution: ImpactSectionExecution,
        trust: Option<ImpactSectionTrust>,
        completeness: Option<ResultCompleteness>,
        result_handle: Option<String>,
        rows: ImpactSectionRows,
        proof_targets: Vec<ImpactProofTarget>,
    ) -> Option<Self> {
        let result = Self {
            section,
            execution,
            trust,
            completeness,
            result_handle,
            rows,
            proof_targets,
        };
        result.is_valid().then_some(result)
    }

    fn is_valid(&self) -> bool {
        if self.rows.section() != self.section {
            return false;
        }
        match self.execution {
            ImpactSectionExecution::Included => {
                if self.trust.is_none() || self.completeness.is_none() {
                    return false;
                }
                // Empty child responses legitimately have no result handle. They cannot carry a
                // proof target; non-empty/proofable sections must remain handle-bound.
                let has_rows = match &self.rows {
                    ImpactSectionRows::Symbol(rows) => !rows.is_empty(),
                    ImpactSectionRows::Reference(rows) => !rows.is_empty(),
                    ImpactSectionRows::IncomingCall(rows) => !rows.is_empty(),
                    ImpactSectionRows::Implementation(rows) => !rows.is_empty(),
                    ImpactSectionRows::TestMention(rows) => !rows.is_empty(),
                };
                if (has_rows || !self.proof_targets.is_empty())
                    && self.result_handle.as_deref().is_none_or(str::is_empty)
                {
                    return false;
                }
                let bound_targets = self.rows.bound_row_targets();
                bound_targets.len() == self.proof_targets.len()
                    && bound_targets.iter().all(|target| {
                        self.proof_targets
                            .iter()
                            .filter(|proof| proof.target == *target)
                            .count()
                            == 1
                    })
                    && self.proof_targets.iter().all(|proof| {
                        proof.section == self.section
                            && self.result_handle.as_deref()
                                == Some(proof.target.result_handle.as_str())
                            && self.rows.has_bound_row(&proof.target)
                    })
            }
            ImpactSectionExecution::OmittedByPolicy
            | ImpactSectionExecution::NotRunTargetUnresolved => {
                self.trust.is_none()
                    && self.completeness.is_none()
                    && self.result_handle.is_none()
                    && self.proof_targets.is_empty()
                    && match &self.rows {
                        ImpactSectionRows::Symbol(rows) => rows.is_empty(),
                        ImpactSectionRows::Reference(rows) => rows.is_empty(),
                        ImpactSectionRows::IncomingCall(rows) => rows.is_empty(),
                        ImpactSectionRows::Implementation(rows) => rows.is_empty(),
                        ImpactSectionRows::TestMention(rows) => rows.is_empty(),
                    }
            }
        }
    }
}

impl<'de> Deserialize<'de> for ImpactSectionResult {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Raw {
            section: ImpactSection,
            execution: ImpactSectionExecution,
            trust: Option<ImpactSectionTrust>,
            completeness: Option<ResultCompleteness>,
            result_handle: Option<String>,
            rows: ImpactSectionRows,
            #[serde(default)]
            proof_targets: Vec<ImpactProofTarget>,
        }

        let raw = Raw::deserialize(deserializer)?;
        Self::new(
            raw.section,
            raw.execution,
            raw.trust,
            raw.completeness,
            raw.result_handle,
            raw.rows,
            raw.proof_targets,
        )
        .ok_or_else(|| serde::de::Error::custom("invalid impact section result state"))
    }
}

/// Exact handle-bound result row addressed by an impact proof.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ImpactProofRowTarget {
    #[schemars(length(min = 1))]
    pub result_handle: String,
    #[schemars(length(min = 1))]
    pub match_id: String,
    #[schemars(length(min = 1))]
    pub target_scope: String,
}

impl<'de> Deserialize<'de> for ImpactProofRowTarget {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Raw {
            result_handle: String,
            match_id: String,
            target_scope: String,
        }

        let raw = Raw::deserialize(deserializer)?;
        Self::new(raw.result_handle, raw.match_id, raw.target_scope).ok_or_else(|| {
            serde::de::Error::custom("impact proof row target fields must not be empty")
        })
    }
}

impl ImpactProofRowTarget {
    /// Construct an exact, non-empty result-row target.
    pub fn new(result_handle: String, match_id: String, target_scope: String) -> Option<Self> {
        (!result_handle.is_empty() && !match_id.is_empty() && !target_scope.is_empty()).then_some(
            Self {
                result_handle,
                match_id,
                target_scope,
            },
        )
    }

    /// Convert this proof-only identity back to the shared spec-011 target type.
    pub fn as_target_ref(&self) -> TargetRef {
        TargetRef::ResultMatch {
            result_handle: self.result_handle.clone(),
            match_id: self.match_id.clone(),
            target_scope: self.target_scope.clone(),
        }
    }
}

/// Deterministic proof target for one returned row in one impact section.
///
/// The action id names the canonical typed action that reads this exact handle-bound row.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ImpactProofTarget {
    pub section: ImpactSection,
    pub target: ImpactProofRowTarget,
    pub action_id: super::NextActionId,
}

impl<'de> Deserialize<'de> for ImpactProofTarget {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Raw {
            section: ImpactSection,
            target: ImpactProofRowTarget,
            action_id: super::NextActionId,
        }

        let raw = Raw::deserialize(deserializer)?;
        (!raw.action_id.0.trim().is_empty())
            .then_some(Self {
                section: raw.section,
                target: raw.target,
                action_id: raw.action_id,
            })
            .ok_or_else(|| serde::de::Error::custom("impact proof action_id must not be empty"))
    }
}

impl ImpactProofTarget {
    /// Construct a proof target only for one exact bound row and one canonical action id.
    pub fn new(
        section: ImpactSection,
        target: ImpactProofRowTarget,
        action_id: super::NextActionId,
    ) -> Option<Self> {
        (!action_id.0.trim().is_empty()).then_some(Self {
            section,
            target,
            action_id,
        })
    }
}

/// Section role for a path tally row in `ImpactBundleSummary.top_paths`.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum ImpactBundlePathRole {
    /// Selected/primary symbol hit (first search_symbol match used for nav composition).
    Symbol,
    Reference,
    IncomingCall,
    Implementation,
}

impl ImpactBundlePathRole {
    /// Tie-break priority under equal counts (lower sorts earlier after count desc).
    fn plan_priority(self) -> u8 {
        match self {
            Self::Symbol => 0,
            Self::Reference => 1,
            Self::IncomingCall => 2,
            Self::Implementation => 3,
        }
    }
}

/// Path tally row for compact impact planning (EXP-nav-impact-shape B).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactBundlePathTally {
    pub path: String,
    pub role: ImpactBundlePathRole,
    pub count: usize,
}

/// Always-on cardinality summary for `impact_bundle`. Plan from summary first; lists/handles for proof. Counts mirror returned lists; composition uses the first symbol hit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ImpactBundleSummary {
    pub symbols_count: usize,
    pub references_count: usize,
    pub incoming_calls_count: usize,
    pub implementations_count: usize,
    pub implementations_included: bool,
    pub references_mode: NavigationMode,
    pub incoming_calls_mode: NavigationMode,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub implementations_mode: Option<NavigationMode>,
    /// Highest-count path×role tallies (global cap 8); empty when no hits.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub top_paths: Vec<ImpactBundlePathTally>,
    /// True when more path×role tallies existed than the top_paths cap.
    pub top_paths_truncated: bool,
}

/// Composed impact: hits + refs + callers (+ optional impls). One next-step channel via flattened suggested_next only.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ImpactBundleResponse {
    pub symbol: String,
    pub path_class: String,
    /// Selection evidence when the supplied legacy symbol needs a more specific target.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<NavigationTargetSelectionSummary>,
    /// Always-on plan-friendly counts / modes / top paths (EXP-nav-impact-shape B).
    pub summary: ImpactBundleSummary,
    /// Authoritative execution/trust/coverage envelope for every impact section. Legacy arrays
    /// below are compatibility projections of these section results.
    #[serde(default)]
    pub sections: Vec<ImpactSectionResult>,
    /// Deterministic index of every proofable returned row, qualified by its section.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub proof_targets: Vec<ImpactProofTarget>,
    pub symbols: Vec<crate::domain::model::SymbolMatch>,
    /// Cardinality and coverage for the symbol lookup section.
    pub symbols_completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub symbols_result_handle: Option<String>,
    pub references: Vec<crate::domain::model::ReferenceMatch>,
    /// Cardinality and coverage for the references section.
    pub references_completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub references_result_handle: Option<String>,
    pub references_mode: NavigationMode,
    pub incoming_calls: Vec<CallHierarchyMatch>,
    /// Cardinality and coverage for the incoming-call section.
    pub incoming_calls_completeness: ResultCompleteness,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub incoming_calls_result_handle: Option<String>,
    pub incoming_calls_mode: NavigationMode,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub implementations: Vec<ImplementationMatch>,
    /// Cardinality and coverage for implementations when that section was explicitly included.
    /// `None` is a policy omission, not hidden truncation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub implementations_completeness: Option<ResultCompleteness>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub implementations_result_handle: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub implementations_mode: Option<NavigationMode>,
    pub implementations_included: bool,
    /// Aggregate truth across every included section. It never upgrades a child section's
    /// coverage or truncation state.
    pub completeness: ResultCompleteness,
    /// Flattened recovery + **only** `suggested_next` channel (success and zero-hit paths).
    #[serde(flatten, default)]
    pub recovery: super::RecoveryFields,
}

impl ImpactBundleResponse {
    /// Build the always-on summary from current list sections (global top_paths cap 8).
    #[allow(clippy::too_many_arguments)]
    pub fn compute_summary(
        symbols: &[crate::domain::model::SymbolMatch],
        references: &[crate::domain::model::ReferenceMatch],
        incoming_calls: &[CallHierarchyMatch],
        implementations: &[ImplementationMatch],
        references_mode: NavigationMode,
        incoming_calls_mode: NavigationMode,
        implementations_mode: Option<NavigationMode>,
        implementations_included: bool,
    ) -> ImpactBundleSummary {
        const TOP_PATHS_CAP: usize = 8;
        use std::collections::BTreeMap;

        let mut tallies: BTreeMap<(String, ImpactBundlePathRole), usize> = BTreeMap::new();
        if let Some(m) = symbols.first() {
            *tallies
                .entry((m.path.clone(), ImpactBundlePathRole::Symbol))
                .or_default() += 1;
        }
        for m in references {
            *tallies
                .entry((m.path.clone(), ImpactBundlePathRole::Reference))
                .or_default() += 1;
        }
        for m in incoming_calls {
            *tallies
                .entry((m.path.clone(), ImpactBundlePathRole::IncomingCall))
                .or_default() += 1;
        }
        for m in implementations {
            *tallies
                .entry((m.path.clone(), ImpactBundlePathRole::Implementation))
                .or_default() += 1;
        }

        let total_tallies = tallies.len();
        let mut top_paths: Vec<ImpactBundlePathTally> = tallies
            .into_iter()
            .map(|((path, role), count)| ImpactBundlePathTally { path, role, count })
            .collect();
        top_paths.sort_by(|a, b| {
            b.count
                .cmp(&a.count)
                .then_with(|| a.role.plan_priority().cmp(&b.role.plan_priority()))
                .then_with(|| a.path.cmp(&b.path))
        });
        let top_paths_truncated = total_tallies > TOP_PATHS_CAP;
        top_paths.truncate(TOP_PATHS_CAP);

        ImpactBundleSummary {
            symbols_count: symbols.len(),
            references_count: references.len(),
            incoming_calls_count: incoming_calls.len(),
            implementations_count: implementations.len(),
            implementations_included,
            references_mode,
            incoming_calls_mode,
            implementations_mode,
            top_paths,
            top_paths_truncated,
        }
    }

    /// Recompute `summary` from the response's current lists/modes.
    pub fn with_computed_summary(mut self) -> Self {
        self.summary = Self::compute_summary(
            &self.symbols,
            &self.references,
            &self.incoming_calls,
            &self.implementations,
            self.references_mode,
            self.incoming_calls_mode,
            self.implementations_mode,
            self.implementations_included,
        );
        self
    }

    /// Preserve section truth in the bundle-level envelope. The aggregate's unit is the number
    /// of included sections rather than a misleading sum of heterogeneous row units.
    pub fn aggregate_completeness(sections: &[&ResultCompleteness]) -> ResultCompleteness {
        let returned = sections.len();
        let truncated = sections.iter().any(|section| section.truncated);
        let complete = sections.iter().all(|section| section.complete);
        let mut truncation_reasons = Vec::new();
        let mut incomplete_reasons = Vec::new();
        for section in sections {
            if section.truncated {
                truncation_reasons.push(super::ResultTruncationReason::ChildLimit);
            }
            if !section.complete {
                incomplete_reasons.push(super::ResultIncompleteReason::ChildIncomplete);
                incomplete_reasons.extend(section.incomplete_reasons.iter().copied());
            }
        }
        ResultCompleteness::try_new(
            super::ResultUnit::ImpactSection,
            returned,
            Some(returned),
            complete,
            truncated,
            truncation_reasons,
            incomplete_reasons,
            None,
        )
        .expect("impact aggregate completeness must preserve valid child state")
    }
}

/// Optional evidence-packet claim shape for review/security (not a live MCP tool response).
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EvidencePacketClaim {
    pub claim: String,
    pub tool: String,
    pub path: String,
    pub start_line: usize,
    pub end_line: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result_handle: Option<String>,
}

/// Optional multi-claim evidence packet envelope for review/security.
///
/// Mirrors the skill-documented JSON shape; not a live MCP tool response.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct EvidencePacket {
    pub claims: Vec<EvidencePacketClaim>,
}

/// Whether `search_structural` returns grouped match rows or raw capture rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum StructuralResultMode {
    Matches,
    Captures,
}

/// Capture-selection policy used to derive a structural match anchor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum StructuralAnchorSelection {
    PrimaryCapture,
    MatchCapture,
    FirstUsefulNamedCapture,
    FirstCapture,
    CaptureRow,
}

/// Parameters for `search_structural`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchStructuralParams {
    pub query: String,
    pub language: Option<String>,
    pub repository_id: Option<String>,
    pub path_regex: Option<String>,
    pub limit: Option<usize>,
    /// Grouped or raw result shape.
    pub result_mode: Option<StructuralResultMode>,
    /// Anchor capture name for grouped results.
    pub primary_capture: Option<String>,
    /// Include structural follow-up suggestions.
    pub include_follow_up_structural: Option<bool>,
    /// Opaque v2 continuation. Structural results are replayed deterministically after lookup.
    pub continuation: Option<String>,
}

/// One named capture from a structural query match.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StructuralCaptureItem {
    pub name: String,
    pub line: usize,
    pub column: usize,
    pub end_line: usize,
    pub end_column: usize,
    pub excerpt: String,
}

/// One structural query match with anchor capture and follow-up suggestions.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct StructuralMatch {
    pub repository_id: String,
    pub path: String,
    pub line: usize,
    pub column: usize,
    pub end_line: usize,
    pub end_column: usize,
    pub excerpt: String,
    pub anchor_capture_name: Option<String>,
    pub anchor_selection: StructuralAnchorSelection,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub captures: Vec<StructuralCaptureItem>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub follow_up_structural: Vec<GeneratedStructuralFollowUp>,
}

/// Response from `search_structural`.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct SearchStructuralResponse {
    pub matches: Vec<StructuralMatch>,
    pub result_mode: StructuralResultMode,
    /// Canonical cardinality and paging truth for the selected structural row unit.
    pub completeness: super::ResultCompleteness,
    #[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>,
}

#[cfg(test)]
mod tests {
    use super::{
        EvidencePacket, EvidencePacketClaim, ImpactBundlePathRole, ImpactBundleResponse,
        ImpactBundleSummary, NavigationMode,
    };
    use crate::mcp::types::{
        RecoveryFields, ResultCompleteness, ResultIncompleteReason, ResultTruncationReason,
        ResultUnit, SuggestedNext,
    };

    fn empty_impact_summary(
        references_mode: NavigationMode,
        incoming_calls_mode: NavigationMode,
    ) -> ImpactBundleSummary {
        ImpactBundleResponse::compute_summary(
            &[],
            &[],
            &[],
            &[],
            references_mode,
            incoming_calls_mode,
            None,
            false,
        )
    }

    #[test]
    fn with_provisional_honesty_forces_provisional_on_wire() {
        use super::{
            NavigationEdgeTrust, NavigationMode, OUTGOING_CALLS_TRUST_NOTE, OutgoingCallsResponse,
        };
        use crate::mcp::types::{RecoveryFields, ResultCompleteness, ResultUnit};

        let response = OutgoingCallsResponse {
            completeness: ResultCompleteness::complete(ResultUnit::OutgoingCall, 0, 0)
                .expect("empty fixture is complete"),
            matches: Vec::new(),
            result_handle: None,
            mode: NavigationMode::HeuristicNoPrecise,
            availability: None,
            target_selection: None,
            metadata: None,
            note: Some("full diagnostic only".to_owned()),
            trust: NavigationEdgeTrust::Verified,
            trust_note: String::new(),
            recovery: RecoveryFields::default(),
        }
        .with_provisional_honesty();
        assert_eq!(response.trust, NavigationEdgeTrust::Provisional);
        assert_eq!(response.trust_note, OUTGOING_CALLS_TRUST_NOTE);

        let value = serde_json::to_value(&response).expect("serialize");
        assert_eq!(value["trust"], "provisional");
        assert_eq!(value["trust_note"], OUTGOING_CALLS_TRUST_NOTE);
        assert_eq!(value["note"], "full diagnostic only");
    }

    #[test]
    fn go_to_definition_ambiguous_location_serializes_when_true() {
        use super::GoToDefinitionResponse;
        use crate::mcp::types::{NavigationMode, RecoveryFields, ResultCompleteness, ResultUnit};
        use serde_json::json;

        let response = GoToDefinitionResponse {
            completeness: ResultCompleteness::try_new(
                ResultUnit::Definition,
                0,
                Some(0),
                false,
                false,
                vec![],
                vec![crate::mcp::types::ResultIncompleteReason::NavigationHeuristicCoverage],
                None,
            )
            .expect("heuristic fixture is internally consistent"),
            matches: Vec::new(),
            result_handle: None,
            handle_scope: None,
            handle_expires: None,
            mode: NavigationMode::HeuristicNoPrecise,
            target_selection: None,
            metadata: None,
            note: None,
            location_warning: Some("dense line".to_owned()),
            ambiguous_location: Some(true),
            recovery: RecoveryFields {
                correction_hint: Some("retry with symbol".to_owned()),
                ..RecoveryFields::default()
            },
        };
        let value = serde_json::to_value(&response).expect("serialize");
        assert_eq!(value["ambiguous_location"], json!(true));
        assert_eq!(value["location_warning"], "dense line");
        assert_eq!(value["correction_hint"], "retry with symbol");

        let quiet = GoToDefinitionResponse {
            completeness: ResultCompleteness::complete(ResultUnit::Definition, 0, 0)
                .expect("empty precise fixture is complete"),
            matches: Vec::new(),
            result_handle: None,
            handle_scope: None,
            handle_expires: None,
            mode: NavigationMode::Precise,
            target_selection: None,
            metadata: None,
            note: None,
            location_warning: None,
            ambiguous_location: None,
            recovery: RecoveryFields::default(),
        };
        let quiet_value = serde_json::to_value(&quiet).expect("serialize quiet");
        assert!(quiet_value.get("ambiguous_location").is_none());
        assert!(quiet_value.get("location_warning").is_none());
    }

    #[test]
    fn impact_bundle_response_single_suggested_next_channel() {
        let success = ImpactBundleResponse {
            symbol: "catalog_entries".to_owned(),
            path_class: "runtime".to_owned(),
            target_selection: None,
            summary: empty_impact_summary(NavigationMode::Precise, NavigationMode::Precise),
            sections: Vec::new(),
            proof_targets: Vec::new(),
            symbols: Vec::new(),
            symbols_completeness: ResultCompleteness::complete(ResultUnit::Symbol, 0, 0)
                .expect("empty symbols fixture is complete"),
            symbols_result_handle: Some("symbols:h1".to_owned()),
            references: Vec::new(),
            references_completeness: ResultCompleteness::complete(ResultUnit::Reference, 0, 0)
                .expect("empty references fixture is complete"),
            references_result_handle: Some("refs:h1".to_owned()),
            references_mode: NavigationMode::Precise,
            incoming_calls: Vec::new(),
            incoming_calls_completeness: ResultCompleteness::complete(
                ResultUnit::IncomingCall,
                0,
                0,
            )
            .expect("empty incoming fixture is complete"),
            incoming_calls_result_handle: None,
            incoming_calls_mode: NavigationMode::Precise,
            implementations: Vec::new(),
            implementations_completeness: None,
            implementations_result_handle: None,
            implementations_mode: None,
            implementations_included: false,
            completeness: ResultCompleteness::complete(ResultUnit::ImpactSection, 3, 3)
                .expect("all included fixture sections are complete"),
            recovery: RecoveryFields {
                suggested_next: vec![
                    SuggestedNext::tool("read_match").with_reason("proof clusters"),
                    SuggestedNext::tool("search_text")
                        .with_query("catalog_entries")
                        .with_path_regex("^tests/")
                        .with_reason("tests pass"),
                ],
                ..RecoveryFields::default()
            },
        };
        let value = serde_json::to_value(&success).expect("serialize success impact");
        let next = value["suggested_next"]
            .as_array()
            .expect("flattened recovery must expose suggested_next");
        assert_eq!(next.len(), 2);
        assert_eq!(
            next[0]["tool"], "read_match",
            "success next steps serialize from recovery.suggested_next"
        );
        assert_eq!(value["symbol"], "catalog_entries");
        assert_eq!(value["symbols_result_handle"], "symbols:h1");
        assert_eq!(value["references_result_handle"], "refs:h1");
        assert!(value.get("summary").is_some());
        assert_eq!(value["summary"]["references_count"], 0);
        assert!(value.get("error_code").is_none());
        assert!(value.get("recovery").is_none());

        let zero = ImpactBundleResponse {
            symbol: "missing_sym".to_owned(),
            path_class: "runtime".to_owned(),
            target_selection: None,
            summary: empty_impact_summary(
                NavigationMode::UnavailableNoPrecise,
                NavigationMode::UnavailableNoPrecise,
            ),
            sections: Vec::new(),
            proof_targets: Vec::new(),
            symbols: Vec::new(),
            symbols_completeness: ResultCompleteness::try_new(
                ResultUnit::Symbol,
                0,
                None,
                false,
                false,
                vec![],
                vec![ResultIncompleteReason::NavigationUnavailable],
                None,
            )
            .expect("unavailable symbols fixture is valid"),
            symbols_result_handle: None,
            references: Vec::new(),
            references_completeness: ResultCompleteness::try_new(
                ResultUnit::Reference,
                0,
                None,
                false,
                false,
                vec![],
                vec![ResultIncompleteReason::NavigationUnavailable],
                None,
            )
            .expect("unavailable references fixture is valid"),
            references_result_handle: None,
            references_mode: NavigationMode::UnavailableNoPrecise,
            incoming_calls: Vec::new(),
            incoming_calls_completeness: ResultCompleteness::try_new(
                ResultUnit::IncomingCall,
                0,
                None,
                false,
                false,
                vec![],
                vec![ResultIncompleteReason::NavigationUnavailable],
                None,
            )
            .expect("unavailable incoming fixture is valid"),
            incoming_calls_result_handle: None,
            incoming_calls_mode: NavigationMode::UnavailableNoPrecise,
            implementations: Vec::new(),
            implementations_completeness: None,
            implementations_result_handle: None,
            implementations_mode: None,
            implementations_included: false,
            completeness: ResultCompleteness::try_new(
                ResultUnit::ImpactSection,
                3,
                Some(3),
                false,
                false,
                vec![],
                vec![ResultIncompleteReason::ChildIncomplete],
                None,
            )
            .expect("incomplete aggregate fixture is valid"),
            recovery: RecoveryFields {
                error_code: Some("ZERO_HIT".to_owned()),
                message: Some("no symbol hits".to_owned()),
                suggested_next: vec![
                    SuggestedNext::tool("search_symbol")
                        .with_symbol("missing_sym")
                        .with_reason("retry"),
                ],
                ..RecoveryFields::default()
            },
        };
        let zero_value = serde_json::to_value(&zero).expect("serialize zero impact");
        assert_eq!(
            zero_value["suggested_next"]
                .as_array()
                .map(|a| a.len())
                .unwrap_or(0),
            1
        );
        assert_eq!(zero_value["error_code"], "ZERO_HIT");
        assert!(zero_value.get("recovery").is_none());
        let back: ImpactBundleResponse =
            serde_json::from_value(zero_value).expect("deserialize impact");
        assert_eq!(back.recovery.suggested_next.len(), 1);
        assert_eq!(back.recovery.error_code.as_deref(), Some("ZERO_HIT"));

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

    #[test]
    fn impact_bundle_aggregate_completeness_preserves_child_truncation() {
        let complete = ResultCompleteness::complete(ResultUnit::Symbol, 1, 1)
            .expect("complete symbol section");
        let capped = ResultCompleteness::try_new(
            ResultUnit::Reference,
            10,
            Some(11),
            false,
            true,
            vec![ResultTruncationReason::PageLimit],
            vec![],
            Some("continuation-test".to_owned()),
        )
        .expect("capped reference section");
        let aggregate = ImpactBundleResponse::aggregate_completeness(&[&complete, &capped]);
        assert_eq!(aggregate.unit, ResultUnit::ImpactSection);
        assert_eq!(aggregate.returned, 2);
        assert_eq!(aggregate.total, Some(2));
        assert!(!aggregate.complete);
        assert!(aggregate.truncated);
        assert!(
            aggregate
                .truncation_reasons
                .contains(&ResultTruncationReason::ChildLimit)
        );
        assert!(
            aggregate
                .incomplete_reasons
                .contains(&ResultIncompleteReason::ChildIncomplete)
        );
        assert!(aggregate.continuation.is_none());
    }

    #[test]
    fn impact_bundle_summary_counts_and_top_paths() {
        use super::{CallHierarchyMatch, ImplementationMatch};
        use crate::domain::model::{ReferenceMatch, ReferenceMatchKind, SymbolMatch};

        let symbols = vec![SymbolMatch {
            match_id: None,
            target_ref: None,
            stable_symbol_id: None,
            repository_id: "r1".to_owned(),
            symbol: "target".to_owned(),
            kind: "function".to_owned(),
            path: "src/lib.rs".to_owned(),
            line: 1,
            column: Some(1),
            excerpt: None,
            path_class: Some("runtime".to_owned()),
            container: None,
            signature: None,
        }];
        let references = vec![
            ReferenceMatch {
                match_id: None,
                target_ref: None,
                stable_symbol_id: None,
                repository_id: "r1".to_owned(),
                symbol: "target".to_owned(),
                path: "src/a.rs".to_owned(),
                line: 2,
                column: 1,
                match_kind: ReferenceMatchKind::Reference,
                precision: None,
                fallback_reason: None,
                container: None,
                signature: None,
                follow_up_structural: Vec::new(),
            },
            ReferenceMatch {
                match_id: None,
                target_ref: None,
                stable_symbol_id: None,
                repository_id: "r1".to_owned(),
                symbol: "target".to_owned(),
                path: "src/a.rs".to_owned(),
                line: 5,
                column: 1,
                match_kind: ReferenceMatchKind::Reference,
                precision: None,
                fallback_reason: None,
                container: None,
                signature: None,
                follow_up_structural: Vec::new(),
            },
            ReferenceMatch {
                match_id: None,
                target_ref: None,
                stable_symbol_id: None,
                repository_id: "r1".to_owned(),
                symbol: "target".to_owned(),
                path: "src/b.rs".to_owned(),
                line: 3,
                column: 1,
                match_kind: ReferenceMatchKind::Reference,
                precision: None,
                fallback_reason: None,
                container: None,
                signature: None,
                follow_up_structural: Vec::new(),
            },
        ];
        let incoming = vec![CallHierarchyMatch {
            match_id: None,
            target_ref: None,
            source_stable_symbol_id: None,
            target_stable_symbol_id: None,
            source_symbol: "caller".to_owned(),
            target_symbol: "target".to_owned(),
            repository_id: "r1".to_owned(),
            path: "src/a.rs".to_owned(),
            line: 10,
            column: 1,
            relation: "calls".to_owned(),
            source_container: None,
            target_container: None,
            source_signature: None,
            target_signature: None,
            precision: None,
            call_path: None,
            call_line: None,
            call_column: None,
            call_end_line: None,
            call_end_column: None,
            follow_up_structural: Vec::new(),
        }];
        let implementations: Vec<ImplementationMatch> = Vec::new();

        let summary = ImpactBundleResponse::compute_summary(
            &symbols,
            &references,
            &incoming,
            &implementations,
            NavigationMode::Precise,
            NavigationMode::HeuristicNoPrecise,
            None,
            false,
        );
        assert_eq!(summary.symbols_count, 1);
        assert_eq!(summary.references_count, 3);
        assert_eq!(summary.incoming_calls_count, 1);
        assert_eq!(summary.implementations_count, 0);
        assert!(!summary.implementations_included);
        assert_eq!(summary.references_mode, NavigationMode::Precise);
        assert_eq!(
            summary.incoming_calls_mode,
            NavigationMode::HeuristicNoPrecise
        );
        assert!(
            summary.top_paths.iter().any(|p| {
                p.path == "src/a.rs" && p.role == ImpactBundlePathRole::Reference && p.count == 2
            }),
            "top_paths should tally reference paths: {:?}",
            summary.top_paths
        );
        assert!(
            summary.top_paths.first().is_some_and(|p| p.count >= 2),
            "highest tally should lead top_paths: {:?}",
            summary.top_paths
        );
        assert!(
            summary
                .top_paths
                .iter()
                .any(|p| p.role == ImpactBundlePathRole::Symbol && p.path == "src/lib.rs"),
            "selected symbol path should stay visible in top_paths: {:?}",
            summary.top_paths
        );
        assert!(!summary.top_paths_truncated);

        let value = serde_json::to_value(&summary).expect("serialize summary");
        assert_eq!(value["references_count"], 3);
        assert_eq!(value["references_mode"], "precise");
        assert_eq!(value["top_paths_truncated"], false);

        let many_refs: Vec<ReferenceMatch> = (0..10)
            .map(|i| ReferenceMatch {
                match_id: None,
                target_ref: None,
                stable_symbol_id: None,
                repository_id: "r1".to_owned(),
                symbol: "target".to_owned(),
                path: format!("src/p{i}.rs"),
                line: 1,
                column: 1,
                match_kind: ReferenceMatchKind::Reference,
                precision: None,
                fallback_reason: None,
                container: None,
                signature: None,
                follow_up_structural: Vec::new(),
            })
            .collect();
        let capped = ImpactBundleResponse::compute_summary(
            &symbols,
            &many_refs,
            &[],
            &[],
            NavigationMode::Precise,
            NavigationMode::Precise,
            None,
            false,
        );
        assert_eq!(capped.top_paths.len(), 8);
        assert!(capped.top_paths_truncated);
        assert!(
            capped
                .top_paths
                .iter()
                .any(|p| p.role == ImpactBundlePathRole::Symbol),
            "symbol anchor should survive cap under ties: {:?}",
            capped.top_paths
        );
    }

    #[test]
    fn evidence_packet_claim_serde_round_trip() {
        let claim = EvidencePacketClaim {
            claim: "catalog_entries registers callable operations".to_owned(),
            tool: "search_symbol".to_owned(),
            path: "src/catalog/mod.rs".to_owned(),
            start_line: 40,
            end_line: 72,
            match_id: Some("symbols:m1".to_owned()),
            result_handle: Some("result-000001".to_owned()),
        };

        let json = serde_json::to_string(&claim).expect("claim should serialize");
        let back: EvidencePacketClaim =
            serde_json::from_str(&json).expect("claim should deserialize");
        assert_eq!(back.claim, claim.claim);
        assert_eq!(back.tool, "search_symbol");
        assert_eq!(back.path, "src/catalog/mod.rs");
        assert_eq!(back.start_line, 40);
        assert_eq!(back.end_line, 72);
        assert_eq!(back.match_id.as_deref(), Some("symbols:m1"));
        assert_eq!(back.result_handle.as_deref(), Some("result-000001"));
    }

    #[test]
    fn evidence_packet_claim_omits_optional_handle_fields_when_none() {
        let claim = EvidencePacketClaim {
            claim: "path/line witness only".to_owned(),
            tool: "read_file".to_owned(),
            path: "src/lib.rs".to_owned(),
            start_line: 1,
            end_line: 3,
            match_id: None,
            result_handle: None,
        };
        let value = serde_json::to_value(&claim).expect("serialize");
        assert!(value.get("match_id").is_none());
        assert!(value.get("result_handle").is_none());
        assert_eq!(value["path"], "src/lib.rs");
        assert_eq!(value["tool"], "read_file");
    }

    #[test]
    fn evidence_packet_skill_shaped_multi_claim_json_deserializes() {
        let skill_json = r#"{
          "claims": [
            {
              "claim": "catalog_entries registers callable operations",
              "tool": "search_symbol",
              "path": "src/catalog/mod.rs",
              "start_line": 40,
              "end_line": 72,
              "match_id": "symbols:m1",
              "result_handle": "result-aaa"
            },
            {
              "claim": "caller reaches catalog_entries from the HTTP surface",
              "tool": "incoming_calls",
              "path": "src/http/routes.rs",
              "start_line": 88,
              "end_line": 110,
              "match_id": "nav:m2",
              "result_handle": "result-bbb"
            }
          ]
        }"#;

        let packet: EvidencePacket =
            serde_json::from_str(skill_json).expect("skill-shaped packet should deserialize");
        assert_eq!(packet.claims.len(), 2);
        assert_eq!(packet.claims[0].tool, "search_symbol");
        assert_eq!(packet.claims[0].path, "src/catalog/mod.rs");
        assert_eq!(packet.claims[0].start_line, 40);
        assert_eq!(packet.claims[1].tool, "incoming_calls");
        assert_eq!(packet.claims[1].match_id.as_deref(), Some("nav:m2"));

        let round = serde_json::to_value(&packet).expect("packet should re-serialize");
        assert_eq!(round["claims"].as_array().map(|a| a.len()), Some(2));
    }
}