code-moniker-query 0.4.0

Shared daemon query DSL and protocol DTOs for code-moniker.
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
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
use std::collections::BTreeMap;
use std::fmt::{self, Write};
use std::str::FromStr;

use serde::{Deserialize, Serialize};

mod discovery;
pub use discovery::*;

#[cfg(feature = "rpc")]
pub mod rpc {
	use jsonrpsee::core::SubscriptionResult;
	use jsonrpsee::proc_macros::rpc;
	use jsonrpsee::types::ErrorObjectOwned;

	use crate::{
		CommandRequest, CommandResponse, HandshakeResponse, QueryRequest, QueryResponse,
		WorkspaceEventDto,
	};

	pub const RPC_NAMESPACE: &str = "moniker";

	#[rpc(server, client, namespace = "moniker")]
	pub trait DaemonRpc {
		#[method(name = "handshake")]
		async fn handshake(&self, client: String) -> Result<HandshakeResponse, ErrorObjectOwned>;

		#[method(name = "query")]
		async fn query(&self, request: QueryRequest) -> Result<QueryResponse, ErrorObjectOwned>;

		#[method(name = "command")]
		async fn command(
			&self,
			request: CommandRequest,
		) -> Result<CommandResponse, ErrorObjectOwned>;

		#[method(name = "shutdown")]
		async fn shutdown(&self) -> Result<(), ErrorObjectOwned>;

		#[subscription(name = "subscribeEvents" => "events", unsubscribe = "unsubscribeEvents", item = WorkspaceEventDto)]
		async fn subscribe_events(&self) -> SubscriptionResult;
	}
}

#[cfg(feature = "rpc")]
pub use rpc::*;

pub const PROTOCOL_VERSION: u32 = 1;

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProtocolRequest {
	Query(Box<QueryRequest>),
	Command(CommandRequest),
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ProtocolResponse {
	Query(Box<QueryResponse>),
	Command(CommandResponse),
	Error(QueryError),
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct HandshakeResponse {
	pub protocol_version: u32,
	pub daemon_version: String,
	pub workspace_root: String,
	pub workspace_roots: Vec<String>,
	pub capabilities: CapabilitySet,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct DaemonWorkspaceConfig {
	pub roots: Vec<String>,
	pub project: Option<String>,
	pub cache_dir: Option<String>,
	pub live_refresh: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CapabilitySet {
	pub queries: Vec<String>,
	pub commands: Vec<String>,
	pub events: Vec<String>,
}

impl Default for CapabilitySet {
	fn default() -> Self {
		Self {
			queries: vec![
				"workspace.status".to_string(),
				"tree.children".to_string(),
				"symbol.search".to_string(),
				"symbol.insights".to_string(),
				"symbol.detail".to_string(),
				"symbol.usages".to_string(),
				"view.read".to_string(),
				"rules.list".to_string(),
				"rules.check".to_string(),
				"change.review".to_string(),
				"symbol.graph".to_string(),
				"identity.children".to_string(),
				"identity.graph".to_string(),
				"resolution.audit".to_string(),
				"notes".to_string(),
			],
			commands: vec!["workspace.refresh".to_string()],
			events: Vec::new(),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct QueryRequest {
	pub query: Query,
	pub consistency: Consistency,
	pub page: Page,
}

impl QueryRequest {
	pub fn new(query: Query) -> Self {
		Self {
			query,
			consistency: Consistency::Current,
			page: Page::default(),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Query {
	WorkspaceStatus,
	TreeChildren(TreeChildrenQuery),
	SymbolSearch(SymbolSearchQuery),
	SymbolInsights(SymbolSearchQuery),
	SymbolDetail(SymbolDetailQuery),
	SymbolUsages(SymbolUsagesQuery),
	ViewRead(ViewReadQuery),
	RulesList(RulesListQuery),
	RulesCheck(RulesCheckQuery),
	ChangeReview(ChangeReviewQuery),
	SymbolGraph(SymbolGraphQuery),
	IdentityChildren(IdentityChildrenQuery),
	IdentityGraph(IdentityChildrenQuery),
	ResolutionAudit(ResolutionAuditQuery),
	Notes(NotesQuery),
}

impl Query {
	pub fn capability(&self) -> &'static str {
		match self {
			Self::WorkspaceStatus => "workspace.status",
			Self::TreeChildren(_) => "tree.children",
			Self::SymbolSearch(_) => "symbol.search",
			Self::SymbolInsights(_) => "symbol.insights",
			Self::SymbolDetail(_) => "symbol.detail",
			Self::SymbolUsages(_) => "symbol.usages",
			Self::ViewRead(_) => "view.read",
			Self::RulesList(_) => "rules.list",
			Self::RulesCheck(_) => "rules.check",
			Self::ChangeReview(_) => "change.review",
			Self::SymbolGraph(_) => "symbol.graph",
			Self::IdentityChildren(_) => "identity.children",
			Self::IdentityGraph(_) => "identity.graph",
			Self::ResolutionAudit(_) => "resolution.audit",
			Self::Notes(_) => "notes",
		}
	}
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TreeChildrenQuery {
	pub workspace: Option<String>,
	pub path: Vec<String>,
	pub depth: usize,
	pub lang: Vec<String>,
	pub projection: Vec<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolSearchQuery {
	pub workspace: Option<String>,
	pub text: Option<String>,
	pub path: Vec<String>,
	pub lang: Vec<String>,
	pub kind: Vec<String>,
	pub shape: Vec<String>,
	pub name: Option<String>,
	pub include_non_navigable: bool,
	pub include_code: bool,
	pub context_lines: usize,
	pub projection: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolDetailQuery {
	pub workspace: Option<String>,
	pub uri: String,
	pub context_lines: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolUsagesQuery {
	pub workspace: Option<String>,
	pub uri: String,
	pub direction: UsageDirection,
	pub path: Vec<String>,
	pub lang: Vec<String>,
	pub projection: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewReadQuery {
	pub uri: String,
	pub scheme: Option<String>,
	pub context_lines: usize,
	pub include_code: bool,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ResolutionAuditQuery {
	pub workspace: Option<String>,
	pub prefix: String,
	pub limit: usize,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum UsageDirection {
	#[default]
	Incoming,
	Outgoing,
	Both,
}

impl UsageDirection {
	pub fn as_str(self) -> &'static str {
		match self {
			Self::Incoming => "incoming",
			Self::Outgoing => "outgoing",
			Self::Both => "both",
		}
	}
}

impl FromStr for UsageDirection {
	type Err = QueryParseError;

	fn from_str(value: &str) -> Result<Self, Self::Err> {
		match value {
			"incoming" => Ok(Self::Incoming),
			"outgoing" => Ok(Self::Outgoing),
			"both" => Ok(Self::Both),
			_ => Err(QueryParseError::InvalidValue {
				key: "direction".to_string(),
				value: value.to_string(),
			}),
		}
	}
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RulesListQuery {
	pub workspace: Option<String>,
	pub profile: Option<String>,
	pub rules: Option<String>,
	pub lang: Vec<String>,
	pub severity: Vec<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RulesCheckQuery {
	pub workspace: Option<String>,
	pub profile: Option<String>,
	pub rules: Option<String>,
	pub file: Vec<String>,
	pub report: bool,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewQuery {
	pub workspace: Option<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolGraphQuery {
	pub workspace: Option<String>,
	pub focus: String,
}

// One level of the identity tree: children of a moniker identity prefix
// (`""` = the workspace root). The symbolic navigation surface - no
// filesystem involved.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct IdentityChildrenQuery {
	pub workspace: Option<String>,
	pub prefix: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct NotesQuery {
	pub action: NotesAction,
	pub id: Option<String>,
	pub moniker: Option<String>,
	pub kind: Option<String>,
	pub status: Option<String>,
	pub title: Option<String>,
	pub body: Option<String>,
	pub created_by: Option<String>,
	pub orphan: Option<bool>,
	pub include_done: bool,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum NotesAction {
	#[default]
	List,
	Get,
	Create,
	Update,
	Transition,
	Delete,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CommandRequest {
	pub command: Command,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum Command {
	WorkspaceRefresh,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Consistency {
	#[default]
	Current,
	RefreshIfStale,
	StaleOk,
}

impl FromStr for Consistency {
	type Err = QueryParseError;

	fn from_str(value: &str) -> Result<Self, Self::Err> {
		match value {
			"current" => Ok(Self::Current),
			"refresh-if-stale" => Ok(Self::RefreshIfStale),
			"stale-ok" => Ok(Self::StaleOk),
			_ => Err(QueryParseError::InvalidValue {
				key: "consistency".to_string(),
				value: value.to_string(),
			}),
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Page {
	pub cursor: Option<QueryCursor>,
	pub limit: usize,
}

impl Default for Page {
	fn default() -> Self {
		Self {
			cursor: None,
			limit: 80,
		}
	}
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct QueryCursor {
	pub offset: usize,
	pub generation: Option<WorkspaceGeneration>,
}

impl QueryCursor {
	pub fn new(offset: usize, generation: Option<WorkspaceGeneration>) -> Self {
		Self { offset, generation }
	}
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkspaceGeneration(pub u64);

/// A workspace change pushed to attached clients over a daemon subscription.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkspaceEventDto {
	pub kind: WorkspaceEventKind,
	pub generation: Option<WorkspaceGeneration>,
	pub stale_summary: Option<String>,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceEventKind {
	Stale,
	Refreshed,
	Notes,
	GitBase,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct QueryResponse {
	pub generation: Option<WorkspaceGeneration>,
	pub result: QueryResult,
	pub next_cursor: Option<QueryCursor>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", content = "data", rename_all = "snake_case")]
pub enum QueryResult {
	WorkspaceStatus(WorkspaceStatus),
	TreeChildren(TreeChildrenResult),
	SymbolList(SymbolListResult),
	SymbolInsights(SymbolInsightsResult),
	SymbolDetail(SymbolDetailResult),
	SymbolUsages(Box<SymbolUsagesResult>),
	ViewRead(ViewReadResult),
	RulesList(RulesListResult),
	RulesCheck(RulesCheckResult),
	ChangeReview(Box<ChangeReviewResult>),
	SymbolGraph(Box<SymbolGraphResult>),
	IdentityChildren(IdentityChildrenResult),
	IdentityGraph(Box<IdentityGraphResult>),
	ResolutionAudit(Box<ResolutionAuditResult>),
	Notes(NotesResult),
}

// Refs without an in-workspace target, decomposed so external-by-design
// never masquerades as a resolution gap: `external` links to declared
// packages, `manifest_blocked` hit the manifest policy, `unresolved` are the
// real misses, ventilated by reason.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UnlinkedRefsDto {
	pub external: usize,
	pub manifest_blocked: usize,
	pub unresolved: usize,
	pub unresolved_reasons: BTreeMap<String, usize>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolGraphResult {
	pub focus: SymbolGraphFocus,
	pub members: Vec<SymbolDto>,
	pub internal_edges: Vec<SymbolGraphEdge>,
	pub callers: Vec<SymbolGraphNeighbor>,
	pub callees: Vec<SymbolGraphNeighbor>,
	pub unlinked: UnlinkedRefsDto,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum SymbolGraphFocus {
	Symbol { symbol: Box<SymbolDto> },
	File { path: String },
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolGraphNeighbor {
	pub symbol: SymbolDto,
	pub kinds: Vec<String>,
	pub count: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolGraphEdge {
	pub source: String,
	pub target: String,
	pub kinds: Vec<String>,
	pub count: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct IdentityChildrenResult {
	pub prefix: String,
	pub children: Vec<IdentitySegmentDto>,
}

// One child segment under the requested prefix. `symbol` is attached when the
// segment itself is a navigable definition; organizational segments (package,
// dir, srcset, lang, module wrappers) only aggregate what lives below.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct IdentitySegmentDto {
	pub segment: String,
	pub kind: String,
	pub name: String,
	pub identity: String,
	pub defs: usize,
	pub has_children: bool,
	pub symbol: Option<Box<SymbolDto>>,
}

// The embedded resolution audit: unresolved references (and name-match
// resolutions, the false-link candidates) clustered under mechanical pattern
// keys, with samples and per-zone rollups — the daemon's own diagnosis
// surface, so agents stop rebuilding external harnesses.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ResolutionAuditResult {
	pub prefix: String,
	pub totals: AuditTotalsDto,
	pub clusters: Vec<AuditClusterDto>,
	pub zones: Vec<AuditZoneDto>,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AuditTotalsDto {
	pub references: usize,
	pub resolved: usize,
	pub external: usize,
	pub blocked: usize,
	pub unresolved: usize,
	pub name_match_resolved: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AuditClusterDto {
	pub pattern: String,
	pub count: usize,
	pub samples: Vec<AuditSampleDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AuditSampleDto {
	pub source: String,
	pub call_name: String,
	pub receiver: String,
	pub target: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct AuditZoneDto {
	pub zone: String,
	pub unresolved: usize,
	pub dominant_pattern: String,
}

// The scoped exploration graph: one level of the identity tree projected as
// a graph. Nodes are the prefix's children; edges are resolved references
// rolled up to the pair of child segments they connect; ports aggregate what
// crosses the scope boundary.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct IdentityGraphResult {
	pub prefix: String,
	pub nodes: Vec<IdentitySegmentDto>,
	pub edges: Vec<IdentityGraphEdge>,
	pub ports_in: Vec<IdentityGraphPort>,
	pub ports_out: Vec<IdentityGraphPort>,
	pub unlinked: UnlinkedRefsDto,
}

// source/target are child segment identities of the requested prefix.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct IdentityGraphEdge {
	pub source: String,
	pub target: String,
	pub kinds: Vec<String>,
	pub count: usize,
}

// Aggregated boundary crossing: `identity` is the nearest out-of-scope
// segment (rolled up to the scope's own depth in the identity tree).
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct IdentityGraphPort {
	pub identity: String,
	pub kinds: Vec<String>,
	pub count: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewResult {
	pub scope: String,
	pub summary: ChangeReviewSummary,
	pub files: Vec<ChangeReviewFile>,
	pub symbol_changes: Vec<ChangeReviewSymbol>,
	pub ref_changes: Vec<ChangeReviewRef>,
	pub diagnostics: Vec<String>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewSummary {
	pub files: usize,
	pub analyzable_files: usize,
	pub symbol_changes: usize,
	pub ref_changes: usize,
	pub retargeted_refs: usize,
	pub residual_files: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewFile {
	pub old_path: Option<String>,
	pub new_path: Option<String>,
	pub disposition: String,
	pub analyzable: bool,
	pub symbol_changes: usize,
	pub moved_symbols: usize,
	pub coverage_explained: bool,
	pub old_residual: Vec<(u32, u32)>,
	pub new_residual: Vec<(u32, u32)>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewSymbol {
	pub kind: String,
	pub confidence: String,
	pub body_changed: bool,
	pub signature_changed: bool,
	pub visibility_changed: bool,
	pub header_changed: bool,
	pub file_moved: bool,
	pub old: Option<ChangeReviewSide>,
	pub new: Option<ChangeReviewSide>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewSide {
	pub identity: String,
	pub file: String,
	pub kind: String,
	pub name: String,
	pub visibility: String,
	pub lines: Option<(u32, u32)>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ChangeReviewRef {
	pub kind: String,
	pub file: String,
	pub ref_kind: String,
	pub old_target: Option<String>,
	pub new_target: Option<String>,
	pub old_lines: Option<(u32, u32)>,
	pub new_lines: Option<(u32, u32)>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CommandResponse {
	pub generation: Option<WorkspaceGeneration>,
	pub message: String,
	pub status: Option<WorkspaceStatus>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ViewReadResult {
	List(ViewListResult),
	Detail(Box<ViewDetailResult>),
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewListResult {
	pub views: Vec<ViewSummaryDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewSummaryDto {
	pub id: String,
	pub title: Option<String>,
	pub fragment: String,
	pub anchor: String,
	pub scope: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewDetailResult {
	pub id: String,
	pub title: Option<String>,
	pub fragment: String,
	pub anchor: String,
	pub scope: String,
	pub intent: Option<String>,
	pub summary: Option<String>,
	pub rules: Vec<ViewRuleDto>,
	pub boundaries: Vec<ViewBoundaryDto>,
	pub gotchas: Vec<ViewGotchaDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewRuleDto {
	pub id: String,
	pub severity: String,
	pub domain: String,
	pub rationale: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewRuleRefDto {
	pub id: String,
	pub present: bool,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewBoundaryDto {
	pub id: String,
	pub owns: Vec<String>,
	pub forbids: Vec<String>,
	pub forbid_rules: Vec<String>,
	pub rationale: Option<String>,
	pub rule_refs: Vec<ViewRuleRefDto>,
	pub evidence: Vec<ViewEvidenceDto>,
	pub missing: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewGotchaDto {
	pub id: String,
	pub rationale: String,
	pub check: Option<String>,
	pub rule_refs: Vec<ViewRuleRefDto>,
	pub evidence: Vec<ViewEvidenceDto>,
	pub missing: Vec<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViewEvidenceDto {
	pub selector: String,
	pub label: String,
	pub moniker: String,
	pub file: String,
	pub slice: Option<(u32, u32)>,
	pub active_slice: Option<(u32, u32)>,
	pub code: Vec<SourceLine>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkspaceStatus {
	pub root: String,
	pub phase: String,
	pub roots: Vec<WorkspaceRootStatus>,
	pub generation: Option<WorkspaceGeneration>,
	pub files: usize,
	pub symbols: usize,
	pub references: usize,
	pub stale: bool,
	pub stale_summary: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct WorkspaceRootStatus {
	pub root: String,
	pub generation: Option<WorkspaceGeneration>,
	pub files: usize,
	pub symbols: usize,
	pub references: usize,
	pub stale: bool,
	pub stale_summary: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TreeChildrenResult {
	pub root: String,
	pub roots: Vec<String>,
	pub rows: Vec<TreeNode>,
	pub total: usize,
	pub total_files: usize,
	pub scoped_files: usize,
	pub languages: Vec<CountDto>,
	pub prefixes: Vec<CountDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct TreeNode {
	pub root: String,
	pub path: String,
	pub kind: TreeNodeKind,
	pub language: Option<String>,
	pub defs: usize,
	pub refs: usize,
	pub change_count: usize,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum TreeNodeKind {
	File,
	Directory,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolListResult {
	pub rows: Vec<SymbolDto>,
	pub total: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolDto {
	pub root: String,
	pub uri: String,
	pub id: String,
	pub name: String,
	pub kind: String,
	pub visibility: String,
	pub signature: String,
	pub file: String,
	pub language: String,
	pub line_range: Option<(u32, u32)>,
	pub navigable: bool,
	pub score: Option<u32>,
	pub match_reason: Option<String>,
	pub source: Option<SourceSnippet>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolInsightsResult {
	pub files: usize,
	pub symbols: usize,
	pub references: usize,
	pub navigable_symbols: usize,
	pub non_navigable_symbols: usize,
	pub languages: Vec<CountDto>,
	pub kinds: Vec<CountDto>,
	pub shapes: Vec<CountDto>,
	pub top_files_by_symbols: Vec<CountDto>,
	pub top_files_by_refs: Vec<CountDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolDetailResult {
	pub symbol: SymbolDto,
	pub source: Option<SourceSnippet>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SourceSnippet {
	pub file: String,
	pub first_line: u32,
	pub last_line: u32,
	pub lines: Vec<SourceLine>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SourceLine {
	pub number: u32,
	pub text: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct SymbolUsagesResult {
	pub target: SymbolDto,
	pub direction: UsageDirection,
	pub rows: Vec<UsageDto>,
	pub total: usize,
	pub incoming_summary: Option<UsageSummaryDto>,
	pub outgoing_summary: Option<UsageSummaryDto>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UsageSummaryDto {
	pub refs: usize,
	pub files: usize,
	pub contexts: usize,
	pub prefixes: usize,
	pub dominant_prefix: String,
	pub kinds: Vec<CountDto>,
	pub top_actors: Vec<CountDto>,
	pub top_prefixes: Vec<CountDto>,
	pub shared_helper_signal: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct UsageDto {
	pub root: String,
	pub direction: UsageDirection,
	pub reference: String,
	pub kind: String,
	pub actor: String,
	pub context: String,
	pub endpoint: String,
	pub file: String,
	pub prefix: String,
	pub location: String,
	pub line_range: Option<(u32, u32)>,
	pub via: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RulesListResult {
	pub roots: Vec<String>,
	pub rows: Vec<RuleDto>,
	pub total: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RuleDto {
	pub root: String,
	pub id: String,
	pub severity: String,
	pub lang: String,
	pub domain: String,
	pub kind: Option<String>,
	pub expr: String,
	pub expanded_expr: String,
	pub message: Option<String>,
	pub rationale: Option<String>,
	pub require_doc_comment: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RulesCheckResult {
	pub exit: String,
	pub summary: CheckSummaryDto,
	pub roots: Vec<RulesCheckRootResult>,
	pub violations: Vec<ViolationDto>,
	pub errors: Vec<FileErrorDto>,
	pub rule_reports: Vec<RuleReportDto>,
	pub skip_reasons: Vec<CheckSkipReasonDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RulesCheckRootResult {
	pub root: String,
	pub exit: String,
	pub summary: CheckSummaryDto,
	pub violations: Vec<ViolationDto>,
	pub errors: Vec<FileErrorDto>,
	pub rule_reports: Vec<RuleReportDto>,
	pub skip_reason: Option<CheckSkipReasonDto>,
}

#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CheckSummaryDto {
	pub files_scanned: usize,
	pub files_with_violations: usize,
	pub total_violations: usize,
	pub total_rule_errors: usize,
	pub total_warnings: usize,
	pub files_with_errors: usize,
	pub total_errors: usize,
	pub elapsed_ms: u64,
	pub failed_rules: Vec<FailedRuleDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FailedRuleDto {
	pub rule_id: String,
	pub severity: String,
	pub violations: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ViolationDto {
	pub root: String,
	pub path: String,
	pub rule_id: String,
	pub severity: String,
	pub moniker: String,
	pub kind: String,
	pub lines: (u32, u32),
	pub message: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct FileErrorDto {
	pub root: String,
	pub path: String,
	pub error: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct RuleReportDto {
	pub root: String,
	pub path: Option<String>,
	pub rule_id: String,
	pub severity: String,
	pub domain: String,
	pub evaluated: usize,
	pub matches: usize,
	pub violations: usize,
	pub antecedent_matches: Option<usize>,
	pub warning: Option<String>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CheckSkipReasonDto {
	pub root: String,
	pub reason: String,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct NotesResult {
	pub action: String,
	pub total: usize,
	pub rows: Vec<NoteDto>,
	pub deleted: Option<NoteDto>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct NoteDto {
	pub id: String,
	pub moniker: String,
	pub kind: String,
	pub status: String,
	pub title: String,
	pub body: String,
	pub created_by: String,
	pub updated_at: String,
	pub resolution: NoteResolutionDto,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "status", rename_all = "snake_case")]
pub enum NoteResolutionDto {
	Resolved {
		target: String,
		file: String,
		slice: Option<(u32, u32)>,
	},
	Orphan,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct CountDto {
	pub name: String,
	pub count: usize,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum DaemonEvent {
	WorkspaceStale {
		generation: Option<WorkspaceGeneration>,
		summary: String,
	},
	WorkspaceRefreshed {
		generation: WorkspaceGeneration,
	},
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct QueryError {
	pub code: String,
	pub message: String,
}

impl QueryError {
	pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
		Self {
			code: code.into(),
			message: message.into(),
		}
	}
}

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

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

#[derive(Debug, thiserror::Error)]
pub enum QueryParseError {
	#[error("empty query")]
	Empty,
	#[error("unknown query operation `{0}`")]
	UnknownOperation(String),
	#[error("invalid token `{0}`")]
	InvalidToken(String),
	#[error("invalid value for `{key}`: `{value}`")]
	InvalidValue { key: String, value: String },
	#[error("missing required `{0}`")]
	MissingRequired(&'static str),
	#[error("unknown field `{key}` for `{op}`{hint}")]
	UnknownField {
		op: String,
		key: String,
		hint: String,
	},
	#[error("unexpected argument `{value}` for `{op}`")]
	UnexpectedArgument { op: String, value: String },
	#[error("`project` is not supported by `{op}`")]
	UnsupportedProjection { op: String },
}

pub fn parse_query(input: &str) -> Result<QueryRequest, QueryParseError> {
	let mut lines = input.lines().map(str::trim).filter(|line| !line.is_empty());
	let first = lines.next().ok_or(QueryParseError::Empty)?;
	let mut tokens = tokenize(first)?;
	let op = tokens.first().cloned().ok_or(QueryParseError::Empty)?;
	tokens.remove(0);
	let mut fields = FieldBag::default();
	let mut positional = Vec::new();
	collect_tokens(&tokens, &mut fields, &mut positional)?;
	for line in lines {
		collect_line(line, &mut fields, &mut positional)?;
	}
	fields.positional = positional;
	let spec = verb_spec(&op).ok_or_else(|| QueryParseError::UnknownOperation(op.clone()))?;
	validate_fields(&op, &spec, &fields)?;
	if let Some(value) = fields.one("consistency") {
		fields.consistency = value.parse()?;
	}
	let page = fields.page()?;
	let consistency = fields.consistency;
	let query = build_query(&op, fields)?;
	Ok(QueryRequest {
		query,
		consistency,
		page,
	})
}

fn collect_line(
	line: &str,
	fields: &mut FieldBag,
	positional: &mut Vec<String>,
) -> Result<(), QueryParseError> {
	let mut tokens = tokenize(line)?;
	if tokens.is_empty() {
		return Ok(());
	}
	let section = tokens.remove(0);
	if section.contains(':') {
		let mut all = vec![section];
		all.extend(tokens);
		return collect_tokens(&all, fields, positional);
	}
	match section.as_str() {
		"filter" | "page" => collect_tokens(&tokens, fields, positional)?,
		"project" => {
			fields.projection.extend(
				tokens
					.into_iter()
					.map(|token| token.trim_end_matches(',').to_string())
					.filter(|token| !token.is_empty()),
			);
		}
		"consistency" => {
			let value = tokens
				.first()
				.ok_or(QueryParseError::MissingRequired("consistency value"))?;
			fields.consistency = value.parse()?;
		}
		"direction" => {
			let value = tokens
				.first()
				.ok_or(QueryParseError::MissingRequired("direction value"))?;
			fields.values.push(("direction".to_string(), value.clone()));
		}
		_ => return Err(QueryParseError::InvalidToken(section)),
	}
	Ok(())
}

fn build_query(op: &str, fields: FieldBag) -> Result<Query, QueryParseError> {
	let query = match op {
		"workspace.status" => Query::WorkspaceStatus,
		"tree.children" => Query::TreeChildren(TreeChildrenQuery {
			workspace: fields.one("workspace"),
			path: fields.many("path"),
			depth: fields.usize("depth")?.unwrap_or(1),
			lang: fields.many("lang"),
			projection: fields.projection,
		}),
		"symbol.search" => Query::SymbolSearch(symbol_search_query(&fields)?),
		"symbol.insights" => Query::SymbolInsights(symbol_insights_query(&fields)?),
		"symbol.detail" => Query::SymbolDetail(SymbolDetailQuery {
			workspace: fields.one("workspace"),
			uri: fields
				.one("uri")
				.or_else(|| fields.positional.first().cloned())
				.ok_or(QueryParseError::MissingRequired("uri"))?,
			context_lines: fields.usize("context_lines")?.unwrap_or(2),
		}),
		"symbol.usages" => Query::SymbolUsages(SymbolUsagesQuery {
			workspace: fields.one("workspace"),
			uri: fields
				.one("uri")
				.or_else(|| fields.positional.first().cloned())
				.ok_or(QueryParseError::MissingRequired("uri"))?,
			direction: fields
				.one("direction")
				.unwrap_or_else(|| "incoming".to_string())
				.parse()?,
			path: fields.many("path"),
			lang: fields.many("lang"),
			projection: fields.projection,
		}),
		"view.read" => Query::ViewRead(ViewReadQuery {
			uri: fields
				.one("uri")
				.or_else(|| fields.positional.first().cloned())
				.ok_or(QueryParseError::MissingRequired("uri"))?,
			scheme: fields.one("scheme"),
			context_lines: fields.usize("context_lines")?.unwrap_or(2),
			include_code: fields.bool("include_code")?.unwrap_or(false),
		}),
		"rules.list" => Query::RulesList(RulesListQuery {
			workspace: fields.one("workspace"),
			profile: fields.one("profile"),
			rules: fields.one("rules"),
			lang: fields.many("lang"),
			severity: fields.many("severity"),
		}),
		"rules.check" => Query::RulesCheck(RulesCheckQuery {
			workspace: fields.one("workspace"),
			profile: fields.one("profile"),
			rules: fields.one("rules"),
			file: fields.many("file"),
			report: fields.bool("report")?.unwrap_or(true),
		}),
		"change.review" => Query::ChangeReview(ChangeReviewQuery {
			workspace: fields.one("workspace"),
		}),
		"symbol.graph" => Query::SymbolGraph(symbol_graph_query(&fields)?),
		"identity.children" => Query::IdentityChildren(identity_children_query(&fields)),
		"identity.graph" => Query::IdentityGraph(identity_children_query(&fields)),
		"resolution.audit" => Query::ResolutionAudit(ResolutionAuditQuery {
			workspace: fields.one("workspace"),
			prefix: fields.one("prefix").unwrap_or_default(),
			limit: fields
				.one("limit")
				.and_then(|value| value.parse().ok())
				.unwrap_or(20),
		}),
		"notes" => Query::Notes(notes_query(&fields)?),
		_ => return Err(QueryParseError::UnknownOperation(op.to_string())),
	};
	Ok(query)
}

struct VerbSpec {
	fields: &'static [&'static str],
	positionals: usize,
	projection: bool,
}

const COMMON_FIELDS: &[&str] = &["limit", "cursor", "consistency"];
const BRACKET_LIST_FIELDS: &[&str] = &["lang", "kind", "shape", "severity"];

fn verb_spec(op: &str) -> Option<VerbSpec> {
	let spec = match op {
		"workspace.status" => VerbSpec {
			fields: &[],
			positionals: 0,
			projection: false,
		},
		"tree.children" => VerbSpec {
			fields: &["workspace", "path", "depth", "lang"],
			positionals: 0,
			projection: true,
		},
		"symbol.search" => VerbSpec {
			fields: &[
				"workspace",
				"path",
				"lang",
				"kind",
				"shape",
				"name",
				"include_non_navigable",
				"include_code",
				"context_lines",
			],
			positionals: 1,
			projection: true,
		},
		"symbol.insights" => VerbSpec {
			fields: &[
				"workspace",
				"path",
				"lang",
				"kind",
				"shape",
				"name",
				"include_non_navigable",
			],
			positionals: 0,
			projection: true,
		},
		"symbol.detail" => VerbSpec {
			fields: &["workspace", "uri", "context_lines"],
			positionals: 1,
			projection: false,
		},
		"symbol.usages" => VerbSpec {
			fields: &["workspace", "uri", "direction", "path", "lang"],
			positionals: 1,
			projection: true,
		},
		"view.read" => VerbSpec {
			fields: &["uri", "scheme", "context_lines", "include_code"],
			positionals: 1,
			projection: false,
		},
		"rules.list" => VerbSpec {
			fields: &["workspace", "profile", "rules", "lang", "severity"],
			positionals: 0,
			projection: false,
		},
		"rules.check" => VerbSpec {
			fields: &["workspace", "profile", "rules", "file", "report"],
			positionals: 0,
			projection: false,
		},
		"change.review" => VerbSpec {
			fields: &["workspace"],
			positionals: 0,
			projection: false,
		},
		"symbol.graph" => VerbSpec {
			fields: &["workspace", "focus"],
			positionals: 1,
			projection: false,
		},
		"resolution.audit" => VerbSpec {
			fields: &["workspace", "prefix", "limit", "consistency"],
			positionals: 1,
			projection: false,
		},
		"identity.children" | "identity.graph" => VerbSpec {
			fields: &["workspace", "prefix"],
			positionals: 1,
			projection: false,
		},
		"notes" => VerbSpec {
			fields: &[
				"action",
				"id",
				"moniker",
				"kind",
				"status",
				"title",
				"body",
				"created_by",
				"orphan",
				"include_done",
			],
			positionals: 0,
			projection: false,
		},
		_ => return None,
	};
	Some(spec)
}

fn validate_fields(op: &str, spec: &VerbSpec, fields: &FieldBag) -> Result<(), QueryParseError> {
	for (key, value) in &fields.values {
		let key = key.as_str();
		if !COMMON_FIELDS.contains(&key) && !spec.fields.contains(&key) {
			return Err(QueryParseError::UnknownField {
				op: op.to_string(),
				key: key.to_string(),
				hint: field_hint(key, spec.fields),
			});
		}
		if BRACKET_LIST_FIELDS.contains(&key) && value.starts_with('[') != value.ends_with(']') {
			return Err(QueryParseError::InvalidValue {
				key: key.to_string(),
				value: value.clone(),
			});
		}
	}
	if let Some(extra) = fields.positional.get(spec.positionals) {
		return Err(QueryParseError::UnexpectedArgument {
			op: op.to_string(),
			value: extra.clone(),
		});
	}
	if !spec.projection && !fields.projection.is_empty() {
		return Err(QueryParseError::UnsupportedProjection { op: op.to_string() });
	}
	Ok(())
}

fn field_hint(key: &str, allowed: &'static [&'static str]) -> String {
	if let Some(suggestion) = suggest_field(key, allowed) {
		return format!(", did you mean `{suggestion}`?");
	}
	let mut valid: Vec<&str> = allowed.iter().chain(COMMON_FIELDS).copied().collect();
	valid.sort_unstable();
	format!(" (valid fields: {})", valid.join(", "))
}

fn suggest_field(key: &str, allowed: &'static [&'static str]) -> Option<&'static str> {
	const ALIASES: &[(&str, &str)] = &[("text", "name"), ("query", "name"), ("filename", "path")];
	for (alias, target) in ALIASES {
		if *alias == key && allowed.contains(target) {
			return Some(target);
		}
	}
	allowed
		.iter()
		.chain(COMMON_FIELDS)
		.copied()
		.map(|candidate| (candidate, levenshtein(key, candidate)))
		.filter(|(_, distance)| *distance <= 2)
		.min_by_key(|(_, distance)| *distance)
		.map(|(candidate, _)| candidate)
}

fn levenshtein(a: &str, b: &str) -> usize {
	let b: Vec<char> = b.chars().collect();
	let mut row: Vec<usize> = (0..=b.len()).collect();
	for (i, ca) in a.chars().enumerate() {
		let mut previous = row[0];
		row[0] = i + 1;
		for (j, cb) in b.iter().enumerate() {
			let substitution = previous + usize::from(ca != *cb);
			previous = row[j + 1];
			row[j + 1] = substitution.min(previous + 1).min(row[j] + 1);
		}
	}
	row[b.len()]
}

fn symbol_search_query(fields: &FieldBag) -> Result<SymbolSearchQuery, QueryParseError> {
	Ok(SymbolSearchQuery {
		workspace: fields.one("workspace"),
		text: fields.positional.first().cloned(),
		path: fields.many("path"),
		lang: fields.many("lang"),
		kind: fields.many("kind"),
		shape: fields.many("shape"),
		name: fields.one("name"),
		include_non_navigable: fields.bool("include_non_navigable")?.unwrap_or(false),
		include_code: fields.bool("include_code")?.unwrap_or(false),
		context_lines: fields.usize("context_lines")?.unwrap_or(0),
		projection: fields.projection.clone(),
	})
}

fn symbol_insights_query(fields: &FieldBag) -> Result<SymbolSearchQuery, QueryParseError> {
	let mut query = symbol_search_query(fields)?;
	query.text = None;
	query.include_code = false;
	query.context_lines = 0;
	Ok(query)
}

fn notes_query(fields: &FieldBag) -> Result<NotesQuery, QueryParseError> {
	Ok(NotesQuery {
		action: parse_notes_action(fields.one("action").as_deref().unwrap_or("list"))?,
		id: fields.one("id"),
		moniker: fields.one("moniker"),
		kind: fields.one("kind"),
		status: fields.one("status"),
		title: fields.one("title"),
		body: fields.one("body"),
		created_by: fields.one("created_by"),
		orphan: fields.bool("orphan")?,
		include_done: fields.bool("include_done")?.unwrap_or(false),
	})
}

fn identity_children_query(fields: &FieldBag) -> IdentityChildrenQuery {
	IdentityChildrenQuery {
		workspace: fields.one("workspace"),
		prefix: fields
			.one("prefix")
			.or_else(|| fields.positional.first().cloned())
			.unwrap_or_default(),
	}
}

fn symbol_graph_query(fields: &FieldBag) -> Result<SymbolGraphQuery, QueryParseError> {
	Ok(SymbolGraphQuery {
		workspace: fields.one("workspace"),
		focus: fields
			.one("focus")
			.or_else(|| fields.positional.first().cloned())
			.ok_or(QueryParseError::MissingRequired("focus"))?,
	})
}

fn parse_notes_action(value: &str) -> Result<NotesAction, QueryParseError> {
	match value {
		"list" => Ok(NotesAction::List),
		"get" => Ok(NotesAction::Get),
		"create" => Ok(NotesAction::Create),
		"update" => Ok(NotesAction::Update),
		"transition" => Ok(NotesAction::Transition),
		"delete" => Ok(NotesAction::Delete),
		_ => Err(QueryParseError::InvalidValue {
			key: "action".to_string(),
			value: value.to_string(),
		}),
	}
}

pub fn format_query_response(response: &QueryResponse) -> String {
	let mut out = String::new();
	if let Some(generation) = response.generation {
		let _ = writeln!(out, "generation: {}", generation.0);
	}
	if let Some(cursor) = &response.next_cursor {
		if let Some(generation) = cursor.generation {
			let _ = writeln!(out, "next_cursor: {}:{}", generation.0, cursor.offset);
		} else {
			let _ = writeln!(out, "next_cursor: {}", cursor.offset);
		}
	}
	match &response.result {
		QueryResult::WorkspaceStatus(status) => {
			let _ = writeln!(out, "workspace: {}", status.root);
			let _ = writeln!(out, "phase: {}", status.phase);
			let _ = writeln!(
				out,
				"files: {} symbols: {} references: {}",
				status.files, status.symbols, status.references
			);
			let _ = writeln!(out, "stale: {} ({})", status.stale, status.stale_summary);
			if status.roots.len() > 1 {
				let _ = writeln!(out, "roots:");
				for root in &status.roots {
					let _ = writeln!(
						out,
						"- {} files:{} symbols:{} references:{} stale:{}",
						root.root, root.files, root.symbols, root.references, root.stale
					);
				}
			}
		}
		QueryResult::TreeChildren(result) => {
			let _ = writeln!(out, "tree: {}", result.root);
			for row in &result.rows {
				let kind = match row.kind {
					TreeNodeKind::File => "file",
					TreeNodeKind::Directory => "dir",
				};
				let _ = writeln!(
					out,
					"- {kind} {} defs:{} refs:{}",
					row.path, row.defs, row.refs
				);
			}
		}
		QueryResult::SymbolList(result) => {
			let _ = writeln!(out, "symbols: {}", result.total);
			for row in &result.rows {
				let _ = writeln!(out, "- {} {} {} {}", row.kind, row.name, row.file, row.uri);
			}
		}
		QueryResult::SymbolInsights(result) => format_symbol_insights(&mut out, result),
		QueryResult::SymbolDetail(result) => {
			let symbol = &result.symbol;
			let _ = writeln!(out, "symbol: {} {}", symbol.kind, symbol.name);
			let _ = writeln!(out, "uri: {}", symbol.uri);
			let _ = writeln!(out, "file: {}", symbol.file);
			if let Some(source) = &result.source {
				for line in &source.lines {
					let _ = writeln!(out, "{:>6} | {}", line.number, line.text);
				}
			}
		}
		QueryResult::SymbolUsages(result) => {
			let _ = writeln!(out, "uri: {}", result.target.uri);
			let _ = writeln!(out, "direction: {}", result.direction.as_str());
			let _ = writeln!(out, "usages: {}", result.total);
			for row in &result.rows {
				let _ = writeln!(
					out,
					"- {} {} {} {}",
					row.direction.as_str(),
					row.kind,
					row.actor,
					row.file
				);
			}
		}
		QueryResult::ViewRead(result) => match result {
			ViewReadResult::List(list) => {
				let _ = writeln!(out, "views: {}", list.views.len());
				for view in &list.views {
					let _ = writeln!(out, "- {} ({})", view.id, view.scope);
				}
			}
			ViewReadResult::Detail(detail) => {
				let _ = writeln!(out, "view: {}", detail.id);
				let _ = writeln!(out, "fragment: {}", detail.fragment);
				let _ = writeln!(out, "scope: {}", detail.scope);
				let _ = writeln!(
					out,
					"rules: {} boundaries: {} gotchas: {}",
					detail.rules.len(),
					detail.boundaries.len(),
					detail.gotchas.len()
				);
			}
		},
		QueryResult::RulesList(result) => {
			let _ = writeln!(out, "rules: {}", result.total);
			format_rules_list_rows(&mut out, result);
		}
		QueryResult::RulesCheck(result) => format_rules_check(&mut out, result),
		QueryResult::ChangeReview(result) => format_change_review(&mut out, result),
		QueryResult::SymbolGraph(result) => format_symbol_graph(&mut out, result),
		QueryResult::IdentityChildren(result) => format_identity_children(&mut out, result),
		QueryResult::IdentityGraph(result) => format_identity_graph(&mut out, result),
		QueryResult::ResolutionAudit(result) => format_resolution_audit(&mut out, result),
		QueryResult::Notes(result) => format_notes(&mut out, result),
	}
	out
}

fn format_resolution_audit(out: &mut String, result: &ResolutionAuditResult) {
	let t = &result.totals;
	if !result.prefix.is_empty() {
		let _ = writeln!(out, "prefix: {}", result.prefix);
	}
	let _ = writeln!(
		out,
		"refs: {} resolved: {} external: {} blocked: {} unresolved: {} name_match_resolved: {}",
		t.references, t.resolved, t.external, t.blocked, t.unresolved, t.name_match_resolved
	);
	let _ = writeln!(out, "clusters:");
	for cluster in &result.clusters {
		let _ = writeln!(out, "- [{:>6}] {}", cluster.count, cluster.pattern);
		if let Some(sample) = cluster.samples.first() {
			let _ = writeln!(
				out,
				"           ex: {} {} -> {}",
				sample.call_name, sample.receiver, sample.target
			);
		}
	}
	let _ = writeln!(out, "zones:");
	for zone in &result.zones {
		let _ = writeln!(
			out,
			"- [{:>5}] {} — {}",
			zone.unresolved, zone.zone, zone.dominant_pattern
		);
	}
}

fn format_symbol_insights(out: &mut String, result: &SymbolInsightsResult) {
	let _ = writeln!(out, "files: {}", result.files);
	let _ = writeln!(out, "symbols: {}", result.symbols);
	let _ = writeln!(out, "refs: {}", result.references);
	let _ = writeln!(out, "languages:");
	for row in &result.languages {
		let _ = writeln!(out, "- {}: {}", row.name, row.count);
	}
}

fn format_notes(out: &mut String, result: &NotesResult) {
	let _ = writeln!(out, "action: {}", result.action);
	let _ = writeln!(out, "notes: {}", result.total);
	for row in &result.rows {
		let _ = writeln!(out, "- {} [{}] {}", row.id, row.status, row.title);
	}
}

fn format_rules_list_rows(out: &mut String, result: &RulesListResult) {
	for row in &result.rows {
		let _ = writeln!(
			out,
			"- {} [{}] root={} lang={} domain={}",
			row.id, row.severity, row.root, row.lang, row.domain
		);
		if let Some(message) = &row.message {
			let _ = writeln!(out, "  message: {message}");
		}
	}
}

fn format_identity_children(out: &mut String, result: &IdentityChildrenResult) {
	let prefix = if result.prefix.is_empty() {
		"<root>"
	} else {
		&result.prefix
	};
	let _ = writeln!(out, "prefix: {prefix}");
	let _ = writeln!(out, "children: {}", result.children.len());
	for child in &result.children {
		let marker = if child.symbol.is_some() { "def" } else { "…" };
		let _ = writeln!(
			out,
			"- {} [{}] defs={} {}",
			child.segment, marker, child.defs, child.identity
		);
	}
}

fn format_unlinked(out: &mut String, unlinked: &UnlinkedRefsDto) {
	let _ = writeln!(
		out,
		"unlinked refs: external {} · manifest-blocked {} · unresolved {}",
		unlinked.external, unlinked.manifest_blocked, unlinked.unresolved
	);
	if !unlinked.unresolved_reasons.is_empty() {
		let reasons = unlinked
			.unresolved_reasons
			.iter()
			.map(|(reason, count)| format!("{reason} {count}"))
			.collect::<Vec<_>>()
			.join(" · ");
		let _ = writeln!(out, "unresolved by reason: {reasons}");
	}
}

fn format_identity_graph(out: &mut String, result: &IdentityGraphResult) {
	let prefix = if result.prefix.is_empty() {
		"<root>"
	} else {
		&result.prefix
	};
	let _ = writeln!(out, "scope: {prefix}");
	let _ = writeln!(
		out,
		"nodes: {} edges: {}",
		result.nodes.len(),
		result.edges.len()
	);
	format_unlinked(out, &result.unlinked);
	for edge in &result.edges {
		let _ = writeln!(
			out,
			"- {} -> {} x{} [{}]",
			edge.source,
			edge.target,
			edge.count,
			edge.kinds.join(",")
		);
	}
	for port in &result.ports_in {
		let _ = writeln!(
			out,
			"< {} x{} [{}]",
			port.identity,
			port.count,
			port.kinds.join(",")
		);
	}
	for port in &result.ports_out {
		let _ = writeln!(
			out,
			"> {} x{} [{}]",
			port.identity,
			port.count,
			port.kinds.join(",")
		);
	}
}

fn format_symbol_graph(out: &mut String, result: &SymbolGraphResult) {
	match &result.focus {
		SymbolGraphFocus::Symbol { symbol } => {
			let _ = writeln!(
				out,
				"focus: {} {} ({})",
				symbol.kind, symbol.name, symbol.file
			);
		}
		SymbolGraphFocus::File { path } => {
			let _ = writeln!(out, "focus: file {path}");
		}
	}
	let _ = writeln!(
		out,
		"members: {} internal edges: {}",
		result.members.len(),
		result.internal_edges.len()
	);
	format_unlinked(out, &result.unlinked);
	for caller in &result.callers {
		let _ = writeln!(
			out,
			"< {} {} ({}) x{} [{}]",
			caller.symbol.kind,
			caller.symbol.name,
			caller.symbol.file,
			caller.count,
			caller.kinds.join(",")
		);
	}
	for callee in &result.callees {
		let _ = writeln!(
			out,
			"> {} {} ({}) x{} [{}]",
			callee.symbol.kind,
			callee.symbol.name,
			callee.symbol.file,
			callee.count,
			callee.kinds.join(",")
		);
	}
}

fn format_change_review(out: &mut String, result: &ChangeReviewResult) {
	let _ = writeln!(out, "scope: {}", result.scope);
	let _ = writeln!(
		out,
		"files: {} ({} analyzable) symbols: {} refs: {} ({} retargeted) residual: {}",
		result.summary.files,
		result.summary.analyzable_files,
		result.summary.symbol_changes,
		result.summary.ref_changes,
		result.summary.retargeted_refs,
		result.summary.residual_files
	);
	for file in &result.files {
		let path = match (&file.old_path, &file.new_path) {
			(Some(old), Some(new)) if old != new => format!("{old} -> {new}"),
			(_, Some(new)) => new.clone(),
			(Some(old), None) => old.clone(),
			(None, None) => "<unknown>".to_string(),
		};
		let _ = writeln!(
			out,
			"- {path} {}{}{}",
			file.disposition,
			if file.analyzable {
				""
			} else {
				" (not analyzable)"
			},
			if file.coverage_explained {
				""
			} else {
				" [residual]"
			}
		);
	}
	for change in &result.symbol_changes {
		let side = change.new.as_ref().or(change.old.as_ref());
		let Some(side) = side else { continue };
		let _ = writeln!(
			out,
			"  {} {} {} [{}]",
			change.kind, side.kind, side.name, change.confidence
		);
	}
	for diagnostic in &result.diagnostics {
		let _ = writeln!(out, "diagnostic: {diagnostic}");
	}
}

fn format_rules_check(out: &mut String, result: &RulesCheckResult) {
	let _ = writeln!(out, "exit: {}", result.exit);
	let _ = writeln!(
		out,
		"violations: {} errors: {} elapsed_ms: {}",
		result.summary.total_violations, result.summary.total_errors, result.summary.elapsed_ms
	);
	for violation in &result.violations {
		let _ = writeln!(
			out,
			"- {} {}:{}-{} [{}] {}",
			violation.root,
			violation.path,
			violation.lines.0,
			violation.lines.1,
			violation.rule_id,
			violation.message
		);
	}
	if !result.rule_reports.is_empty() {
		let _ = writeln!(out, "rule_reports: {}", result.rule_reports.len());
	}
}

#[derive(Default)]
struct FieldBag {
	values: Vec<(String, String)>,
	positional: Vec<String>,
	projection: Vec<String>,
	consistency: Consistency,
}

impl FieldBag {
	fn bool(&self, key: &str) -> Result<Option<bool>, QueryParseError> {
		self.one(key)
			.map(|value| match value.as_str() {
				"true" => Ok(true),
				"false" => Ok(false),
				_ => Err(QueryParseError::InvalidValue {
					key: key.to_string(),
					value,
				}),
			})
			.transpose()
	}

	fn page(&self) -> Result<Page, QueryParseError> {
		let limit = self.usize("limit")?.unwrap_or(80);
		let cursor = self
			.one("cursor")
			.map(|value| parse_cursor(&value))
			.transpose()?;
		Ok(Page { cursor, limit })
	}

	fn usize(&self, key: &str) -> Result<Option<usize>, QueryParseError> {
		self.one(key)
			.map(|value| {
				value
					.parse::<usize>()
					.map_err(|_| QueryParseError::InvalidValue {
						key: key.to_string(),
						value,
					})
			})
			.transpose()
	}

	fn one(&self, key: &str) -> Option<String> {
		self.many(key).into_iter().next()
	}

	fn many(&self, key: &str) -> Vec<String> {
		self.values
			.iter()
			.filter(|(candidate, _)| candidate == key)
			.flat_map(|(_, value)| split_csv(strip_bracket_list(key, value)))
			.collect()
	}
}

fn collect_tokens(
	tokens: &[String],
	fields: &mut FieldBag,
	positional: &mut Vec<String>,
) -> Result<(), QueryParseError> {
	for token in tokens {
		if let Some((key, value)) = token.split_once(':') {
			fields.values.push((key.to_string(), value.to_string()));
		} else {
			positional.push(token.trim_end_matches(',').to_string());
		}
	}
	Ok(())
}

fn parse_cursor(value: &str) -> Result<QueryCursor, QueryParseError> {
	let Some((generation, offset)) = value.split_once(':') else {
		return Err(QueryParseError::InvalidValue {
			key: "cursor".to_string(),
			value: value.to_string(),
		});
	};
	let generation = generation
		.parse::<u64>()
		.map_err(|_| QueryParseError::InvalidValue {
			key: "cursor".to_string(),
			value: value.to_string(),
		})?;
	let offset = offset
		.parse::<usize>()
		.map_err(|_| QueryParseError::InvalidValue {
			key: "cursor".to_string(),
			value: value.to_string(),
		})?;
	Ok(QueryCursor::new(
		offset,
		Some(WorkspaceGeneration(generation)),
	))
}

fn tokenize(input: &str) -> Result<Vec<String>, QueryParseError> {
	let mut tokens = Vec::new();
	let mut current = String::new();
	let mut chars = input.chars().peekable();
	let mut quoted = false;
	while let Some(ch) = chars.next() {
		match ch {
			'"' => {
				quoted = !quoted;
			}
			'\\' if quoted => {
				if let Some(next) = chars.next() {
					current.push(next);
				}
			}
			ch if ch.is_whitespace() && !quoted => {
				if !current.is_empty() {
					tokens.push(std::mem::take(&mut current));
				}
			}
			ch => current.push(ch),
		}
	}
	if quoted {
		return Err(QueryParseError::InvalidToken(input.to_string()));
	}
	if !current.is_empty() {
		tokens.push(current);
	}
	Ok(tokens)
}

// `shape:[callable,type]` list sugar, restricted to enum-like fields so glob
// character classes in `path:`/`file:` values stay untouched.
fn strip_bracket_list<'a>(key: &str, value: &'a str) -> &'a str {
	if !BRACKET_LIST_FIELDS.contains(&key) {
		return value;
	}
	value
		.strip_prefix('[')
		.and_then(|inner| inner.strip_suffix(']'))
		.unwrap_or(value)
}

pub fn split_csv(value: &str) -> Vec<String> {
	value
		.split(',')
		.map(str::trim)
		.filter(|entry| !entry.is_empty())
		.map(ToOwned::to_owned)
		.collect()
}

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

	#[test]
	fn parses_human_symbol_search() {
		let query = parse_query(
			r#"symbol.search "SharedWorkspaceIndex"
  filter path:"crates/**" shape:type
  project name, kind, uri
  page limit:20 cursor:7:40"#,
		)
		.expect("query");
		assert_eq!(query.page.limit, 20);
		assert_eq!(
			query.page.cursor,
			Some(QueryCursor::new(40, Some(WorkspaceGeneration(7))))
		);
		match query.query {
			Query::SymbolSearch(search) => {
				assert_eq!(search.text.as_deref(), Some("SharedWorkspaceIndex"));
				assert_eq!(search.path, vec!["crates/**"]);
				assert_eq!(search.shape, vec!["type"]);
				assert_eq!(search.projection, vec!["name", "kind", "uri"]);
			}
			other => panic!("unexpected query {other:?}"),
		}
	}

	#[test]
	fn parses_rules_check_consistency() {
		let query = parse_query(
			r#"rules.check profile:"agent"
  consistency refresh-if-stale
  page limit:50"#,
		)
		.expect("query");
		assert_eq!(query.consistency, Consistency::RefreshIfStale);
		assert_eq!(query.page.limit, 50);
	}

	#[test]
	fn rejects_offset_only_human_cursor() {
		let error =
			parse_query("symbol.search Customer\npage cursor:40").expect_err("offset-only cursor");
		assert!(matches!(
			error,
			QueryParseError::InvalidValue { ref key, .. } if key == "cursor"
		));
	}

	#[test]
	fn parses_bracket_list_shape() {
		let query = parse_query("symbol.search shape:[callable,type] limit:5").expect("query");
		match query.query {
			Query::SymbolSearch(search) => assert_eq!(search.shape, vec!["callable", "type"]),
			other => panic!("unexpected query {other:?}"),
		}
	}

	#[test]
	fn rejects_unterminated_bracket_list() {
		let error = parse_query("symbol.search shape:[callable").expect_err("unterminated list");
		assert!(matches!(
			error,
			QueryParseError::InvalidValue { ref key, .. } if key == "shape"
		));
	}

	#[test]
	fn rejects_unknown_field_with_alias_suggestion() {
		let error = parse_query(r#"symbol.search text:"foo""#).expect_err("unknown field");
		let message = error.to_string();
		assert!(
			message.contains("unknown field `text` for `symbol.search`"),
			"{message}"
		);
		assert!(message.contains("did you mean `name`?"), "{message}");
	}

	#[test]
	fn rejects_typo_field_with_suggestion() {
		let error = parse_query("rules.check profil:agent").expect_err("typo field");
		let message = error.to_string();
		assert!(message.contains("did you mean `profile`?"), "{message}");
	}

	#[test]
	fn lists_valid_fields_without_close_match() {
		let error = parse_query("change.review foobarbaz:1").expect_err("unknown field");
		let message = error.to_string();
		assert!(
			message.contains("valid fields: consistency, cursor, limit, workspace"),
			"{message}"
		);
	}

	#[test]
	fn rejects_unexpected_positional() {
		let error = parse_query("workspace.status extra").expect_err("positional");
		assert!(matches!(
			error,
			QueryParseError::UnexpectedArgument { ref value, .. } if value == "extra"
		));
	}

	#[test]
	fn rejects_projection_on_unsupported_verb() {
		let error = parse_query("rules.list\nproject name").expect_err("projection");
		assert!(matches!(
			error,
			QueryParseError::UnsupportedProjection { .. }
		));
	}

	#[test]
	fn parses_inline_consistency() {
		let query =
			parse_query("rules.check profile:agent consistency:refresh-if-stale").expect("query");
		assert_eq!(query.consistency, Consistency::RefreshIfStale);
	}

	#[test]
	fn formats_generation_aware_cursor() {
		let response = QueryResponse {
			generation: Some(WorkspaceGeneration(7)),
			result: QueryResult::SymbolList(SymbolListResult {
				rows: Vec::new(),
				total: 0,
			}),
			next_cursor: Some(QueryCursor::new(40, Some(WorkspaceGeneration(7)))),
		};
		let formatted = format_query_response(&response);
		assert!(formatted.contains("next_cursor: 7:40"));
	}
}

/// Umbrella over every root RPC type, used only to emit a single JSON Schema
/// document (`export-schema`) whose definitions cover the whole wire contract.
#[cfg(feature = "schema")]
#[derive(schemars::JsonSchema)]
#[allow(dead_code)]
pub struct DaemonProtocol {
	pub handshake: HandshakeResponse,
	pub registry_entry: DaemonRegistryEntry,
	pub workspace_config: DaemonWorkspaceConfig,
	pub query_request: QueryRequest,
	pub query: Query,
	pub query_response: QueryResponse,
	pub query_result: QueryResult,
	pub command_request: CommandRequest,
	pub command_response: CommandResponse,
	pub event: WorkspaceEventDto,
	pub error: QueryError,
}

#[cfg(test)]
mod contract_tests {
	//! Lock the serde wire shapes the JSON Schema (and every generated client)
	//! depends on. These guard the contract, not the Rust layout.
	use super::*;
	use serde_json::json;

	#[test]
	fn query_is_op_tagged() {
		let query = Query::SymbolSearch(SymbolSearchQuery {
			text: Some("widget".to_string()),
			..Default::default()
		});
		let value = serde_json::to_value(&query).unwrap();
		assert_eq!(value["op"], "symbol_search");
		assert_eq!(value["text"], "widget");
	}

	#[test]
	fn query_result_is_kind_and_data_tagged() {
		let result = QueryResult::SymbolList(SymbolListResult {
			rows: Vec::new(),
			total: 0,
		});
		assert_eq!(
			serde_json::to_value(&result).unwrap(),
			json!({ "kind": "symbol_list", "data": { "rows": [], "total": 0 } }),
		);
	}

	#[test]
	fn generation_serializes_as_scalar() {
		assert_eq!(
			serde_json::to_value(WorkspaceGeneration(7)).unwrap(),
			json!(7)
		);
	}

	#[test]
	fn line_range_is_a_two_element_array() {
		let range: Option<(u32, u32)> = Some((3, 9));
		assert_eq!(serde_json::to_value(range).unwrap(), json!([3, 9]));
		assert_eq!(
			serde_json::to_value(Option::<(u32, u32)>::None).unwrap(),
			json!(null)
		);
	}

	#[test]
	fn consistency_is_snake_case() {
		assert_eq!(
			serde_json::to_value(Consistency::RefreshIfStale).unwrap(),
			json!("refresh_if_stale"),
		);
	}

	#[test]
	fn event_kind_is_snake_case() {
		let event = WorkspaceEventDto {
			kind: WorkspaceEventKind::GitBase,
			generation: None,
			stale_summary: None,
		};
		assert_eq!(serde_json::to_value(&event).unwrap()["kind"], "git_base");
	}
}