symforge 10.0.0

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
pub mod ccr;
pub mod conventions;
pub(crate) mod edit;
pub(crate) mod edit_format;
pub mod edit_hooks;
pub mod edit_plan;
pub(crate) mod edit_tools;
pub mod explore;
pub mod format;
pub mod investigation;
pub(crate) mod knowledge_curation;
pub(crate) mod knowledge_model;
pub(crate) mod knowledge_review;
pub(crate) mod knowledge_search;
pub mod prompts;
pub(crate) mod read_gate;
pub(crate) mod read_tools;
pub mod resources;
pub mod result_status;
pub(crate) mod search_format;
pub(crate) mod search_tools;
pub mod session;
pub mod smart_query;
pub mod surface_probe;
pub mod tools;

use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use parking_lot::{Mutex, RwLock};

use rmcp::RoleServer;
use rmcp::handler::server::router::prompt::PromptRouter;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::model::{
    ListResourceTemplatesResult, ListResourcesResult, ListToolsResult, PaginatedRequestParams,
    ReadResourceRequestParams, ServerCapabilities, ServerInfo, Tool,
};
use rmcp::service::RequestContext;
use rmcp::{ServerHandler, tool_handler};

use crate::domain::{
    CapabilityStatus, CapabilityUnavailableReason, ControlStateDir, ProjectStateDir, StatePlacement,
};
use crate::live_index::SharedIndex;
use crate::protocol::result_status::OutcomeClass;
use crate::sidecar::TokenStats;
use crate::watcher::WatcherInfo;

/// Tracks in-flight durable-ledger `spawn_blocking` writes so [`crate::server::serve::run`]
/// can drain them on shutdown instead of dropping economics events scheduled
/// just before SIGINT/SIGTERM (review finding P2-3).
///
/// Dependency-free: an atomic in-flight counter polled by [`Self::drain`]. Each
/// scheduled write holds a [`LedgerWriteGuard`] whose `Drop` decrements the
/// counter when the blocking write returns.
#[cfg(feature = "server")]
#[derive(Debug, Default)]
pub struct LedgerWriteTracker {
    in_flight: std::sync::atomic::AtomicUsize,
}

#[cfg(feature = "server")]
impl LedgerWriteTracker {
    /// Register a write about to be scheduled; the returned guard decrements the
    /// in-flight count on drop (i.e. when the blocking write completes).
    fn begin(self: &std::sync::Arc<Self>) -> LedgerWriteGuard {
        self.in_flight
            .fetch_add(1, std::sync::atomic::Ordering::AcqRel);
        LedgerWriteGuard(std::sync::Arc::clone(self))
    }

    /// Number of durable writes still in flight.
    fn pending(&self) -> usize {
        self.in_flight.load(std::sync::atomic::Ordering::Acquire)
    }

    /// Wait until every scheduled durable write completes, or `timeout` elapses
    /// (whichever comes first). Polls the in-flight counter; on timeout it logs
    /// the residual count rather than blocking shutdown indefinitely.
    pub async fn drain(&self, timeout: std::time::Duration) {
        let deadline = std::time::Instant::now() + timeout;
        while self.pending() != 0 {
            if std::time::Instant::now() >= deadline {
                tracing::warn!(
                    pending = self.pending(),
                    "durable ledger drain timed out; some economics events may be unwritten"
                );
                return;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        }
    }
}

/// Guard returned by [`LedgerWriteTracker::begin`]; decrements the in-flight
/// count when the blocking durable write completes (on drop).
#[cfg(feature = "server")]
struct LedgerWriteGuard(std::sync::Arc<LedgerWriteTracker>);

#[cfg(feature = "server")]
impl Drop for LedgerWriteGuard {
    fn drop(&mut self) {
        self.0
            .in_flight
            .fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
    }
}

#[cfg(all(test, feature = "server"))]
mod ledger_write_tracker_tests {
    use super::LedgerWriteTracker;
    use std::sync::Arc;
    use std::time::Duration;

    #[tokio::test]
    async fn drain_returns_after_pending_write_completes() {
        let tracker = Arc::new(LedgerWriteTracker::default());
        let guard = tracker.begin();
        assert_eq!(tracker.pending(), 1);
        // Release the guard shortly; drain must wait for it, then return.
        let t2 = Arc::clone(&tracker);
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(20)).await;
            drop(guard);
            let _ = &t2;
        });
        tracker.drain(Duration::from_secs(2)).await;
        assert_eq!(
            tracker.pending(),
            0,
            "drain returned with a write still pending"
        );
    }

    #[tokio::test]
    async fn drain_times_out_without_hanging_on_a_stuck_write() {
        let tracker = Arc::new(LedgerWriteTracker::default());
        let _held = tracker.begin(); // never released => simulates a stuck write
        let start = std::time::Instant::now();
        tracker.drain(Duration::from_millis(50)).await;
        assert!(
            start.elapsed() >= Duration::from_millis(50),
            "drain returned before the timeout elapsed"
        );
        assert_eq!(tracker.pending(), 1, "stuck write must still be counted");
    }
}
/// The MCP server struct.
///
/// Holds a `SharedIndex` and a `ToolRouter` generated by the `#[tool_router]` macro.
/// Holds a `PromptRouter` generated by the `#[prompt_router]` macro.
/// The `project_name` field is passed through to `format::repo_outline`.
/// The `watcher_info` field is read by the health tool to report live watcher state.
/// The `repo_root` field is used by `index_folder` to restart the watcher at a new root.
/// The `token_stats` field provides live hook token savings to the health tool (AD-4 simpler path).
#[derive(Clone)]
pub struct SymForgeServer {
    pub(crate) index: SharedIndex,
    pub(crate) tool_router: ToolRouter<Self>,
    pub(crate) prompt_router: PromptRouter<Self>,
    pub(crate) project_name: String,
    pub(crate) watcher_info: Arc<Mutex<WatcherInfo>>,
    /// MUST NOT be held across `.await`. Use `.lock().take()` and
    /// `.lock().replace(...)` around async work; `parking_lot::Mutex` is
    /// non-async and held-across-await would deadlock the runtime.
    /// Some only in local-stdio mode where this server owns its watcher.
    /// None in daemon-proxy mode and daemon-degraded mode.
    pub(crate) watcher_handle: Arc<Mutex<Option<crate::watcher::WatcherTaskHandle>>>,
    /// Root directory the watcher is currently watching. Stored in shared mutable
    /// state so local stdio tools can keep using the latest project root after
    /// `index_folder` rebinds the server to a new workspace.
    pub(crate) repo_root: Arc<RwLock<Option<PathBuf>>>,
    /// Persistence placement selected for the currently bound project.
    ///
    /// Kept beside `repo_root` so checkpoint/reset paths consume the same typed
    /// placement selected during binding instead of reconstructing
    /// `<source>/.symforge`. A mixed root/placement observation during a
    /// concurrent rebind is fail-closed by the persistence root-ID check.
    pub(crate) state_placement: Arc<RwLock<Option<StatePlacement>>>,
    /// Process-global coordination namespace selected once for daemon/sidecar
    /// discovery. It is independent from the bound project's persistence
    /// placement and must never be reconstructed from the source root.
    pub(crate) control_state_dir: Option<ControlStateDir>,
    /// Runtime durability of the selected project-state owner. Placement is
    /// stable for the binding lifetime; a later write failure changes only this
    /// health signal and the capabilities derived from it.
    pub(crate) persistence_health: Arc<RwLock<CapabilityStatus>>,
    /// One ledger-mutation coordinator shared by every session bound to the
    /// same project runtime. It owns preview/apply serialization, durability
    /// probe caching, durable replay, and crash recovery for Gate K.
    pub(crate) curation_coordinator: Arc<knowledge_curation::KnowledgeCurationCoordinator>,
    /// Shared token stats from the HTTP sidecar. Present when the sidecar is running.
    /// The health tool reads this to display token savings accumulated during the session.
    pub(crate) token_stats: Option<Arc<TokenStats>>,
    /// Optional daemon-backed proxy session. When present, tool calls are forwarded to the
    /// shared daemon-owned project runtime instead of the local in-process index.
    /// Wrapped in `tokio::sync::RwLock` so reconnection can swap in a fresh client.
    pub(crate) daemon_client: Option<Arc<tokio::sync::RwLock<crate::daemon::DaemonSessionClient>>>,
    /// Set to `true` after a failed reconnection attempt. While degraded,
    /// calls make one success probe but avoid repeated reconnect attempts.
    pub(crate) daemon_degraded: Arc<AtomicBool>,
    /// Session context tracking: records what the LLM has fetched this session.
    pub(crate) session_context: Arc<session::SessionContext>,
    /// Per-session CCR blob store for reversible bulk compression (011).
    pub(crate) ccr_store: Arc<Mutex<ccr::CcrStore>>,
    /// In-memory STEL L4 ledger for compact `symforge` invocations (no persistence yet).
    pub(crate) stel_ledger: Arc<Mutex<crate::stel::ledger::SessionLedger>>,
    /// Tracks edit-tool calls that omitted `working_directory` while the
    /// transitional worktree observability knob was on. Surfaced by the
    /// `health` tool as a rolling "last hour" signal.
    pub(crate) worktree_misuse: Arc<crate::worktree::WorktreeMisuseCounter>,
    /// Bounded analytics queue. Disabled by default until an explicit local
    /// analytics configuration installs an enabled recorder.
    pub(crate) analytics_recorder: Arc<RwLock<crate::analytics::AnalyticsRecorder>>,
    /// Durable STEL L4 economics ledger. `Some` when `serve::run` (US3) or the
    /// stdio/daemon-proxy bootstrap (US1 T020/T021) wires the opened store in;
    /// `None` otherwise. The same `Arc` is shared with `ServerRuntime` so there
    /// is exactly one durable ledger path (no economics double-count). When
    /// `Some` it may be [`crate::stel::ledger_store::StelLedgerStore::Disabled`]
    /// if the DB could not open — write-through then degrades to a logged no-op
    /// (FR-011).
    ///
    /// Server-gated: embed durability is DEFERRED — `protocol` is crate-root
    /// server-gated (`src/lib.rs`), so an `any(server, embed)` cfg here would be
    /// dead under embed. Reaching the store from embed needs a structural
    /// protocol-free seam (out of US1 scope; spec FR-001 note).
    #[cfg(feature = "server")]
    pub(crate) stel_ledger_store: Option<Arc<crate::stel::ledger_store::StelLedgerStore>>,
    /// In-flight durable-ledger write tracker (P2-3): lets `serve::run` drain
    /// pending `spawn_blocking` economics writes on shutdown so events accepted
    /// just before SIGINT/SIGTERM are not lost.
    #[cfg(feature = "server")]
    pub(crate) ledger_writes: Arc<LedgerWriteTracker>,
}

fn default_analytics_db_path(project_state_dir: Option<&ProjectStateDir>) -> PathBuf {
    project_state_dir
        .map(|state_dir| {
            crate::paths::project_state_path(state_dir, crate::paths::ANALYTICS_DB_NAME)
        })
        // Disabled analytics performs no I/O. With no durable project-state
        // owner, retain an empty diagnostic path instead of inventing a
        // CWD-relative fallback.
        .unwrap_or_default()
}

fn disabled_analytics_recorder(
    project_state_dir: Option<&ProjectStateDir>,
) -> crate::analytics::AnalyticsRecorder {
    crate::analytics::AnalyticsRecorder::disabled(default_analytics_db_path(project_state_dir))
}

fn estimate_tokens(response_bytes: u64) -> u64 {
    response_bytes.saturating_add(3) / 4
}

impl SymForgeServer {
    pub(crate) fn tool_router() -> ToolRouter<Self> {
        Self::core_tool_router() + Self::edit_tool_router()
    }

    /// Create a new server with the given shared index, project name, and watcher state.
    ///
    /// `token_stats` is optional — when `Some`, the health tool will include a token savings
    /// section showing per-hook-type fire counts and estimated tokens saved this session.
    pub fn new(
        index: SharedIndex,
        project_name: String,
        watcher_info: Arc<Mutex<WatcherInfo>>,
        repo_root: Option<PathBuf>,
        token_stats: Option<Arc<TokenStats>>,
    ) -> Self {
        let (repo_root, state_placement) = match repo_root.as_deref() {
            Some(root) => match crate::discovery::resolve_root_candidate(
                root,
                crate::domain::RootCandidateSource::LaunchCwd,
                crate::domain::RootRequestMode::Automatic,
            ) {
                crate::domain::RootResolution::Bound(binding) => {
                    let placement = crate::discovery::resolve_state_placement(&binding);
                    (Some(binding.canonical_root), Some(placement))
                }
                crate::domain::RootResolution::Unbound { .. } => (None, None),
            },
            None => (None, None),
        };
        Self::new_with_state_placement(
            index,
            project_name,
            watcher_info,
            repo_root,
            state_placement,
            token_stats,
        )
    }

    /// Create a server with an already-resolved project state placement.
    ///
    /// Production bind paths use this constructor so root authorization and
    /// state placement run once and every persistence consumer receives the
    /// same typed result. [`Self::new`] remains the compatibility constructor
    /// for callers that only have an automatically authorized normal root.
    pub fn new_with_state_placement(
        index: SharedIndex,
        project_name: String,
        watcher_info: Arc<Mutex<WatcherInfo>>,
        repo_root: Option<PathBuf>,
        state_placement: Option<StatePlacement>,
        token_stats: Option<Arc<TokenStats>>,
    ) -> Self {
        crate::worktree::register_if_feature_enabled();
        let analytics_recorder = disabled_analytics_recorder(
            state_placement.as_ref().and_then(StatePlacement::directory),
        );
        let persistence_health = if matches!(
            state_placement.as_ref(),
            Some(StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. })
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        // This constructor is 99.1% of `serve: runtime built` on a cold index
        // (2.91s of 2.94s) but is ~free when the index came from a snapshot
        // restore. Only ONE thing in here takes the index, so name it: the
        // routers below are static and would cost the same on both paths.
        let curation_coordinator =
            Arc::new(knowledge_curation::KnowledgeCurationCoordinator::default());
        let phase = std::time::Instant::now();
        if let Some(root) = repo_root.as_deref()
            && let Err(error) = curation_coordinator.recover_on_project_load(
                &index,
                root,
                state_placement.as_ref(),
                persistence_health,
            )
        {
            tracing::warn!("knowledge curation startup recovery remained fail-closed: {error}");
        }
        tracing::info!(
            "serve: protocol/curation recover_on_project_load in {:?}",
            phase.elapsed()
        );

        let phase = std::time::Instant::now();
        let tool_router = Self::tool_router();
        let prompt_router = Self::prompt_router();
        tracing::info!("serve: protocol/routers in {:?}", phase.elapsed());
        Self {
            index,
            tool_router,
            prompt_router,
            project_name,
            watcher_info,
            watcher_handle: Arc::new(Mutex::new(None)),
            repo_root: Arc::new(RwLock::new(repo_root)),
            state_placement: Arc::new(RwLock::new(state_placement)),
            control_state_dir: crate::paths::process_control_state_placement()
                .directory()
                .cloned(),
            persistence_health: Arc::new(RwLock::new(persistence_health)),
            curation_coordinator,
            token_stats,
            daemon_client: None,
            daemon_degraded: Arc::new(AtomicBool::new(false)),
            session_context: Arc::new(session::SessionContext::new()),
            ccr_store: Arc::new(Mutex::new(ccr::CcrStore::new())),
            stel_ledger: Arc::new(Mutex::new(crate::stel::ledger::SessionLedger::new())),
            worktree_misuse: Arc::new(crate::worktree::WorktreeMisuseCounter::new()),
            analytics_recorder: Arc::new(RwLock::new(analytics_recorder)),
            #[cfg(feature = "server")]
            stel_ledger_store: None,
            #[cfg(feature = "server")]
            ledger_writes: Arc::new(LedgerWriteTracker::default()),
        }
    }

    pub fn new_daemon_proxy(daemon_client: crate::daemon::DaemonSessionClient) -> Self {
        let repo_root = daemon_client.project_root().map(|p| p.to_path_buf());
        let state_placement = repo_root.as_deref().and_then(|root| {
            match crate::discovery::resolve_root_candidate(
                root,
                crate::domain::RootCandidateSource::LaunchCwd,
                crate::domain::RootRequestMode::Automatic,
            ) {
                crate::domain::RootResolution::Bound(binding) => {
                    Some(crate::discovery::resolve_state_placement(&binding))
                }
                crate::domain::RootResolution::Unbound { .. } => None,
            }
        });
        Self::new_daemon_proxy_with_state_placement(daemon_client, state_placement)
    }

    /// Create a daemon proxy with a placement already resolved by the adapter.
    ///
    /// This keeps every adapter-side persistence consumer on the same typed
    /// owner instead of resolving state independently from the source root.
    pub fn new_daemon_proxy_with_state_placement(
        daemon_client: crate::daemon::DaemonSessionClient,
        state_placement: Option<StatePlacement>,
    ) -> Self {
        use crate::watcher::WatcherInfo;

        crate::worktree::register_if_feature_enabled();
        let project_name = daemon_client.project_name().to_string();
        let repo_root = daemon_client.project_root().map(|p| p.to_path_buf());
        let analytics_recorder = disabled_analytics_recorder(
            state_placement.as_ref().and_then(StatePlacement::directory),
        );
        let persistence_health = if matches!(
            state_placement.as_ref(),
            Some(StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. })
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        Self {
            index: crate::live_index::LiveIndex::empty(),
            tool_router: Self::tool_router(),
            prompt_router: Self::prompt_router(),
            project_name,
            watcher_info: Arc::new(Mutex::new(WatcherInfo::default())),
            watcher_handle: Arc::new(Mutex::new(None)),
            repo_root: Arc::new(RwLock::new(repo_root)),
            state_placement: Arc::new(RwLock::new(state_placement)),
            control_state_dir: Some(daemon_client.control_state_dir().clone()),
            persistence_health: Arc::new(RwLock::new(persistence_health)),
            curation_coordinator: Arc::new(
                knowledge_curation::KnowledgeCurationCoordinator::default(),
            ),
            token_stats: None,
            daemon_client: Some(Arc::new(tokio::sync::RwLock::new(daemon_client))),
            daemon_degraded: Arc::new(AtomicBool::new(false)),
            session_context: Arc::new(session::SessionContext::new()),
            ccr_store: Arc::new(Mutex::new(ccr::CcrStore::new())),
            stel_ledger: Arc::new(Mutex::new(crate::stel::ledger::SessionLedger::new())),
            worktree_misuse: Arc::new(crate::worktree::WorktreeMisuseCounter::new()),
            analytics_recorder: Arc::new(RwLock::new(analytics_recorder)),
            #[cfg(feature = "server")]
            stel_ledger_store: None,
            #[cfg(feature = "server")]
            ledger_writes: Arc::new(LedgerWriteTracker::default()),
        }
    }

    /// Attach a durable STEL economics ledger store to this server (US3/T028).
    ///
    /// Builder-style; consumed by `server::serve::build_serve_runtime` so the
    /// same `Arc<StelLedgerStore>` is shared with `ServerRuntime`. This is the
    /// single durable ledger path — the in-memory `SessionLedger` write and the
    /// durable write-through both happen in `finalize_symforge_with_ledger`, so
    /// no economics row is counted twice.
    #[cfg(feature = "server")]
    pub fn with_stel_ledger_store(
        mut self,
        store: Arc<crate::stel::ledger_store::StelLedgerStore>,
    ) -> Self {
        self.stel_ledger_store = Some(store);
        self
    }

    /// Write one finalized ledger event through to the durable store (US3/T028).
    ///
    /// Called from `finalize_symforge_with_ledger` AFTER the in-memory
    /// `SessionLedger` push. The durable write degrades to a logged no-op on a
    /// store error and never fails the request (FR-011): `StelLedgerStore::record`
    /// no-ops when `Disabled` and logs-and-continues on an insert error. On
    /// stdio/embed builds (`server` feature off) this is a compile-time no-op.
    ///
    /// P2-C (resolved — non-blocking durable write): `StelLedgerStore::record`
    /// takes a `std::sync::Mutex<Connection>` and runs a sync INSERT under an
    /// up-to-5000ms busy-timeout. Running that inline on the tokio worker serving
    /// `/mcp` could stall concurrent HTTP clients. So when a tokio runtime is
    /// present we offload the blocking write onto `spawn_blocking` (the store is
    /// behind `Arc`, the event is cloned), and the request task returns without
    /// waiting on the DB lock. The in-memory `SessionLedger` push stays
    /// synchronous/immediate in `finalize_symforge_with_ledger`; only this
    /// durable write moves off the hot path. When no runtime is present (sync
    /// tests / embed call sites) we record synchronously so events are never
    /// lost. Either way `record` degrades silently on store error.
    #[cfg(feature = "server")]
    fn persist_ledger_event_durably(&self, event: &crate::stel::types::StelLedgerEvent) {
        let Some(store) = self.stel_ledger_store.as_ref() else {
            return;
        };
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                // Offload the blocking SQLite write off the request task so the
                // DB lock / busy-timeout never stalls the tokio worker serving
                // MCP. Fire-and-forget: the durable write is best-effort and
                // degrades silently inside `record` on any store error.
                let store = Arc::clone(store);
                let event = event.clone();
                // P2-3: register the write so serve::run can drain in-flight
                // durable writes on shutdown instead of dropping them.
                let guard = self.ledger_writes.begin();
                handle.spawn_blocking(move || {
                    let _guard = guard; // decrements the in-flight count on completion
                    store.record(&event);
                    // T031: after the new sample lands, run the tuning pass and
                    // persist an accepted candidate — off the hot path, in the
                    // same blocking task, so the auto-tune never stalls the MCP
                    // worker. Degrades silently on any store error.
                    Self::maybe_persist_tuning(&store);
                });
            }
            Err(_) => {
                // No tokio runtime (sync test / embed context): record inline so
                // events are never dropped. There is no async worker to protect
                // here, so blocking is acceptable.
                store.record(event);
                Self::maybe_persist_tuning(store);
            }
        }
    }

    /// The in-flight durable-ledger write tracker (P2-3), exposed so
    /// `serve::run` can drain pending economics writes on shutdown.
    #[cfg(feature = "server")]
    pub(crate) fn ledger_write_tracker(&self) -> &Arc<LedgerWriteTracker> {
        &self.ledger_writes
    }

    /// Run a tuning pass over the durable samples and persist an accepted
    /// candidate (feature 013, T031 / FR-008 audited gated action).
    ///
    /// Reads the current-estimator samples, derives + held-out-validates a
    /// candidate `response_correction_factor` against the correction currently in
    /// force (identity `1.0`, or the active tuning's factor — the D13 hysteresis
    /// anchor), and on an accepted `Tuned` verdict writes it via
    /// `store_active_tuning` with the audit fields (factor, sample_size,
    /// error_before/after, tuned_at). Idempotent: when the accepted candidate's
    /// factor equals the already-stored one, it is NOT re-written (no SQLite
    /// churn, no oscillation). Non-blocking off the hot path (called inside the durable
    /// write's `spawn_blocking`); a `Disabled`/absent store degrades to a no-op
    /// and never serves a bad tuning. NO frecency bump (Principle V).
    #[cfg(feature = "server")]
    fn maybe_persist_tuning(store: &crate::stel::ledger_store::StelLedgerStore) {
        use crate::stel::calibration::{
            CalibrationVerdict, NO_CORRECTION_FACTOR, PredictionSample, compute_calibration_verdict,
        };
        use crate::stel::controller::active_tuning_in_force;
        use crate::stel::ledger_store::{CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX};

        // Newest-first current-version samples (excludes pre-013). Bounded by the
        // retention cap so the pass is O(cap) at worst.
        let Ok(records) =
            store.samples_for_estimator(CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX)
        else {
            return;
        };
        let samples: Vec<PredictionSample> = records.iter().map(PredictionSample::from).collect();

        // In-force correction factor = the active tuning's if present (D13
        // hysteresis anchor: a re-tune must beat the correction already LIVE),
        // else the identity 1.0 (no tuning). The validate gate scores a candidate
        // against this, so a re-tune must out-perform what is already applied.
        let active = store
            .load_active_tuning(CURRENT_ESTIMATOR_VERSION)
            .ok()
            .flatten();
        let in_force = active_tuning_in_force(active.clone(), CURRENT_ESTIMATOR_VERSION);
        let in_force_factor = in_force
            .as_ref()
            .map_or(NO_CORRECTION_FACTOR, |c| c.response_correction_factor);

        let (verdict, candidate) = compute_calibration_verdict(&samples, in_force_factor);
        if !matches!(verdict, CalibrationVerdict::Tuned { .. }) {
            return;
        }
        let Some(mut candidate) = candidate else {
            return;
        };

        // Idempotence / oscillation guard: if the accepted candidate's correction
        // equals what is already stored, do not re-write (the validate gate already
        // requires a >= margin beat over the in-force factor, so this only fires on
        // an exact-equal stored factor — pure churn avoidance).
        if let Some(existing) = active.as_ref()
            && existing.response_correction_factor == candidate.response_correction_factor
        {
            return;
        }

        candidate.tuned_at_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);

        // Audited gated action (FR-008): store_active_tuning persists the new
        // correction factor, sample_size, error_before/after (the held-out real
        // residual baseline + corrected), tuned_at. Degrades silently on a store
        // error (never fails a request; never a bad tuning).
        if let Err(error) = store.store_active_tuning(&candidate) {
            tracing::warn!(error = %error, "stel tuning persist failed; keeping prior constants");
        } else {
            tracing::info!(
                response_correction_factor = candidate.response_correction_factor,
                sample_size = candidate.sample_size,
                error_before = candidate.error_before,
                error_after = candidate.error_after,
                "stel auto-tune accepted: persisted calibrated correction (013 US2)"
            );
        }
    }

    /// The validated tuned-constant set currently IN FORCE for the current
    /// estimator version (feature 013, T032 / FR-006), or `None`.
    ///
    /// Loads the active tuning from the durable store and applies the R3 in-force
    /// rule via [`active_tuning_in_force`]: a tuning whose `estimator_version`
    /// does not match the current estimator is NOT returned, so a stale-version
    /// set never silently applies. A `Disabled`/absent store yields `None` and
    /// the economics fall back to the static floors — never serves a bad tuning
    /// (FR-003). Read-only; no frecency bump (Principle V).
    ///
    /// [`active_tuning_in_force`]: crate::stel::controller::active_tuning_in_force
    #[cfg(feature = "server")]
    pub(crate) fn active_tuning_for_economics(
        &self,
    ) -> Option<crate::stel::ledger_store::TunedEstimateConstants> {
        use crate::stel::controller::active_tuning_in_force;
        use crate::stel::ledger_store::CURRENT_ESTIMATOR_VERSION;

        let store = self.stel_ledger_store.as_ref()?;
        let loaded = store.load_active_tuning(CURRENT_ESTIMATOR_VERSION).ok()?;
        active_tuning_in_force(loaded, CURRENT_ESTIMATOR_VERSION)
    }

    /// Compute the honest [`CalibrationVerdict`] from the DURABLE calibration
    /// state for the `status` surface (feature 013, T033 / FR-009).
    ///
    /// `Tuned` is returned ONLY when an active tuning is in force AND it carries a
    /// before/after held-out error artifact (`error_before > error_after`),
    /// reading the artifact straight off the persisted set so the surface never
    /// claims `tuned` without it. Otherwise the verdict reflects the durable
    /// sample count (`Deferred` / `Accumulating(n/min)`). When no durable store is
    /// wired, returns `None` so the caller keeps the in-memory view. When a wired
    /// store cannot answer the sample query, pins the verdict to `Deferred` so a
    /// stale in-memory session cannot claim `Tuned` while no validated tuning is
    /// readable. Read-only; no frecency bump.
    ///
    /// [`CalibrationVerdict`]: crate::stel::calibration::CalibrationVerdict
    #[cfg(feature = "server")]
    pub(crate) fn durable_calibration_verdict(
        &self,
    ) -> Option<crate::stel::calibration::CalibrationVerdict> {
        use crate::stel::calibration::{CalibrationVerdict, TUNING_MIN_CORPUS};
        use crate::stel::ledger_store::{CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX};

        let store = self.stel_ledger_store.as_ref()?;
        // A wired but failing store cannot prove any tuning is in force.
        let records =
            match store.samples_for_estimator(CURRENT_ESTIMATOR_VERSION, LEDGER_RETENTION_MAX) {
                Ok(records) => records,
                Err(_) => return Some(CalibrationVerdict::Deferred),
            };
        let n = records.len();

        // An active, in-force tuning with a real reduction artifact reads `Tuned`.
        if let Some(active) = self.active_tuning_for_economics()
            && active.error_before > active.error_after
        {
            return Some(CalibrationVerdict::Tuned {
                sample_size: active.sample_size as usize,
                error_before: active.error_before,
                error_after: active.error_after,
            });
        }

        if n == 0 {
            Some(CalibrationVerdict::Deferred)
        } else {
            Some(CalibrationVerdict::Accumulating {
                n,
                min: TUNING_MIN_CORPUS,
            })
        }
    }

    /// Clear accumulated calibration for the current estimator (feature 013,
    /// T037 / FR-011 operator reset). Returns the number of sample rows cleared,
    /// or `None` when no durable store is wired. Never rebuilds the index.
    #[cfg(feature = "server")]
    pub(crate) fn reset_calibration(&self) -> Option<usize> {
        use crate::stel::ledger_store::CURRENT_ESTIMATOR_VERSION;
        let store = self.stel_ledger_store.as_ref()?;
        store
            .clear_calibration_for_estimator(CURRENT_ESTIMATOR_VERSION)
            .ok()
    }

    #[cfg(not(feature = "server"))]
    #[inline]
    fn persist_ledger_event_durably(&self, _event: &crate::stel::types::StelLedgerEvent) {}

    /// Durable-ledger subsystem state for the `status` tool (US3/T029
    /// restart-survival; N-3 / TR-17 / FR-008).
    ///
    /// Maps the wired durable store's [`subsystem_state`] onto the
    /// feature-independent surface enum. Reports `Unavailable` when no store is
    /// attached, `Disabled { reason }` for a wired-but-failing store (open failed
    /// at startup or live query failed — N-3, never swallowed), and `Durable`
    /// otherwise. On embed builds (`server` feature off) this is a compile-time
    /// `Unavailable`.
    ///
    /// Reachability note (honest scope of N-3/FR-008): a durable store is wired by
    /// `server::serve::run` (the `/mcp` surface) AND by the stdio + daemon-proxy
    /// bootstrap (US1 T020/T021). On the daemon-proxy `status` path the proxy
    /// itself holds the store, so `status_stel_tool` overlays THIS value (among
    /// all proxy-owned lines) onto the proxied worker body
    /// (`overlay_proxy_status_lines`) — the operator sees the proxy's real
    /// `Durable`/`Disabled` state, not the storeless worker's `unavailable`
    /// (D2-ROOT). It stays `Unavailable` only when no store is attached anywhere.
    ///
    /// [`subsystem_state`]: crate::stel::ledger_store::StelLedgerStore::subsystem_state
    #[cfg(feature = "server")]
    fn durable_ledger_summary_for_status(&self) -> crate::stel::status::DurableLedgerState {
        use crate::stel::ledger_store::LedgerSubsystemState;
        use crate::stel::status::{DurableLedgerState, DurableLedgerSummary};

        let Some(store) = self.stel_ledger_store.as_ref() else {
            return DurableLedgerState::Unavailable;
        };
        match store.subsystem_state() {
            LedgerSubsystemState::Durable { summary } => {
                DurableLedgerState::Durable(DurableLedgerSummary {
                    total_events: summary.total_events,
                    total_net_vs_manual: summary.total_net_vs_manual,
                    session_count: summary.session_count,
                })
            }
            LedgerSubsystemState::Disabled { reason } => DurableLedgerState::Disabled { reason },
        }
    }

    #[cfg(not(feature = "server"))]
    #[inline]
    fn durable_ledger_summary_for_status(&self) -> crate::stel::status::DurableLedgerState {
        crate::stel::status::DurableLedgerState::Unavailable
    }

    /// Accessor for tests.
    pub fn index(&self) -> &SharedIndex {
        &self.index
    }

    /// Accessor for STEL ledger integration tests.
    #[doc(hidden)]
    pub fn stel_ledger(&self) -> &Arc<Mutex<crate::stel::ledger::SessionLedger>> {
        &self.stel_ledger
    }

    /// Return the MCP tool definitions advertised by this server.
    ///
    /// This is a read-only view over the generated router metadata so integration
    /// tests and diagnostics can validate client compatibility without spinning up
    /// a full stdio transport.
    pub fn tool_definitions() -> Vec<Tool> {
        Self::tool_router().list_all()
    }

    pub(crate) fn capture_repo_root(&self) -> Option<PathBuf> {
        self.repo_root.read().clone()
    }

    pub(crate) fn capture_state_placement(&self) -> Option<StatePlacement> {
        self.state_placement.read().clone()
    }

    pub(crate) fn capture_control_state_dir(&self) -> Option<ControlStateDir> {
        self.control_state_dir.clone()
    }

    #[cfg(test)]
    pub(crate) fn with_control_state_dir_for_test(
        mut self,
        control_state_dir: ControlStateDir,
    ) -> Self {
        self.control_state_dir = Some(control_state_dir);
        self
    }

    pub(crate) fn capture_project_state_dir(&self) -> Option<ProjectStateDir> {
        self.state_placement
            .read()
            .as_ref()
            .and_then(StatePlacement::directory)
            .cloned()
    }

    /// Record a frecency bump for the given paths against the bound workspace.
    ///
    /// No-op when no repo root is bound (the feature has nothing to anchor
    /// the per-workspace store to). Forwards to
    /// [`crate::live_index::frecency::bump`], which itself resolves session,
    /// persistent, or disabled collection policy.
    pub(crate) fn bump_frecency(&self, paths: &[PathBuf]) {
        if let Some(root) = self.capture_repo_root() {
            let project_state = self.capture_project_state_dir();
            crate::live_index::frecency::bump(&root, project_state.as_ref(), paths);
        }
    }

    pub(crate) fn effective_repo_root_for_git_tools(&self) -> Option<PathBuf> {
        self.capture_repo_root()
            .or_else(crate::discovery::find_project_root)
    }

    pub(crate) fn set_repo_root(&self, repo_root: Option<PathBuf>) {
        *self.repo_root.write() = repo_root.clone();
        if self.analytics_recorder.read().status().disabled {
            let state_dir = self.capture_project_state_dir();
            *self.analytics_recorder.write() = disabled_analytics_recorder(state_dir.as_ref());
        }
    }

    pub(crate) fn set_bound_project_state(
        &self,
        repo_root: Option<PathBuf>,
        state_placement: Option<StatePlacement>,
    ) {
        *self.persistence_health.write() = if matches!(
            state_placement.as_ref(),
            Some(StatePlacement::ProjectLocal { .. } | StatePlacement::UserLocal { .. })
        ) {
            CapabilityStatus::Available
        } else {
            CapabilityStatus::Unavailable {
                reason: CapabilityUnavailableReason::PersistentStateUnavailable,
            }
        };
        *self.state_placement.write() = state_placement;
        self.set_repo_root(repo_root);
    }

    /// Bump the worktree-awareness misuse counter when an edit handler
    /// was called without `working_directory` while worktree routing is active.
    /// No-op when the caller supplied the parameter or policy disables routing.
    /// The counter surfaces in `health` output as a rolling "last hour" signal
    /// for callers that should already be passing worktree routing context.
    pub(crate) fn note_worktree_misuse_if_active(&self, working_directory: Option<&str>) {
        if working_directory.is_none()
            && crate::worktree::routing_policy_from_env()
                == crate::capability::WorktreeRoutingPolicy::ExplicitCallTime
        {
            self.worktree_misuse.record_missing_working_directory();
        }
    }

    /// Record token savings from an MCP tool response so the health counter accumulates.
    pub(crate) fn record_read_savings(&self, saved_tokens: u64) {
        if let Some(ref stats) = self.token_stats {
            stats
                .read_saved_tokens
                .fetch_add(saved_tokens, std::sync::atomic::Ordering::Relaxed);
            stats
                .read_fires
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }
    }

    /// Record token savings from a named MCP tool, tracking per-tool breakdown.
    pub(crate) fn record_tool_savings_named(
        &self,
        tool_name: &str,
        estimated_raw_tokens: u64,
        output_tokens: u64,
    ) {
        if let Some(ref stats) = self.token_stats {
            let saved = estimated_raw_tokens.saturating_sub(output_tokens);
            stats
                .read_saved_tokens
                .fetch_add(saved, std::sync::atomic::Ordering::Relaxed);
            stats
                .read_fires
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            stats.record_tool_tokens(tool_name, output_tokens, saved);
        }
    }

    /// Apply token budget with CCR offload for eligible discovery tools (011).
    pub(crate) fn apply_ccr_budget(
        &self,
        tool_name: &str,
        result: String,
        max_tokens: Option<u64>,
    ) -> String {
        let budget = ccr::resolve_tool_max_tokens(tool_name, max_tokens);
        if ccr::profile_for_tool(tool_name).is_some_and(|p| p.ccr_eligible) {
            let mut store = self.ccr_store.lock();
            return ccr::enforce_token_budget_with_ccr(&mut store, tool_name, result, budget);
        }
        format::enforce_token_budget(result, budget)
    }

    /// Apply a token budget using a caller-provided, block-safe summary before
    /// CCR stores the complete output. This is used by structured multi-line
    /// results whose generic line cut could otherwise expose half a record.
    pub(crate) fn apply_ccr_budget_with_summary(
        &self,
        tool_name: &str,
        result: String,
        summary: String,
        max_tokens: Option<u64>,
    ) -> String {
        let budget = ccr::resolve_tool_max_tokens(tool_name, max_tokens);
        let Some(tokens) = budget.filter(|tokens| *tokens > 0) else {
            return result;
        };
        if ccr::profile_for_tool(tool_name).is_some_and(|profile| profile.ccr_eligible) {
            let summary = format::enforce_token_budget(summary, Some(tokens));
            let mut store = self.ccr_store.lock();
            return ccr::apply_ccr_overflow(&mut store, tool_name, summary, result, tokens);
        }
        format::enforce_token_budget(result, Some(tokens))
    }

    pub(crate) fn format_read_cache_hit(
        &self,
        meta: &crate::protocol::session::SessionCacheHitMeta,
        reason: &str,
    ) -> String {
        self.session_context.record_cache_hit();
        format::format_session_cache_hit_body(meta, reason)
    }

    pub(crate) fn compression_economics(&self) -> crate::protocol::ccr::CcrEconomics {
        self.ccr_store.lock().economics()
    }

    pub fn session_compression_heuristic(
        &self,
    ) -> crate::protocol::ccr::SessionCompressionHeuristic {
        let cache_hits = self.session_context.snapshot().cache_hit_count;
        crate::protocol::ccr::SessionCompressionHeuristic::from_parts(
            cache_hits,
            self.compression_economics(),
        )
    }

    pub(crate) fn record_tool_completion(
        &self,
        tool_name: &'static str,
        response_text: &str,
        duration: Duration,
        outcome_class: OutcomeClass,
    ) {
        let recorder = self.analytics_recorder.read().clone();
        let response_bytes = response_text.len() as u64;
        let observation = crate::analytics::AnalyticsObservation::new(
            tool_name,
            crate::analytics::AnalyticsSurface::Tool,
            recorder.configured_scope(),
            response_bytes,
            Some(estimate_tokens(response_bytes)),
            duration,
            !outcome_class.is_error(),
            outcome_class,
        );
        let _ = recorder.enqueue(observation);
    }

    #[cfg(test)]
    pub(crate) fn set_analytics_recorder_for_tests(
        &self,
        recorder: crate::analytics::AnalyticsRecorder,
    ) {
        *self.analytics_recorder.write() = recorder;
    }

    #[cfg(test)]
    pub(crate) fn analytics_queue_status_for_tests(
        &self,
    ) -> crate::analytics::AnalyticsQueueStatus {
        self.analytics_recorder.read().status()
    }

    /// Forward a tool call to the daemon. Returns:
    /// - `Some(result)` on success
    /// - `None` on connection failure (after one reconnect attempt), signalling
    ///   the caller to fall through to local execution
    pub(crate) async fn proxy_tool_call<T>(&self, tool_name: &str, params: &T) -> Option<String>
    where
        T: serde::Serialize,
    {
        let daemon_lock = self.daemon_client.as_ref()?;

        let was_degraded = self.daemon_degraded.load(Ordering::Relaxed);

        let value = match serde_json::to_value(params) {
            Ok(value) => value,
            Err(error) => return Some(format!("Daemon proxy serialization failed: {error}")),
        };

        // First attempt.
        // IMPORTANT: The read lock on daemon_lock is held for the duration of
        // the HTTP call. If this hangs, it blocks reconnect (which needs a
        // write lock). We wrap in a timeout so read locks release promptly
        // on failure — the reqwest client also has its own timeout as a
        // backstop, but this ensures lock release within a tighter window.
        {
            let client = daemon_lock.read().await;
            match tokio::time::timeout(
                std::time::Duration::from_secs(10),
                client.call_tool_value(tool_name, value.clone()),
            )
            .await
            {
                Ok(Ok(result)) => {
                    self.daemon_degraded.store(false, Ordering::Relaxed);
                    return Some(result);
                }
                Ok(Err(error)) => {
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call failed, attempting reconnect: {error}"
                    );
                }
                Err(_elapsed) => {
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call timed out after 10s, attempting reconnect"
                    );
                }
            }
        }

        if was_degraded {
            tracing::warn!(
                tool = tool_name,
                "daemon proxy probe failed while degraded, falling back to local execution"
            );
            self.ensure_local_index().await;
            return None;
        }

        // Reconnect attempt — take a write lock so only one caller does this.
        let reconnected = {
            let mut client = daemon_lock.write().await;
            match client.reconnect().await {
                Ok(new_client) => {
                    tracing::info!("daemon reconnected successfully");
                    *client = new_client;
                    true
                }
                Err(reconnect_error) => {
                    tracing::warn!(
                        "daemon reconnect failed, falling back to local execution: {reconnect_error}"
                    );
                    self.daemon_degraded.store(true, Ordering::Relaxed);
                    self.ensure_local_index().await;
                    false
                }
            }
        };

        if !reconnected {
            return None;
        }

        // Retry with the fresh client.
        {
            let client = daemon_lock.read().await;
            match tokio::time::timeout(
                std::time::Duration::from_secs(30),
                client.call_tool_value(tool_name, value),
            )
            .await
            {
                Ok(Ok(result)) => {
                    self.daemon_degraded.store(false, Ordering::Relaxed);
                    Some(result)
                }
                Ok(Err(error)) => {
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call failed after reconnect, falling back to local: {error}"
                    );
                    self.daemon_degraded.store(true, Ordering::Relaxed);
                    self.ensure_local_index().await;
                    None
                }
                Err(_elapsed) => {
                    tracing::warn!(
                        tool = tool_name,
                        "daemon proxy call timed out after reconnect, falling back to local"
                    );
                    self.daemon_degraded.store(true, Ordering::Relaxed);
                    self.ensure_local_index().await;
                    None
                }
            }
        }
    }

    pub(crate) async fn proxy_tool_call_without_params(&self, tool_name: &str) -> Option<String> {
        self.proxy_tool_call(tool_name, &serde_json::json!({}))
            .await
    }

    /// Lazily initialize the local index when the daemon is unreachable.
    /// Uses `SharedIndexHandle::reload` to populate the empty in-process index
    /// from disk, enabling graceful degradation to local-only mode.
    ///
    /// Root-mismatch invalidation: the early return fires only when the index is
    /// non-empty AND was built from the SAME root we are now targeting. If the
    /// target `repo_root` changed (a project switch via any `set_repo_root`
    /// caller) the recorded root no longer matches, so we fall through and
    /// reload from the current root instead of serving the previous project.
    /// This closes the stale-project class structurally — no caller has to
    /// remember to call `reset_to_empty` for correctness (that path still works
    /// and remains as defense in depth). Both roots are normalized via the same
    /// [`normalize_root`](crate::live_index::store::normalize_root) helper so the
    /// steady state (same project, repeated calls) never reloads on a cosmetic
    /// `\\?\` / trailing-slash / separator / case difference.
    async fn ensure_local_index(&self) {
        {
            let mut watcher = self.watcher_info.lock();
            *watcher = WatcherInfo::detached_local_fallback();
        }

        let repo_root = self.capture_repo_root();

        // Early return only when the index is non-empty AND its recorded root
        // matches the current target root (normalized compare). A non-empty
        // index built from a different root is stale: fall through to reload.
        let published = self.index.published_state();
        if published.file_count > 0 {
            let target_root = repo_root
                .as_deref()
                .map(crate::live_index::store::normalize_root);
            match (&published.indexed_root, &target_root) {
                // Same project: serve the loaded index, no reload.
                (Some(indexed), Some(target)) if indexed == target => return,
                // No target root to compare against (cannot do better than the
                // already-loaded index): keep serving it rather than dropping to
                // an empty index we cannot repopulate.
                (_, None) => return,
                // Root mismatch (or an index with no recorded root): stale —
                // fall through and reload from the current target root.
                _ => {}
            }
        }

        if let Some(root) = repo_root {
            tracing::info!(
                root = %root.display(),
                "daemon unreachable — loading local index as fallback"
            );
            match self.index.reload(&root) {
                Ok(()) => {
                    let published = self.index.published_state();
                    tracing::info!(
                        files = published.file_count,
                        symbols = published.symbol_count,
                        "local fallback index loaded"
                    );

                    // Spawn git temporal computation so co-change queries work
                    // after daemon degradation (mirrors index_folder behaviour).
                    let expected_gen = self.index.current_project_generation();
                    crate::live_index::git_temporal::spawn_git_temporal_computation(
                        Arc::clone(&self.index),
                        root,
                        expected_gen,
                    );
                }
                Err(error) => {
                    tracing::error!("failed to load local fallback index: {error}");
                }
            }
        } else {
            tracing::warn!("daemon unreachable and no repo root available for local fallback");
        }
    }

    /// Bind the workspace from MCP client-declared roots when nothing else did.
    ///
    /// Called from [`ServerHandler::on_initialized`] after the client sends
    /// `notifications/initialized`, this queries the client's `roots/list` and
    /// resolves a workspace root with strict precedence:
    /// `SYMFORGE_WORKSPACE_ROOT` > client roots > launch-CWD walk
    /// ([`crate::discovery::resolve_workspace_root`]).
    ///
    /// Precedence is honored against the *already-bound* server state rather
    /// than re-deciding it: startup resolved the env override and the CWD walk
    /// before the transport came up. The env override always wins — if it is set
    /// and valid the bound root came from it and this is a deliberate no-op.
    ///
    /// Two paths let declared client roots bind/retarget despite an existing
    /// binding, both narrowly gated (see the body):
    ///   - the keystone home-CWD case where neither env nor CWD bound anything
    ///     (Cursor from a home directory: `repo_root: None`, empty index); and
    ///   - (012 D4-A) a daemon-proxy session that came up bound to a CWD-derived
    ///     root with NO env override — there client roots are authoritative
    ///     (`roots > CWD`) and retarget the live session, fixing the wrong-repo
    ///     binding that a stale launch CWD would otherwise pin forever.
    ///
    /// In both cases the resolved root drives the existing [`Self::index_folder`]
    /// path, which loads the local in-process index or, in a daemon-proxy server,
    /// proxies the rebind to `index_folder_for_session` (the per-session retarget).
    /// A local (non-proxy) server that is already bound still returns immediately,
    /// preserving its loaded index byte-for-byte.
    ///
    /// Failures are logged and swallowed: a client that declares no roots, an
    /// unreachable `roots/list`, or a forbidden root must never break the
    /// session — the server simply stays in its existing (empty) state, exactly
    /// as before this hook existed.
    // ponytail: SEP-2577 deprecates the entire MCP Roots capability (Root,
    // ListRootsResult, peer.list_roots()) with NO replacement in rmcp 2.0 — it is
    // slated for removal from the spec, not renamed. `roots/list` is still the only
    // way a client can declare its workspace, so we keep using it and scope the
    // allow to this fn. Upgrade path: when the spec settles on a successor
    // capability (or rmcp removes Roots), migrate this single function.
    // https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577
    #[allow(deprecated)]
    async fn bind_workspace_from_client_roots(&self, peer: &rmcp::Peer<RoleServer>) {
        // Precedence: `SYMFORGE_WORKSPACE_ROOT (env) > client roots > CWD walk`.
        //
        // Two cases let declared client roots win over an already-bound root, both
        // gated so the single-harness happy path and the local (non-daemon) loaded
        // index are never disturbed:
        //
        //   1. Nothing was bound at startup (env + CWD both resolved nothing):
        //      client roots are the only signal — bind from them. This is the
        //      original home-CWD launcher fix (Cursor) and is unconditional.
        //
        //   2. (012 D4-A, per-connection RETARGET) A daemon-proxy session is
        //      ALWAYS bound at startup (to whatever the launch CWD resolved), so
        //      case 1 never fires for it and a stale CWD binding would silently
        //      win forever — the #1 field wrong-repo bug. When the bound root did
        //      NOT come from the env override, the client's declared roots are
        //      authoritative (`roots > CWD`) and must retarget the session via the
        //      existing `index_folder` → `index_folder_for_session` path.
        //
        // The env override always wins (case skipped) so `env > roots` holds, and
        // a local (non-proxy) server keeps its exact prior behavior: it returns
        // here whenever it is already bound, never reloading a loaded index.
        if self.capture_repo_root().is_some() {
            let bound_from_env = crate::discovery::workspace_root_env_override().is_some();
            let is_daemon_proxy = self.daemon_client.is_some();
            if bound_from_env || !is_daemon_proxy {
                return;
            }
            tracing::debug!(
                "daemon-proxy bound from CWD (no env override); allowing client roots to retarget"
            );
        }

        // Spec correctness: only issue `roots/list` when the client actually
        // declared the `roots` capability at `initialize`. A client that did not
        // advertise roots (capabilities `{}`) has no obligation to answer a
        // `roots/list` request and may never reply, which would hang this hook
        // (and the session) indefinitely. `peer_info()` is the client's stored
        // `InitializeRequestParams`; absent or roots-less capabilities => skip.
        let declares_roots = peer
            .peer_info()
            .map(|info| info.capabilities.roots.is_some())
            .unwrap_or(false);
        if !declares_roots {
            tracing::debug!("client did not declare the roots capability; workspace stays unbound");
            return;
        }

        // Defense in depth: even a roots-declaring client could stall. Bound the
        // request so a non-answering peer cannot hang the session — on timeout we
        // simply leave the workspace unbound, identical to the no-roots path.
        let roots = match tokio::time::timeout(std::time::Duration::from_secs(5), peer.list_roots())
            .await
        {
            Ok(Ok(result)) => result.roots,
            Ok(Err(error)) => {
                // Client declined / transport error. Stay unbound (pre-hook behavior).
                tracing::debug!(%error, "client roots/list failed; workspace stays unbound");
                return;
            }
            Err(_elapsed) => {
                tracing::warn!(
                    "client roots/list did not respond within 5s; workspace stays unbound"
                );
                return;
            }
        };

        if roots.is_empty() {
            tracing::debug!("client declared no roots; workspace stays unbound");
            return;
        }

        let root_uris: Vec<String> = roots.into_iter().map(|root| root.uri).collect();

        // env is None here: reaching this point guarantees the bound root did
        // NOT come from the env override (the gate above returns early when
        // `workspace_root_env_override().is_some()`), so passing None cannot let
        // a client root jump ahead of the env override — `env > roots` holds.
        let Some(resolved) = crate::discovery::resolve_workspace_root(None, &root_uris, None)
        else {
            tracing::info!(
                roots = ?root_uris,
                "no usable workspace among client roots (forbidden/unparseable); staying unbound"
            );
            return;
        };

        tracing::info!(
            root = %resolved.display(),
            "binding workspace from MCP client roots (no env/CWD root at startup)"
        );

        // Drive the existing index path. `index_folder` handles both the local
        // in-process reload (this server) and, in a daemon-proxy server, the
        // proxied session rebind — so no new index plumbing is introduced.
        let input = crate::protocol::tools::IndexFolderInput {
            path: resolved.display().to_string(),
            idempotency_key: None,
            add: None,
            allow_protected_root: None,
        };
        let result = self
            .index_folder(rmcp::handler::server::wrapper::Parameters(input))
            .await;
        tracing::info!(outcome = %result, "workspace bind from client roots complete");
    }

    /// Test-only dispatcher that routes a tool call by name and JSON payload.
    ///
    /// Mirrors the tool-name match in `daemon::execute_tool_call`, but takes
    /// `&self` so parity tests can exercise handlers directly without a live
    /// daemon or MCP transport. Only the tools needed by the `tests/` suites
    /// are wired up here.
    #[doc(hidden)]
    pub async fn dispatch_tool_for_tests(
        &self,
        tool_name: &str,
        params: serde_json::Value,
    ) -> String {
        use rmcp::handler::server::wrapper::Parameters;
        fn decode<T: serde::de::DeserializeOwned>(params: serde_json::Value) -> Result<T, String> {
            serde_json::from_value(params).map_err(|e| format!("invalid tool parameters: {e}"))
        }
        macro_rules! call {
            ($method:ident, $input:ty) => {{
                match decode::<$input>(params) {
                    Ok(input) => self.$method(Parameters(input)).await,
                    Err(e) => e,
                }
            }};
        }
        match tool_name {
            "replace_symbol_body" => call!(replace_symbol_body, edit::ReplaceSymbolBodyInput),
            "insert_symbol" => call!(insert_symbol, edit::InsertSymbolInput),
            "delete_symbol" => call!(delete_symbol, edit::DeleteSymbolInput),
            "edit_within_symbol" => call!(edit_within_symbol, edit::EditWithinSymbolInput),
            "batch_edit" => call!(batch_edit, edit::BatchEditInput),
            "batch_rename" => call!(batch_rename, edit::BatchRenameInput),
            "batch_insert" => call!(batch_insert, edit::BatchInsertInput),
            "search_files" => call!(search_files, tools::SearchFilesInput),
            "search_text" => call!(search_text, tools::SearchTextInput),
            "search_knowledge" => call!(search_knowledge, tools::SearchKnowledgeInput),
            "review_knowledge" => call!(review_knowledge, tools::ReviewKnowledgeInput),
            "curate_knowledge" => call!(curate_knowledge, tools::CurateKnowledgeInput),
            "search_symbols" => call!(search_symbols, tools::SearchSymbolsInput),
            "get_file_context" => call!(get_file_context, tools::GetFileContextInput),
            "get_file_content" => call!(get_file_content, tools::GetFileContentInput),
            "get_symbol" => call!(get_symbol, tools::GetSymbolInput),
            "get_symbol_context" => call!(get_symbol_context, tools::GetSymbolContextInput),
            "find_references" => call!(find_references, tools::FindReferencesInput),
            "find_dependents" => call!(find_dependents, tools::FindDependentsInput),
            "analyze_file_impact" => call!(analyze_file_impact, tools::AnalyzeFileImpactInput),
            "edit_plan" => call!(edit_plan, tools::EditPlanInput),
            "index_folder" => call!(index_folder, tools::IndexFolderInput),
            "detect_impact" => call!(detect_impact, tools::DetectImpactInput),
            "explore" => call!(explore, tools::ExploreInput),
            "ask" => call!(ask, tools::SmartQueryInput),
            "get_repo_map" => call!(get_repo_map, tools::GetRepoMapInput),
            "context_inventory" => self.context_inventory().await,
            "symforge_retrieve" => call!(symforge_retrieve, read_tools::SymforgeRetrieveInput),
            "health" => call!(health, tools::HealthInput),
            "health_compact" => self.health_compact().await,
            "conventions" => self.conventions().await,
            other => format!("dispatch_tool_for_tests: unknown tool '{other}'"),
        }
    }

    /// Test-only dispatcher that preserves public `CallToolResult` status metadata.
    ///
    /// This intentionally wires only handlers that already emit the SFB09 result-status
    /// contract. It lets conformance tests replay canonical JSON requests without
    /// starting an MCP transport or accepting string-only fake success paths.
    #[doc(hidden)]
    pub async fn dispatch_tool_result_for_tests(
        &self,
        tool_name: &str,
        params: serde_json::Value,
    ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
        use rmcp::handler::server::wrapper::Parameters;

        fn invalid_request_result(
            tool_name: &str,
            message: impl Into<String>,
        ) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {
            let text = format!(
                "Invalid request for tool `{tool_name}`: {}\nRecovery: compare the request JSON with the advertised input schema from tool_definitions().",
                message.into()
            );
            Ok(
                result_status::ResultStatus::new(result_status::OutcomeClass::InvalidRequest)
                    .into_call_tool_result(text),
            )
        }

        fn decode<T: serde::de::DeserializeOwned>(params: serde_json::Value) -> Result<T, String> {
            serde_json::from_value(params).map_err(|e| format!("invalid tool parameters: {e}"))
        }

        macro_rules! call_statused {
            ($method:ident, $input:ty) => {{
                match decode::<$input>(params) {
                    Ok(input) => self.$method(Parameters(input)).await,
                    Err(error) => invalid_request_result(tool_name, error),
                }
            }};
        }

        match tool_name {
            "replace_symbol_body" => {
                call_statused!(replace_symbol_body_tool, edit::ReplaceSymbolBodyInput)
            }
            "batch_edit" => call_statused!(batch_edit_tool, edit::BatchEditInput),
            "batch_insert" => call_statused!(batch_insert_tool, edit::BatchInsertInput),
            "search_files" => call_statused!(search_files_tool, tools::SearchFilesInput),
            "search_text" => call_statused!(search_text_tool, tools::SearchTextInput),
            "search_symbols" => call_statused!(search_symbols_tool, tools::SearchSymbolsInput),
            "get_file_content" => {
                call_statused!(get_file_content_tool, tools::GetFileContentInput)
            }
            "get_symbol" => call_statused!(get_symbol_tool, tools::GetSymbolInput),
            "get_symbol_context" => {
                call_statused!(get_symbol_context_tool, tools::GetSymbolContextInput)
            }
            "find_references" => call_statused!(find_references_tool, tools::FindReferencesInput),
            "symforge" => call_statused!(symforge_facade_tool, crate::stel::SymforgeCallInput),
            "symforge_edit" => {
                call_statused!(symforge_edit_facade_tool, crate::stel::StelEditRequest)
            }
            "status" => call_statused!(status_stel_tool, crate::stel::StelStatusRequest),
            other => {
                let text = format!(
                    "Unsupported tool `{other}` in public conformance harness.\nRecovery: add a statused dispatcher branch before adding the case, or remove the case from the public corpus."
                );
                Ok(
                    result_status::ResultStatus::new(result_status::OutcomeClass::InvalidRequest)
                        .into_call_tool_result(text),
                )
            }
        }
    }
}

/// Wire `SymForgeServer` as an MCP `ServerHandler`.
///
/// The `#[tool_handler]` macro delegates tool dispatch to `self.tool_router`
/// and supplies the `call_tool` / `list_tools` implementations automatically.
///
/// The prompt methods are hand-written (no `#[prompt_handler]`): unlike
/// `#[tool_handler]`, which defers to a manually defined method, the 3.x
/// `#[prompt_handler]` macro REPLACES a manual `list_prompts` in the annotated
/// impl block with its generated body (rmcp-macros 3.1.0
/// `prompt_handler.rs:85-87`), which would silently clobber the FR-310
/// cache-hint override. `get_prompt`/`list_prompts` below carry the exact
/// router delegation the macro would have generated.
#[tool_handler(router = self.tool_router)]
impl ServerHandler for SymForgeServer {
    fn get_info(&self) -> ServerInfo {
        // Override rmcp's `from_build_env` default, which expands
        // `CARGO_CRATE_NAME`/`CARGO_PKG_VERSION` inside the rmcp crate and would
        // otherwise identify this server as "rmcp"/<rmcp version>. `env!` here
        // expands in the symforge crate, staying in sync with Cargo.toml.
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .enable_resources()
                .build(),
        )
        .with_server_info(rmcp::model::Implementation::new(
            "symforge",
            env!("CARGO_PKG_VERSION"),
        ))
    }

    /// FR-307 allow-list freeze (spec 025). rmcp 3.1.0's default already
    /// returns `KNOWN_VERSIONS` including `V_2026_07_28`; this override pins
    /// TODAY'S set explicitly so a future rmcp `"3.1"` semver update cannot
    /// auto-advertise a protocol revision symforge has never tested. Protocol
    /// exposure changes only by deliberate edit here. Extend, never shrink.
    fn supported_protocol_versions(
        &self,
    ) -> std::borrow::Cow<'static, [rmcp::model::ProtocolVersion]> {
        use rmcp::model::ProtocolVersion;
        std::borrow::Cow::Borrowed(&[
            ProtocolVersion::V_2024_11_05,
            ProtocolVersion::V_2025_03_26,
            ProtocolVersion::V_2025_06_18,
            ProtocolVersion::V_2025_11_25,
            ProtocolVersion::V_2026_07_28,
        ])
    }

    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourcesResult, rmcp::ErrorData>> + Send + '_
    {
        // FR-310/FR-311: static list surface — constructor seeds
        // `result_type: Some(COMPLETE)` (FR-305 pinned shape); 1h TTL, Public
        // (`resource_definitions()` embeds no workspace data).
        std::future::ready(Ok(ListResourcesResult::with_all_items(
            self.resource_definitions(),
        )
        .with_ttl_ms(3_600_000)
        .with_cache_scope(rmcp::model::CacheScope::Public)))
    }

    fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourceTemplatesResult, rmcp::ErrorData>>
    + Send
    + '_ {
        // FR-310/FR-311: static list surface — same cache policy as
        // `list_resources`.
        std::future::ready(Ok(ListResourceTemplatesResult::with_all_items(
            self.resource_template_definitions(),
        )
        .with_ttl_ms(3_600_000)
        .with_cache_scope(rmcp::model::CacheScope::Public)))
    }

    fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<
        Output = Result<rmcp::model::ReadResourceResponse, rmcp::ErrorData>,
    > + Send
    + '_ {
        let uri = request.uri;
        // INV-1: the response enum exists only at this trait boundary; all
        // internal resource logic (and the spec-023 admission gating it wraps)
        // stays on `ReadResourceResult`.
        //
        // FR-319: resource reads never pass through `ResultStatus`, so project
        // evidence is attached here at the seam, inside the same evidence
        // scope `tools/call` uses (an inner daemon-proxied handler may
        // overwrite the seeded local evidence with its receipt).
        async move {
            result_status::with_project_evidence_scope(self.local_project_evidence(), async {
                self.read_resource_uri(&uri).await.map(|mut result| {
                    result_status::attach_project_evidence_meta(&mut result.meta);
                    rmcp::model::ReadResourceResponse::Complete(result)
                })
            })
            .await
        }
    }

    /// MCP `tools/call` dispatch with a central compact-surface gate (P1-A).
    ///
    /// The `#[tool_handler]` macro only generates `call_tool` when the impl block
    /// does not already define one; by providing this method we replace the
    /// generated body while preserving its exact router delegation. The added
    /// gate enforces [`FR-008`] at dispatch (not just at `tools/list`): when the
    /// active surface is [`SurfaceProfile::Compact`], a `tools/call` for any tool
    /// name NOT in the advertised compact-3 set
    /// ([`crate::stel::surface::COMPACT_TOOL_NAMES`]) is rejected with an MCP
    /// `InvalidRequest` error. Full and Meta surfaces are unaffected, so the
    /// default full surface (and any explicit `SYMFORGE_SURFACE=full`) reaches
    /// every legacy tool; `SYMFORGE_SURFACE=compact` is the opt-in escape hatch
    /// that gates them. This is shared by both transports because stdio and the HTTP `/mcp`
    /// serve path dispatch through the same `ServerHandler::call_tool`.
    async fn call_tool(
        &self,
        request: rmcp::model::CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
        surface_probe::enforce_compact_surface(request.name.as_ref())?;
        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
        // Task 7: bind the selected-project evidence slot for this dispatch,
        // seeded with the LOCAL bound project; the daemon proxy layer
        // overwrites it with the daemon's receipt when it answers. Statused
        // results attach whatever is current at render time.
        result_status::with_project_evidence_scope(self.local_project_evidence(), async {
            let response = self.tool_router.call(tcc).await;
            // FR-319 central evidence attachment (plan D1): statused results
            // already attached evidence inside `into_call_tool_result`
            // (single-writer wins — this seam never overwrites); plain-String
            // tools gain it here, and an unbound server discloses the explicit
            // unbound marker. Runs INSIDE the scope so a daemon receipt
            // recorded during the call is what gets attached. Wildcard arm per
            // FR-A2: this server only ever emits `Complete`.
            response.map(|response| match response {
                rmcp::model::CallToolResponse::Complete(mut result) => {
                    result_status::attach_project_evidence_meta(&mut result.meta);
                    rmcp::model::CallToolResponse::Complete(result)
                }
                other => other,
            })
        })
        .await
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, rmcp::ErrorData> {
        let profile = surface_probe::surface_profile_from_env();
        let tools = match profile {
            surface_probe::SurfaceProfile::Compact => crate::stel::compact_surface_tools(),
            _ => surface_probe::list_tools_for_profile(profile),
        };
        // FR-305 pinned struct shape: the constructor seeds
        // `result_type: Some(COMPLETE)`. FR-310/FR-311: 1h TTL, Public — the
        // surface is fixed per-process (`SYMFORGE_SURFACE` is env-driven) and
        // the INV-2 dispatch gate rejects off-surface calls, so a stale cached
        // full list is harmless. Ordering is deterministic (router insertion
        // order), verified by test (SC-313).
        Ok(ListToolsResult::with_all_items(tools)
            .with_ttl_ms(3_600_000)
            .with_cache_scope(rmcp::model::CacheScope::Public))
    }

    /// Hand-written prompt dispatch — identical to what `#[prompt_handler]`
    /// would generate (see the impl-block doc comment for why the macro is not
    /// used).
    async fn get_prompt(
        &self,
        request: rmcp::model::GetPromptRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::GetPromptResponse, rmcp::ErrorData> {
        let prompt_context = rmcp::handler::server::prompt::PromptContext::new(
            self,
            request.name,
            request.arguments,
            context,
        );
        self.prompt_router.get_prompt(prompt_context).await
    }

    /// Manual `list_prompts` override (FR-310): the macro body plus the
    /// FR-311 static-list cache hints.
    async fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<rmcp::model::ListPromptsResult, rmcp::ErrorData> {
        Ok(
            rmcp::model::ListPromptsResult::with_all_items(self.prompt_router.list_all())
                .with_ttl_ms(3_600_000)
                .with_cache_scope(rmcp::model::CacheScope::Public),
        )
    }

    /// React to the client's `notifications/initialized`.
    ///
    /// After the handshake completes, the client's MCP `roots` capability (the
    /// open workspace folder it declared) becomes queryable via `roots/list`.
    /// We use it to bind the workspace when the launch CWD and
    /// `SYMFORGE_WORKSPACE_ROOT` resolved nothing at startup — the keystone
    /// "index won't load" case for home-CWD launchers (Cursor). Precedence
    /// (`SYMFORGE_WORKSPACE_ROOT` > client roots > launch-CWD walk) is enforced
    /// inside [`Self::bind_workspace_from_client_roots`], which is a deliberate
    /// no-op whenever startup already bound a root.
    ///
    /// Scope (FR-316, spec 025): this hook fires only for stdio /
    /// legacy-lifecycle clients that send `notifications/initialized`. The
    /// stateless HTTP `/mcp` path serves requests directly with no handshake
    /// enforcement, so this hook never runs there; modern discover-lifecycle
    /// clients are bound by the fallback chain (`SYMFORGE_WORKSPACE_ROOT` >
    /// `index_folder` > CWD walk), with the residual wrong-binding case
    /// disclosed via `_meta` project evidence (FR-319).
    async fn on_initialized(&self, context: rmcp::service::NotificationContext<RoleServer>) {
        tracing::info!("client initialized");
        self.bind_workspace_from_client_roots(&context.peer).await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::Router;
    use axum::extract::State;
    use axum::routing::post;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tokio::net::TcpListener;

    #[derive(Clone)]
    struct FakeToolState {
        calls: Arc<AtomicUsize>,
        body: Arc<String>,
    }

    async fn fake_tool_handler(State(state): State<FakeToolState>) -> String {
        state.calls.fetch_add(1, Ordering::Relaxed);
        state.body.as_ref().clone()
    }

    async fn spawn_fake_tool_server(
        body: &str,
    ) -> (String, tokio::sync::oneshot::Sender<()>, Arc<AtomicUsize>) {
        let listener = TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind fake daemon tool server");
        let base_url = format!("http://{}", listener.local_addr().expect("listener addr"));
        let calls = Arc::new(AtomicUsize::new(0));
        let state = FakeToolState {
            calls: Arc::clone(&calls),
            body: Arc::new(body.to_string()),
        };
        let app = Router::new()
            .route(
                "/v1/sessions/{session_id}/tools/{tool_name}",
                post(fake_tool_handler),
            )
            .with_state(state);
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            let shutdown = async move {
                let _ = shutdown_rx.await;
            };
            let _ = axum::serve(listener, app)
                .with_graceful_shutdown(shutdown)
                .await;
        });
        (base_url, shutdown_tx, calls)
    }

    #[tokio::test]
    async fn daemon_degraded_clears_on_next_success() {
        let (base_url, shutdown, calls) = spawn_fake_tool_server("daemon-ok").await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client);
        server.daemon_degraded.store(true, Ordering::Relaxed);

        let result = server
            .proxy_tool_call("health", &serde_json::json!({}))
            .await;
        let _ = shutdown.send(());

        assert_eq!(result.as_deref(), Some("daemon-ok"));
        assert_eq!(
            calls.load(Ordering::Relaxed),
            1,
            "degraded proxy should still probe the daemon once"
        );
        assert!(
            !server.daemon_degraded.load(Ordering::Relaxed),
            "successful proxy call should clear daemon_degraded"
        );
    }

    /// Feature 013 US1 (T021): a daemon-PROXY server with a durable
    /// `StelLedgerStore` attached records the `symforge` economics event through
    /// to that store. This is the load-bearing invariant the daemon-default
    /// stdio wiring relies on: in the operator's real (daemon-backed) deployment
    /// the `symforge` compact tool — the ONLY ledger-recording tool — runs on
    /// the PROXY (the daemon worker's `execute_tool_call` has no `symforge`
    /// arm), so the durable store must be attached on the proxy path
    /// (`run_remote_mcp_server_async`) for durable accumulation to work. Here a
    /// fake daemon returns the served body for proxied primitives; the proxy
    /// itself captures the economics and write-throughs to the attached store.
    ///
    /// We call `symforge_stel_handler` directly (the inner handler, below the
    /// `SYMFORGE_SURFACE` facade gate) so the test needs no process-global env
    /// mutation and is deterministic under the parallel harness.
    #[tokio::test]
    async fn daemon_proxy_with_durable_store_records_symforge_event_through() {
        // Fake daemon returns a non-empty body for any proxied primitive so the
        // serve path produces a real served body to finalize.
        let (base_url, shutdown, _calls) =
            spawn_fake_tool_server("references to cfg_if:\n  src/lib.rs:1").await;
        let daemon_client = crate::daemon::DaemonSessionClient::new_for_test(
            base_url,
            "project-id".to_string(),
            "session-id".to_string(),
            "project-name".to_string(),
        );

        // Attach an in-memory durable store on the PROXY path — exactly what
        // `run_remote_mcp_server_async` does (T021), just in-memory for the test.
        let store = Arc::new(
            crate::stel::ledger_store::StelLedgerStore::open_in_memory("stdio-daemon-test")
                .expect("in-memory durable store"),
        );
        let server = SymForgeServer::new_daemon_proxy(daemon_client)
            .with_stel_ledger_store(Arc::clone(&store));

        // The proxy holds the store; durable accumulation starts at zero.
        assert_eq!(store.summary().expect("summary").total_events, 0);

        // Drive a real economics invocation through the inner handler (skips the
        // env-gated facade). The proxy fetches the served body from the fake
        // daemon, then captures + write-throughs the economics event.
        let request = crate::stel::StelRequest {
            query: "who references cfg_if".to_string(),
            ..Default::default()
        };
        let _ = server
            .symforge_stel_handler(&request)
            .await
            .expect("symforge_stel_handler dispatch");
        let _ = shutdown.send(());

        // The in-memory ledger recorded one event synchronously...
        assert_eq!(
            server.stel_ledger().lock().len(),
            1,
            "the proxy's in-memory ledger must record the event"
        );

        // ...and the DURABLE store on the proxy eventually holds it (the write is
        // offloaded onto spawn_blocking — poll briefly). This is the T021 proof:
        // durable accumulation works on the daemon-backed stdio path.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let total = loop {
            let total = store.summary().map(|s| s.total_events).unwrap_or(0);
            if total >= 1 || std::time::Instant::now() >= deadline {
                break total;
            }
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
        };
        assert_eq!(
            total, 1,
            "the durable store attached on the daemon-proxy path must record the symforge event"
        );
        let recent = store.recent(10).expect("recent durable rows");
        assert_eq!(recent.len(), 1);
        assert_eq!(
            recent[0].session_id, "stdio-daemon-test",
            "the durable row carries the proxy store's session id"
        );
    }

    // ── ensure_local_index: root-mismatch invalidation (M2) ──────────────────

    /// Build a local-mode server (no daemon proxy) starting from an empty index,
    /// targeting `repo_root`. Mirrors the production `SymForgeServer::new` wiring
    /// used by the local stdio path.
    fn make_local_server(repo_root: Option<std::path::PathBuf>) -> SymForgeServer {
        let index = crate::live_index::LiveIndex::empty();
        let watcher_info = Arc::new(Mutex::new(WatcherInfo::default()));
        SymForgeServer::new(
            index,
            "test_project".to_string(),
            watcher_info,
            repo_root,
            None,
        )
    }

    /// Write a single `.rs` file under `dir` so a real local reload produces a
    /// non-empty index whose contents identify the project.
    fn seed_project(dir: &std::path::Path, file_name: &str, body: &str) {
        std::fs::write(dir.join(file_name), body).expect("seed project source file");
    }

    /// Core M2 regression: a changed `repo_root` (WITHOUT `reset_to_empty`) must
    /// force `ensure_local_index` to reload the new root instead of serving the
    /// previous project. Fails without the root-mismatch guard.
    #[tokio::test]
    async fn ensure_local_index_reloads_on_root_mismatch_without_reset() {
        let dir_a = tempfile::TempDir::new().expect("temp dir A");
        let dir_b = tempfile::TempDir::new().expect("temp dir B");
        seed_project(dir_a.path(), "alpha.rs", "fn alpha_only() {}\n");
        seed_project(dir_b.path(), "beta.rs", "fn beta_only() {}\n");

        // 1. Load project A.
        let server = make_local_server(Some(dir_a.path().to_path_buf()));
        server.ensure_local_index().await;

        let published_a = server.index.published_state();
        assert!(
            published_a.file_count > 0,
            "project A should have loaded a non-empty index"
        );
        assert_eq!(
            published_a.indexed_root.as_deref(),
            Some(crate::live_index::store::normalize_root(dir_a.path()).as_path()),
            "loaded index must record project A's normalized root"
        );
        assert!(
            server.index.read().get_file("alpha.rs").is_some(),
            "project A's file should be present after the first load"
        );

        // 2. Switch the target root to B WITHOUT calling reset_to_empty.
        server.set_repo_root(Some(dir_b.path().to_path_buf()));

        // 3. The next ensure_local_index must detect the root mismatch and reload B.
        server.ensure_local_index().await;

        let published_b = server.index.published_state();
        assert_eq!(
            published_b.indexed_root.as_deref(),
            Some(crate::live_index::store::normalize_root(dir_b.path()).as_path()),
            "after a root switch, ensure_local_index must serve project B's root"
        );
        assert!(
            server.index.read().get_file("beta.rs").is_some(),
            "project B's file must be present after the root-mismatch reload"
        );
        assert!(
            server.index.read().get_file("alpha.rs").is_none(),
            "project A's stale file must be gone after switching to project B"
        );
    }

    /// Steady-state guard: repeated `ensure_local_index` calls against the SAME
    /// root must NOT rebuild the index. A spurious reload bumps the project
    /// generation, so an unchanged generation (and unchanged recorded root)
    /// proves no reload occurred — verifying normalization makes the common path
    /// cheap rather than reloading on every call.
    #[tokio::test]
    async fn ensure_local_index_does_not_reload_on_repeated_same_root_calls() {
        let dir_a = tempfile::TempDir::new().expect("temp dir A");
        seed_project(dir_a.path(), "alpha.rs", "fn alpha_only() {}\n");

        let server = make_local_server(Some(dir_a.path().to_path_buf()));

        // First call performs the one and only load.
        server.ensure_local_index().await;
        let gen_after_first = server.index.current_project_generation();
        let root_after_first = server.index.published_state().indexed_root.clone();
        assert!(
            server.index.published_state().file_count > 0,
            "first ensure_local_index call should have loaded project A"
        );

        // Repeated calls with the same root must be no-ops (no reload).
        for _ in 0..3 {
            server.ensure_local_index().await;
        }

        assert_eq!(
            server.index.current_project_generation(),
            gen_after_first,
            "repeated same-root ensure_local_index calls must not reload (project generation must not change)"
        );
        assert_eq!(
            server.index.published_state().indexed_root,
            root_after_first,
            "repeated same-root calls must leave the recorded root unchanged"
        );
    }

    /// SF-STRESS-022: `initialize` serverInfo must identify symforge, not the
    /// rmcp framework default. Without `with_server_info`, rmcp's
    /// `Implementation::from_build_env` reports "rmcp"/<rmcp version>.
    #[test]
    fn get_info_reports_symforge_name_and_crate_version() {
        let server = make_local_server(None);
        let info = ServerHandler::get_info(&server);
        assert_eq!(
            info.server_info.name, "symforge",
            "serverInfo.name must identify symforge, not the rmcp framework"
        );
        assert_eq!(
            info.server_info.version,
            env!("CARGO_PKG_VERSION"),
            "serverInfo.version must track the symforge crate version"
        );
    }
}