blit-remote 0.44.0

Remote blit protocol, frame state, and callback DOM renderer
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
//! Language intelligence wire protocol (docs/design/lsp.md).
//!
//! The server terminates LSP and projects it into blit-native records:
//! per-backend phase/capabilities are *pushed* as whole-snapshot
//! `LSP_STATE` messages ([`LspStateMirror`]), diagnostics are *pushed* as
//! per-file replacement sets against a server-held cache
//! ([`LspDiagMirror`]), and point-in-time answers are *pulled* through the
//! single nonce-correlated `LSP_QUERY` opcode whose `kind` byte selects
//! the operation.
//!
//! Positions are 0-based lines with UTF-8 byte columns in both
//! directions; the server transcodes to each backend's negotiated
//! encoding. All integers little-endian, tightly packed, as everywhere in
//! the protocol.

use std::collections::BTreeMap;

/// `S2C_HELLO` feature bit: server supports the `LSP_*` message family.
pub const FEATURE_LSP: u32 = 1 << 8;

// C2S opcodes.

/// Attach to the workspace containing a path: [0x60][nonce:2][flags:1][diag_latency_ms:2][path_len:2][path:N]
/// `path` is plain UTF-8 (client-chosen filesystem location, like
/// `FS_SYNC`); the server walks upward for root markers.
pub const C2S_LSP_OPEN: u8 = 0x60;
/// Release an attachment (backends stay warm): [0x61][lsp_id:2]
pub const C2S_LSP_CLOSE: u8 = 0x61;
/// Acknowledge a pushed update: [0x62][lsp_id:2][stream:1][update_id:4]
/// `stream` is [`LSP_STREAM_STATE`] or [`LSP_STREAM_DIAG`].
pub const C2S_LSP_ACK: u8 = 0x62;
/// Point-in-time query: [0x63][nonce:2][lsp_id:2][kind:1][flags:1][line:4][col:4][path_len:2][path:N][arg_len:2][arg:N]
/// `kind` is one of `LSP_QUERY_*`; `line`/`col` are ignored by the symbol
/// kinds (for `WS_SYMBOLS` the `line` field is reserved as a future
/// SymbolKind bitmask filter); `arg` carries the `WS_SYMBOLS` query
/// string or the `RENAME` new name.
pub const C2S_LSP_QUERY: u8 = 0x63;
/// Advisory cancel of an in-flight query: [0x64][nonce:2]
pub const C2S_LSP_CANCEL: u8 = 0x64;
/// Enumerate every live backend, daemon-wide: [0x65][nonce:2]
pub const C2S_LSP_SERVERS: u8 = 0x65;
/// Shut one backend down by `server_ref`: [0x66][nonce:2][server_ref:2]
/// A later query respawns it; observability before force.
pub const C2S_LSP_STOP: u8 = 0x66;
/// Buffer overlay: [0x67][lsp_id:2][flags:1][path_len:2][path:N][text:LZ4]
/// The full live buffer of an open editor (emitted-form path, like query
/// paths); while overlaid, the engine's byte source for the document is
/// the overlay, not disk (docs/design/lsp.md "LSP_BUFFER"). Flags bit 0
/// [`LSP_BUFFER_RELEASE`] drops the overlay (`text` empty). No reply:
/// idempotent last-writer-wins state on an ordered transport.
pub const C2S_LSP_BUFFER: u8 = 0x67;

// S2C opcodes.

/// Open outcome: [0x60][nonce:2][lsp_id:2][status:1][flags:1][root_len:2][root:N][detail_len:2][detail:N]
/// On failure `lsp_id` = [`LSP_ID_INVALID`] and `detail` carries a
/// diagnostic; on success `root` is the canonical workspace root,
/// escaped.
pub const S2C_LSP_OPENED: u8 = 0x60;
/// Whole-state snapshot: [0x61][lsp_id:2][state_id:4][flags:1][records:LZ4]
/// One `SERVER` record per live backend of the attachment.
pub const S2C_LSP_STATE: u8 = 0x61;
/// Diagnostics update: [0x62][lsp_id:2][update_id:4][flags:1][records:LZ4]
/// Per-file replacement sets; bit 0 [`LSP_DIAG_FULL`] carries the
/// complete workspace state (drop everything, then apply).
pub const S2C_LSP_DIAG: u8 = 0x62;
/// Query response: [0x63][nonce:2][status:1][flags:1][detail_len:2][detail:N][records:LZ4]
/// `detail` is a human-readable failure reason (empty on success).
pub const S2C_LSP_QUERY: u8 = 0x63;
/// Attachment ended server-side: [0x64][lsp_id:2][reason:1]
pub const S2C_LSP_CLOSED: u8 = 0x64;
/// Backend enumeration: [0x65][nonce:2][status:1][flags:1][records:LZ4]
/// `SERVER` records as in `LSP_STATE` plus the escaped root.
pub const S2C_LSP_SERVERS: u8 = 0x65;
/// Stop outcome: [0x66][nonce:2][status:1]
pub const S2C_LSP_STOPPED: u8 = 0x66;

// Unified status table (docs/design/lsp.md "Statuses"): the git.md codes
// 0-9 with the same numbers and semantics where they overlap, plus
// WARMING.
pub const LSP_STATUS_OK: u8 = 0;
/// `lsp_id` unknown or already closed.
pub const LSP_STATUS_UNKNOWN_ID: u8 = 1;
/// Path, symbol, or backend does not exist; discovery failures name the
/// missing binary in the detail field.
pub const LSP_STATUS_NOT_FOUND: u8 = 2;
/// The element cannot answer this query (e.g. rename on a non-symbol).
pub const LSP_STATUS_WRONG_TYPE: u8 = 3;
pub const LSP_STATUS_PERMISSION: u8 = 4;
/// Over a size cap; truncation flags cover the paginatable cases.
pub const LSP_STATUS_TOO_LARGE: u8 = 5;
/// A budget was exhausted with no way to truncate.
pub const LSP_STATUS_BUDGET: u8 = 6;
/// Malformed request (unknown flags, kind, or field combination).
pub const LSP_STATUS_INVALID: u8 = 7;
/// Ended by `LSP_CANCEL`.
pub const LSP_STATUS_CANCELLED: u8 = 8;
/// Diagnostic in the message's detail field where it has one.
pub const LSP_STATUS_OTHER: u8 = 9;
/// The backing server has not finished initialize/indexing; retryable.
pub const LSP_STATUS_WARMING: u8 = 10;

/// Human-readable name for an `LSP_STATUS_*` code.
pub fn lsp_status_text(status: u8) -> &'static str {
    match status {
        LSP_STATUS_OK => "ok",
        LSP_STATUS_UNKNOWN_ID => "unknown attachment",
        LSP_STATUS_NOT_FOUND => "not found",
        LSP_STATUS_WRONG_TYPE => "wrong type",
        LSP_STATUS_PERMISSION => "permission denied",
        LSP_STATUS_TOO_LARGE => "too large",
        LSP_STATUS_BUDGET => "budget exhausted",
        LSP_STATUS_INVALID => "invalid request",
        LSP_STATUS_CANCELLED => "cancelled",
        LSP_STATUS_WARMING => "warming up",
        _ => "error",
    }
}

// C2S_LSP_OPEN flags.

/// Stream `LSP_STATE`.
pub const LSP_OPEN_WATCH: u8 = 1 << 0;
/// Stream `LSP_DIAG`; implies `WATCH`.
pub const LSP_OPEN_DIAGS: u8 = 1 << 1;
/// Resolve the workspace path from a pty's live cwd: a trailing
/// `[src_pty_id:2]` names a pty and the server joins `path` onto its cwd
/// before the root-marker walk (docs/ide.md Decision 3).
pub const LSP_OPEN_FROM_PTY: u8 = 1 << 2;

/// `lsp_id` value reporting an open failure.
pub const LSP_ID_INVALID: u16 = 0xFFFF;

// C2S_LSP_ACK streams.

pub const LSP_STREAM_STATE: u8 = 0;
pub const LSP_STREAM_DIAG: u8 = 1;

// C2S_LSP_QUERY kinds.

/// → `LOCATION` records.
pub const LSP_QUERY_DEFINITION: u8 = 1;
/// → `LOCATION` records; flags bit 0 [`LSP_REFS_INCLUDE_DECLARATION`].
pub const LSP_QUERY_REFERENCES: u8 = 2;
/// → one `MARKUP` record (plus an optional `LOCATION` for the range).
pub const LSP_QUERY_HOVER: u8 = 3;
/// → `SYMBOL` records, pre-order; `line`/`col` ignored.
pub const LSP_QUERY_DOC_SYMBOLS: u8 = 4;
/// → `SYMBOL` records; `path` empty, `arg` = query string.
pub const LSP_QUERY_WS_SYMBOLS: u8 = 5;
/// → `EDIT` records; `arg` = new name. Data, never applied.
pub const LSP_QUERY_RENAME: u8 = 6;
/// → `COMPLETION` records; the response's [`LSP_RESP_INCOMPLETE`] flag
/// mirrors the server's `isIncomplete` (retype should re-query).
pub const LSP_QUERY_COMPLETION: u8 = 7;
/// → `SIGNATURE` records, active signature first.
pub const LSP_QUERY_SIGNATURE: u8 = 8;

// C2S_LSP_QUERY flags.

/// `REFERENCES`: include the declaration itself.
pub const LSP_REFS_INCLUDE_DECLARATION: u8 = 1 << 0;

// C2S_LSP_BUFFER flags.

/// Drop the overlay and revert the document to disk truth (`text` must
/// be empty).
pub const LSP_BUFFER_RELEASE: u8 = 1 << 0;

// S2C_LSP_DIAG flags.

/// The update carries complete workspace diagnostic state: drop
/// everything, then apply. Every `DIAGS` subscribe begins with one (the
/// cache replay), and the server may send one at any time instead of an
/// incremental update.
pub const LSP_DIAG_FULL: u8 = 1 << 0;

// S2C response flags (query, state, diag, servers).

/// The entries budget was hit; records present are valid.
pub const LSP_RESP_TRUNCATED: u8 = 1 << 0;
/// A `RENAME` plan dropped file operations it cannot project (create /
/// rename / delete of whole files in a `WorkspaceEdit`): the returned
/// `EDIT` records are the text edits only, so the plan is incomplete.
pub const LSP_RESP_INCOMPLETE: u8 = 1 << 1;

// S2C_LSP_CLOSED reasons.

pub const LSP_CLOSED_CLIENT_REQUEST: u8 = 0;
pub const LSP_CLOSED_ROOT_GONE: u8 = 1;
pub const LSP_CLOSED_PERMISSION_LOST: u8 = 2;
pub const LSP_CLOSED_BACKEND_FAILED: u8 = 3;
pub const LSP_CLOSED_RESOURCE_LIMIT: u8 = 4;

// SERVER record phases.

pub const LSP_PHASE_SPAWNING: u8 = 0;
pub const LSP_PHASE_INITIALIZING: u8 = 1;
pub const LSP_PHASE_INDEXING: u8 = 2;
pub const LSP_PHASE_READY: u8 = 3;
pub const LSP_PHASE_FAILED: u8 = 4;

/// `progress_pct` value when the backend reports no percentage.
pub const LSP_PROGRESS_UNKNOWN: u8 = 255;

// SERVER record capability bits (`caps:4`), aligned with query kinds:
// bit `kind - 1`.

pub const LSP_CAP_DEFINITION: u32 = 1 << 0;
pub const LSP_CAP_REFERENCES: u32 = 1 << 1;
pub const LSP_CAP_HOVER: u32 = 1 << 2;
pub const LSP_CAP_DOC_SYMBOLS: u32 = 1 << 3;
pub const LSP_CAP_WS_SYMBOLS: u32 = 1 << 4;
pub const LSP_CAP_RENAME: u32 = 1 << 5;
pub const LSP_CAP_COMPLETION: u32 = 1 << 6;
pub const LSP_CAP_SIGNATURE: u32 = 1 << 7;

// COMPLETION record flags.

pub const LSP_COMPLETION_DEPRECATED: u8 = 1 << 0;
/// `insert` is LSP snippet syntax; a client without snippet UI degrades
/// it to plain text.
pub const LSP_COMPLETION_SNIPPET: u8 = 1 << 1;
pub const LSP_COMPLETION_PRESELECT: u8 = 1 << 2;

// SIGNATURE record flags.

/// The active signature (emitted first).
pub const LSP_SIGNATURE_ACTIVE: u8 = 1 << 0;

/// `SIGNATURE.active_param` value when no parameter is active.
pub const LSP_SIGNATURE_NO_PARAM: u16 = 0xFFFF;

// DIAG record severities (LSP values).

pub const LSP_SEVERITY_ERROR: u8 = 1;
pub const LSP_SEVERITY_WARNING: u8 = 2;
pub const LSP_SEVERITY_INFO: u8 = 3;
pub const LSP_SEVERITY_HINT: u8 = 4;

// DIAG record flags (LSP diagnostic tags).

pub const LSP_DIAG_UNNECESSARY: u8 = 1 << 0;
pub const LSP_DIAG_DEPRECATED: u8 = 1 << 1;

// MARKUP record formats.

pub const LSP_MARKUP_PLAIN: u8 = 0;
pub const LSP_MARKUP_MARKDOWN: u8 = 1;

// SYMBOL record flags.

pub const LSP_SYMBOL_DEPRECATED: u8 = 1 << 0;

// Record kinds, namespaced per message type.

pub const LSP_STATE_RECORD_SERVER: u8 = 0x01;
pub const LSP_DIAG_RECORD_FILE: u8 = 0x01;
pub const LSP_DIAG_RECORD_DIAG: u8 = 0x02;
pub const LSP_QUERY_RECORD_LOCATION: u8 = 0x01;
pub const LSP_QUERY_RECORD_MARKUP: u8 = 0x02;
pub const LSP_QUERY_RECORD_SYMBOL: u8 = 0x03;
pub const LSP_QUERY_RECORD_EDIT: u8 = 0x04;
pub const LSP_QUERY_RECORD_COMPLETION: u8 = 0x05;
pub const LSP_QUERY_RECORD_SIGNATURE: u8 = 0x06;

/// BLAKE3 truncated to 128 bits, as in the fs family: the content
/// version a record describes.
pub type LspHash = [u8; 16];

/// The all-zero hash: content version unknown.
pub const LSP_HASH_NONE: LspHash = [0; 16];

/// Decompress a `compress_prepend_size` payload, refusing declared sizes
/// over the protocol-wide [`crate::MAX_DECOMPRESSED`] *before* allocating
/// (docs/protocol.md "Compressed payloads").
fn decompress_guarded(data: &[u8]) -> Option<Vec<u8>> {
    if data.len() < 4 {
        return None;
    }
    let declared = u32::from_le_bytes(data[0..4].try_into().unwrap()) as usize;
    if declared > crate::MAX_DECOMPRESSED {
        return None;
    }
    lz4_flex::decompress_size_prepended(data).ok()
}

// ---------------------------------------------------------------------------
// Field codec helpers
// ---------------------------------------------------------------------------

fn push_str(buf: &mut Vec<u8>, s: &str) {
    let b = s.as_bytes();
    buf.extend_from_slice(&(b.len() as u16).to_le_bytes());
    buf.extend_from_slice(b);
}

/// A u32-length-prefixed byte string (diagnostic messages, markup, edit
/// text).
fn push_bytes(buf: &mut Vec<u8>, b: &[u8]) {
    buf.extend_from_slice(&(b.len() as u32).to_le_bytes());
    buf.extend_from_slice(b);
}

fn take_u8(b: &mut &[u8]) -> Option<u8> {
    let (&x, rest) = b.split_first()?;
    *b = rest;
    Some(x)
}

fn take_u16(b: &mut &[u8]) -> Option<u16> {
    if b.len() < 2 {
        return None;
    }
    let v = u16::from_le_bytes([b[0], b[1]]);
    *b = &b[2..];
    Some(v)
}

fn take_u32(b: &mut &[u8]) -> Option<u32> {
    if b.len() < 4 {
        return None;
    }
    let v = u32::from_le_bytes(b[0..4].try_into().unwrap());
    *b = &b[4..];
    Some(v)
}

fn take_u64(b: &mut &[u8]) -> Option<u64> {
    if b.len() < 8 {
        return None;
    }
    let v = u64::from_le_bytes(b[0..8].try_into().unwrap());
    *b = &b[8..];
    Some(v)
}

fn take_hash(b: &mut &[u8]) -> Option<LspHash> {
    if b.len() < 16 {
        return None;
    }
    let hash: LspHash = b[0..16].try_into().unwrap();
    *b = &b[16..];
    Some(hash)
}

fn take_str<'a>(b: &mut &'a [u8]) -> Option<&'a str> {
    let len = take_u16(b)? as usize;
    if b.len() < len {
        return None;
    }
    let s = std::str::from_utf8(&b[..len]).ok()?;
    *b = &b[len..];
    Some(s)
}

fn take_text<'a>(b: &mut &'a [u8]) -> Option<&'a str> {
    let len = take_u32(b)? as usize;
    if b.len() < len {
        return None;
    }
    let s = std::str::from_utf8(&b[..len]).ok()?;
    *b = &b[len..];
    Some(s)
}

/// Check `msg` starts with `opcode` and return the body after it.
fn body_of(msg: &[u8], opcode: u8) -> Option<&[u8]> {
    if msg.first() != Some(&opcode) {
        return None;
    }
    Some(&msg[1..])
}

// Record framing: [record_len:4][kind:1][…], unknown kinds skippable,
// malformed records end the payload.

fn begin_record(buf: &mut Vec<u8>) -> usize {
    let start = buf.len();
    buf.extend_from_slice(&0u32.to_le_bytes());
    start
}

fn end_record(buf: &mut [u8], start: usize) {
    let len = (buf.len() - start - 4) as u32;
    buf[start..start + 4].copy_from_slice(&len.to_le_bytes());
}

/// Pop the next record: `(kind, body)`. `None` ends iteration (clean end
/// or malformed framing).
fn next_record<'a>(data: &mut &'a [u8]) -> Option<(u8, &'a [u8])> {
    let mut b = *data;
    let len = take_u32(&mut b)? as usize;
    if b.len() < len || len == 0 {
        return None;
    }
    let record = &b[..len];
    *data = &b[len..];
    Some((record[0], &record[1..]))
}

// ---------------------------------------------------------------------------
// C2S message builders and parsers
// ---------------------------------------------------------------------------

pub fn msg_lsp_open(nonce: u16, flags: u8, diag_latency_ms: u16, path: &str) -> Vec<u8> {
    let mut msg = Vec::with_capacity(8 + path.len());
    msg.push(C2S_LSP_OPEN);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.push(flags);
    msg.extend_from_slice(&diag_latency_ms.to_le_bytes());
    push_str(&mut msg, path);
    msg
}

/// Build a `C2S_LSP_OPEN` whose workspace path the server resolves from a
/// pty's live cwd: sets `LSP_OPEN_FROM_PTY` and appends `[src_pty_id:2]`
/// after the path (docs/ide.md Decision 3).
pub fn msg_lsp_open_from_pty(
    nonce: u16,
    flags: u8,
    diag_latency_ms: u16,
    path: &str,
    src_pty_id: u16,
) -> Vec<u8> {
    let mut msg = msg_lsp_open(nonce, flags | LSP_OPEN_FROM_PTY, diag_latency_ms, path);
    msg.extend_from_slice(&src_pty_id.to_le_bytes());
    msg
}

/// Extract the trailing `src_pty_id` from a `FROM_PTY` `C2S_LSP_OPEN`.
pub fn lsp_open_src_pty(msg: &[u8]) -> Option<u16> {
    if msg.first().copied() != Some(C2S_LSP_OPEN) || msg.len() < 8 {
        return None;
    }
    if msg[3] & LSP_OPEN_FROM_PTY == 0 {
        return None;
    }
    let path_len = u16::from_le_bytes([msg[6], msg[7]]) as usize;
    let off = 8usize.checked_add(path_len)?;
    let b = msg.get(off..off + 2)?;
    Some(u16::from_le_bytes([b[0], b[1]]))
}

/// Rebase a `FROM_PTY` `C2S_LSP_OPEN` onto a resolved `cwd` (join `cwd`/`path`,
/// clear `FROM_PTY`), producing a plain path-based open the handler consumes
/// unchanged. `cwd` `None` (source pty gone) keeps `path` verbatim.
pub fn lsp_open_rebase(msg: &[u8], cwd: Option<&str>) -> Option<Vec<u8>> {
    lsp_open_src_pty(msg)?;
    let (nonce, flags, diag_ms, path) = parse_lsp_open(msg)?;
    let joined = cwd.map(|dir| {
        std::path::Path::new(dir)
            .join(path)
            .to_string_lossy()
            .into_owned()
    });
    let eff = joined.as_deref().unwrap_or(path);
    Some(msg_lsp_open(
        nonce,
        flags & !LSP_OPEN_FROM_PTY,
        diag_ms,
        eff,
    ))
}

/// Parse `C2S_LSP_OPEN` into `(nonce, flags, diag_latency_ms, path)`.
pub fn parse_lsp_open(msg: &[u8]) -> Option<(u16, u8, u16, &str)> {
    let mut b = body_of(msg, C2S_LSP_OPEN)?;
    let nonce = take_u16(&mut b)?;
    let flags = take_u8(&mut b)?;
    let diag_latency_ms = take_u16(&mut b)?;
    let path = take_str(&mut b)?;
    Some((nonce, flags, diag_latency_ms, path))
}

pub fn msg_lsp_close(lsp_id: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_LSP_CLOSE);
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg
}

pub fn parse_lsp_close(msg: &[u8]) -> Option<u16> {
    let mut b = body_of(msg, C2S_LSP_CLOSE)?;
    take_u16(&mut b)
}

pub fn msg_lsp_ack(lsp_id: u16, stream: u8, update_id: u32) -> Vec<u8> {
    let mut msg = Vec::with_capacity(8);
    msg.push(C2S_LSP_ACK);
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg.push(stream);
    msg.extend_from_slice(&update_id.to_le_bytes());
    msg
}

/// Parse `C2S_LSP_ACK` into `(lsp_id, stream, update_id)`.
pub fn parse_lsp_ack(msg: &[u8]) -> Option<(u16, u8, u32)> {
    let mut b = body_of(msg, C2S_LSP_ACK)?;
    let lsp_id = take_u16(&mut b)?;
    let stream = take_u8(&mut b)?;
    let update_id = take_u32(&mut b)?;
    Some((lsp_id, stream, update_id))
}

/// A decoded `C2S_LSP_QUERY` request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LspQueryRequest<'a> {
    pub nonce: u16,
    pub lsp_id: u16,
    /// One of `LSP_QUERY_*`.
    pub kind: u8,
    pub flags: u8,
    /// 0-based; ignored by the symbol kinds.
    pub line: u32,
    /// UTF-8 byte offset within the line; ignored by the symbol kinds.
    pub col: u32,
    /// Escaped form; empty for `WS_SYMBOLS`.
    pub path: &'a str,
    /// `WS_SYMBOLS` query string or `RENAME` new name; empty otherwise.
    pub arg: &'a str,
}

pub fn msg_lsp_query(req: &LspQueryRequest<'_>) -> Vec<u8> {
    let mut msg = Vec::with_capacity(19 + req.path.len() + req.arg.len());
    msg.push(C2S_LSP_QUERY);
    msg.extend_from_slice(&req.nonce.to_le_bytes());
    msg.extend_from_slice(&req.lsp_id.to_le_bytes());
    msg.push(req.kind);
    msg.push(req.flags);
    msg.extend_from_slice(&req.line.to_le_bytes());
    msg.extend_from_slice(&req.col.to_le_bytes());
    push_str(&mut msg, req.path);
    push_str(&mut msg, req.arg);
    msg
}

pub fn parse_lsp_query(msg: &[u8]) -> Option<LspQueryRequest<'_>> {
    let mut b = body_of(msg, C2S_LSP_QUERY)?;
    let nonce = take_u16(&mut b)?;
    let lsp_id = take_u16(&mut b)?;
    let kind = take_u8(&mut b)?;
    let flags = take_u8(&mut b)?;
    let line = take_u32(&mut b)?;
    let col = take_u32(&mut b)?;
    let path = take_str(&mut b)?;
    let arg = take_str(&mut b)?;
    Some(LspQueryRequest {
        nonce,
        lsp_id,
        kind,
        flags,
        line,
        col,
        path,
        arg,
    })
}

pub fn msg_lsp_cancel(nonce: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_LSP_CANCEL);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg
}

pub fn parse_lsp_cancel(msg: &[u8]) -> Option<u16> {
    let mut b = body_of(msg, C2S_LSP_CANCEL)?;
    take_u16(&mut b)
}

pub fn msg_lsp_servers(nonce: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(3);
    msg.push(C2S_LSP_SERVERS);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg
}

pub fn parse_lsp_servers(msg: &[u8]) -> Option<u16> {
    let mut b = body_of(msg, C2S_LSP_SERVERS)?;
    take_u16(&mut b)
}

pub fn msg_lsp_stop(nonce: u16, server_ref: u16) -> Vec<u8> {
    let mut msg = Vec::with_capacity(5);
    msg.push(C2S_LSP_STOP);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.extend_from_slice(&server_ref.to_le_bytes());
    msg
}

/// Parse `C2S_LSP_STOP` into `(nonce, server_ref)`.
pub fn parse_lsp_stop(msg: &[u8]) -> Option<(u16, u16)> {
    let mut b = body_of(msg, C2S_LSP_STOP)?;
    let nonce = take_u16(&mut b)?;
    let server_ref = take_u16(&mut b)?;
    Some((nonce, server_ref))
}

/// Build a `C2S_LSP_BUFFER`: `text` is the full buffer content,
/// LZ4-compressed on the wire. A [`LSP_BUFFER_RELEASE`] must carry empty
/// `text`.
pub fn msg_lsp_buffer(lsp_id: u16, flags: u8, path: &str, text: &[u8]) -> Vec<u8> {
    let compressed = lz4_flex::compress_prepend_size(text);
    let mut msg = Vec::with_capacity(6 + path.len() + compressed.len());
    msg.push(C2S_LSP_BUFFER);
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg.push(flags);
    push_str(&mut msg, path);
    msg.extend_from_slice(&compressed);
    msg
}

/// Parse `C2S_LSP_BUFFER` into `(lsp_id, flags, path, text)` with the
/// text decompressed.
pub fn parse_lsp_buffer(msg: &[u8]) -> Option<(u16, u8, &str, Vec<u8>)> {
    let mut b = body_of(msg, C2S_LSP_BUFFER)?;
    let lsp_id = take_u16(&mut b)?;
    let flags = take_u8(&mut b)?;
    let path = take_str(&mut b)?;
    let text = decompress_guarded(b)?;
    Some((lsp_id, flags, path, text))
}

// ---------------------------------------------------------------------------
// S2C message builders and parsers
// ---------------------------------------------------------------------------

pub fn msg_lsp_opened(
    nonce: u16,
    lsp_id: u16,
    status: u8,
    flags: u8,
    root: &str,
    detail: &str,
) -> Vec<u8> {
    let mut msg = Vec::with_capacity(11 + root.len() + detail.len());
    msg.push(S2C_LSP_OPENED);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg.push(status);
    msg.push(flags);
    push_str(&mut msg, root);
    push_str(&mut msg, detail);
    msg
}

/// A decoded `S2C_LSP_OPENED`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LspOpened<'a> {
    pub nonce: u16,
    pub lsp_id: u16,
    pub status: u8,
    pub flags: u8,
    /// Escaped canonical workspace root; empty on failure.
    pub root: &'a str,
    /// Diagnostic on failure.
    pub detail: &'a str,
}

pub fn parse_lsp_opened(msg: &[u8]) -> Option<LspOpened<'_>> {
    let mut b = body_of(msg, S2C_LSP_OPENED)?;
    let nonce = take_u16(&mut b)?;
    let lsp_id = take_u16(&mut b)?;
    let status = take_u8(&mut b)?;
    let flags = take_u8(&mut b)?;
    let root = take_str(&mut b)?;
    let detail = take_str(&mut b)?;
    Some(LspOpened {
        nonce,
        lsp_id,
        status,
        flags,
        root,
        detail,
    })
}

pub fn msg_lsp_state(lsp_id: u16, state_id: u32, flags: u8, records: &[u8]) -> Vec<u8> {
    let compressed = lz4_flex::compress_prepend_size(records);
    let mut msg = Vec::with_capacity(8 + compressed.len());
    msg.push(S2C_LSP_STATE);
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg.extend_from_slice(&state_id.to_le_bytes());
    msg.push(flags);
    msg.extend_from_slice(&compressed);
    msg
}

/// Parse `S2C_LSP_STATE` into `(lsp_id, state_id, flags, records)` with
/// the records decompressed.
pub fn parse_lsp_state(msg: &[u8]) -> Option<(u16, u32, u8, Vec<u8>)> {
    let mut b = body_of(msg, S2C_LSP_STATE)?;
    let lsp_id = take_u16(&mut b)?;
    let state_id = take_u32(&mut b)?;
    let flags = take_u8(&mut b)?;
    let records = decompress_guarded(b)?;
    Some((lsp_id, state_id, flags, records))
}

pub fn msg_lsp_diag(lsp_id: u16, update_id: u32, flags: u8, records: &[u8]) -> Vec<u8> {
    let compressed = lz4_flex::compress_prepend_size(records);
    let mut msg = Vec::with_capacity(8 + compressed.len());
    msg.push(S2C_LSP_DIAG);
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg.extend_from_slice(&update_id.to_le_bytes());
    msg.push(flags);
    msg.extend_from_slice(&compressed);
    msg
}

/// Parse `S2C_LSP_DIAG` into `(lsp_id, update_id, flags, records)` with
/// the records decompressed.
pub fn parse_lsp_diag(msg: &[u8]) -> Option<(u16, u32, u8, Vec<u8>)> {
    let mut b = body_of(msg, S2C_LSP_DIAG)?;
    let lsp_id = take_u16(&mut b)?;
    let update_id = take_u32(&mut b)?;
    let flags = take_u8(&mut b)?;
    let records = decompress_guarded(b)?;
    Some((lsp_id, update_id, flags, records))
}

pub fn msg_lsp_query_resp(
    nonce: u16,
    status: u8,
    flags: u8,
    detail: &str,
    records: &[u8],
) -> Vec<u8> {
    let compressed = lz4_flex::compress_prepend_size(records);
    let mut msg = Vec::with_capacity(7 + detail.len() + compressed.len());
    msg.push(S2C_LSP_QUERY);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.push(status);
    msg.push(flags);
    push_str(&mut msg, detail);
    msg.extend_from_slice(&compressed);
    msg
}

/// A decoded `S2C_LSP_QUERY` response.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LspQueryResp {
    pub nonce: u16,
    pub status: u8,
    pub flags: u8,
    /// Human-readable failure reason (e.g. the upstream server's own
    /// error message on `OTHER`); empty on success.
    pub detail: String,
    /// Decompressed response records.
    pub records: Vec<u8>,
}

/// Parse `S2C_LSP_QUERY` with the records decompressed.
pub fn parse_lsp_query_resp(msg: &[u8]) -> Option<LspQueryResp> {
    let mut b = body_of(msg, S2C_LSP_QUERY)?;
    let nonce = take_u16(&mut b)?;
    let status = take_u8(&mut b)?;
    let flags = take_u8(&mut b)?;
    let detail = take_str(&mut b)?.to_string();
    let records = decompress_guarded(b)?;
    Some(LspQueryResp {
        nonce,
        status,
        flags,
        detail,
        records,
    })
}

pub fn msg_lsp_closed(lsp_id: u16, reason: u8) -> Vec<u8> {
    let mut msg = Vec::with_capacity(4);
    msg.push(S2C_LSP_CLOSED);
    msg.extend_from_slice(&lsp_id.to_le_bytes());
    msg.push(reason);
    msg
}

/// Parse `S2C_LSP_CLOSED` into `(lsp_id, reason)`.
pub fn parse_lsp_closed(msg: &[u8]) -> Option<(u16, u8)> {
    let mut b = body_of(msg, S2C_LSP_CLOSED)?;
    let lsp_id = take_u16(&mut b)?;
    let reason = take_u8(&mut b)?;
    Some((lsp_id, reason))
}

pub fn msg_lsp_servers_resp(nonce: u16, status: u8, flags: u8, records: &[u8]) -> Vec<u8> {
    let compressed = lz4_flex::compress_prepend_size(records);
    let mut msg = Vec::with_capacity(5 + compressed.len());
    msg.push(S2C_LSP_SERVERS);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.push(status);
    msg.push(flags);
    msg.extend_from_slice(&compressed);
    msg
}

/// Parse `S2C_LSP_SERVERS` into `(nonce, status, flags, records)` with
/// the records decompressed.
pub fn parse_lsp_servers_resp(msg: &[u8]) -> Option<(u16, u8, u8, Vec<u8>)> {
    let mut b = body_of(msg, S2C_LSP_SERVERS)?;
    let nonce = take_u16(&mut b)?;
    let status = take_u8(&mut b)?;
    let flags = take_u8(&mut b)?;
    let records = decompress_guarded(b)?;
    Some((nonce, status, flags, records))
}

pub fn msg_lsp_stopped(nonce: u16, status: u8) -> Vec<u8> {
    let mut msg = Vec::with_capacity(4);
    msg.push(S2C_LSP_STOPPED);
    msg.extend_from_slice(&nonce.to_le_bytes());
    msg.push(status);
    msg
}

/// Parse `S2C_LSP_STOPPED` into `(nonce, status)`.
pub fn parse_lsp_stopped(msg: &[u8]) -> Option<(u16, u8)> {
    let mut b = body_of(msg, S2C_LSP_STOPPED)?;
    let nonce = take_u16(&mut b)?;
    let status = take_u8(&mut b)?;
    Some((nonce, status))
}

// ---------------------------------------------------------------------------
// LSP_STATE records
// ---------------------------------------------------------------------------

/// One decoded record from an `LSP_STATE` payload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LspStateRecord<'a> {
    /// SERVER 0x01: [kind:1][server_ref:2][phase:1][progress_pct:1][caps:4]
    /// [epoch:4][refused_edits:4][rss:8][id_len:2][id:N][msg_len:2][msg:N]
    Server {
        /// Daemon-scoped backend id (`LSP_STOP` target).
        server_ref: u16,
        /// One of `LSP_PHASE_*`.
        phase: u8,
        /// 0-100, or [`LSP_PROGRESS_UNKNOWN`].
        progress_pct: u8,
        /// `LSP_CAP_*` bits.
        caps: u32,
        /// Increments on dynamic capability (re)registration.
        epoch: u32,
        /// `workspace/applyEdit` requests answered `applied:false`.
        refused_edits: u32,
        /// Best-effort resident set size in bytes; 0 = unknown.
        rss: u64,
        /// Server id from the discovery table (e.g. `rust-analyzer`).
        id: &'a str,
        /// Last progress or showMessage line.
        msg: &'a str,
    },
}

/// Append one record to an uncompressed `LSP_STATE` records buffer.
pub fn append_lsp_state_record(buf: &mut Vec<u8>, record: &LspStateRecord<'_>) {
    let start = begin_record(buf);
    match record {
        LspStateRecord::Server {
            server_ref,
            phase,
            progress_pct,
            caps,
            epoch,
            refused_edits,
            rss,
            id,
            msg,
        } => {
            buf.push(LSP_STATE_RECORD_SERVER);
            buf.extend_from_slice(&server_ref.to_le_bytes());
            buf.push(*phase);
            buf.push(*progress_pct);
            buf.extend_from_slice(&caps.to_le_bytes());
            buf.extend_from_slice(&epoch.to_le_bytes());
            buf.extend_from_slice(&refused_edits.to_le_bytes());
            buf.extend_from_slice(&rss.to_le_bytes());
            push_str(buf, id);
            push_str(buf, msg);
        }
    }
    end_record(buf, start);
}

pub struct LspStateRecordIter<'a> {
    data: &'a [u8],
}

/// Iterate records in an uncompressed `LSP_STATE` payload.
pub fn lsp_state_records(data: &[u8]) -> LspStateRecordIter<'_> {
    LspStateRecordIter { data }
}

impl<'a> Iterator for LspStateRecordIter<'a> {
    type Item = LspStateRecord<'a>;

    fn next(&mut self) -> Option<LspStateRecord<'a>> {
        loop {
            let (kind, mut b) = next_record(&mut self.data)?;
            match kind {
                LSP_STATE_RECORD_SERVER => {
                    let server_ref = take_u16(&mut b)?;
                    let phase = take_u8(&mut b)?;
                    let progress_pct = take_u8(&mut b)?;
                    let caps = take_u32(&mut b)?;
                    let epoch = take_u32(&mut b)?;
                    let refused_edits = take_u32(&mut b)?;
                    let rss = take_u64(&mut b)?;
                    let id = take_str(&mut b)?;
                    let msg = take_str(&mut b)?;
                    return Some(LspStateRecord::Server {
                        server_ref,
                        phase,
                        progress_pct,
                        caps,
                        epoch,
                        refused_edits,
                        rss,
                        id,
                        msg,
                    });
                }
                _ => continue, // unknown kind: skip via record_len
            }
        }
    }
}

// ---------------------------------------------------------------------------
// LSP_SERVERS records
// ---------------------------------------------------------------------------

/// One decoded record from an `LSP_SERVERS` payload: the `LSP_STATE`
/// `SERVER` layout plus the escaped workspace root.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LspServersRecord<'a> {
    /// SERVER 0x01: the `LSP_STATE` layout + [root_len:2][root:N]
    Server {
        server_ref: u16,
        phase: u8,
        progress_pct: u8,
        caps: u32,
        epoch: u32,
        refused_edits: u32,
        rss: u64,
        id: &'a str,
        msg: &'a str,
        /// Escaped canonical workspace root.
        root: &'a str,
    },
}

/// Append one record to an uncompressed `LSP_SERVERS` records buffer.
pub fn append_lsp_servers_record(buf: &mut Vec<u8>, record: &LspServersRecord<'_>) {
    let start = begin_record(buf);
    match record {
        LspServersRecord::Server {
            server_ref,
            phase,
            progress_pct,
            caps,
            epoch,
            refused_edits,
            rss,
            id,
            msg,
            root,
        } => {
            buf.push(LSP_STATE_RECORD_SERVER);
            buf.extend_from_slice(&server_ref.to_le_bytes());
            buf.push(*phase);
            buf.push(*progress_pct);
            buf.extend_from_slice(&caps.to_le_bytes());
            buf.extend_from_slice(&epoch.to_le_bytes());
            buf.extend_from_slice(&refused_edits.to_le_bytes());
            buf.extend_from_slice(&rss.to_le_bytes());
            push_str(buf, id);
            push_str(buf, msg);
            push_str(buf, root);
        }
    }
    end_record(buf, start);
}

pub struct LspServersRecordIter<'a> {
    data: &'a [u8],
}

/// Iterate records in an uncompressed `LSP_SERVERS` payload.
pub fn lsp_servers_records(data: &[u8]) -> LspServersRecordIter<'_> {
    LspServersRecordIter { data }
}

impl<'a> Iterator for LspServersRecordIter<'a> {
    type Item = LspServersRecord<'a>;

    fn next(&mut self) -> Option<LspServersRecord<'a>> {
        loop {
            let (kind, mut b) = next_record(&mut self.data)?;
            match kind {
                LSP_STATE_RECORD_SERVER => {
                    let server_ref = take_u16(&mut b)?;
                    let phase = take_u8(&mut b)?;
                    let progress_pct = take_u8(&mut b)?;
                    let caps = take_u32(&mut b)?;
                    let epoch = take_u32(&mut b)?;
                    let refused_edits = take_u32(&mut b)?;
                    let rss = take_u64(&mut b)?;
                    let id = take_str(&mut b)?;
                    let msg = take_str(&mut b)?;
                    let root = take_str(&mut b)?;
                    return Some(LspServersRecord::Server {
                        server_ref,
                        phase,
                        progress_pct,
                        caps,
                        epoch,
                        refused_edits,
                        rss,
                        id,
                        msg,
                        root,
                    });
                }
                _ => continue, // unknown kind: skip via record_len
            }
        }
    }
}

// ---------------------------------------------------------------------------
// LSP_DIAG records
// ---------------------------------------------------------------------------

/// One decoded record from an `LSP_DIAG` payload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LspDiagRecord<'a> {
    /// FILE 0x01: [kind:1][hash:16][n:2][path_len:2][path:N]
    /// Replaces the file's entire diagnostic set (the following `n`
    /// `Diag` records); `n` = 0 clears. `hash` names the content version
    /// the set describes; zero when unknown.
    File {
        hash: LspHash,
        n: u16,
        path: &'a str,
    },
    /// DIAG 0x02: [kind:1][severity:1][flags:1][line:4][col:4][end_line:4][end_col:4]
    /// [code_len:2][code:N][src_len:2][source:N][msg_len:4][msg:N]
    Diag {
        /// One of `LSP_SEVERITY_*`.
        severity: u8,
        /// `LSP_DIAG_UNNECESSARY` / `LSP_DIAG_DEPRECATED`.
        flags: u8,
        line: u32,
        col: u32,
        end_line: u32,
        end_col: u32,
        code: &'a str,
        /// The producing backend (e.g. `rust-analyzer`, `clippy`).
        source: &'a str,
        msg: &'a str,
    },
}

/// Append one record to an uncompressed `LSP_DIAG` records buffer.
pub fn append_lsp_diag_record(buf: &mut Vec<u8>, record: &LspDiagRecord<'_>) {
    let start = begin_record(buf);
    match record {
        LspDiagRecord::File { hash, n, path } => {
            buf.push(LSP_DIAG_RECORD_FILE);
            buf.extend_from_slice(hash);
            buf.extend_from_slice(&n.to_le_bytes());
            push_str(buf, path);
        }
        LspDiagRecord::Diag {
            severity,
            flags,
            line,
            col,
            end_line,
            end_col,
            code,
            source,
            msg,
        } => {
            buf.push(LSP_DIAG_RECORD_DIAG);
            buf.push(*severity);
            buf.push(*flags);
            buf.extend_from_slice(&line.to_le_bytes());
            buf.extend_from_slice(&col.to_le_bytes());
            buf.extend_from_slice(&end_line.to_le_bytes());
            buf.extend_from_slice(&end_col.to_le_bytes());
            push_str(buf, code);
            push_str(buf, source);
            push_bytes(buf, msg.as_bytes());
        }
    }
    end_record(buf, start);
}

pub struct LspDiagRecordIter<'a> {
    data: &'a [u8],
}

/// Iterate records in an uncompressed `LSP_DIAG` payload.
pub fn lsp_diag_records(data: &[u8]) -> LspDiagRecordIter<'_> {
    LspDiagRecordIter { data }
}

impl<'a> Iterator for LspDiagRecordIter<'a> {
    type Item = LspDiagRecord<'a>;

    fn next(&mut self) -> Option<LspDiagRecord<'a>> {
        loop {
            let (kind, mut b) = next_record(&mut self.data)?;
            match kind {
                LSP_DIAG_RECORD_FILE => {
                    let hash = take_hash(&mut b)?;
                    let n = take_u16(&mut b)?;
                    let path = take_str(&mut b)?;
                    return Some(LspDiagRecord::File { hash, n, path });
                }
                LSP_DIAG_RECORD_DIAG => {
                    let severity = take_u8(&mut b)?;
                    let flags = take_u8(&mut b)?;
                    let line = take_u32(&mut b)?;
                    let col = take_u32(&mut b)?;
                    let end_line = take_u32(&mut b)?;
                    let end_col = take_u32(&mut b)?;
                    let code = take_str(&mut b)?;
                    let source = take_str(&mut b)?;
                    let msg = take_text(&mut b)?;
                    return Some(LspDiagRecord::Diag {
                        severity,
                        flags,
                        line,
                        col,
                        end_line,
                        end_col,
                        code,
                        source,
                        msg,
                    });
                }
                _ => continue, // unknown kind: skip via record_len
            }
        }
    }
}

// ---------------------------------------------------------------------------
// LSP_QUERY response records
// ---------------------------------------------------------------------------

/// One decoded record from an `LSP_QUERY` response payload.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LspQueryRecord<'a> {
    /// LOCATION 0x01: [kind:1][flags:1][hash:16][line:4][col:4][end_line:4][end_col:4][path_len:2][path:N]
    Location {
        flags: u8,
        /// Content version the location refers into; zero when unknown.
        hash: LspHash,
        line: u32,
        col: u32,
        end_line: u32,
        end_col: u32,
        path: &'a str,
    },
    /// MARKUP 0x02: [kind:1][format:1][text_len:4][text:N]
    Markup {
        /// [`LSP_MARKUP_PLAIN`] or [`LSP_MARKUP_MARKDOWN`].
        format: u8,
        text: &'a str,
    },
    /// SYMBOL 0x03: [kind:1][sym_kind:1][flags:1][depth:1][line:4][col:4]
    /// [end_line:4][end_col:4][name_len:2][name:N][path_len:2][path:N]
    /// `depth` nests document outlines (pre-order); 0 at the top level.
    Symbol {
        /// LSP SymbolKind value.
        sym_kind: u8,
        /// [`LSP_SYMBOL_DEPRECATED`].
        flags: u8,
        depth: u8,
        line: u32,
        col: u32,
        end_line: u32,
        end_col: u32,
        name: &'a str,
        path: &'a str,
    },
    /// EDIT 0x04: [kind:1][flags:1][hash:16][line:4][col:4][end_line:4][end_col:4]
    /// [new_len:4][new_text:N][path_len:2][path:N]
    /// One ordered edit of a rename plan, against the content version
    /// named by `hash`. Data, never applied.
    Edit {
        flags: u8,
        hash: LspHash,
        line: u32,
        col: u32,
        end_line: u32,
        end_col: u32,
        new_text: &'a str,
        path: &'a str,
    },
    /// COMPLETION 0x05: [kind:1][item_kind:1][flags:1][line:4][col:4]
    /// [end_line:4][end_col:4][label_len:2][label:N][insert_len:2][insert:N]
    /// [detail_len:2][detail:N]
    /// The range is the item's primary replace range (zero range → the
    /// client picks its own word boundary); empty `insert` → insert the
    /// label.
    Completion {
        /// LSP CompletionItemKind value; 0 unknown.
        item_kind: u8,
        /// `LSP_COMPLETION_*` bits.
        flags: u8,
        line: u32,
        col: u32,
        end_line: u32,
        end_col: u32,
        label: &'a str,
        insert: &'a str,
        detail: &'a str,
    },
    /// SIGNATURE 0x06: [kind:1][flags:1][active_param:2][param_start:2]
    /// [param_end:2][label_len:2][label:N][doc_len:4][doc:N]
    /// One signature, the active one first ([`LSP_SIGNATURE_ACTIVE`]);
    /// `param_start`/`param_end` bound the active parameter within
    /// `label` in UTF-8 bytes (0,0 = unknown).
    Signature {
        /// `LSP_SIGNATURE_*` bits.
        flags: u8,
        /// Active parameter index, or [`LSP_SIGNATURE_NO_PARAM`].
        active_param: u16,
        param_start: u16,
        param_end: u16,
        label: &'a str,
        doc: &'a str,
    },
}

/// Append one record to an uncompressed `LSP_QUERY` response buffer.
pub fn append_lsp_query_record(buf: &mut Vec<u8>, record: &LspQueryRecord<'_>) {
    let start = begin_record(buf);
    match record {
        LspQueryRecord::Location {
            flags,
            hash,
            line,
            col,
            end_line,
            end_col,
            path,
        } => {
            buf.push(LSP_QUERY_RECORD_LOCATION);
            buf.push(*flags);
            buf.extend_from_slice(hash);
            buf.extend_from_slice(&line.to_le_bytes());
            buf.extend_from_slice(&col.to_le_bytes());
            buf.extend_from_slice(&end_line.to_le_bytes());
            buf.extend_from_slice(&end_col.to_le_bytes());
            push_str(buf, path);
        }
        LspQueryRecord::Markup { format, text } => {
            buf.push(LSP_QUERY_RECORD_MARKUP);
            buf.push(*format);
            push_bytes(buf, text.as_bytes());
        }
        LspQueryRecord::Symbol {
            sym_kind,
            flags,
            depth,
            line,
            col,
            end_line,
            end_col,
            name,
            path,
        } => {
            buf.push(LSP_QUERY_RECORD_SYMBOL);
            buf.push(*sym_kind);
            buf.push(*flags);
            buf.push(*depth);
            buf.extend_from_slice(&line.to_le_bytes());
            buf.extend_from_slice(&col.to_le_bytes());
            buf.extend_from_slice(&end_line.to_le_bytes());
            buf.extend_from_slice(&end_col.to_le_bytes());
            push_str(buf, name);
            push_str(buf, path);
        }
        LspQueryRecord::Edit {
            flags,
            hash,
            line,
            col,
            end_line,
            end_col,
            new_text,
            path,
        } => {
            buf.push(LSP_QUERY_RECORD_EDIT);
            buf.push(*flags);
            buf.extend_from_slice(hash);
            buf.extend_from_slice(&line.to_le_bytes());
            buf.extend_from_slice(&col.to_le_bytes());
            buf.extend_from_slice(&end_line.to_le_bytes());
            buf.extend_from_slice(&end_col.to_le_bytes());
            push_bytes(buf, new_text.as_bytes());
            push_str(buf, path);
        }
        LspQueryRecord::Completion {
            item_kind,
            flags,
            line,
            col,
            end_line,
            end_col,
            label,
            insert,
            detail,
        } => {
            buf.push(LSP_QUERY_RECORD_COMPLETION);
            buf.push(*item_kind);
            buf.push(*flags);
            buf.extend_from_slice(&line.to_le_bytes());
            buf.extend_from_slice(&col.to_le_bytes());
            buf.extend_from_slice(&end_line.to_le_bytes());
            buf.extend_from_slice(&end_col.to_le_bytes());
            push_str(buf, label);
            push_str(buf, insert);
            push_str(buf, detail);
        }
        LspQueryRecord::Signature {
            flags,
            active_param,
            param_start,
            param_end,
            label,
            doc,
        } => {
            buf.push(LSP_QUERY_RECORD_SIGNATURE);
            buf.push(*flags);
            buf.extend_from_slice(&active_param.to_le_bytes());
            buf.extend_from_slice(&param_start.to_le_bytes());
            buf.extend_from_slice(&param_end.to_le_bytes());
            push_str(buf, label);
            push_bytes(buf, doc.as_bytes());
        }
    }
    end_record(buf, start);
}

pub struct LspQueryRecordIter<'a> {
    data: &'a [u8],
}

/// Iterate records in an uncompressed `LSP_QUERY` response payload.
pub fn lsp_query_records(data: &[u8]) -> LspQueryRecordIter<'_> {
    LspQueryRecordIter { data }
}

impl<'a> Iterator for LspQueryRecordIter<'a> {
    type Item = LspQueryRecord<'a>;

    fn next(&mut self) -> Option<LspQueryRecord<'a>> {
        loop {
            let (kind, mut b) = next_record(&mut self.data)?;
            match kind {
                LSP_QUERY_RECORD_LOCATION => {
                    let flags = take_u8(&mut b)?;
                    let hash = take_hash(&mut b)?;
                    let line = take_u32(&mut b)?;
                    let col = take_u32(&mut b)?;
                    let end_line = take_u32(&mut b)?;
                    let end_col = take_u32(&mut b)?;
                    let path = take_str(&mut b)?;
                    return Some(LspQueryRecord::Location {
                        flags,
                        hash,
                        line,
                        col,
                        end_line,
                        end_col,
                        path,
                    });
                }
                LSP_QUERY_RECORD_MARKUP => {
                    let format = take_u8(&mut b)?;
                    let text = take_text(&mut b)?;
                    return Some(LspQueryRecord::Markup { format, text });
                }
                LSP_QUERY_RECORD_SYMBOL => {
                    let sym_kind = take_u8(&mut b)?;
                    let flags = take_u8(&mut b)?;
                    let depth = take_u8(&mut b)?;
                    let line = take_u32(&mut b)?;
                    let col = take_u32(&mut b)?;
                    let end_line = take_u32(&mut b)?;
                    let end_col = take_u32(&mut b)?;
                    let name = take_str(&mut b)?;
                    let path = take_str(&mut b)?;
                    return Some(LspQueryRecord::Symbol {
                        sym_kind,
                        flags,
                        depth,
                        line,
                        col,
                        end_line,
                        end_col,
                        name,
                        path,
                    });
                }
                LSP_QUERY_RECORD_EDIT => {
                    let flags = take_u8(&mut b)?;
                    let hash = take_hash(&mut b)?;
                    let line = take_u32(&mut b)?;
                    let col = take_u32(&mut b)?;
                    let end_line = take_u32(&mut b)?;
                    let end_col = take_u32(&mut b)?;
                    let new_text = take_text(&mut b)?;
                    let path = take_str(&mut b)?;
                    return Some(LspQueryRecord::Edit {
                        flags,
                        hash,
                        line,
                        col,
                        end_line,
                        end_col,
                        new_text,
                        path,
                    });
                }
                LSP_QUERY_RECORD_COMPLETION => {
                    let item_kind = take_u8(&mut b)?;
                    let flags = take_u8(&mut b)?;
                    let line = take_u32(&mut b)?;
                    let col = take_u32(&mut b)?;
                    let end_line = take_u32(&mut b)?;
                    let end_col = take_u32(&mut b)?;
                    let label = take_str(&mut b)?;
                    let insert = take_str(&mut b)?;
                    let detail = take_str(&mut b)?;
                    return Some(LspQueryRecord::Completion {
                        item_kind,
                        flags,
                        line,
                        col,
                        end_line,
                        end_col,
                        label,
                        insert,
                        detail,
                    });
                }
                LSP_QUERY_RECORD_SIGNATURE => {
                    let flags = take_u8(&mut b)?;
                    let active_param = take_u16(&mut b)?;
                    let param_start = take_u16(&mut b)?;
                    let param_end = take_u16(&mut b)?;
                    let label = take_str(&mut b)?;
                    let doc = take_text(&mut b)?;
                    return Some(LspQueryRecord::Signature {
                        flags,
                        active_param,
                        param_start,
                        param_end,
                        label,
                        doc,
                    });
                }
                _ => continue, // unknown kind: skip via record_len
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Client-side reducers
// ---------------------------------------------------------------------------

/// One backend's projected state, from a `SERVER` record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LspServerState {
    pub phase: u8,
    pub progress_pct: u8,
    pub caps: u32,
    pub epoch: u32,
    pub refused_edits: u32,
    pub rss: u64,
    pub id: String,
    pub msg: String,
}

/// The complete client obligation for `LSP_STATE`: replace the whole
/// map, ack.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LspStateMirror {
    /// Keyed by `server_ref`.
    pub servers: BTreeMap<u16, LspServerState>,
    /// The last snapshot's flags.
    pub flags: u8,
}

impl LspStateMirror {
    pub fn new() -> Self {
        Self::default()
    }

    /// Apply one `LSP_STATE` message (starting at the opcode byte),
    /// replacing the whole state. Returns `Some(state_id)` to
    /// acknowledge, `None` if malformed.
    pub fn apply_state(&mut self, msg: &[u8]) -> Option<u32> {
        let (_lsp_id, state_id, flags, records) = parse_lsp_state(msg)?;
        let mut next = LspStateMirror {
            flags,
            ..Default::default()
        };
        for record in lsp_state_records(&records) {
            match record {
                LspStateRecord::Server {
                    server_ref,
                    phase,
                    progress_pct,
                    caps,
                    epoch,
                    refused_edits,
                    rss,
                    id,
                    msg,
                } => {
                    next.servers.insert(
                        server_ref,
                        LspServerState {
                            phase,
                            progress_pct,
                            caps,
                            epoch,
                            refused_edits,
                            rss,
                            id: id.to_string(),
                            msg: msg.to_string(),
                        },
                    );
                }
            }
        }
        *self = next;
        Some(state_id)
    }
}

/// One diagnostic, owned, from a `DIAG` record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LspDiagnostic {
    pub severity: u8,
    pub flags: u8,
    pub line: u32,
    pub col: u32,
    pub end_line: u32,
    pub end_col: u32,
    pub code: String,
    pub source: String,
    pub msg: String,
}

/// One file's diagnostic set.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LspFileDiags {
    /// Content version the set describes; zero when unknown.
    pub hash: LspHash,
    pub diags: Vec<LspDiagnostic>,
}

/// The complete client obligation for `LSP_DIAG`: apply per-file
/// replacement sets, ack. Absence of a path means unknown, not clean.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct LspDiagMirror {
    /// Keyed by escaped workspace-relative path.
    pub files: BTreeMap<String, LspFileDiags>,
}

impl LspDiagMirror {
    pub fn new() -> Self {
        Self::default()
    }

    /// Apply one `LSP_DIAG` message (starting at the opcode byte).
    /// Returns `Some(update_id)` to acknowledge, `None` if malformed.
    pub fn apply_diag(&mut self, msg: &[u8]) -> Option<u32> {
        let (_lsp_id, update_id, flags, records) = parse_lsp_diag(msg)?;
        if flags & LSP_DIAG_FULL != 0 {
            self.files.clear();
        }
        // `Diag` records attach to the most recent `File` record.
        let mut current: Option<String> = None;
        for record in lsp_diag_records(&records) {
            match record {
                LspDiagRecord::File { hash, n, path } => {
                    if n == 0 {
                        self.files.remove(path);
                        current = None;
                    } else {
                        let entry = self.files.entry(path.to_string()).or_default();
                        entry.hash = hash;
                        entry.diags.clear();
                        current = Some(path.to_string());
                    }
                }
                LspDiagRecord::Diag {
                    severity,
                    flags,
                    line,
                    col,
                    end_line,
                    end_col,
                    code,
                    source,
                    msg,
                } => {
                    if let Some(file) = current.as_ref().and_then(|p| self.files.get_mut(p)) {
                        file.diags.push(LspDiagnostic {
                            severity,
                            flags,
                            line,
                            col,
                            end_line,
                            end_col,
                            code: code.to_string(),
                            source: source.to_string(),
                            msg: msg.to_string(),
                        });
                    }
                }
            }
        }
        Some(update_id)
    }
}

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

    #[test]
    fn lsp_open_from_pty_roundtrip_and_rebase() {
        let m = msg_lsp_open_from_pty(7, LSP_OPEN_WATCH, 500, "sub", 3);
        assert_eq!(
            m,
            vec![
                0x60, 0x07, 0x00, 0x05, 0xf4, 0x01, 0x03, 0x00, 0x73, 0x75, 0x62, 0x03, 0x00
            ]
        );
        assert_eq!(lsp_open_src_pty(&m), Some(3));
        assert_eq!(
            lsp_open_src_pty(&msg_lsp_open(7, LSP_OPEN_WATCH, 500, "sub")),
            None
        );
        let (_, flags, _, path) = parse_lsp_open(&m).unwrap();
        assert_eq!(flags & LSP_OPEN_FROM_PTY, LSP_OPEN_FROM_PTY);
        assert_eq!(path, "sub");
        // Rebase joins cwd + path and clears FROM_PTY.
        let reb = lsp_open_rebase(&m, Some("/w")).unwrap();
        let (_, rf, _, rp) = parse_lsp_open(&reb).unwrap();
        assert_eq!(rf & LSP_OPEN_FROM_PTY, 0);
        assert_eq!(rp, "/w/sub");
    }

    fn hex(b: &[u8]) -> String {
        b.iter().map(|x| format!("{x:02x}")).collect()
    }

    fn hash(fill: u8) -> LspHash {
        [fill; 16]
    }

    #[test]
    fn request_roundtrips() {
        let msg = msg_lsp_open(7, LSP_OPEN_WATCH | LSP_OPEN_DIAGS, 500, "/src");
        assert_eq!(parse_lsp_open(&msg), Some((7, 3, 500, "/src")));

        let msg = msg_lsp_close(9);
        assert_eq!(parse_lsp_close(&msg), Some(9));

        let msg = msg_lsp_ack(9, LSP_STREAM_DIAG, 0x01020304);
        assert_eq!(parse_lsp_ack(&msg), Some((9, LSP_STREAM_DIAG, 0x01020304)));

        let req = LspQueryRequest {
            nonce: 3,
            lsp_id: 9,
            kind: LSP_QUERY_REFERENCES,
            flags: LSP_REFS_INCLUDE_DECLARATION,
            line: 10,
            col: 4,
            path: "src/lib.rs",
            arg: "",
        };
        assert_eq!(parse_lsp_query(&msg_lsp_query(&req)), Some(req));

        let msg = msg_lsp_cancel(3);
        assert_eq!(parse_lsp_cancel(&msg), Some(3));

        let msg = msg_lsp_servers(4);
        assert_eq!(parse_lsp_servers(&msg), Some(4));

        let msg = msg_lsp_stop(5, 2);
        assert_eq!(parse_lsp_stop(&msg), Some((5, 2)));

        // Buffer overlay: text crosses LZ4, so roundtrip only (fixtures pin
        // uncompressed payloads elsewhere).
        let msg = msg_lsp_buffer(9, 0, "src/lib.rs", b"fn main() {}\n");
        assert_eq!(
            parse_lsp_buffer(&msg),
            Some((9, 0, "src/lib.rs", b"fn main() {}\n".to_vec()))
        );
        let msg = msg_lsp_buffer(9, LSP_BUFFER_RELEASE, "src/lib.rs", b"");
        assert_eq!(
            parse_lsp_buffer(&msg),
            Some((9, LSP_BUFFER_RELEASE, "src/lib.rs", Vec::new()))
        );
    }

    #[test]
    fn response_roundtrips() {
        let msg = msg_lsp_opened(7, 1, LSP_STATUS_OK, 0, "/src", "");
        assert_eq!(
            parse_lsp_opened(&msg),
            Some(LspOpened {
                nonce: 7,
                lsp_id: 1,
                status: LSP_STATUS_OK,
                flags: 0,
                root: "/src",
                detail: "",
            })
        );

        let msg = msg_lsp_opened(
            8,
            LSP_ID_INVALID,
            LSP_STATUS_NOT_FOUND,
            0,
            "",
            "gopls: not found on PATH",
        );
        let opened = parse_lsp_opened(&msg).unwrap();
        assert_eq!(opened.lsp_id, LSP_ID_INVALID);
        assert_eq!(opened.detail, "gopls: not found on PATH");

        let mut records = Vec::new();
        append_lsp_state_record(
            &mut records,
            &LspStateRecord::Server {
                server_ref: 1,
                phase: LSP_PHASE_INDEXING,
                progress_pct: 42,
                caps: LSP_CAP_DEFINITION | LSP_CAP_HOVER,
                epoch: 2,
                refused_edits: 1,
                rss: 3 << 30,
                id: "rust-analyzer",
                msg: "indexing 42%",
            },
        );
        let msg = msg_lsp_state(1, 5, 0, &records);
        let (lsp_id, state_id, flags, decoded) = parse_lsp_state(&msg).unwrap();
        assert_eq!((lsp_id, state_id, flags), (1, 5, 0));
        assert_eq!(decoded, records);

        let msg = msg_lsp_diag(1, 6, LSP_DIAG_FULL, &[]);
        assert_eq!(parse_lsp_diag(&msg), Some((1, 6, LSP_DIAG_FULL, vec![])));

        let msg = msg_lsp_query_resp(3, LSP_STATUS_OK, 0, "", &[]);
        assert_eq!(
            parse_lsp_query_resp(&msg),
            Some(LspQueryResp {
                nonce: 3,
                status: LSP_STATUS_OK,
                flags: 0,
                detail: String::new(),
                records: vec![],
            })
        );
        // A failure carries the reason.
        let msg = msg_lsp_query_resp(4, LSP_STATUS_OTHER, 0, "gopls: boom", &[]);
        let resp = parse_lsp_query_resp(&msg).unwrap();
        assert_eq!(resp.status, LSP_STATUS_OTHER);
        assert_eq!(resp.detail, "gopls: boom");

        let msg = msg_lsp_closed(1, LSP_CLOSED_BACKEND_FAILED);
        assert_eq!(parse_lsp_closed(&msg), Some((1, LSP_CLOSED_BACKEND_FAILED)));

        let msg = msg_lsp_servers_resp(4, LSP_STATUS_OK, 0, &[]);
        assert_eq!(
            parse_lsp_servers_resp(&msg),
            Some((4, LSP_STATUS_OK, 0, vec![]))
        );

        let msg = msg_lsp_stopped(5, LSP_STATUS_OK);
        assert_eq!(parse_lsp_stopped(&msg), Some((5, LSP_STATUS_OK)));
    }

    #[test]
    fn state_record_roundtrip() {
        let record = LspStateRecord::Server {
            server_ref: 2,
            phase: LSP_PHASE_READY,
            progress_pct: LSP_PROGRESS_UNKNOWN,
            caps: LSP_CAP_RENAME,
            epoch: 0,
            refused_edits: 0,
            rss: 0,
            id: "gopls",
            msg: "",
        };
        let mut buf = Vec::new();
        append_lsp_state_record(&mut buf, &record);
        let decoded: Vec<_> = lsp_state_records(&buf).collect();
        assert_eq!(decoded, vec![record]);
    }

    #[test]
    fn servers_record_roundtrip() {
        let record = LspServersRecord::Server {
            server_ref: 2,
            phase: LSP_PHASE_READY,
            progress_pct: 100,
            caps: 0x3F,
            epoch: 1,
            refused_edits: 0,
            rss: 1 << 20,
            id: "gopls",
            msg: "ready",
            root: "/work/api",
        };
        let mut buf = Vec::new();
        append_lsp_servers_record(&mut buf, &record);
        let decoded: Vec<_> = lsp_servers_records(&buf).collect();
        assert_eq!(decoded, vec![record]);
    }

    #[test]
    fn diag_record_roundtrip() {
        let records = vec![
            LspDiagRecord::File {
                hash: hash(0xAB),
                n: 1,
                path: "src/lib.rs",
            },
            LspDiagRecord::Diag {
                severity: LSP_SEVERITY_ERROR,
                flags: LSP_DIAG_UNNECESSARY,
                line: 10,
                col: 4,
                end_line: 10,
                end_col: 9,
                code: "E0308",
                source: "rustc",
                msg: "mismatched types",
            },
            LspDiagRecord::File {
                hash: LSP_HASH_NONE,
                n: 0,
                path: "src/old.rs",
            },
        ];
        let mut buf = Vec::new();
        for r in &records {
            append_lsp_diag_record(&mut buf, r);
        }
        let decoded: Vec<_> = lsp_diag_records(&buf).collect();
        assert_eq!(decoded, records);
    }

    #[test]
    fn query_record_roundtrip() {
        let records = vec![
            LspQueryRecord::Location {
                flags: 0,
                hash: hash(0xCD),
                line: 5,
                col: 0,
                end_line: 5,
                end_col: 12,
                path: "src/main.rs",
            },
            LspQueryRecord::Markup {
                format: LSP_MARKUP_MARKDOWN,
                text: "```rust\nfn main()\n```",
            },
            LspQueryRecord::Symbol {
                sym_kind: 12, // Function
                flags: LSP_SYMBOL_DEPRECATED,
                depth: 1,
                line: 3,
                col: 4,
                end_line: 9,
                end_col: 1,
                name: "main",
                path: "src/main.rs",
            },
            LspQueryRecord::Edit {
                flags: 0,
                hash: hash(0xEF),
                line: 3,
                col: 7,
                end_line: 3,
                end_col: 11,
                new_text: "run",
                path: "src/main.rs",
            },
            LspQueryRecord::Completion {
                item_kind: 3, // Function
                flags: LSP_COMPLETION_SNIPPET | LSP_COMPLETION_PRESELECT,
                line: 4,
                col: 2,
                end_line: 4,
                end_col: 6,
                label: "push",
                insert: "push(${1:value})",
                detail: "fn(&mut self, value: T)",
            },
            LspQueryRecord::Signature {
                flags: LSP_SIGNATURE_ACTIVE,
                active_param: 1,
                param_start: 14,
                param_end: 22,
                label: "fn get(&self, index: usize)",
                doc: "Returns a reference to an element.",
            },
        ];
        let mut buf = Vec::new();
        for r in &records {
            append_lsp_query_record(&mut buf, r);
        }
        let decoded: Vec<_> = lsp_query_records(&buf).collect();
        assert_eq!(decoded, records);
    }

    #[test]
    fn unknown_record_kind_is_skipped() {
        let mut buf = Vec::new();
        // A future record kind: [record_len][0x7F][payload].
        let start = begin_record(&mut buf);
        buf.push(0x7F);
        buf.extend_from_slice(b"future");
        end_record(&mut buf, start);
        append_lsp_query_record(
            &mut buf,
            &LspQueryRecord::Markup {
                format: LSP_MARKUP_PLAIN,
                text: "hi",
            },
        );
        let decoded: Vec<_> = lsp_query_records(&buf).collect();
        assert_eq!(
            decoded,
            vec![LspQueryRecord::Markup {
                format: LSP_MARKUP_PLAIN,
                text: "hi",
            }]
        );
    }

    #[test]
    fn malformed_record_ends_iteration() {
        let mut buf = Vec::new();
        append_lsp_diag_record(
            &mut buf,
            &LspDiagRecord::File {
                hash: LSP_HASH_NONE,
                n: 0,
                path: "a",
            },
        );
        // Declared length overruns the buffer: iteration must end, not panic.
        buf.extend_from_slice(&99u32.to_le_bytes());
        buf.push(LSP_DIAG_RECORD_FILE);
        let decoded: Vec<_> = lsp_diag_records(&buf).collect();
        assert_eq!(decoded.len(), 1);
    }

    #[test]
    fn oversized_declared_length_is_rejected_before_allocation() {
        let mut msg = vec![S2C_LSP_STATE];
        msg.extend_from_slice(&1u16.to_le_bytes());
        msg.extend_from_slice(&1u32.to_le_bytes());
        msg.push(0);
        // A hostile 4 GiB declared size must be refused before allocating.
        msg.extend_from_slice(&(u32::MAX).to_le_bytes());
        msg.extend_from_slice(&[0; 8]);
        assert_eq!(parse_lsp_state(&msg), None);
    }

    #[test]
    fn state_mirror_replaces_whole_state() {
        let mut records = Vec::new();
        append_lsp_state_record(
            &mut records,
            &LspStateRecord::Server {
                server_ref: 1,
                phase: LSP_PHASE_INDEXING,
                progress_pct: 10,
                caps: 0,
                epoch: 0,
                refused_edits: 0,
                rss: 0,
                id: "rust-analyzer",
                msg: "indexing",
            },
        );
        let mut mirror = LspStateMirror::new();
        assert_eq!(
            mirror.apply_state(&msg_lsp_state(1, 1, 0, &records)),
            Some(1)
        );
        assert_eq!(mirror.servers.len(), 1);
        assert_eq!(mirror.servers[&1].phase, LSP_PHASE_INDEXING);

        // The next snapshot replaces, never merges.
        let mut records = Vec::new();
        append_lsp_state_record(
            &mut records,
            &LspStateRecord::Server {
                server_ref: 2,
                phase: LSP_PHASE_READY,
                progress_pct: 100,
                caps: 0x3F,
                epoch: 0,
                refused_edits: 0,
                rss: 0,
                id: "gopls",
                msg: "",
            },
        );
        assert_eq!(
            mirror.apply_state(&msg_lsp_state(1, 2, 0, &records)),
            Some(2)
        );
        assert_eq!(mirror.servers.len(), 1);
        assert!(mirror.servers.contains_key(&2));
    }

    #[test]
    fn diag_mirror_applies_replacement_sets() {
        let mut mirror = LspDiagMirror::new();

        // FULL replay: one file, one diagnostic.
        let mut records = Vec::new();
        append_lsp_diag_record(
            &mut records,
            &LspDiagRecord::File {
                hash: hash(1),
                n: 1,
                path: "a.rs",
            },
        );
        append_lsp_diag_record(
            &mut records,
            &LspDiagRecord::Diag {
                severity: LSP_SEVERITY_ERROR,
                flags: 0,
                line: 1,
                col: 0,
                end_line: 1,
                end_col: 5,
                code: "E1",
                source: "t",
                msg: "boom",
            },
        );
        assert_eq!(
            mirror.apply_diag(&msg_lsp_diag(1, 1, LSP_DIAG_FULL, &records)),
            Some(1)
        );
        assert_eq!(mirror.files.len(), 1);
        assert_eq!(mirror.files["a.rs"].diags.len(), 1);

        // Incremental: replace a.rs with an empty set (n=0 removes).
        let mut records = Vec::new();
        append_lsp_diag_record(
            &mut records,
            &LspDiagRecord::File {
                hash: hash(2),
                n: 0,
                path: "a.rs",
            },
        );
        append_lsp_diag_record(
            &mut records,
            &LspDiagRecord::File {
                hash: hash(3),
                n: 1,
                path: "b.rs",
            },
        );
        append_lsp_diag_record(
            &mut records,
            &LspDiagRecord::Diag {
                severity: LSP_SEVERITY_WARNING,
                flags: 0,
                line: 2,
                col: 1,
                end_line: 2,
                end_col: 2,
                code: "",
                source: "t",
                msg: "hm",
            },
        );
        assert_eq!(mirror.apply_diag(&msg_lsp_diag(1, 2, 0, &records)), Some(2));
        assert!(!mirror.files.contains_key("a.rs"));
        assert_eq!(mirror.files["b.rs"].hash, hash(3));

        // A later FULL drops files it does not re-list.
        assert_eq!(
            mirror.apply_diag(&msg_lsp_diag(1, 3, LSP_DIAG_FULL, &[])),
            Some(3)
        );
        assert!(mirror.files.is_empty());
    }

    /// Byte-exact fixtures pinned across the Rust and TypeScript codecs
    /// (js/core/src/lsp.ts): drift fails on one side or the other.
    #[test]
    fn wire_fixtures() {
        assert_eq!(
            hex(&msg_lsp_open(
                0x0102,
                LSP_OPEN_WATCH | LSP_OPEN_DIAGS,
                500,
                "/src"
            )),
            "60020103f40104002f737263"
        );
        assert_eq!(hex(&msg_lsp_close(7)), "610700");
        assert_eq!(
            hex(&msg_lsp_ack(7, LSP_STREAM_DIAG, 0x01020304)),
            "6207000104030201"
        );
        assert_eq!(
            hex(&msg_lsp_query(&LspQueryRequest {
                nonce: 3,
                lsp_id: 7,
                kind: LSP_QUERY_DEFINITION,
                flags: 0,
                line: 10,
                col: 4,
                path: "a.rs",
                arg: "",
            })),
            "630300070001000a000000040000000400612e72730000"
        );
        assert_eq!(hex(&msg_lsp_cancel(10)), "640a00");
        assert_eq!(hex(&msg_lsp_servers(11)), "650b00");
        assert_eq!(hex(&msg_lsp_stop(12, 2)), "660c000200");
        assert_eq!(
            hex(&msg_lsp_opened(5, 1, LSP_STATUS_OK, 0, "/w", "")),
            "6005000100000002002f770000"
        );
        assert_eq!(hex(&msg_lsp_closed(1, LSP_CLOSED_ROOT_GONE)), "64010001");
        assert_eq!(hex(&msg_lsp_stopped(6, LSP_STATUS_OK)), "66060000");

        // Uncompressed record-buffer fixtures (LZ4 output is
        // implementation-specific, so cross-codec pinning happens on the
        // record bytes, not the compressed message).
        let mut buf = Vec::new();
        append_lsp_diag_record(
            &mut buf,
            &LspDiagRecord::File {
                hash: hash(0xAB),
                n: 1,
                path: "a.rs",
            },
        );
        assert_eq!(
            hex(&buf),
            format!("1900000001{}01000400612e7273", "ab".repeat(16))
        );
        let mut buf = Vec::new();
        append_lsp_query_record(
            &mut buf,
            &LspQueryRecord::Markup {
                format: LSP_MARKUP_MARKDOWN,
                text: "hi",
            },
        );
        assert_eq!(hex(&buf), "080000000201020000006869");
        let mut buf = Vec::new();
        append_lsp_query_record(
            &mut buf,
            &LspQueryRecord::Completion {
                item_kind: 2,
                flags: 0,
                line: 1,
                col: 2,
                end_line: 1,
                end_col: 4,
                label: "ab",
                insert: "",
                detail: "T",
            },
        );
        assert_eq!(
            hex(&buf),
            "1c00000005020001000000020000000100000004000000020061620000010054"
        );
        let mut buf = Vec::new();
        append_lsp_query_record(
            &mut buf,
            &LspQueryRecord::Signature {
                flags: LSP_SIGNATURE_ACTIVE,
                active_param: 0,
                param_start: 2,
                param_end: 6,
                label: "f(a: T)",
                doc: "d",
            },
        );
        assert_eq!(
            hex(&buf),
            "16000000060100000200060007006628613a2054290100000064"
        );
    }
}