ryo-app 0.1.0

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

use crate::intent::Goal;
use ryo_analysis::SymbolKind;
use ryo_suggest::EnhancedSuggestion;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

// Re-export from ryo-query-language for unified types
pub use ryo_query_language::{QueryResponse, ViewMode};

// ============================================================================
// Execution Status (HTTP-inspired status codes for CLI results)
// ============================================================================

/// Status code for execution results, inspired by HTTP status codes.
///
/// Provides a systematic categorization of execution outcomes:
/// - 2xx: Success (operation completed as intended)
/// - 4xx: Client Error (invalid input, not found, conflicts)
///
/// # Example
///
/// ```ignore
/// match status.code {
///     StatusCode::Ok => println!("Changes applied successfully"),
///     StatusCode::NoChange => println!("No changes needed"),
///     StatusCode::Conflict => println!("Conflicts require resolution"),
///     _ => {}
/// }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatusCode {
    // ---- Success (2xx) ----
    /// 200: Operation succeeded with changes applied.
    Ok,
    /// 204: Operation succeeded but no changes were made (target already in desired state).
    NoChange,
    /// 206: Operation succeeded with automatic conflict resolution.
    Resolved,

    // ---- Client Error (4xx) ----
    /// 400: Invalid goal or planning failed.
    Invalid,
    /// 404: Target symbol or file not found.
    NotFound,
    /// 409: Conflicts detected that require manual resolution.
    Conflict,
    /// 422: Syntax validation failed after mutation.
    SyntaxError,
}

impl StatusCode {
    /// Returns true if this is a success status (2xx equivalent).
    pub fn is_success(&self) -> bool {
        matches!(self, Self::Ok | Self::NoChange | Self::Resolved)
    }

    /// Returns true if this is an error status (4xx equivalent).
    pub fn is_error(&self) -> bool {
        !self.is_success()
    }

    /// Returns the HTTP-like numeric code for reference.
    pub fn as_http_code(&self) -> u16 {
        match self {
            Self::Ok => 200,
            Self::NoChange => 204,
            Self::Resolved => 206,
            Self::Invalid => 400,
            Self::NotFound => 404,
            Self::Conflict => 409,
            Self::SyntaxError => 422,
        }
    }

    /// Returns the standard label for this status code.
    pub fn label(&self) -> &'static str {
        match self {
            Self::Ok => "OK",
            Self::NoChange => "NO_CHANGE",
            Self::Resolved => "RESOLVED",
            Self::Invalid => "INVALID",
            Self::NotFound => "NOT_FOUND",
            Self::Conflict => "CONFLICT",
            Self::SyntaxError => "SYNTAX_ERROR",
        }
    }
}

impl std::fmt::Display for StatusCode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.label())
    }
}

/// Detailed information about the execution status.
///
/// Provides rich context for both success and error cases,
/// enabling informative CLI output and debugging.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct StatusDetail {
    /// Short reason (one line, suitable for status line).
    /// Example: "3 changes in 2 files"
    /// Example: "Symbol 'foo' not found in registry"
    pub reason: String,

    /// Detailed explanation (can be multi-line).
    /// Example: "The rename operation completed successfully.\nAll references were updated."
    /// Example: "The pattern 'foo*' matched 0 symbols.\nTry 'ryo discover foo*' to see available symbols."
    pub explanation: Option<String>,

    /// Actionable suggestions for the user.
    /// Example: ["Try 'ryo discover <pattern>' to find symbols", "Check spelling of symbol name"]
    pub suggestions: Vec<String>,

    /// Related context (e.g., conflicting symbols, matched patterns).
    pub context: Vec<String>,
}

impl StatusDetail {
    /// Create a new StatusDetail with just a reason.
    pub fn new(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            ..Default::default()
        }
    }

    /// Add an explanation.
    pub fn with_explanation(mut self, explanation: impl Into<String>) -> Self {
        self.explanation = Some(explanation.into());
        self
    }

    /// Add a suggestion.
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestions.push(suggestion.into());
        self
    }

    /// Add multiple suggestions.
    pub fn with_suggestions(
        mut self,
        suggestions: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.suggestions
            .extend(suggestions.into_iter().map(Into::into));
        self
    }

    /// Add context information.
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context.push(context.into());
        self
    }
}

/// Complete execution status combining code and detail.
///
/// This is the primary type for representing execution outcomes.
/// It provides both machine-readable status codes and human-readable details.
///
/// # Example
///
/// ```ignore
/// let status = ExecutionStatus::ok("3 changes in 2 files")
///     .with_explanation("Renamed 'foo' to 'bar' across the codebase.");
///
/// if status.is_success() {
///     println!("{}: {}", status.code, status.detail.reason);
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionStatus {
    /// The status code.
    pub code: StatusCode,
    /// Detailed information.
    pub detail: StatusDetail,
}

impl ExecutionStatus {
    /// Create a new ExecutionStatus.
    pub fn new(code: StatusCode, detail: StatusDetail) -> Self {
        Self { code, detail }
    }

    // ---- Success constructors ----

    /// Create an OK status (200).
    pub fn ok(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::Ok, StatusDetail::new(reason))
    }

    /// Create a NO_CHANGE status (204).
    pub fn no_change(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::NoChange, StatusDetail::new(reason))
    }

    /// Create a RESOLVED status (206).
    pub fn resolved(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::Resolved, StatusDetail::new(reason))
    }

    // ---- Error constructors ----

    /// Create an INVALID status (400).
    pub fn invalid(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::Invalid, StatusDetail::new(reason))
    }

    /// Create a NOT_FOUND status (404).
    pub fn not_found(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::NotFound, StatusDetail::new(reason))
    }

    /// Create a CONFLICT status (409).
    pub fn conflict(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::Conflict, StatusDetail::new(reason))
    }

    /// Create a SYNTAX_ERROR status (422).
    pub fn syntax_error(reason: impl Into<String>) -> Self {
        Self::new(StatusCode::SyntaxError, StatusDetail::new(reason))
    }

    // ---- Builder methods ----

    /// Add an explanation.
    pub fn with_explanation(mut self, explanation: impl Into<String>) -> Self {
        self.detail.explanation = Some(explanation.into());
        self
    }

    /// Add a suggestion.
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.detail.suggestions.push(suggestion.into());
        self
    }

    /// Add multiple suggestions.
    pub fn with_suggestions(
        mut self,
        suggestions: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.detail
            .suggestions
            .extend(suggestions.into_iter().map(Into::into));
        self
    }

    /// Add context.
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.detail.context.push(context.into());
        self
    }

    // ---- Query methods ----

    /// Returns true if this is a success status.
    pub fn is_success(&self) -> bool {
        self.code.is_success()
    }

    /// Returns true if this is an error status.
    pub fn is_error(&self) -> bool {
        self.code.is_error()
    }
}

impl std::fmt::Display for ExecutionStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.code, self.detail.reason)
    }
}

// ============================================================================
// Discover
// ============================================================================

/// Sort order for discovery results.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub enum SortOrder {
    /// Sort by name alphabetically.
    Alpha,
    /// Sort by reference count (most referenced first).
    #[default]
    Refs,
    /// Sort by impl count.
    Impls,
}

/// Request for symbol discovery.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverRequest {
    /// Pattern to search for (glob-like: `*`, `?`, `[a-z]`).
    pub pattern: String,
    /// Filter by item kind (function, struct, enum, etc.).
    pub kind: Option<SymbolKind>,
    /// Sort order for results.
    pub sort: Option<SortOrder>,
    /// Maximum number of results to return.
    pub limit: Option<usize>,
    /// Output detail level (snippet, precise, count, def, full).
    #[serde(default)]
    pub view: Option<ViewMode>,
    /// Filter for async functions only (true = async only, false = non-async only).
    #[serde(default)]
    pub is_async: Option<bool>,
    /// Filter for unsafe functions/traits (true = unsafe only, false = safe only).
    #[serde(default)]
    pub is_unsafe: Option<bool>,
    /// Filter by file path pattern (glob, e.g. "src/handlers/**").
    #[serde(default)]
    pub scope_path: Option<String>,
    /// Case-insensitive pattern matching (A-Z == a-z).
    #[serde(default)]
    pub ignore_case: bool,
    /// Ignore word separators and casing style (snake_case == camelCase == PascalCase).
    #[serde(default)]
    pub ignore_word_separate: bool,
    /// Filter by attribute pattern (e.g., "deprecated", "allow(dead_code)").
    #[serde(default)]
    pub attr: Option<String>,
    /// Interpret pattern as SymbolId instead of name pattern.
    ///
    /// When true, the `pattern` field is parsed as a SymbolId (e.g., "165v1")
    /// and a direct registry lookup is performed instead of pattern matching.
    #[serde(default)]
    pub is_id: bool,
}

impl Default for DiscoverRequest {
    fn default() -> Self {
        Self {
            pattern: "*".to_string(),
            kind: None,
            sort: None,
            limit: None,
            view: None,
            is_async: None,
            is_unsafe: None,
            scope_path: None,
            ignore_case: false,
            ignore_word_separate: false,
            attr: None,
            is_id: false,
        }
    }
}

/// A discovered symbol (tarpc-compatible, Bincode-safe).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoveredSymbol {
    /// SymbolId as string (e.g., "165v1")
    ///
    /// **Warning**: This ID is session-volatile. Use `uuid` for persistent references.
    pub id: String,
    /// Persistent UUID for cross-session symbol tracking.
    ///
    /// This UUID survives server restarts and symbol renames.
    /// Returns `None` if the symbol hasn't been assigned a persistent ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Full symbol path (e.g., "ryo_analysis::registry::DetectRegistry")
    pub path: String,
    /// Symbol name
    pub name: String,
    /// Item kind (e.g., "Function", "Struct")
    pub kind: String,
    /// View mode used
    pub view_mode: String,
    /// Definition (for Def/Full modes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub definition: Option<String>,
    /// Documentation (for Def/Full modes)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doc: Option<String>,
    /// Function body (for Full mode)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Code snippet (for Snippet mode)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub snippet: Option<String>,
}

/// Response from symbol discovery (tarpc-compatible, Bincode-safe).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiscoverResponse {
    /// Query status
    pub status: String,
    /// Discovered symbols
    pub symbols: Vec<DiscoveredSymbol>,
    /// Total matches
    pub total: usize,
    /// Elapsed time in ms
    pub elapsed_ms: u32,
    /// Alternative search hint when 0 results with kind filter
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hint: Option<String>,
}

// ============================================================================
// Overview
// ============================================================================

/// Request for codebase overview.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OverviewRequest {}

/// A crate with its module tree.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrateOverview {
    /// Crate name.
    pub name: String,
    /// Module paths within this crate.
    pub modules: Vec<String>,
}

/// A symbol with a count metric (ref_count or impl_count).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OverviewSymbol {
    /// Full symbol path.
    pub path: String,
    /// Metric count (references or implementations).
    pub count: usize,
}

/// Symbol kind statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OverviewStats {
    /// Number of crates.
    pub crate_count: usize,
    /// Counts by symbol kind (e.g., [("Functions", 120), ("Structs", 45)]).
    pub by_kind: Vec<(String, usize)>,
}

/// Response from codebase overview.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OverviewResponse {
    /// Crate/module structure.
    pub crates: Vec<CrateOverview>,
    /// Top structs by reference count.
    pub top_structs: Vec<OverviewSymbol>,
    /// Top traits by implementation count.
    pub top_traits: Vec<OverviewSymbol>,
    /// Statistics.
    pub stats: OverviewStats,
    /// Elapsed time in ms.
    pub elapsed_ms: u32,
}

// ============================================================================
// Literal Search
// ============================================================================

/// Request for literal search.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiteralSearchRequest {
    /// Pattern to search for (glob-style: `*error*`, `"hello"`, etc.).
    pub pattern: String,
    /// Filter by literal kind (e.g., "string", "int", "bool").
    #[serde(default)]
    pub kind: Option<String>,
    /// Maximum number of results.
    #[serde(default = "default_literal_limit")]
    pub limit: usize,
}

fn default_literal_limit() -> usize {
    100
}

/// A single literal match result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiteralMatchResult {
    /// The literal value as it appears in source.
    pub value: String,
    /// The literal kind (e.g., "String", "Int", "Bool").
    pub kind: String,
    /// SymbolId of the containing symbol.
    pub symbol_id: String,
    /// File path containing this literal.
    pub file_path: String,
    /// Search relevance score.
    pub score: f32,
}

/// Response from literal search.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LiteralSearchResponse {
    /// Matched literals.
    pub matches: Vec<LiteralMatchResult>,
    /// Total matches found.
    pub total: usize,
    /// Elapsed time in ms.
    pub elapsed_ms: u32,
}

// ============================================================================
// RyoQL Query
// ============================================================================

/// Request for RyoQL query execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RyoqlRequest {
    /// The RyoQL query content (YAML or JSON string).
    pub query: String,
    /// Default view mode when the query itself does not specify one.
    #[serde(default)]
    pub default_view: Option<ViewMode>,
}

// Note: Response type is `QueryResponse` re-exported from ryo-query-language (line 12).

// ============================================================================
// Suggest
// ============================================================================

/// Request for code improvement suggestions.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuggestRequest {
    /// Optional pattern to filter suggestions.
    pub pattern_filter: Option<String>,
    /// Only show high-impact suggestions.
    pub high_impact: bool,
    /// Quick mode (fewer but faster suggestions).
    pub quick: bool,
    /// Run scan before returning suggestions.
    /// When true, executes suggest_scan() to detect new suggestions.
    pub scan: bool,
    /// Run pre-check on each suggestion during scan.
    /// When true, uses suggest_scan_with_precheck() which validates
    /// each suggestion before storing, ensuring Apply will succeed.
    #[serde(default)]
    pub precheck: bool,
    /// Rule IDs to exclude (e.g., ["RL021", "RL020"]).
    #[serde(default)]
    pub exclude_rules: Vec<String>,
    /// Return enhanced suggestions with design choices and verification status.
    #[serde(default)]
    pub enhanced: bool,
    /// Scope filter: only include suggestions from these scopes (lib, bin, test).
    /// Empty means include all scopes.
    #[serde(default)]
    pub scope_filter: Vec<String>,
}

/// A code improvement suggestion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Suggestion {
    /// Unique identifier for the suggestion.
    pub id: String,
    /// Rule ID for @spec:allow directive (e.g., "RL001").
    pub rule_id: Option<String>,
    /// Human-readable title.
    pub title: String,
    /// Detailed description.
    pub description: String,
    /// Category (refactoring, performance, readability, etc.).
    pub category: String,
    /// Impact level (high, medium, low).
    pub impact: String,
    /// File where the suggestion applies.
    pub file: PathBuf,
    /// Symbol path for precise location (e.g., "crate::module::MyStruct").
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol_path: Option<String>,
    /// The Intent that would fix this issue.
    pub fix_intent: Option<String>,
}

/// Summary of suggestions.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuggestionSummary {
    /// Total number of suggestions.
    pub total: usize,
    /// Number of high-impact suggestions.
    pub high_impact: usize,
    /// Categories with counts.
    pub by_category: Vec<(String, usize)>,
}

/// Response from suggestion engine.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SuggestResponse {
    /// List of suggestions.
    pub suggestions: Vec<Suggestion>,
    /// Summary statistics.
    pub summary: SuggestionSummary,
    /// Enhanced suggestions (when request.enhanced = true).
    /// Contains design choices, verification status, and apply commands.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub enhanced: Vec<EnhancedSuggestion>,
}

// ============================================================================
// Suggest Apply
// ============================================================================

/// Request to apply suggestions by ID.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestApplyRequest {
    /// Suggestion IDs to apply (e.g., ["S001g0", "S002g0"]).
    pub ids: Vec<String>,
    /// Skip actual execution (preview only).
    pub dry_run: bool,
    /// Verify syntax after mutations.
    pub check_syntax: bool,
    /// Specific design choice to apply (e.g., "A", "B").
    /// If None, uses the recommended choice.
    #[serde(default)]
    pub choice_id: Option<String>,
    /// Run full verification (cargo check) before applying.
    #[serde(default)]
    pub verify: bool,
}

impl SuggestApplyRequest {
    /// Create a new apply request with suggestion IDs.
    pub fn new(ids: Vec<String>) -> Self {
        Self {
            ids,
            dry_run: false,
            check_syntax: false,
            choice_id: None,
            verify: false,
        }
    }

    /// Enable dry-run mode.
    pub fn dry_run(mut self) -> Self {
        self.dry_run = true;
        self
    }

    /// Enable syntax checking.
    pub fn check_syntax(mut self) -> Self {
        self.check_syntax = true;
        self
    }

    /// Set a specific design choice to apply.
    pub fn choice(mut self, choice_id: impl Into<String>) -> Self {
        self.choice_id = Some(choice_id.into());
        self
    }

    /// Enable verification before applying.
    pub fn verify(mut self) -> Self {
        self.verify = true;
        self
    }
}

/// Response from applying suggestions.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SuggestApplyResponse {
    /// Whether execution completed successfully.
    pub success: bool,
    /// Number of files modified.
    pub files_modified: usize,
    /// Total number of changes made.
    pub total_changes: usize,
    /// Paths of modified files.
    pub modified_files: Vec<PathBuf>,
    /// Suggestions that were successfully applied.
    pub applied_ids: Vec<String>,
    /// Suggestions that failed to apply (with error messages).
    pub failed: Vec<(String, String)>,
    /// Syntax errors found (if check_syntax enabled).
    pub syntax_errors: Vec<String>,
    /// Error message (if completely failed).
    pub error: Option<String>,
}

// ============================================================================
// Suggest Choices
// ============================================================================

/// Request to get design choices for a suggestion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestChoicesRequest {
    /// Suggestion ID (e.g., "S001g0").
    pub id: String,
}

impl SuggestChoicesRequest {
    /// Create a new choices request.
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into() }
    }
}

/// A design choice option.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesignChoiceInfo {
    /// Choice ID (e.g., "A", "B").
    pub id: String,
    /// Short label for display.
    pub label: String,
    /// Human-readable title.
    pub title: String,
    /// Detailed description.
    pub description: String,
    /// Extensibility rating (1-3 stars).
    pub extensibility: u8,
    /// Performance rating (1-3 stars).
    pub performance: u8,
    /// Complexity rating (1-3 stars).
    pub complexity: u8,
    /// Whether this is a breaking change.
    pub breaking_change: bool,
    /// Number of files affected.
    pub affected_files: usize,
    /// Whether this is the recommended choice.
    pub recommended: bool,
}

/// Response with design choices for a suggestion.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SuggestChoicesResponse {
    /// Suggestion ID.
    pub suggestion_id: String,
    /// Pattern name that generated these choices.
    pub pattern_name: String,
    /// Available choices.
    pub choices: Vec<DesignChoiceInfo>,
    /// Whether choices are available.
    pub has_choices: bool,
    /// Error message if failed.
    pub error: Option<String>,
}

// ============================================================================
// Suggest Verify
// ============================================================================

/// Verification level.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub enum VerifyLevel {
    /// Fast in-memory check (GraphChecker, ~100ms).
    #[default]
    Light,
    /// Full cargo check in temp workspace.
    Full,
}

/// Request to verify a suggestion before applying.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestVerifyRequest {
    /// Suggestion ID (e.g., "S001g0").
    pub id: String,
    /// Specific choice to verify (if multiple choices exist).
    #[serde(default)]
    pub choice_id: Option<String>,
    /// Verification level.
    #[serde(default)]
    pub level: VerifyLevel,
}

impl SuggestVerifyRequest {
    /// Create a new verify request.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            choice_id: None,
            level: VerifyLevel::default(),
        }
    }

    /// Set a specific choice to verify.
    pub fn choice(mut self, choice_id: impl Into<String>) -> Self {
        self.choice_id = Some(choice_id.into());
        self
    }

    /// Set verification level.
    pub fn level(mut self, level: VerifyLevel) -> Self {
        self.level = level;
        self
    }
}

/// Response from verification.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SuggestVerifyResponse {
    /// Suggestion ID.
    pub suggestion_id: String,
    /// Choice ID (if specified).
    pub choice_id: Option<String>,
    /// Whether verification passed.
    pub passed: bool,
    /// Verification level used.
    pub level: String,
    /// Duration in milliseconds.
    pub duration_ms: u64,
    /// Diagnostics (errors/warnings).
    pub diagnostics: Vec<String>,
    /// Error message if failed.
    pub error: Option<String>,
}

// ============================================================================
// Suggest Compare
// ============================================================================

/// Request to compare design choices.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestCompareRequest {
    /// Suggestion ID (e.g., "S001g0").
    pub id: String,
}

impl SuggestCompareRequest {
    /// Create a new compare request.
    pub fn new(id: impl Into<String>) -> Self {
        Self { id: id.into() }
    }
}

/// Comparison result for choices.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SuggestCompareResponse {
    /// Suggestion ID.
    pub suggestion_id: String,
    /// Formatted comparison table.
    pub comparison_table: String,
    /// Choices sorted by score (best first).
    pub ranked_choices: Vec<DesignChoiceInfo>,
    /// Recommendation reason.
    pub recommendation_reason: Option<String>,
    /// Error message if failed.
    pub error: Option<String>,
}

// ============================================================================
// Suggest Generate
// ============================================================================

/// Request to generate code from parameterized patterns.
///
/// Use `list: true` to discover available patterns.
/// Use `pattern` + `params` to generate code.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuggestGenerateRequest {
    /// Pattern name to use (e.g., "api-pattern", "domain-struct").
    pub pattern: Option<String>,
    /// Parameters for the pattern as key-value pairs.
    /// E.g., `{"name": "Order", "fields": "id:u64,status:String"}`.
    #[serde(default)]
    pub params: std::collections::HashMap<String, String>,
    /// List available parameterized patterns instead of generating.
    #[serde(default)]
    pub list: bool,
    /// Apply generated changes immediately (skip preview).
    #[serde(default)]
    pub apply: bool,
    /// Skip actual execution (preview only).
    #[serde(default)]
    pub dry_run: bool,
}

impl SuggestGenerateRequest {
    /// Create a request to list available patterns.
    pub fn list_patterns() -> Self {
        Self {
            list: true,
            ..Default::default()
        }
    }

    /// Create a request to generate from a pattern.
    pub fn generate(pattern: impl Into<String>) -> Self {
        Self {
            pattern: Some(pattern.into()),
            ..Default::default()
        }
    }

    /// Add a parameter.
    pub fn with_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.params.insert(key.into(), value.into());
        self
    }

    /// Set apply mode.
    pub fn apply(mut self) -> Self {
        self.apply = true;
        self
    }

    /// Set dry-run mode.
    pub fn dry_run(mut self) -> Self {
        self.dry_run = true;
        self
    }
}

/// Information about a parameterized pattern.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternInfo {
    /// Pattern name (e.g., "api-pattern").
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Category (e.g., "Pattern").
    pub category: String,
    /// Parameters this pattern accepts.
    pub params: Vec<ParamInfo>,
}

/// Information about a pattern parameter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParamInfo {
    /// Parameter name (e.g., "name").
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Whether this parameter is required.
    pub required: bool,
}

/// Response from code generation.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuggestGenerateResponse {
    /// Available patterns (when request.list = true).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub patterns: Vec<PatternInfo>,
    /// Generated suggestions (when pattern specified).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suggestions: Vec<Suggestion>,
    /// Preview of changes (code diff).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preview: Option<String>,
    /// Applied changes (when apply = true).
    #[serde(default)]
    pub applied: bool,
    /// Number of files modified (when apply = true).
    #[serde(default)]
    pub files_modified: usize,
    /// Error message if failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

// ============================================================================
// Run (Execute)
// ============================================================================

/// Request for code transformation execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunRequest {
    /// The goal to execute.
    pub goal: Goal,
    /// Skip actual execution (plan and validate only).
    pub dry_run: bool,
    /// Verify syntax after mutations.
    pub check_syntax: bool,
}

impl RunRequest {
    /// Create a new run request with a goal.
    pub fn new(goal: Goal) -> Self {
        Self {
            goal,
            dry_run: false,
            check_syntax: false,
        }
    }

    /// Enable dry-run mode.
    pub fn dry_run(mut self) -> Self {
        self.dry_run = true;
        self
    }

    /// Enable syntax checking.
    pub fn check_syntax(mut self) -> Self {
        self.check_syntax = true;
        self
    }
}

/// Response from code transformation execution.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RunResponse {
    /// Whether execution completed successfully.
    pub success: bool,
    /// Number of files modified.
    pub files_modified: usize,
    /// Total number of changes made.
    pub total_changes: usize,
    /// Paths of modified files.
    pub modified_files: Vec<PathBuf>,
    /// Conflict descriptions (if any).
    pub conflicts: Vec<String>,
    /// Syntax errors found (if check_syntax enabled).
    pub syntax_errors: Vec<String>,
    /// Error message (if failed).
    pub error: Option<String>,
}

// ============================================================================
// Graph Cascade
// ============================================================================

/// Request for cascade analysis.
///
/// Use `ryo discover` to find the SymbolId or UUID.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CascadeRequest {
    /// SymbolId to analyze (e.g., "741v1").
    /// Get this from `ryo discover` output.
    /// **Warning**: Session-volatile. Prefer `uuid` for persistent references.
    pub id: String,
    /// Persistent UUID for cross-session symbol tracking.
    /// Takes precedence over `id` if provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Maximum depth to traverse (default: 3).
    pub depth: Option<usize>,
}

impl CascadeRequest {
    /// Create a new cascade request with SymbolId.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            uuid: None,
            depth: None,
        }
    }

    /// Create a new cascade request with UUID.
    pub fn with_uuid(uuid: impl Into<String>) -> Self {
        Self {
            id: String::new(),
            uuid: Some(uuid.into()),
            depth: None,
        }
    }

    /// Set the traversal depth.
    pub fn depth(mut self, depth: usize) -> Self {
        self.depth = Some(depth);
        self
    }
}

/// Response from cascade analysis.
///
/// For detailed type impact analysis, use `graph type` instead.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CascadeResponse {
    /// Display name of the target symbol.
    pub display_name: String,
    /// Functions/methods that call the target.
    pub callers: Vec<String>,
    /// Types/functions that use the target as a type reference.
    pub users: Vec<String>,
    /// Functions containing match expressions on this enum.
    /// Only populated when the target is an Enum.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub match_functions: Vec<String>,
    /// Types that contain this type as a field.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub containing_types: Vec<String>,
}

// ============================================================================
// Graph Summary
// ============================================================================

/// Request for code graph summary.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GraphSummaryRequest {
    /// Detailed output with file paths and type breakdown.
    #[serde(default)]
    pub detailed: bool,
    /// Compact output for minimal display.
    #[serde(default)]
    pub compact: bool,
    /// Maximum items per section.
    #[serde(default)]
    pub max_items: Option<usize>,
}

impl GraphSummaryRequest {
    /// Create a new default request.
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable detailed output.
    pub fn detailed(mut self) -> Self {
        self.detailed = true;
        self
    }

    /// Enable compact output.
    pub fn compact(mut self) -> Self {
        self.compact = true;
        self
    }

    /// Set max items per section.
    pub fn max_items(mut self, n: usize) -> Self {
        self.max_items = Some(n);
        self
    }
}

/// Response from code graph summary.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphSummaryResponse {
    /// Formatted summary content (ready to print).
    pub content: String,
    /// Build time in milliseconds.
    pub build_time_ms: u64,
    /// Number of nodes in the graph.
    pub node_count: usize,
    /// Number of edges in the graph.
    pub edge_count: usize,
    /// Number of files analyzed.
    pub file_count: usize,
}

// ============================================================================
// Ping
// ============================================================================

/// Response from ping (health check with version).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PingResponse {
    /// Server version (from Cargo.toml).
    pub version: String,
}

// ============================================================================
// Status
// ============================================================================

/// Response from status query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StatusResponse {
    /// Project root path.
    pub project: PathBuf,
    /// Number of symbols in registry.
    pub symbols: usize,
    /// Number of files loaded.
    pub files: usize,
}

// ============================================================================
// Error Types (for RPC transport)
// ============================================================================

/// Structured error type for API responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ApiErrorKind {
    /// Symbol or resource not found.
    NotFound { name: String },
    /// Parse or syntax error.
    ParseError { message: String },
    /// Invalid request parameters.
    InvalidRequest { message: String },
    /// Internal server error.
    Internal { message: String },
}

impl std::fmt::Display for ApiErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound { name } => write!(f, "not found: {}", name),
            Self::ParseError { message } => write!(f, "parse error: {}", message),
            Self::InvalidRequest { message } => write!(f, "invalid request: {}", message),
            Self::Internal { message } => write!(f, "internal error: {}", message),
        }
    }
}

impl std::error::Error for ApiErrorKind {}

// ============================================================================
// Spec
// ============================================================================

/// Request for spec hierarchy query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecRequest {
    /// Query kind.
    pub query: SpecQueryKind,
}

/// Spec query kinds.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SpecQueryKind {
    /// Show full hierarchy (groups, relations, stats).
    Show,
    /// List all group names.
    Groups,
    /// List specs in a specific group.
    TypesInGroup { group: String },
    /// Get dependencies of a spec.
    Dependencies { type_name: String },
    /// Get dependents (reverse dependencies) of a spec.
    Dependents { type_name: String },
    /// Get statistics.
    Stats,
    /// Lint specs for consistency.
    Lint,
    /// Generate Mermaid diagram.
    Mermaid,
}

impl SpecRequest {
    /// Create a show request.
    pub fn show() -> Self {
        Self {
            query: SpecQueryKind::Show,
        }
    }

    /// Create a groups request.
    pub fn groups() -> Self {
        Self {
            query: SpecQueryKind::Groups,
        }
    }

    /// Create a types-in-group request.
    pub fn types_in_group(group: impl Into<String>) -> Self {
        Self {
            query: SpecQueryKind::TypesInGroup {
                group: group.into(),
            },
        }
    }

    /// Create a stats request.
    pub fn stats() -> Self {
        Self {
            query: SpecQueryKind::Stats,
        }
    }

    /// Create a lint request.
    pub fn lint() -> Self {
        Self {
            query: SpecQueryKind::Lint,
        }
    }

    /// Create a mermaid request.
    pub fn mermaid() -> Self {
        Self {
            query: SpecQueryKind::Mermaid,
        }
    }
}

/// Response from spec query.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SpecResponse {
    /// Full hierarchy response.
    Show(SpecShowData),
    /// List of group names.
    Groups(Vec<String>),
    /// List of specs in a group.
    TypesInGroup(Vec<SpecInfoData>),
    /// Dependency list.
    Dependencies(Vec<String>),
    /// Dependent list.
    Dependents(Vec<String>),
    /// Statistics.
    Stats(SpecStatsData),
    /// Lint result.
    Lint(SpecLintData),
    /// Mermaid diagram.
    Mermaid(String),
}

/// Full spec hierarchy data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecShowData {
    /// All groups with their specs.
    pub groups: Vec<SpecGroupData>,
    /// All dependency relations.
    pub relations: Vec<SpecRelationData>,
    /// Statistics.
    pub stats: SpecStatsData,
}

/// Group information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecGroupData {
    /// Group name.
    pub name: String,
    /// Specs in this group.
    pub specs: Vec<SpecInfoData>,
}

/// Spec information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecInfoData {
    /// Alias name (e.g., "DbConfig").
    pub alias_name: String,
    /// Wrapped type name (e.g., "DatabaseConfig").
    pub wrapped_type_name: String,
    /// Source kind.
    pub source: String,
}

/// Spec relation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecRelationData {
    /// Source spec name.
    pub from: String,
    /// Target spec name.
    pub to: String,
    /// Relation kind.
    pub kind: String,
}

/// Statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecStatsData {
    /// Number of groups.
    pub groups: usize,
    /// Number of specs.
    pub specs: usize,
    /// Total node count.
    pub nodes: usize,
    /// Total edge count.
    pub edges: usize,
}

/// Lint result data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecLintData {
    /// All issues found.
    pub issues: Vec<SpecLintIssueData>,
    /// Number of warnings.
    pub warnings: usize,
    /// Number of errors.
    pub errors: usize,
}

/// Lint issue data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpecLintIssueData {
    /// Severity ("warning" or "error").
    pub severity: String,
    /// Issue message.
    pub message: String,
    /// Optional location.
    pub location: Option<String>,
}

// ============================================================================
// Graph Type Analysis
// ============================================================================

/// Analysis mode for type relationships.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub enum TypeAnalysisMode {
    /// Show type definition details.
    Definition,
    /// Show all usages of this type.
    Usage,
    /// Show impact of changing this type.
    #[default]
    Impact,
}

/// Request for type analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeAnalysisRequest {
    /// Type name to analyze (used if id/uuid not provided).
    #[serde(default)]
    pub name: Option<String>,
    /// SymbolId to analyze directly (e.g., "165v1").
    /// **Warning**: Session-volatile. Prefer `uuid` for persistent references.
    #[serde(default)]
    pub id: Option<String>,
    /// Persistent UUID for cross-session symbol tracking.
    /// Takes precedence over `id` and `name` if provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Analysis mode.
    #[serde(default)]
    pub mode: TypeAnalysisMode,
    /// Maximum depth for traversal.
    #[serde(default)]
    pub depth: Option<usize>,
}

impl TypeAnalysisRequest {
    /// Create a new type analysis request by name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            id: None,
            uuid: None,
            mode: TypeAnalysisMode::default(),
            depth: None,
        }
    }

    /// Create a new type analysis request by SymbolId.
    pub fn with_id(id: impl Into<String>) -> Self {
        Self {
            name: None,
            id: Some(id.into()),
            uuid: None,
            mode: TypeAnalysisMode::default(),
            depth: None,
        }
    }

    /// Create a new type analysis request by UUID.
    pub fn with_uuid(uuid: impl Into<String>) -> Self {
        Self {
            name: None,
            id: None,
            uuid: Some(uuid.into()),
            mode: TypeAnalysisMode::default(),
            depth: None,
        }
    }

    /// Set the analysis mode.
    pub fn mode(mut self, mode: TypeAnalysisMode) -> Self {
        self.mode = mode;
        self
    }
}

/// Response from type analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeAnalysisResponse {
    /// Symbol ID string.
    pub symbol_id: String,
    /// Display name.
    pub display_name: String,
    /// Module path.
    pub mod_path: Option<String>,
    /// Kind (Struct, Enum, etc.).
    pub kind: Option<String>,
    /// Usage count.
    pub usage_count: usize,
    /// Usages (context, ref_kind). Populated for Usage/Impact modes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<TypeUsageInfo>,
    /// Impact info (direct usages, bound usages, containing types). Populated for Impact mode.
    pub impact: Option<TypeImpactInfo>,
    /// Supertraits (for traits only): parent traits from `trait Foo: Bar + Baz`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub supertraits: Vec<String>,
    /// Implementors (for traits only): types that implement this trait.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub implementors: Vec<String>,
    /// Struct/enum fields. Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fields: Vec<TypeFieldInfo>,
    /// Enum variants. Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub variants: Vec<TypeVariantInfo>,
    /// Function parameters. Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub params: Vec<TypeParamInfo>,
    /// Function return type. Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub return_type: Option<String>,
    /// Trait method names. Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub methods: Vec<String>,
    /// Generic parameters string (e.g. "<T, U: Clone>"). Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub generics: Option<String>,
    /// Attributes (e.g. ["derive", "serde"]). Populated for Definition mode.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attrs: Vec<String>,
}

/// Field information for definition mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeFieldInfo {
    /// Field name.
    pub name: String,
    /// Type as string.
    pub ty: String,
    /// Is publicly visible.
    pub is_public: bool,
}

/// Enum variant information for definition mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeVariantInfo {
    /// Variant name.
    pub name: String,
    /// Fields of this variant.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fields: Vec<TypeFieldInfo>,
}

/// Parameter information for definition mode.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeParamInfo {
    /// Parameter name.
    pub name: String,
    /// Type as string.
    pub ty: String,
}

/// Type usage information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeUsageInfo {
    /// Usage context.
    pub context: String,
    /// Reference kind.
    pub ref_kind: String,
    /// Container symbol path (the function/struct that uses this type).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub container: Option<String>,
}

/// Type impact information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeImpactInfo {
    /// Direct usage count.
    pub direct_usages: usize,
    /// Bound usage count.
    pub bound_usages: usize,
    /// Containing types.
    pub containing_types: Vec<String>,
}

// ============================================================================
// Graph Flow Analysis
// ============================================================================

/// Analysis mode for data flow.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub enum FlowAnalysisMode {
    /// Track where values come from.
    Provenance,
    /// Track where values flow to.
    Impact,
    /// Full chain analysis (provenance + impact).
    #[default]
    Chain,
    /// Find data sources.
    Sources,
    /// Find data sinks.
    Sinks,
}

/// Request for flow analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowAnalysisRequest {
    /// Variable name to analyze (used if id/uuid not provided).
    #[serde(default)]
    pub name: Option<String>,
    /// SymbolId to analyze directly (e.g., "165v1").
    /// **Warning**: Session-volatile. Prefer `uuid` for persistent references.
    #[serde(default)]
    pub id: Option<String>,
    /// Persistent UUID for cross-session symbol tracking.
    /// Takes precedence over `id` and `name` if provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Analysis mode.
    #[serde(default)]
    pub mode: FlowAnalysisMode,
    /// Maximum depth for traversal.
    #[serde(default)]
    pub depth: Option<usize>,
}

impl FlowAnalysisRequest {
    /// Create a new flow analysis request by name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            id: None,
            uuid: None,
            mode: FlowAnalysisMode::default(),
            depth: None,
        }
    }

    /// Create a new flow analysis request by SymbolId.
    pub fn with_id(id: impl Into<String>) -> Self {
        Self {
            name: None,
            id: Some(id.into()),
            uuid: None,
            mode: FlowAnalysisMode::default(),
            depth: None,
        }
    }

    /// Create a new flow analysis request by UUID.
    pub fn with_uuid(uuid: impl Into<String>) -> Self {
        Self {
            name: None,
            id: None,
            uuid: Some(uuid.into()),
            mode: FlowAnalysisMode::default(),
            depth: None,
        }
    }
}

/// Variable information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VarInfo {
    /// Variable name.
    pub name: String,
    /// Variable kind.
    pub kind: String,
    /// Parent function.
    pub parent: String,
    /// Symbol path.
    pub symbol_path: Option<String>,
}

/// Response from flow analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlowAnalysisResponse {
    /// Display name.
    pub display_name: String,
    /// Found variables.
    pub found_vars: Vec<VarInfo>,
    /// Provenance (sources).
    pub provenance: Vec<VarInfo>,
    /// Impact (targets).
    pub impact: Vec<VarInfo>,
    /// Sources (data origins).
    pub sources: Vec<VarInfo>,
    /// Sinks (data destinations).
    pub sinks: Vec<VarInfo>,
}

// ============================================================================
// Graph Borrow Analysis
// ============================================================================

/// Request for borrow analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorrowAnalysisRequest {
    /// Variable name to analyze (used if id/uuid not provided).
    #[serde(default)]
    pub name: Option<String>,
    /// SymbolId to analyze directly (e.g., "165v1").
    /// **Warning**: Session-volatile. Prefer `uuid` for persistent references.
    #[serde(default)]
    pub id: Option<String>,
    /// Persistent UUID for cross-session symbol tracking.
    /// Takes precedence over `id` and `name` if provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Show only conflicts.
    #[serde(default)]
    pub conflicts_only: bool,
}

impl BorrowAnalysisRequest {
    /// Create a new borrow analysis request by name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            id: None,
            uuid: None,
            conflicts_only: false,
        }
    }

    /// Create a new borrow analysis request by SymbolId.
    pub fn with_id(id: impl Into<String>) -> Self {
        Self {
            name: None,
            id: Some(id.into()),
            uuid: None,
            conflicts_only: false,
        }
    }

    /// Create a new borrow analysis request by UUID.
    pub fn with_uuid(uuid: impl Into<String>) -> Self {
        Self {
            name: None,
            id: None,
            uuid: Some(uuid.into()),
            conflicts_only: false,
        }
    }
}

/// Borrow status for a variable.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorrowStatus {
    /// Variable name.
    pub var_name: String,
    /// Line number.
    pub line: u32,
    /// Parent function.
    pub parent_info: String,
    /// Has conflict.
    pub has_conflict: bool,
    /// Conflict errors.
    pub errors: Vec<String>,
}

/// Response from borrow analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BorrowAnalysisResponse {
    /// Display name.
    pub display_name: String,
    /// Found variables count.
    pub found_count: usize,
    /// Borrow statuses.
    pub statuses: Vec<BorrowStatus>,
}

// ============================================================================
// Graph Lock Analysis
// ============================================================================

/// Request for lock analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockAnalysisRequest {
    /// Lock name pattern (used if id/uuid not provided).
    #[serde(default)]
    pub name: Option<String>,
    /// SymbolId to analyze directly (e.g., "165v1").
    /// **Warning**: Session-volatile. Prefer `uuid` for persistent references.
    #[serde(default)]
    pub id: Option<String>,
    /// Persistent UUID for cross-session symbol tracking.
    /// Takes precedence over `id` and `name` if provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Show optimization suggestions.
    #[serde(default)]
    pub suggest: bool,
}

impl LockAnalysisRequest {
    /// Create a new lock analysis request by name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
            id: None,
            uuid: None,
            suggest: false,
        }
    }

    /// Create a new lock analysis request by SymbolId.
    pub fn with_id(id: impl Into<String>) -> Self {
        Self {
            name: None,
            id: Some(id.into()),
            uuid: None,
            suggest: false,
        }
    }

    /// Create a new lock analysis request by UUID.
    pub fn with_uuid(uuid: impl Into<String>) -> Self {
        Self {
            name: None,
            id: None,
            uuid: Some(uuid.into()),
            suggest: false,
        }
    }
}

/// Lock statistics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockStats {
    /// Total locks.
    pub total_locks: u32,
    /// Mutex count.
    pub mutex_count: u32,
    /// RwLock count.
    pub rwlock_count: u32,
    /// RefCell count.
    pub refcell_count: u32,
    /// Total field accesses.
    pub total_field_accesses: u32,
    /// Max critical section span.
    pub max_cs_span: u32,
}

/// Lock acquisition info.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockAcquisition {
    /// Lock name.
    pub lock_name: String,
    /// Lock type.
    pub lock_type: String,
    /// Line number.
    pub line: u32,
}

/// Lock suggestion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockSuggestionInfo {
    /// Suggestion kind.
    pub kind: String,
    /// Target name.
    pub target: String,
    /// Description.
    pub description: String,
    /// Line number.
    pub line: u32,
}

/// Response from lock analysis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockAnalysisResponse {
    /// Display name.
    pub display_name: String,
    /// Lock statistics.
    pub stats: LockStats,
    /// Matching acquisitions.
    pub acquisitions: Vec<LockAcquisition>,
    /// Suggestions (if requested).
    pub suggestions: Vec<LockSuggestionInfo>,
}

// ============================================================================
// Graph Chain Analysis (Transitive Call Chain)
// ============================================================================

/// Traversal mode for chain analysis.
///
/// - `Callers`/`Callees`: Call chain traversal (CodeGraphV2)
/// - `TypeUsers`/`TypeDeps`: Type reference chain traversal (TypeFlowGraphV2)
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub enum ChainMode {
    /// Follow incoming call edges (who calls this function?)
    #[default]
    Callers,
    /// Follow outgoing call edges (what does this function call?)
    Callees,
    /// Follow type reference edges: who uses this type? (type → containers)
    TypeUsers,
    /// Follow type reference edges: what types does this use? (container → types)
    TypeDeps,
}

impl std::fmt::Display for ChainMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ChainMode::Callers => write!(f, "callers"),
            ChainMode::Callees => write!(f, "callees"),
            ChainMode::TypeUsers => write!(f, "type_users"),
            ChainMode::TypeDeps => write!(f, "type_deps"),
        }
    }
}

/// Request for chain analysis.
///
/// Traverses call relationships transitively to find all callers or callees
/// up to a specified depth.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainAnalysisRequest {
    /// SymbolId to analyze (e.g., "165v1").
    /// Get this from `ryo discover` output.
    /// **Warning**: Session-volatile. Prefer `uuid` for persistent references.
    pub id: String,
    /// Persistent UUID for cross-session symbol tracking.
    /// Takes precedence over `id` if provided.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub uuid: Option<String>,
    /// Traversal mode.
    #[serde(default)]
    pub mode: ChainMode,
    /// Maximum traversal depth (default: 5).
    #[serde(default)]
    pub depth: Option<usize>,
}

impl ChainAnalysisRequest {
    /// Create a new chain analysis request with SymbolId.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            uuid: None,
            mode: ChainMode::default(),
            depth: None,
        }
    }

    /// Create a new chain analysis request with UUID.
    pub fn with_uuid(uuid: impl Into<String>) -> Self {
        Self {
            id: String::new(),
            uuid: Some(uuid.into()),
            mode: ChainMode::default(),
            depth: None,
        }
    }

    /// Set the traversal mode.
    pub fn mode(mut self, mode: ChainMode) -> Self {
        self.mode = mode;
        self
    }

    /// Set the traversal depth.
    pub fn depth(mut self, depth: usize) -> Self {
        self.depth = Some(depth);
        self
    }
}

/// A node in the chain with depth information.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChainNodeInfo {
    /// SymbolId as string.
    pub id: String,
    /// Full symbol path.
    pub path: String,
    /// Symbol kind (Function, Struct, etc.).
    pub kind: Option<String>,
    /// Depth from starting symbol.
    pub depth: usize,
}

/// Response from chain analysis.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ChainAnalysisResponse {
    /// Display name of the starting symbol.
    pub display_name: String,
    /// Traversal direction used.
    pub direction: String,
    /// Total count of nodes in the chain.
    pub total_count: usize,
    /// Maximum depth actually reached.
    pub max_actual_depth: usize,
    /// Nodes grouped by depth level.
    pub by_depth: std::collections::BTreeMap<usize, Vec<ChainNodeInfo>>,
}