lspf 0.4.0

A Rust framework for building extensible LSP language servers
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
//! The 0.2 connection-owned builder surface (ADR 0017, ADR 0018).
//!
//! [`Server::builder`] collects static registrations against one application
//! state value; [`ServerBuilder::build`] validates them and returns a [`Server`]
//! without performing any I/O or freezing the [`Router`]. The protocol engine
//! freezes the Router later, when it commits the initialize transaction: after a
//! valid `initialize`, it runs the sole [`configure_initialize`] callback
//! against a transactional [`InitializeRegistrar`], then the [`on_initialize`]
//! lifecycle hook. This surface wires typed custom requests and notifications,
//! typed commands beneath `workspace/executeCommand`, the standard features
//! with sealed descriptors in [`lspf::features`](crate::features), and the
//! lifecycle hooks: [`on_initialize`], [`on_initialized`] (which runs once the
//! client acknowledges initialization), and [`on_exit`] (which observes the
//! connection's ending without being able to change its [`Outcome`]).
//!
//! [`configure_initialize`]: ServerBuilder::configure_initialize
//! [`on_initialize`]: ServerBuilder::on_initialize
//! [`on_initialized`]: ServerBuilder::on_initialized
//! [`on_exit`]: ServerBuilder::on_exit

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

#[cfg(test)]
use lsp_types::ServerCapabilities;
use lsp_types::notification::Notification;
use lsp_types::request::Request;
use lsp_types::{
    InitializeParams, InitializedParams, ServerInfo, TextDocumentSyncCapability,
    TextDocumentSyncKind, TextDocumentSyncOptions, TextDocumentSyncSaveOptions,
};
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use tokio_util::sync::CancellationToken;
use tracing::warn;

use crate::capability::{CapabilityBuilder, GeneratedCapabilities};
use crate::codec::erase_value;
use crate::context::Context;
use crate::error::{BuildError, LspError};
use crate::features::{FeatureSpec, NotificationFeatureSpec};
use crate::file_provider::{SharedFileProvider, erase};
use crate::service::{Layer, UserLayer};
use crate::{FileProvider, MemoryFileProvider};

/// Method names owned by the framework's lifecycle; a custom request or
/// notification may not shadow one of them.
const RESERVED_METHODS: &[&str] = &[
    "initialize",
    "shutdown",
    "exit",
    "initialized",
    "$/cancelRequest",
];

/// The wire method commands dispatch beneath. A command registration and an
/// explicit request handler for this method cannot coexist.
const EXECUTE_COMMAND_METHOD: &str = "workspace/executeCommand";

/// A notification whose validation or state mutation the protocol engine owns.
///
/// A `notification` registration for one of these methods records the
/// connection's single post-validation hook rather than a Router route. When
/// the notification mutates protocol state, the hook observes that mutation
/// instead of replacing it. This enum is the one place that says which methods
/// those are.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProtocolNotification {
    Open,
    Change,
    Close,
    WillSave,
    Save,
    WorkspaceFolders,
    Configuration,
    Trace,
    /// `window/workDoneProgress/cancel`: the engine fires the matching
    /// handle's cancellation token; a registration records the
    /// post-validation hook.
    ProgressCancel,
}

impl ProtocolNotification {
    const OPEN_METHOD: &'static str = "textDocument/didOpen";
    const CHANGE_METHOD: &'static str = "textDocument/didChange";
    const CLOSE_METHOD: &'static str = "textDocument/didClose";
    const WILL_SAVE_METHOD: &'static str = "textDocument/willSave";
    const SAVE_METHOD: &'static str = "textDocument/didSave";

    /// The built-in this wire method names, or `None` when the method is an
    /// ordinary route.
    pub(crate) fn from_method(method: &str) -> Option<Self> {
        match method {
            Self::OPEN_METHOD => Some(Self::Open),
            Self::CHANGE_METHOD => Some(Self::Change),
            Self::CLOSE_METHOD => Some(Self::Close),
            Self::WILL_SAVE_METHOD => Some(Self::WillSave),
            Self::SAVE_METHOD => Some(Self::Save),
            "workspace/didChangeWorkspaceFolders" => Some(Self::WorkspaceFolders),
            "workspace/didChangeConfiguration" => Some(Self::Configuration),
            "$/setTrace" => Some(Self::Trace),
            "window/workDoneProgress/cancel" => Some(Self::ProgressCancel),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct DocumentSyncSettings {
    pub(crate) capability: TextDocumentSyncCapability,
    pub(crate) options: TextDocumentSyncOptions,
}

/// The future produced by an erased request or command handler: its decoded,
/// method-erased result or the error to report.
type HandlerFuture = Pin<Box<dyn Future<Output = Result<Value, LspError>> + Send>>;

/// The future produced by an erased notification handler. A notification has no
/// response, so it resolves to `()`; when decoding fails the future logs the
/// error and returns without invoking the typed handler.
type NotificationFuture = Pin<Box<dyn Future<Output = ()> + Send>>;

/// A type-erased custom request handler stored in the frozen [`Router`].
///
/// Its three responsibilities (ADR 0017) are to decode the incoming
/// parameters once, invoke the typed handler with native values, and encode
/// the success value once. Malformed parameters become
/// [`LspError::InvalidParams`] without ever calling the typed handler.
pub(crate) type ErasedRequestHandler<S> =
    Box<dyn Fn(Arc<S>, Context, Value, CancellationToken) -> HandlerFuture + Send + Sync>;

/// A type-erased notification handler stored in the frozen [`Router`].
///
/// Like the request handler it decodes once and invokes the typed handler, but
/// it encodes nothing: notifications have no response. Malformed parameters are
/// logged and dropped without ever calling the typed handler.
pub(crate) type ErasedNotificationHandler<S> =
    Box<dyn Fn(Arc<S>, Context, Value) -> NotificationFuture + Send + Sync>;

/// A type-erased command handler stored in the frozen [`Router`].
///
/// The engine decodes `workspace/executeCommand`'s [`ExecuteCommandParams`] to
/// route by command name, then hands the raw argument array here. The erased
/// handler decodes those arguments into the typed `Args` once, invokes the
/// typed handler, and encodes its `Output` once.
///
/// [`ExecuteCommandParams`]: lsp_types::ExecuteCommandParams
pub(crate) type ErasedCommandHandler<S> =
    Box<dyn Fn(Arc<S>, Context, Vec<Value>, CancellationToken) -> HandlerFuture + Send + Sync>;

/// The synchronous, run-at-most-once initialization-dependent registration
/// callback (ADR 0017). It receives read-only `InitializeParams` and a
/// transactional [`InitializeRegistrar`]; returning `Err` discards the whole
/// transaction. Boxed `FnOnce` because the engine invokes it exactly once.
pub(crate) type ConfigureInitialize<S> =
    Box<dyn FnOnce(&InitializeParams, &mut InitializeRegistrar<S>) -> Result<(), LspError> + Send>;

/// The future produced by the erased `on_initialize` hook: optional
/// [`ServerInfo`] to combine with the generated capabilities, or an
/// [`LspError`] that fails initialization.
type OnInitializeFuture =
    Pin<Box<dyn Future<Output = Result<Option<ServerInfo>, LspError>> + Send>>;

/// The erased `on_initialize` lifecycle hook (ADR 0018). It has the request
/// handler shape but returns optional [`ServerInfo`]; it cannot register routes
/// or replace the generated capabilities.
pub(crate) type OnInitialize<S> = Box<
    dyn Fn(Arc<S>, Context, InitializeParams, CancellationToken) -> OnInitializeFuture
        + Send
        + Sync,
>;

/// The erased `on_initialized` lifecycle hook. It has the notification handler
/// shape — the client's `initialized` notification carries no response — so it
/// resolves to `()`. The engine invokes it at most once, only after the
/// initialize transaction succeeded.
pub(crate) type OnInitialized<S> =
    Box<dyn Fn(Arc<S>, Context, InitializedParams) -> NotificationFuture + Send + Sync>;

/// The erased `on_exit` lifecycle hook. `exit` carries no parameters, so the
/// typed hook receives only the shared state and a [`Context`]; it resolves to
/// `()`, which is what keeps the engine's lifecycle-derived [`Outcome`] beyond
/// its reach.
pub(crate) type OnExit<S> = Box<dyn Fn(Arc<S>, Context) -> NotificationFuture + Send + Sync>;

/// Wrap a typed request handler in the erased closure the [`Router`] stores.
/// Shared by [`ServerBuilder::request`] and [`ServerBuilder::feature`], which
/// differ only in whether the method also contributes a capability.
fn erase_request<S, R, H, Fut>(handler: H) -> ErasedRequestHandler<S>
where
    S: Send + Sync + 'static,
    R: Request,
    H: Fn(Arc<S>, Context, R::Params, CancellationToken) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<R::Result, LspError>> + Send + 'static,
{
    let handler = Arc::new(handler);
    Box::new(move |state, ctx, params, ct| {
        let handler = Arc::clone(&handler);
        Box::pin(async move {
            let parsed: R::Params =
                serde_json::from_value(params).map_err(LspError::invalid_params)?;
            let result = handler(state, ctx, parsed, ct).await?;
            erase_value(result)
        })
    })
}

/// Wrap a typed notification handler in the erased closure the [`Router`]
/// stores. Shared by [`ServerBuilder::notification`] and
/// [`ServerBuilder::feature_notification`], which differ only in whether the
/// method also contributes a capability. Malformed parameters are logged and
/// dropped without ever calling the typed handler.
fn erase_notification<S, N, H, Fut>(handler: H) -> ErasedNotificationHandler<S>
where
    S: Send + Sync + 'static,
    N: Notification,
    H: Fn(Arc<S>, Context, N::Params) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = ()> + Send + 'static,
{
    let handler = Arc::new(handler);
    Box::new(move |state, ctx, params| {
        let handler = Arc::clone(&handler);
        Box::pin(async move {
            let parsed: N::Params = match serde_json::from_value(params) {
                Ok(parsed) => parsed,
                Err(error) => {
                    // A notification has no reply, so a decode failure is
                    // reported through tracing and dropped; later messages
                    // are unaffected (ADR 0017).
                    warn!(
                        method = N::METHOD,
                        %error,
                        "dropping notification with malformed params"
                    );
                    return;
                }
            };
            handler(state, ctx, parsed).await;
        })
    })
}

/// The still-mutable set of handler registrations and their capability
/// contributions (ADR 0017). Both [`ServerBuilder`] and [`InitializeRegistrar`]
/// accumulate into one of these; the protocol engine [`freeze`](Self::freeze)s
/// it into a [`Router`] once the initialize transaction commits.
///
/// Each `add_*` method performs the same conflict detection the frozen table
/// relies on, returning the first [`BuildError`] to its caller, who decides
/// whether to record it (the builder) or abort the transaction (the registrar).
pub(crate) struct Registrations<S> {
    requests: HashMap<String, ErasedRequestHandler<S>>,
    notifications: HashMap<String, ErasedNotificationHandler<S>>,
    /// Post-validation hooks for protocol-owned notifications, kept apart from
    /// `notifications` so no ordinary route can ever shadow a built-in.
    built_in_hooks: HashMap<String, ErasedNotificationHandler<S>>,
    commands: HashMap<String, ErasedCommandHandler<S>>,
    capabilities: CapabilityBuilder,
    document_sync: Option<TextDocumentSyncOptions>,
}

impl<S: Send + Sync + 'static> Registrations<S> {
    fn new() -> Self {
        Self {
            requests: HashMap::new(),
            notifications: HashMap::new(),
            built_in_hooks: HashMap::new(),
            commands: HashMap::new(),
            capabilities: CapabilityBuilder::default(),
            document_sync: None,
        }
    }

    /// Register a standard feature handler and its capability contribution.
    fn add_feature<F, H, Fut>(&mut self, spec: F, handler: H) -> Result<(), BuildError>
    where
        F: FeatureSpec,
        H: Fn(Arc<S>, Context, <F::Marker as Request>::Params, CancellationToken) -> Fut
            + Send
            + Sync
            + 'static,
        Fut: Future<Output = Result<<F::Marker as Request>::Result, LspError>> + Send + 'static,
    {
        let method = <F::Marker as Request>::METHOD.to_string();
        let erased = erase_request::<S, F::Marker, H, Fut>(handler);
        self.insert_request(method, erased)?;
        spec.contribute(&mut self.capabilities)
    }

    /// Register a typed custom request handler (contributes no capability).
    fn add_request<R, H, Fut>(&mut self, handler: H) -> Result<(), BuildError>
    where
        R: Request,
        H: Fn(Arc<S>, Context, R::Params, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<R::Result, LspError>> + Send + 'static,
    {
        let method = R::METHOD.to_string();
        let erased = erase_request::<S, R, H, Fut>(handler);
        self.insert_request(method, erased)
    }

    /// Insert an already-erased request handler under `method`, rejecting a
    /// reserved method or a duplicate. Shared by [`add_feature`](Self::add_feature)
    /// and [`add_request`](Self::add_request), which differ only in the capability
    /// contribution that follows a successful insert.
    fn insert_request(
        &mut self,
        method: String,
        erased: ErasedRequestHandler<S>,
    ) -> Result<(), BuildError> {
        if RESERVED_METHODS.contains(&method.as_str()) {
            return Err(BuildError::ReservedMethod(method));
        }
        if self.requests.insert(method.clone(), erased).is_some() {
            return Err(BuildError::DuplicateMethod(method));
        }
        Ok(())
    }

    /// Register a typed custom notification handler (contributes no capability).
    fn add_notification<N, H, Fut>(&mut self, handler: H) -> Result<(), BuildError>
    where
        N: Notification,
        H: Fn(Arc<S>, Context, N::Params) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let method = N::METHOD.to_string();
        let erased = erase_notification::<S, N, H, Fut>(handler);
        self.insert_notification(method, erased)
    }

    /// Register a standard notification feature handler and its capability
    /// contribution. Shares [`add_notification`](Self::add_notification)'s
    /// routing — a protocol-owned method still records a post-validation hook
    /// rather than a route.
    fn add_feature_notification<F, H, Fut>(&mut self, spec: F, handler: H) -> Result<(), BuildError>
    where
        F: NotificationFeatureSpec,
        H: Fn(Arc<S>, Context, <F::Marker as Notification>::Params) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        let method = <F::Marker as Notification>::METHOD.to_string();
        let erased = erase_notification::<S, F::Marker, H, Fut>(handler);
        self.insert_notification(method, erased)?;
        spec.contribute(&mut self.capabilities)
    }

    /// Insert an already-erased notification handler under `method`, rejecting
    /// a reserved method or a duplicate. A protocol-owned notification records
    /// the connection's one post-validation hook; every other method becomes a
    /// Router route.
    fn insert_notification(
        &mut self,
        method: String,
        erased: ErasedNotificationHandler<S>,
    ) -> Result<(), BuildError> {
        if RESERVED_METHODS.contains(&method.as_str()) {
            return Err(BuildError::ReservedMethod(method));
        }
        let table = if ProtocolNotification::from_method(&method).is_some() {
            &mut self.built_in_hooks
        } else {
            &mut self.notifications
        };
        if table.insert(method.clone(), erased).is_some() {
            return Err(BuildError::DuplicateMethod(method));
        }
        Ok(())
    }

    /// Register a typed command beneath `workspace/executeCommand`.
    fn add_command<Args, Output, H, Fut>(
        &mut self,
        name: String,
        handler: H,
    ) -> Result<(), BuildError>
    where
        Args: DeserializeOwned + Send + 'static,
        Output: Serialize + 'static,
        H: Fn(Arc<S>, Context, Args, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output, LspError>> + Send + 'static,
    {
        if name.is_empty() {
            return Err(BuildError::EmptyCommandName);
        }
        let handler = Arc::new(handler);
        let erased: ErasedCommandHandler<S> = Box::new(move |state, ctx, arguments, ct| {
            let handler = Arc::clone(&handler);
            Box::pin(async move {
                let args: Args = serde_json::from_value(Value::Array(arguments))
                    .map_err(LspError::invalid_params)?;
                let result = handler(state, ctx, args, ct).await?;
                erase_value(result)
            })
        });
        if self.commands.insert(name.clone(), erased).is_some() {
            return Err(BuildError::DuplicateCommand(name));
        }
        self.capabilities.add_command(name);
        Ok(())
    }

    /// Cross-cutting validation that no single registration can detect on its
    /// own. Run both at static build time and when the initialize transaction
    /// commits, so a conditional registration cannot smuggle in a conflict.
    fn validate(&self) -> Result<(), BuildError> {
        self.capabilities.validate()?;
        self.document_sync_settings()?;
        // A command registration and an explicit `workspace/executeCommand`
        // request handler both claim the same method; they cannot coexist.
        if !self.commands.is_empty() && self.requests.contains_key(EXECUTE_COMMAND_METHOD) {
            return Err(BuildError::ExecuteCommandConflict);
        }
        Ok(())
    }

    fn document_sync_settings(&self) -> Result<DocumentSyncSettings, BuildError> {
        let save_hook = self
            .built_in_hooks
            .contains_key(ProtocolNotification::SAVE_METHOD);
        let will_save_hook = self
            .built_in_hooks
            .contains_key(ProtocolNotification::WILL_SAVE_METHOD);
        let wait_until = self.capabilities.has_will_save_wait_until();

        if let Some(explicit) = &self.document_sync {
            let save_disabled = matches!(
                explicit.save,
                Some(TextDocumentSyncSaveOptions::Supported(false))
            );
            if save_hook && save_disabled {
                return Err(BuildError::ConflictingCapability {
                    field: "textDocumentSync.save",
                });
            }
            if will_save_hook && explicit.will_save == Some(false) {
                return Err(BuildError::ConflictingCapability {
                    field: "textDocumentSync.willSave",
                });
            }
            if wait_until && explicit.will_save_wait_until == Some(false) {
                return Err(BuildError::ConflictingCapability {
                    field: "textDocumentSync.willSaveWaitUntil",
                });
            }
            if explicit.change == Some(TextDocumentSyncKind::NONE) {
                let field = if save_hook {
                    Some("textDocumentSync.save")
                } else if will_save_hook {
                    Some("textDocumentSync.willSave")
                } else if wait_until {
                    Some("textDocumentSync.willSaveWaitUntil")
                } else {
                    None
                };
                if let Some(field) = field {
                    return Err(BuildError::ConflictingCapability { field });
                }
            }
        }

        let mut options = self.document_sync.clone().unwrap_or_default();
        options.open_close.get_or_insert(true);
        options
            .change
            .get_or_insert(TextDocumentSyncKind::INCREMENTAL);
        if save_hook && options.save.is_none() {
            options.save = Some(true.into());
        }
        if will_save_hook && options.will_save.is_none() {
            options.will_save = Some(true);
        }
        if wait_until && options.will_save_wait_until.is_none() {
            options.will_save_wait_until = Some(true);
        }

        if options.change == Some(TextDocumentSyncKind::NONE) {
            options.open_close = Some(false);
            options.will_save = Some(false);
            options.will_save_wait_until = Some(false);
            options.save = Some(false.into());
            return Ok(DocumentSyncSettings {
                capability: TextDocumentSyncCapability::Kind(TextDocumentSyncKind::NONE),
                options,
            });
        }

        let capability =
            if self.document_sync.is_none() && !save_hook && !will_save_hook && !wait_until {
                TextDocumentSyncCapability::Kind(TextDocumentSyncKind::INCREMENTAL)
            } else {
                TextDocumentSyncCapability::Options(options.clone())
            };
        Ok(DocumentSyncSettings {
            capability,
            options,
        })
    }

    /// Freeze the registrations into the connection's permanent [`Router`],
    /// computing its capability catalog once from the same registrations used
    /// for dispatch (ADR 0017).
    pub(crate) fn freeze(self) -> Router<S> {
        let document_sync = self
            .document_sync_settings()
            .expect("registrations are validated before freeze");
        Router {
            requests: self.requests,
            notifications: self.notifications,
            built_in_hooks: self.built_in_hooks,
            commands: self.commands,
            capabilities: self.capabilities.finish_generated(),
            document_sync,
        }
    }
}

/// The permanently frozen table of user handlers for one connection
/// (ADR 0017). The protocol engine produces it by freezing [`Registrations`]
/// once the initialize transaction commits; no API mutates it afterward.
pub(crate) struct Router<S> {
    requests: HashMap<String, ErasedRequestHandler<S>>,
    notifications: HashMap<String, ErasedNotificationHandler<S>>,
    built_in_hooks: HashMap<String, ErasedNotificationHandler<S>>,
    commands: HashMap<String, ErasedCommandHandler<S>>,
    /// Capabilities implied by the frozen registrations, computed once at
    /// freeze time from the same registrations used for dispatch.
    capabilities: GeneratedCapabilities,
    document_sync: DocumentSyncSettings,
}

impl<S> Router<S> {
    /// The erased request handler registered for `method`, if any.
    pub(crate) fn request(&self, method: &str) -> Option<&ErasedRequestHandler<S>> {
        self.requests.get(method)
    }

    /// The erased notification handler registered for `method`, if any.
    pub(crate) fn notification(&self, method: &str) -> Option<&ErasedNotificationHandler<S>> {
        self.notifications.get(method)
    }

    /// The erased post-validation hook registered for a protocol-owned `method`,
    /// if any (ADR 0018, ADR 0023). The protocol engine has already decoded and
    /// validated by the time this hook is reached. When the built-in mutates
    /// state, the hook observes that mutation; it cannot replace the built-in.
    pub(crate) fn built_in_hook(&self, method: &str) -> Option<&ErasedNotificationHandler<S>> {
        self.built_in_hooks.get(method)
    }

    /// The erased command handler registered under `name`, if any.
    pub(crate) fn command(&self, name: &str) -> Option<&ErasedCommandHandler<S>> {
        self.commands.get(name)
    }

    /// Whether any command is registered. When true, the engine routes
    /// `workspace/executeCommand` to the command table rather than a request
    /// handler (the two are a build-time conflict and never coexist).
    pub(crate) fn has_commands(&self) -> bool {
        !self.commands.is_empty()
    }

    /// The capabilities implied by the frozen registrations. Custom requests
    /// and notifications contribute nothing; standard features and commands
    /// contribute their fields. The protocol engine layers on any
    /// protocol-owned negotiated fields separately.
    #[cfg(test)]
    pub(crate) fn capabilities(&self) -> ServerCapabilities {
        self.capabilities.standard.clone()
    }

    pub(crate) fn generated_capabilities(&self) -> GeneratedCapabilities {
        self.capabilities.clone()
    }

    pub(crate) fn document_sync(&self) -> DocumentSyncSettings {
        self.document_sync.clone()
    }
}

/// Collects static registrations for one connection before handing them to a
/// [`Server`] (ADR 0017). Registration mistakes are recorded and surfaced by
/// [`build`](Self::build); the builder methods stay chainable.
pub struct ServerBuilder<S> {
    state: Arc<S>,
    file_provider: SharedFileProvider,
    registrations: Registrations<S>,
    configure_initialize: Option<ConfigureInitialize<S>>,
    on_initialize: Option<OnInitialize<S>>,
    on_initialized: Option<OnInitialized<S>>,
    on_exit: Option<OnExit<S>>,
    layers: Vec<UserLayer<S>>,
    concurrency_limit: usize,
    outbound_warning_threshold: usize,
    /// First registration error seen, if any. Reported by `build`.
    error: Option<BuildError>,
}

impl<S: Send + Sync + 'static> ServerBuilder<S> {
    fn new(state: S) -> Self {
        Self {
            state: Arc::new(state),
            file_provider: erase(MemoryFileProvider::new()),
            registrations: Registrations::new(),
            configure_initialize: None,
            on_initialize: None,
            on_initialized: None,
            on_exit: None,
            layers: Vec::new(),
            concurrency_limit: crate::DEFAULT_CONCURRENCY_LIMIT,
            outbound_warning_threshold: crate::DEFAULT_OUTBOUND_WARNING_THRESHOLD,
            error: None,
        }
    }

    /// Configure the connection's protocol-owned text-document synchronization.
    /// Unspecified open/close and change fields retain the framework defaults;
    /// save-related fields are inferred from typed registrations.
    pub fn text_document_sync(mut self, options: TextDocumentSyncOptions) -> Self {
        self.registrations.document_sync = Some(options);
        self
    }

    /// Replace the provider used to resolve resources that are not open in
    /// the editor. The provider is owned by this connection's workspace.
    pub fn file_provider<P: FileProvider>(mut self, provider: P) -> Self {
        self.file_provider = erase(provider);
        self
    }

    /// Register a standard LSP feature and its capability contribution.
    ///
    /// `spec` is a descriptor from [`lspf::features`](crate::features) — for
    /// example [`features::hover()`](crate::features::hover) or
    /// [`features::completion(options)`](crate::features::completion). It fixes
    /// the wire method, the typed parameter and result, and the single
    /// capability field the feature advertises. The handler has the same shape
    /// as a custom [`request`](Self::request) handler for that method.
    ///
    /// Registering two handlers for the same method is a
    /// [`BuildError::DuplicateMethod`]; two features that disagree on a
    /// singular capability field are a
    /// [`BuildError::ConflictingCapability`]. Both are reported by
    /// [`build`](Self::build).
    pub fn feature<F, H, Fut>(mut self, spec: F, handler: H) -> Self
    where
        F: FeatureSpec,
        H: Fn(Arc<S>, Context, <F::Marker as Request>::Params, CancellationToken) -> Fut
            + Send
            + Sync
            + 'static,
        Fut: Future<Output = Result<<F::Marker as Request>::Result, LspError>> + Send + 'static,
    {
        if let Err(err) = self.registrations.add_feature(spec, handler) {
            self.record(err);
        }
        self
    }

    /// Register a typed custom request handler.
    ///
    /// The marker `R` implements [`lspf::types::request::Request`](crate::types)
    /// (lspf's re-export of `lsp_types::request::Request`) and thereby fixes
    /// the wire method, parameter type, and result type used by dispatch. The
    /// handler receives the shared application state, a [`Context`], the
    /// decoded parameters, and a request-scoped [`CancellationToken`].
    ///
    /// Custom requests add nothing to `ServerCapabilities`. Registering two
    /// handlers for the same method, or a method the framework reserves, is a
    /// [`BuildError`] reported by [`build`](Self::build).
    pub fn request<R, H, Fut>(mut self, handler: H) -> Self
    where
        R: Request,
        H: Fn(Arc<S>, Context, R::Params, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<R::Result, LspError>> + Send + 'static,
    {
        if let Err(err) = self.registrations.add_request::<R, H, Fut>(handler) {
            self.record(err);
        }
        self
    }

    /// Register a typed custom notification handler.
    ///
    /// The marker `N` implements
    /// [`lspf::types::notification::Notification`](crate::types) (lspf's
    /// re-export of `lsp_types::notification::Notification`) and fixes the wire
    /// method and parameter type. The handler receives the shared application
    /// state, a [`Context`], and the decoded parameters. A notification has no
    /// response, so the handler returns `()` and there is no cancellation token.
    ///
    /// Custom notifications add nothing to `ServerCapabilities`. Malformed
    /// parameters are logged and dropped without invoking the handler.
    /// Registering two handlers for the same method, or a method the framework
    /// reserves, is a [`BuildError`] reported by [`build`](Self::build).
    pub fn notification<N, H, Fut>(mut self, handler: H) -> Self
    where
        N: Notification,
        H: Fn(Arc<S>, Context, N::Params) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        if let Err(err) = self.registrations.add_notification::<N, H, Fut>(handler) {
            self.record(err);
        }
        self
    }

    /// Register a standard LSP notification feature and its capability
    /// contribution.
    ///
    /// `spec` is a descriptor from [`lspf::features`](crate::features) — for
    /// example [`features::did_create_files(options)`](crate::features::did_create_files).
    /// It fixes the wire method, the typed parameter, and the capability field
    /// the feature advertises. The handler has the same shape as a custom
    /// [`notification`](Self::notification) handler for that method.
    ///
    /// Registering two handlers for the same method is a
    /// [`BuildError::DuplicateMethod`]; two features that disagree on a
    /// singular capability field are a
    /// [`BuildError::ConflictingCapability`]. Both are reported by
    /// [`build`](Self::build).
    pub fn feature_notification<F, H, Fut>(mut self, spec: F, handler: H) -> Self
    where
        F: NotificationFeatureSpec,
        H: Fn(Arc<S>, Context, <F::Marker as Notification>::Params) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        if let Err(err) = self.registrations.add_feature_notification(spec, handler) {
            self.record(err);
        }
        self
    }

    /// Register a typed command dispatched on `workspace/executeCommand`.
    ///
    /// The command is invoked when the editor sends `workspace/executeCommand`
    /// with a matching `name`; its complete `arguments` array is decoded into
    /// `Args` (tuple, struct, and `Vec` types alike), and an absent `arguments`
    /// field decodes as an empty array. The handler's `Output` is returned as
    /// the command result. The
    /// handler receives the shared application state, a [`Context`], the typed
    /// arguments, and a request-scoped [`CancellationToken`]. `Args` and
    /// `Output` are bounded by the serialization required to cross the wire.
    ///
    /// Each registered `name` merges into one de-duplicated execute-command
    /// capability that preserves registration order (ADR 0022). An
    /// empty name, two handlers for the same name, or a command alongside an
    /// explicit `workspace/executeCommand` [`request`](Self::request) handler
    /// is a [`BuildError`] reported by [`build`](Self::build).
    pub fn command<Args, Output, H, Fut>(mut self, name: impl Into<String>, handler: H) -> Self
    where
        Args: DeserializeOwned + Send + 'static,
        Output: Serialize + 'static,
        H: Fn(Arc<S>, Context, Args, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output, LspError>> + Send + 'static,
    {
        if let Err(err) = self
            .registrations
            .add_command::<Args, Output, H, Fut>(name.into(), handler)
        {
            self.record(err);
        }
        self
    }

    /// Register the sole synchronous initialization-dependent registration
    /// callback (ADR 0017).
    ///
    /// After a valid `initialize` request the engine runs `callback` exactly
    /// once against a transactional [`InitializeRegistrar`], passing read-only
    /// `InitializeParams`. The callback may conditionally register features,
    /// requests, notifications, and commands; returning `Err` discards the
    /// whole transaction. It performs no I/O and cannot `.await`.
    ///
    /// Supplying `configure_initialize` more than once is a
    /// [`BuildError::DuplicateConfigureInitialize`] reported by
    /// [`build`](Self::build).
    pub fn configure_initialize<F>(mut self, callback: F) -> Self
    where
        F: FnOnce(&InitializeParams, &mut InitializeRegistrar<S>) -> Result<(), LspError>
            + Send
            + 'static,
    {
        if self.configure_initialize.is_some() {
            self.record(BuildError::DuplicateConfigureInitialize);
        } else {
            self.configure_initialize = Some(Box::new(callback));
        }
        self
    }

    /// Register the `on_initialize` lifecycle hook (ADR 0018).
    ///
    /// The hook runs after the `Workspace`, `Documents`, and negotiated
    /// position encoding are established and after the Router is frozen, but
    /// before the `InitializeResult` is sent. It may contribute an optional
    /// [`ServerInfo`], but it cannot register routes or replace the generated
    /// `ServerCapabilities`. Returning `Err` fails initialization.
    ///
    /// Supplying `on_initialize` more than once is a
    /// [`BuildError::DuplicateLifecycleHook`] reported by [`build`](Self::build).
    pub fn on_initialize<H, Fut>(mut self, hook: H) -> Self
    where
        H: Fn(Arc<S>, Context, InitializeParams, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Option<ServerInfo>, LspError>> + Send + 'static,
    {
        if self.on_initialize.is_some() {
            self.record(BuildError::DuplicateLifecycleHook("on_initialize"));
        } else {
            // The hook runs once, so — unlike the many-shot request handlers —
            // it needs no `Arc`; the erasing closure just boxes its future.
            self.on_initialize = Some(Box::new(move |state, ctx, params, ct| {
                Box::pin(hook(state, ctx, params, ct))
            }));
        }
        self
    }

    /// Register the `on_initialized` lifecycle hook (ADR 0024).
    ///
    /// The hook runs at most once, and only after a successful initialize
    /// transaction: when the client's `initialized` notification arrives while
    /// the connection is running. It receives the shared application state, a
    /// [`Context`], and the typed [`InitializedParams`]. A notification has no
    /// response, so the hook resolves to `()`. An `initialized` notification
    /// received before `initialize` or after `shutdown` is ignored without
    /// consuming the hook, and malformed parameters are dropped.
    ///
    /// Supplying `on_initialized` more than once is a
    /// [`BuildError::DuplicateLifecycleHook`] reported by [`build`](Self::build).
    pub fn on_initialized<H, Fut>(mut self, hook: H) -> Self
    where
        H: Fn(Arc<S>, Context, InitializedParams) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        if self.on_initialized.is_some() {
            self.record(BuildError::DuplicateLifecycleHook("on_initialized"));
        } else {
            self.on_initialized = Some(Box::new(move |state, ctx, params| {
                Box::pin(hook(state, ctx, params))
            }));
        }
        self
    }

    /// Register the `on_exit` lifecycle hook (ADR 0018, ADR 0024).
    ///
    /// The hook runs when the peer's `exit` notification arrives after a
    /// successful initialize transaction, before the protocol engine computes
    /// the exit outcome. It receives the shared application state and a
    /// [`Context`] — the notification-handler shape; `exit` carries no
    /// parameters — and resolves to `()`, so it cannot override the
    /// lifecycle-derived outcome: the reported LSP exit code is still 0 after
    /// a successful `shutdown` and 1 otherwise. An `exit` received before
    /// `initialize` closes the connection with code 1 without running the
    /// hook — no [`Workspace`](crate::Workspace) exists to hand it.
    ///
    /// Supplying `on_exit` more than once is a
    /// [`BuildError::DuplicateLifecycleHook`] reported by [`build`](Self::build).
    pub fn on_exit<H, Fut>(mut self, hook: H) -> Self
    where
        H: Fn(Arc<S>, Context) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        if self.on_exit.is_some() {
            self.record(BuildError::DuplicateLifecycleHook("on_exit"));
        } else {
            self.on_exit = Some(Box::new(move |state, ctx| Box::pin(hook(state, ctx))));
        }
        self
    }

    /// Register a user Layer around normalized user dispatch.
    ///
    /// The last registered Layer is outermost among user Layers. Framework
    /// panic isolation, tracing, and concurrency limiting remain outside it.
    pub fn layer<L>(mut self, layer: L) -> Self
    where
        L: Layer<S>,
    {
        self.layers.push(Arc::new(layer));
        self
    }

    /// Set the maximum number of calls executing inside the complete user
    /// Layer chain. Zero is rejected by [`build`](Self::build).
    pub fn concurrency_limit(mut self, limit: usize) -> Self {
        if limit == 0 {
            self.record(BuildError::InvalidConcurrencyLimit);
        } else {
            self.concurrency_limit = limit;
        }
        self
    }

    /// Set the outbound queue depth at which the engine warns once per upward
    /// crossing. Zero is rejected by [`build`](Self::build). The queue itself
    /// stays unbounded regardless: the threshold only controls when sustained
    /// depth produces a warning, never whether a message is sent.
    pub fn outbound_warning_threshold(mut self, threshold: usize) -> Self {
        if threshold == 0 {
            self.record(BuildError::InvalidOutboundWarningThreshold);
        } else {
            self.outbound_warning_threshold = threshold;
        }
        self
    }

    /// Validate the complete static registration set and return the [`Server`].
    ///
    /// Performs no I/O and does not run `configure_initialize`; the Router is
    /// frozen later, when the engine commits the initialize transaction. Returns
    /// the first [`BuildError`] recorded during registration, if any.
    pub fn build(mut self) -> Result<Server<S>, BuildError> {
        if let Err(err) = self.registrations.validate() {
            self.record(err);
        }
        if let Some(error) = self.error {
            return Err(error);
        }
        Ok(Server {
            state: self.state,
            file_provider: self.file_provider,
            registrations: self.registrations,
            configure_initialize: self.configure_initialize,
            on_initialize: self.on_initialize,
            on_initialized: self.on_initialized,
            on_exit: self.on_exit,
            layers: self.layers,
            concurrency_limit: self.concurrency_limit,
            outbound_warning_threshold: self.outbound_warning_threshold,
        })
    }

    /// Record the first registration error; later ones are dropped because the
    /// first already fails `build`.
    fn record(&mut self, error: BuildError) {
        if self.error.is_none() {
            self.error = Some(error);
        }
    }
}

/// The transactional registrar handed to `configure_initialize` (ADR 0017).
///
/// It offers the same `feature`, `request`, `notification`, and `command`
/// registration semantics as the static [`ServerBuilder`], starting from a
/// view of all static registrations, but exposes no `layer`, nested
/// `configure_initialize`, `build`, or dynamic-client operation. Conditional
/// registration mistakes are recorded and abort the whole transaction when the
/// engine commits it, so no partial route or capability ever becomes visible.
pub struct InitializeRegistrar<S> {
    registrations: Registrations<S>,
    /// First conditional registration error seen, if any. Once set, later
    /// registrations are skipped and the transaction fails on commit.
    error: Option<BuildError>,
}

impl<S: Send + Sync + 'static> InitializeRegistrar<S> {
    pub(crate) fn new(registrations: Registrations<S>) -> Self {
        Self {
            registrations,
            error: None,
        }
    }

    /// Conditionally register a standard feature and its capability. See
    /// [`ServerBuilder::feature`].
    pub fn feature<F, H, Fut>(&mut self, spec: F, handler: H) -> &mut Self
    where
        F: FeatureSpec,
        H: Fn(Arc<S>, Context, <F::Marker as Request>::Params, CancellationToken) -> Fut
            + Send
            + Sync
            + 'static,
        Fut: Future<Output = Result<<F::Marker as Request>::Result, LspError>> + Send + 'static,
    {
        self.try_register(|r| r.add_feature(spec, handler))
    }

    /// Conditionally register a typed custom request. See
    /// [`ServerBuilder::request`].
    pub fn request<R, H, Fut>(&mut self, handler: H) -> &mut Self
    where
        R: Request,
        H: Fn(Arc<S>, Context, R::Params, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<R::Result, LspError>> + Send + 'static,
    {
        self.try_register(|r| r.add_request::<R, H, Fut>(handler))
    }

    /// Conditionally register a typed custom notification. See
    /// [`ServerBuilder::notification`].
    pub fn notification<N, H, Fut>(&mut self, handler: H) -> &mut Self
    where
        N: Notification,
        H: Fn(Arc<S>, Context, N::Params) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.try_register(|r| r.add_notification::<N, H, Fut>(handler))
    }

    /// Conditionally register a standard notification feature and its
    /// capability. See [`ServerBuilder::feature_notification`].
    pub fn feature_notification<F, H, Fut>(&mut self, spec: F, handler: H) -> &mut Self
    where
        F: NotificationFeatureSpec,
        H: Fn(Arc<S>, Context, <F::Marker as Notification>::Params) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = ()> + Send + 'static,
    {
        self.try_register(|r| r.add_feature_notification(spec, handler))
    }

    /// Conditionally register a typed command. See [`ServerBuilder::command`].
    pub fn command<Args, Output, H, Fut>(
        &mut self,
        name: impl Into<String>,
        handler: H,
    ) -> &mut Self
    where
        Args: DeserializeOwned + Send + 'static,
        Output: Serialize + 'static,
        H: Fn(Arc<S>, Context, Args, CancellationToken) -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<Output, LspError>> + Send + 'static,
    {
        self.try_register(|r| r.add_command::<Args, Output, H, Fut>(name.into(), handler))
    }

    /// Apply one registration, recording its first error and skipping later
    /// ones so a broken transaction cannot accumulate more partial state.
    fn try_register(
        &mut self,
        op: impl FnOnce(&mut Registrations<S>) -> Result<(), BuildError>,
    ) -> &mut Self {
        if self.error.is_none()
            && let Err(err) = op(&mut self.registrations)
        {
            self.error = Some(err);
        }
        self
    }

    /// Commit the transaction: on success return the extended, validated
    /// registrations to be frozen; otherwise the first recorded error. Called
    /// by the engine only after `configure_initialize` returns `Ok`.
    pub(crate) fn commit(self) -> Result<Registrations<S>, BuildError> {
        if let Some(error) = self.error {
            return Err(error);
        }
        self.registrations.validate()?;
        Ok(self.registrations)
    }
}

/// Owns exactly one LSP connection: its application state, the static
/// registrations awaiting the initialize transaction, the optional
/// initialization-dependent callback, and the lifecycle hooks (`on_initialize`,
/// `on_initialized`, `on_exit`) (ADR 0017, ADR 0018). A second connection
/// requires a second `Server`; connection state is never shared between
/// servers.
pub struct Server<S> {
    pub(crate) state: Arc<S>,
    pub(crate) file_provider: SharedFileProvider,
    pub(crate) registrations: Registrations<S>,
    pub(crate) configure_initialize: Option<ConfigureInitialize<S>>,
    pub(crate) on_initialize: Option<OnInitialize<S>>,
    pub(crate) on_initialized: Option<OnInitialized<S>>,
    pub(crate) on_exit: Option<OnExit<S>>,
    pub(crate) layers: Vec<UserLayer<S>>,
    pub(crate) concurrency_limit: usize,
    pub(crate) outbound_warning_threshold: usize,
}

impl<S: Send + Sync + 'static> Server<S> {
    /// Begin building a connection-owned server around one application state
    /// value. Every handler for the connection shares `state` as `Arc<S>`.
    pub fn builder(state: S) -> ServerBuilder<S> {
        ServerBuilder::new(state)
    }

    /// Freeze the static registrations into a [`Router`] for inspection,
    /// bypassing the initialize transaction. Test-only: at runtime the engine
    /// freezes the Router after `configure_initialize` commits.
    #[cfg(test)]
    pub(crate) fn into_router(self) -> Router<S> {
        self.registrations.freeze()
    }

    /// Drive this server to completion over a custom [`Transport`](crate::Transport).
    ///
    /// Returns when the peer sends `exit`, the transport closes, the writer
    /// fails, or a failed initialize transaction terminates the connection —
    /// every one of which runs the engine's single close operation first. The
    /// returned [`Outcome`](crate::Outcome) names that ending and carries the
    /// LSP exit code; serving never terminates the process, so the caller
    /// decides what the outcome means. A reader transport error is returned as
    /// [`Error::Transport`](crate::Error::Transport) instead.
    pub async fn serve<T>(self, transport: T) -> crate::Result<crate::Outcome>
    where
        T: crate::Transport,
    {
        crate::engine::run(self, transport).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use lsp_types::request::{ExecuteCommand, HoverRequest, Shutdown};
    use lsp_types::{CompletionOptions, HoverProviderCapability};

    /// A marker for a custom method, reusing an lsp-types request type only to
    /// exercise registration without inventing wire types in the test.
    struct DummyState;

    async fn ok_hover(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::HoverParams,
        _ct: CancellationToken,
    ) -> Result<Option<lsp_types::Hover>, LspError> {
        Ok(None)
    }

    async fn ok_completion(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::CompletionParams,
        _ct: CancellationToken,
    ) -> Result<Option<lsp_types::CompletionResponse>, LspError> {
        Ok(None)
    }

    async fn ok_resolve(
        _state: Arc<DummyState>,
        _ctx: Context,
        item: lsp_types::CompletionItem,
        _ct: CancellationToken,
    ) -> Result<lsp_types::CompletionItem, LspError> {
        Ok(item)
    }

    async fn noop_command(
        _state: Arc<DummyState>,
        _ctx: Context,
        _args: Vec<String>,
        _ct: CancellationToken,
    ) -> Result<(), LspError> {
        Ok(())
    }

    async fn noop_notification(_state: Arc<DummyState>, _ctx: Context, _params: ()) {}

    #[test]
    fn duplicate_request_method_is_a_build_error() {
        let err = Server::builder(DummyState)
            .request::<HoverRequest, _, _>(ok_hover)
            .request::<HoverRequest, _, _>(ok_hover)
            .build()
            .err()
            .expect("second registration for the same method must fail");
        assert_eq!(
            err,
            BuildError::DuplicateMethod("textDocument/hover".to_string())
        );
    }

    #[test]
    fn registering_a_reserved_method_is_a_build_error() {
        async fn shutdown_handler(
            _state: Arc<DummyState>,
            _ctx: Context,
            _params: (),
            _ct: CancellationToken,
        ) -> Result<(), LspError> {
            Ok(())
        }
        let err = Server::builder(DummyState)
            .request::<Shutdown, _, _>(shutdown_handler)
            .build()
            .err()
            .expect("shutdown is framework-reserved");
        assert_eq!(err, BuildError::ReservedMethod("shutdown".to_string()));
    }

    #[test]
    fn a_single_registration_builds_and_advertises_no_extra_capabilities() {
        let server = Server::builder(DummyState)
            .request::<HoverRequest, _, _>(ok_hover)
            .build()
            .expect("a lone custom request builds");
        let router = server.into_router();
        assert!(router.request("textDocument/hover").is_some());
        assert!(router.request("nope").is_none());
        assert_eq!(
            router.capabilities(),
            ServerCapabilities::default(),
            "custom requests must not contribute capabilities"
        );
    }

    #[test]
    fn a_reserved_notification_method_is_a_build_error() {
        let err = Server::builder(DummyState)
            .notification::<lsp_types::notification::Exit, _, _>(noop_notification)
            .build()
            .err()
            .expect("exit is framework-reserved");
        assert_eq!(err, BuildError::ReservedMethod("exit".to_string()));
    }

    #[test]
    fn a_duplicate_notification_method_is_a_build_error() {
        let err = Server::builder(DummyState)
            .notification::<lsp_types::notification::DidChangeConfiguration, _, _>(
                |_s, _c, _p: lsp_types::DidChangeConfigurationParams| async {},
            )
            .notification::<lsp_types::notification::DidChangeConfiguration, _, _>(
                |_s, _c, _p: lsp_types::DidChangeConfigurationParams| async {},
            )
            .build()
            .err()
            .expect("a repeated notification method must fail");
        assert_eq!(
            err,
            BuildError::DuplicateMethod("workspace/didChangeConfiguration".to_string())
        );
    }

    #[test]
    fn workspace_mutation_hooks_contribute_no_catalog_capabilities() {
        let server = Server::builder(DummyState)
            .notification::<lsp_types::notification::DidChangeConfiguration, _, _>(
                |_s, _c, _p: lsp_types::DidChangeConfigurationParams| async {},
            )
            .build()
            .expect("a lone notification builds");
        let router = server.into_router();
        assert!(
            router
                .built_in_hook("workspace/didChangeConfiguration")
                .is_some()
        );
        assert!(
            router
                .notification("workspace/didChangeConfiguration")
                .is_none()
        );
        assert_eq!(router.capabilities(), ServerCapabilities::default());
    }

    #[test]
    fn a_document_sync_registration_records_a_hook_not_a_route() {
        let server = Server::builder(DummyState)
            .notification::<lsp_types::notification::DidOpenTextDocument, _, _>(
                |_s, _c, _p: lsp_types::DidOpenTextDocumentParams| async {},
            )
            .notification::<lsp_types::notification::DidSaveTextDocument, _, _>(
                |_s, _c, _p: lsp_types::DidSaveTextDocumentParams| async {},
            )
            .build()
            .expect("one hook and one ordinary notification build");
        let router = server.into_router();

        assert!(
            router.built_in_hook("textDocument/didOpen").is_some(),
            "a built-in document notification records a post-validation hook"
        );
        assert!(
            router.notification("textDocument/didOpen").is_none(),
            "the hook is not a Router route, so it cannot shadow the built-in"
        );
        assert!(router.notification("textDocument/didSave").is_none());
        assert!(
            router.built_in_hook("textDocument/didSave").is_some(),
            "didSave is protocol-validated before its typed hook runs"
        );
    }

    #[test]
    fn a_progress_cancel_registration_records_a_hook_not_a_route() {
        let server = Server::builder(DummyState)
            .notification::<lsp_types::notification::WorkDoneProgressCancel, _, _>(
                |_s, _c, _p: lsp_types::WorkDoneProgressCancelParams| async {},
            )
            .build()
            .expect("a lone progress-cancel hook builds");
        let router = server.into_router();

        assert!(
            router
                .built_in_hook("window/workDoneProgress/cancel")
                .is_some(),
            "the progress-cancel built-in records a post-validation hook"
        );
        assert!(
            router
                .notification("window/workDoneProgress/cancel")
                .is_none(),
            "the hook is not a Router route, so it cannot replace the built-in"
        );
        assert_eq!(
            router.capabilities(),
            ServerCapabilities::default(),
            "a progress-cancel hook contributes no capabilities"
        );
    }

    #[test]
    fn a_duplicate_document_hook_is_a_build_error() {
        let err = Server::builder(DummyState)
            .notification::<lsp_types::notification::DidChangeTextDocument, _, _>(
                |_s, _c, _p: lsp_types::DidChangeTextDocumentParams| async {},
            )
            .notification::<lsp_types::notification::DidChangeTextDocument, _, _>(
                |_s, _c, _p: lsp_types::DidChangeTextDocumentParams| async {},
            )
            .build()
            .err()
            .expect("a built-in notification takes at most one hook");
        assert_eq!(
            err,
            BuildError::DuplicateMethod("textDocument/didChange".to_string())
        );
    }

    #[test]
    fn document_hooks_contribute_no_capabilities() {
        let without_hook = Server::builder(DummyState)
            .build()
            .expect("an empty server builds")
            .into_router()
            .capabilities();
        let with_hook = Server::builder(DummyState)
            .notification::<lsp_types::notification::DidCloseTextDocument, _, _>(
                |_s, _c, _p: lsp_types::DidCloseTextDocumentParams| async {},
            )
            .build()
            .expect("a lone document hook builds")
            .into_router()
            .capabilities();
        // Compared against a hookless build rather than asserting an absolute
        // set: what a built-in itself advertises is the built-in's business,
        // and observing one must not change it either way.
        assert_eq!(
            with_hook, without_hook,
            "observing a built-in advertises nothing the built-in did not"
        );
    }

    #[test]
    fn an_empty_command_name_is_a_build_error() {
        let err = Server::builder(DummyState)
            .command::<Vec<String>, (), _, _>("", noop_command)
            .build()
            .err()
            .expect("an empty command name must fail");
        assert_eq!(err, BuildError::EmptyCommandName);
    }

    #[test]
    fn a_duplicate_command_name_is_a_build_error() {
        let err = Server::builder(DummyState)
            .command::<Vec<String>, (), _, _>("my.cmd", noop_command)
            .command::<Vec<String>, (), _, _>("my.cmd", noop_command)
            .build()
            .err()
            .expect("a repeated command name must fail");
        assert_eq!(err, BuildError::DuplicateCommand("my.cmd".to_string()));
    }

    #[test]
    fn commands_alongside_an_explicit_execute_command_handler_conflict() {
        async fn raw_execute(
            _state: Arc<DummyState>,
            _ctx: Context,
            _params: lsp_types::ExecuteCommandParams,
            _ct: CancellationToken,
        ) -> Result<Option<serde_json::Value>, LspError> {
            Ok(None)
        }
        let err = Server::builder(DummyState)
            .command::<Vec<String>, (), _, _>("my.cmd", noop_command)
            .request::<ExecuteCommand, _, _>(raw_execute)
            .build()
            .err()
            .expect("a command and a raw execute-command handler cannot coexist");
        assert_eq!(err, BuildError::ExecuteCommandConflict);
    }

    #[test]
    fn registered_commands_contribute_one_execute_command_capability() {
        let server = Server::builder(DummyState)
            .command::<Vec<String>, (), _, _>("b.cmd", noop_command)
            .command::<Vec<String>, (), _, _>("a.cmd", noop_command)
            .build()
            .expect("commands build");
        let provider = server
            .into_router()
            .capabilities()
            .execute_command_provider
            .expect("commands advertise an execute-command capability");
        assert_eq!(
            provider.commands,
            vec!["b.cmd".to_string(), "a.cmd".to_string()],
            "command names merge into one de-duplicated, registration-order list"
        );
    }

    #[test]
    fn hover_feature_sets_only_hover_provider() {
        let server = Server::builder(DummyState)
            .feature(crate::features::hover(), ok_hover)
            .build()
            .expect("hover builds");
        let router = server.into_router();
        let caps = router.capabilities();
        assert_eq!(
            caps.hover_provider,
            Some(HoverProviderCapability::Simple(true))
        );
        assert_eq!(caps.completion_provider, None);
        assert!(router.request("textDocument/hover").is_some());
    }

    #[test]
    fn hover_and_completion_merge_independent_of_order() {
        let options = CompletionOptions {
            trigger_characters: Some(vec![".".to_string()]),
            ..CompletionOptions::default()
        };
        let hover_first = Server::builder(DummyState)
            .feature(crate::features::hover(), ok_hover)
            .feature(crate::features::completion(options.clone()), ok_completion)
            .build()
            .expect("hover then completion builds")
            .into_router()
            .capabilities();
        let completion_first = Server::builder(DummyState)
            .feature(crate::features::completion(options.clone()), ok_completion)
            .feature(crate::features::hover(), ok_hover)
            .build()
            .expect("completion then hover builds")
            .into_router()
            .capabilities();
        assert_eq!(
            hover_first, completion_first,
            "capability merge is independent of registration order"
        );
        assert_eq!(
            hover_first.completion_provider,
            Some(options),
            "completion advertises the supplied options"
        );
    }

    #[test]
    fn a_duplicate_feature_is_a_build_error_not_last_write_wins() {
        let err = Server::builder(DummyState)
            .feature(crate::features::hover(), ok_hover)
            .feature(crate::features::hover(), ok_hover)
            .build()
            .err()
            .expect("registering hover twice must fail");
        assert_eq!(
            err,
            BuildError::DuplicateMethod("textDocument/hover".to_string())
        );
    }

    #[test]
    fn completion_and_resolve_merge_into_one_capability_independent_of_order() {
        let options = || CompletionOptions {
            trigger_characters: Some(vec![".".to_string()]),
            ..CompletionOptions::default()
        };
        let base_first = Server::builder(DummyState)
            .feature(crate::features::completion(options()), ok_completion)
            .feature(crate::features::completion_resolve(), ok_resolve)
            .build()
            .expect("completion then resolve builds")
            .into_router();
        let resolve_first = Server::builder(DummyState)
            .feature(crate::features::completion_resolve(), ok_resolve)
            .feature(crate::features::completion(options()), ok_completion)
            .build()
            .expect("resolve then completion builds")
            .into_router();

        assert_eq!(
            base_first.capabilities(),
            resolve_first.capabilities(),
            "the family merge is independent of registration order"
        );
        let merged = base_first
            .capabilities()
            .completion_provider
            .expect("the family emits one completionProvider capability");
        assert_eq!(merged.resolve_provider, Some(true));
        assert_eq!(merged.trigger_characters, Some(vec![".".to_string()]));
        assert!(base_first.request("textDocument/completion").is_some());
        assert!(base_first.request("completionItem/resolve").is_some());
    }

    #[test]
    fn completion_resolve_without_completion_is_a_build_error() {
        let err = Server::builder(DummyState)
            .feature(crate::features::completion_resolve(), ok_resolve)
            .build()
            .err()
            .expect("resolve without its base feature must fail");
        assert_eq!(
            err,
            BuildError::ConflictingCapability {
                field: "completionProvider"
            }
        );
    }

    #[test]
    fn unequal_resolve_contributions_within_the_family_fail() {
        let err = Server::builder(DummyState)
            .feature(
                crate::features::completion(CompletionOptions {
                    resolve_provider: Some(false),
                    ..CompletionOptions::default()
                }),
                ok_completion,
            )
            .feature(crate::features::completion_resolve(), ok_resolve)
            .build()
            .err()
            .expect("a base that denies resolve and a resolve registration clash");
        assert_eq!(
            err,
            BuildError::ConflictingCapability {
                field: "completionProvider"
            },
            "capability construction never resolves a clash by last-write-wins"
        );
    }

    async fn noop_on_initialize(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::InitializeParams,
        _ct: CancellationToken,
    ) -> Result<Option<lsp_types::ServerInfo>, LspError> {
        Ok(None)
    }

    #[test]
    fn duplicate_configure_initialize_is_a_build_error() {
        let err = Server::builder(DummyState)
            .configure_initialize(|_params, _registrar| Ok(()))
            .configure_initialize(|_params, _registrar| Ok(()))
            .build()
            .err()
            .expect("supplying configure_initialize twice must fail");
        assert_eq!(err, BuildError::DuplicateConfigureInitialize);
    }

    #[test]
    fn duplicate_on_initialize_is_a_build_error() {
        let err = Server::builder(DummyState)
            .on_initialize(noop_on_initialize)
            .on_initialize(noop_on_initialize)
            .build()
            .err()
            .expect("supplying on_initialize twice must fail");
        assert_eq!(err, BuildError::DuplicateLifecycleHook("on_initialize"));
    }

    async fn noop_on_initialized(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::InitializedParams,
    ) {
    }

    async fn noop_on_exit(_state: Arc<DummyState>, _ctx: Context) {}

    #[test]
    fn duplicate_on_initialized_is_a_build_error() {
        let err = Server::builder(DummyState)
            .on_initialized(noop_on_initialized)
            .on_initialized(noop_on_initialized)
            .build()
            .err()
            .expect("supplying on_initialized twice must fail");
        assert_eq!(err, BuildError::DuplicateLifecycleHook("on_initialized"));
    }

    #[test]
    fn duplicate_on_exit_is_a_build_error() {
        let err = Server::builder(DummyState)
            .on_exit(noop_on_exit)
            .on_exit(noop_on_exit)
            .build()
            .err()
            .expect("supplying on_exit twice must fail");
        assert_eq!(err, BuildError::DuplicateLifecycleHook("on_exit"));
    }

    #[test]
    fn lifecycle_hooks_contribute_no_catalog_capabilities() {
        let server = Server::builder(DummyState)
            .on_initialized(noop_on_initialized)
            .on_exit(noop_on_exit)
            .build()
            .expect("a server with only lifecycle hooks builds");
        let router = server.into_router();
        assert!(
            router.notification("initialized").is_none(),
            "initialized is not a Router route; it is a reserved lifecycle notification"
        );
        assert_eq!(
            router.capabilities(),
            ServerCapabilities::default(),
            "lifecycle hooks contribute nothing to the capability catalog"
        );
    }

    #[test]
    fn initialized_is_a_reserved_notification_method() {
        let err = Server::builder(DummyState)
            .notification::<lsp_types::notification::Initialized, _, _>(
                |_s, _c, _p: lsp_types::InitializedParams| async {},
            )
            .build()
            .err()
            .expect("initialized is framework-reserved");
        assert_eq!(err, BuildError::ReservedMethod("initialized".to_string()));
    }

    async fn ok_workspace_symbol(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::WorkspaceSymbolParams,
        _ct: CancellationToken,
    ) -> Result<Option<lsp_types::WorkspaceSymbolResponse>, LspError> {
        Ok(None)
    }

    async fn ok_symbol_resolve(
        _state: Arc<DummyState>,
        _ctx: Context,
        symbol: lsp_types::WorkspaceSymbol,
        _ct: CancellationToken,
    ) -> Result<lsp_types::WorkspaceSymbol, LspError> {
        Ok(symbol)
    }

    async fn ok_will_rename(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::RenameFilesParams,
        _ct: CancellationToken,
    ) -> Result<Option<lsp_types::WorkspaceEdit>, LspError> {
        Ok(None)
    }

    async fn noop_rename_files(
        _state: Arc<DummyState>,
        _ctx: Context,
        _params: lsp_types::RenameFilesParams,
    ) {
    }

    fn rename_filters() -> lsp_types::FileOperationRegistrationOptions {
        lsp_types::FileOperationRegistrationOptions {
            filters: vec![lsp_types::FileOperationFilter {
                scheme: Some("file".to_string()),
                pattern: lsp_types::FileOperationPattern {
                    glob: "**/*.rs".to_string(),
                    matches: Some(lsp_types::FileOperationPatternKind::File),
                    options: None,
                },
            }],
        }
    }

    fn workspace_symbol_options() -> lsp_types::WorkspaceSymbolOptions {
        lsp_types::WorkspaceSymbolOptions {
            work_done_progress_options: Default::default(),
            resolve_provider: None,
        }
    }

    #[test]
    fn workspace_symbol_and_resolve_merge_into_one_capability_independent_of_order() {
        let base_first = Server::builder(DummyState)
            .feature(
                crate::features::workspace_symbol(workspace_symbol_options()),
                ok_workspace_symbol,
            )
            .feature(
                crate::features::workspace_symbol_resolve(),
                ok_symbol_resolve,
            )
            .build()
            .expect("workspace symbol then resolve builds")
            .into_router();
        let resolve_first = Server::builder(DummyState)
            .feature(
                crate::features::workspace_symbol_resolve(),
                ok_symbol_resolve,
            )
            .feature(
                crate::features::workspace_symbol(workspace_symbol_options()),
                ok_workspace_symbol,
            )
            .build()
            .expect("resolve then workspace symbol builds")
            .into_router();

        assert_eq!(
            base_first.capabilities(),
            resolve_first.capabilities(),
            "the family merge is independent of registration order"
        );
        let merged = base_first
            .capabilities()
            .workspace_symbol_provider
            .expect("the family emits one workspaceSymbolProvider capability");
        let lsp_types::OneOf::Right(options) = merged else {
            panic!("the family advertises full options, not a bare boolean");
        };
        assert_eq!(options.resolve_provider, Some(true));
        assert!(base_first.request("workspace/symbol").is_some());
        assert!(base_first.request("workspaceSymbol/resolve").is_some());
    }

    #[test]
    fn workspace_symbol_resolve_without_workspace_symbol_is_a_build_error() {
        let err = Server::builder(DummyState)
            .feature(
                crate::features::workspace_symbol_resolve(),
                ok_symbol_resolve,
            )
            .build()
            .err()
            .expect("resolve without its base feature must fail");
        assert_eq!(
            err,
            BuildError::ConflictingCapability {
                field: "workspaceSymbolProvider"
            }
        );
    }

    #[test]
    fn file_operation_features_share_one_family_capability() {
        let server = Server::builder(DummyState)
            .feature(
                crate::features::will_rename_files(rename_filters()),
                ok_will_rename,
            )
            .feature_notification(
                crate::features::did_rename_files(rename_filters()),
                noop_rename_files,
            )
            .build()
            .expect("identical will/did filters merge");
        let router = server.into_router();
        assert!(router.request("workspace/willRenameFiles").is_some());
        assert!(router.notification("workspace/didRenameFiles").is_some());
        let file_operations = router
            .capabilities()
            .workspace
            .expect("the family advertises the workspace object")
            .file_operations
            .expect("the family advertises a fileOperations capability");
        let expected = Some(rename_filters());
        assert_eq!(file_operations.will_rename, expected.clone());
        assert_eq!(file_operations.did_rename, expected);
        assert_eq!(file_operations.will_create, None);
    }

    #[test]
    fn disagreeing_file_operation_filters_are_a_build_error() {
        let mut other = rename_filters();
        other.filters[0].pattern.glob = "**/*.toml".to_string();
        let err = Server::builder(DummyState)
            .feature(
                crate::features::will_rename_files(rename_filters()),
                ok_will_rename,
            )
            .feature_notification(crate::features::did_rename_files(other), noop_rename_files)
            .build()
            .err()
            .expect("differing filters within one family must fail");
        assert_eq!(
            err,
            BuildError::ConflictingCapability {
                field: "workspace.fileOperations.rename"
            }
        );
    }

    #[test]
    fn a_duplicate_notification_feature_is_a_build_error() {
        let err = Server::builder(DummyState)
            .feature_notification(
                crate::features::did_rename_files(rename_filters()),
                noop_rename_files,
            )
            .feature_notification(
                crate::features::did_rename_files(rename_filters()),
                noop_rename_files,
            )
            .build()
            .err()
            .expect("registering the same notification feature twice must fail");
        assert_eq!(
            err,
            BuildError::DuplicateMethod("workspace/didRenameFiles".to_string())
        );
    }

    #[test]
    fn watched_files_feature_registers_a_route_and_contributes_no_capability() {
        async fn noop_watched(
            _state: Arc<DummyState>,
            _ctx: Context,
            _params: lsp_types::DidChangeWatchedFilesParams,
        ) {
        }
        let server = Server::builder(DummyState)
            .feature_notification(crate::features::did_change_watched_files(), noop_watched)
            .build()
            .expect("the watched-files feature builds");
        let router = server.into_router();
        assert!(
            router
                .notification("workspace/didChangeWatchedFiles")
                .is_some(),
            "watched files is an ordinary route: the framework owns no mutation for it"
        );
        assert_eq!(
            router.capabilities(),
            ServerCapabilities::default(),
            "LSP 3.17 has no watched-files server capability, so none is advertised"
        );
    }

    #[test]
    fn the_outbound_warning_threshold_defaults_to_1024() {
        let server = Server::builder(DummyState)
            .build()
            .expect("the default threshold builds");
        assert_eq!(server.outbound_warning_threshold, 1024);
        assert_eq!(
            server.outbound_warning_threshold,
            crate::DEFAULT_OUTBOUND_WARNING_THRESHOLD
        );
    }

    #[test]
    fn the_outbound_warning_threshold_accepts_positive_values() {
        let server = Server::builder(DummyState)
            .outbound_warning_threshold(7)
            .build()
            .expect("a positive threshold builds");
        assert_eq!(server.outbound_warning_threshold, 7);
    }

    #[test]
    fn a_zero_outbound_warning_threshold_is_a_build_error() {
        let err = Server::builder(DummyState)
            .outbound_warning_threshold(0)
            .build()
            .err()
            .expect("a zero threshold must fail the build");
        assert_eq!(err, BuildError::InvalidOutboundWarningThreshold);
        assert_eq!(
            err.to_string(),
            "outbound warning threshold must be greater than zero"
        );
    }
}