diffler 0.20.0

Standalone magit-style git TUI and code reviewer, on its own or with your coding agent
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
//! Embedded MCP server: agents read review comments, answer them in place,
//! and long-poll for the human's feedback. Tool handlers never touch the
//! review directly: every call is sent through the app event channel as an
//! [`McpRequest`] and answered by `App::handle_mcp` on the main loop, so the
//! app stays the single owner of all state (no locks).

use std::fmt;
use std::io::ErrorKind;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use diffler_core::feedback;
use diffler_core::model::{DiffModel, FileStatus};
use diffler_core::session::{Comment, CommentStatus};
use diffler_core::source::ReviewSource;
use rmcp::handler::server::router::prompt::PromptRouter;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{PromptMessage, Role, ServerCapabilities, ServerConfig};
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use rmcp::{
    ErrorData, Json, ServerHandler, prompt, prompt_handler, prompt_router, schemars, tool,
    tool_handler, tool_router,
};
use serde::Serialize;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::{oneshot, watch};
use tokio::task::JoinHandle;

use crate::event::AppEvent;

/// Author label stamped on replies the agent writes through MCP.
pub const AGENT_AUTHOR: &str = "agent";

/// Claude Code cuts a request at 120 s, so `MAX_WAIT_SECONDS` plus one
/// `REQUEST_TIMEOUT` must stay under it; the caller polls again to keep waiting.
const DEFAULT_WAIT_SECONDS: u64 = 25;
const MAX_WAIT_SECONDS: u64 = 55;
/// The app stalls on a call mostly while `$EDITOR` holds the terminal.
pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// One agent tool call in flight: the app answers on `reply`. `project`
/// names the tab a project-scoped call acts on, the one in front when unset.
pub struct McpRequest {
    pub kind: McpRequestKind,
    pub project: Option<String>,
    pub reply: oneshot::Sender<McpResponse>,
}

impl fmt::Debug for McpRequest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("McpRequest")
            .field("kind", &self.kind)
            .field("project", &self.project)
            .finish_non_exhaustive()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpRequestKind {
    ReviewStatus,
    GetDiff {
        file: Option<String>,
    },
    GetComments {
        status: Option<CommentStatus>,
    },
    ListReviews,
    ReplyComment {
        id: String,
        body: String,
    },
    ProposeResolve {
        id: String,
        note: Option<String>,
    },
    MarkViewed {
        file: String,
    },
    /// A comment in the review the human has open; `as_human` makes the human
    /// its author.
    AddComment {
        file: String,
        line: u32,
        line_end: Option<u32>,
        body: String,
        as_human: bool,
    },
    /// Refused for a human's comment and for a walkthrough stop or note,
    /// which `publish_walkthrough` owns.
    DeleteComment {
        id: String,
    },
    /// Keeps status, replies and anchor. Same refusals as `DeleteComment`.
    EditComment {
        id: String,
        body: String,
    },
    /// Open + replied comments for `wait_for_feedback` after an epoch bump.
    Feedback,
    /// Revises the walkthrough `id` names, or publishes a new one when `id`
    /// is `None`.
    PublishWalkthrough {
        id: Option<String>,
        title: String,
        stops: Vec<StopParams>,
        skipped: Option<String>,
        summary: Option<String>,
    },
    /// The walkthrough `id` names, or the newest one when `id` is `None`.
    GetWalkthrough {
        id: Option<String>,
    },
    /// The agent's own words for the status bar's activity indicator.
    ReportActivity {
        focus: String,
        file: Option<String>,
    },
    OpenProject {
        path: String,
    },
    /// Takes the human to `target`, with `note` in the status line.
    Focus {
        target: FocusTarget,
        note: Option<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FocusTarget {
    /// A comment id or a walkthrough id.
    Id(String),
    Code {
        file: String,
        line: Option<u32>,
        line_end: Option<u32>,
        review: Option<String>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpResponse {
    Status(ReviewStatusResponse),
    Diff(String),
    Comments(Vec<CommentInfo>),
    Reviews(Vec<ReviewSummary>),
    Replied {
        status: String,
    },
    Ok,
    Added {
        id: String,
    },
    /// Domain refusal (unknown id/file): surfaces as a tool error.
    Error(String),
    WalkthroughPublished(WalkthroughPublished),
    Walkthrough(Option<WalkthroughInfo>),
    /// Answers [`McpRequestKind::Feedback`]: the open and replied comments.
    Feedback {
        comments: Vec<CommentInfo>,
    },
    /// Answers [`McpRequestKind::OpenProject`]: the tab now showing it.
    ProjectOpened(ProjectInfo),
    Focused(FocusResponse),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FocusView {
    Diff,
    File,
    /// diffler is fetching what the review needs; the human's view moves
    /// once it arrives.
    Waiting,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct FocusResponse {
    pub project: String,
    /// The review on screen, e.g. "working tree" or "PR #12"; absent when
    /// the file view shows the file as it is on disk.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub review: Option<String>,
    pub view: FocusView,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(with = "Option<Count>")]
    pub line: Option<u32>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ReviewStatusResponse {
    pub repo: String,
    pub branch: Option<String>,
    pub oid7: String,
    pub files_changed: Vec<FileEntry>,
    #[schemars(with = "Count")]
    pub open_comments: usize,
    #[schemars(with = "Count")]
    pub replied_comments: usize,
    #[schemars(with = "Count")]
    pub resolved_comments: usize,
    #[schemars(with = "Count")]
    pub feedback_epoch: u64,
    /// Every persisted review and its comment counts; `files_changed` above is
    /// the working-tree review, the default the human starts on.
    pub reviews: Vec<ReviewSummary>,
    /// Every walkthrough published in the repo, newest first; empty when none
    /// has been published.
    pub walkthroughs: Vec<WalkthroughSummary>,
    /// Filenames under `.diffler/reviews/` that failed to parse and were
    /// skipped: `reviews` and `walkthroughs` above may be missing an entry
    /// because of one of these, rather than the repository having none.
    /// Empty when every review file parsed.
    pub corrupt_reviews: Vec<String>,
    /// Every project open as a tab, with its comment counts. Comments and
    /// feedback cover all of them; `project` targets a call at one.
    pub projects: Vec<ProjectInfo>,
}

/// One project open as a tab in the human's diffler.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ProjectInfo {
    /// The name to pass as `project`: the repository's folder name.
    pub name: String,
    pub root: String,
    /// The tab the human is looking at.
    pub active: bool,
    #[schemars(with = "Count")]
    pub open_comments: usize,
    #[schemars(with = "Count")]
    pub replied_comments: usize,
}

/// What a fresh agent needs to know a walkthrough exists before reading
/// anything else: `get_walkthrough` carries the rest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct WalkthroughSummary {
    /// Pass this to `get_walkthrough` or `publish_walkthrough` to read or
    /// revise this walkthrough.
    pub id: String,
    pub title: String,
    #[schemars(with = "Count")]
    pub stops: usize,
    #[schemars(with = "Count")]
    pub at: u64,
}

/// One review's provenance and comment tally: what was reviewed (working tree,
/// a commit, or a range) and how many comments sit at each status.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ReviewSummary {
    /// The project this review belongs to, when more than one is open.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Stable source key (e.g. `working`, `commit-<oid>`, `range-<a>-<b>`).
    pub source: String,
    /// Human-facing description (e.g. "commit a1b2c3", "range a1b2c3..d4e5f6").
    pub label: String,
    #[schemars(with = "Count")]
    pub open_comments: usize,
    #[schemars(with = "Count")]
    pub replied_comments: usize,
    #[schemars(with = "Count")]
    pub resolved_comments: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct FileEntry {
    pub path: String,
    pub status: String,
    pub viewed: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct DiffResponse {
    pub diff: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct CommentInfo {
    pub id: String,
    /// The project this comment belongs to, when more than one is open.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// Stable key of the review this comment belongs to (see [`ReviewSummary`]).
    pub source: String,
    /// Human-facing description of that review (what the human was looking at).
    pub source_label: String,
    pub file: String,
    #[schemars(with = "Option<Count>")]
    pub line: Option<u32>,
    #[schemars(with = "Option<Count>")]
    pub line_end: Option<u32>,
    /// Which side of the diff the line numbers count: "old" or "new".
    pub side: String,
    pub body: String,
    pub status: String,
    pub author: String,
    pub replies: Vec<ReplyInfo>,
    /// The anchored line changed or vanished since the comment was made.
    pub outdated: bool,
    /// Origin-prefixed diff snippet around the anchored line.
    pub context: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ReplyInfo {
    pub author: String,
    pub body: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct CommentsResponse {
    pub comments: Vec<CommentInfo>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ReviewsResponse {
    pub reviews: Vec<ReviewSummary>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ReplyResponse {
    pub ok: bool,
    pub status: String,
}

/// One line of what `publish_walkthrough` checked or resolved. A refusal
/// (`too_many_stops`, `empty_stops`, `body_too_long`, `total_too_long`,
/// `anchor_unparsed`, `anchor_file_missing`, `nothing_to_anchor`,
/// `note_outside_stop`, `duplicate_id`) means nothing was stored; the rest
/// (`anchor_whole`, `figure_dropped`, `figure_simplified`) land alongside a
/// stored walkthrough so the agent learns what to fix without a broken
/// figure ever reaching the reader.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct ReceiptInfo {
    #[schemars(with = "Option<Count>")]
    pub stop: Option<usize>,
    pub code: String,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct WalkthroughPublished {
    pub id: String,
    #[schemars(with = "Count")]
    pub stops: usize,
    pub receipts: Vec<ReceiptInfo>,
    /// The full commit this walkthrough is pinned to, `None` when the repo
    /// has no commits yet. Revise it once this no longer matches the branch.
    pub rev: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct StopInfo {
    /// The comment this stop is. Pass it back as a stop's `id` to revise the
    /// stop and keep the thread hanging off it.
    pub id: String,
    pub title: String,
    pub anchor: Option<String>,
    pub body: String,
    /// The extra comments this stop carries in its region. Pass a note's `id`
    /// back to keep it; a note whose id you leave out is deleted.
    pub notes: Vec<NoteInfo>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct NoteInfo {
    pub id: String,
    pub anchor: Option<String>,
    pub body: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct WalkthroughInfo {
    pub id: String,
    pub title: String,
    pub author: String,
    #[schemars(with = "Count")]
    pub at: u64,
    pub skipped: Option<String>,
    /// The walkthrough's own overview, when it has one: pass it back
    /// unchanged on a revision to keep it.
    pub summary: Option<String>,
    /// The full commit this walkthrough is pinned to, `None` for one
    /// published before `rev` existed.
    pub rev: Option<String>,
    pub stops: Vec<StopInfo>,
}

/// An MCP tool's structured output must itself describe an object, so a
/// possibly-absent walkthrough is a field here rather than the bare
/// `Option<WalkthroughInfo>` a top-level return would need.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct GetWalkthroughResponse {
    pub walkthrough: Option<WalkthroughInfo>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct OkResponse {
    pub ok: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct WaitForFeedbackResponse {
    #[schemars(with = "Count")]
    pub epoch: u64,
    pub timed_out: bool,
    pub comments: Vec<CommentInfo>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct GetDiffParams {
    /// Restrict the diff to one file (repo-relative path).
    pub file: Option<String>,
    /// The project to act on: its folder name from `review_status`, or its
    /// path. Omit it for the project the human is looking at.
    pub project: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct GetCommentsParams {
    /// Filter by comment status: "open", "replied", or "resolved".
    pub status: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ReplyCommentParams {
    pub id: String,
    pub body: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ProposeResolveParams {
    pub id: String,
    /// Short note on why the comment is addressed.
    pub note: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct MarkViewedParams {
    /// Repo-relative path of a file in the review diff.
    pub file: String,
    /// The project to act on: its folder name from `review_status`, or its
    /// path. Omit it for the project the human is looking at.
    pub project: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct AddCommentParams {
    /// Repo-relative path of a file in the review diff.
    pub file: String,
    /// Line number in the diff (new-side, unless the line was deleted).
    #[schemars(with = "Count")]
    pub line: u32,
    /// Last line of an inclusive range starting at `line`; omit for one line.
    #[schemars(with = "Option<Count>")]
    pub line_end: Option<u32>,
    pub body: String,
    /// Author the comment as the human, so it goes out untouched with their
    /// next submitted review. Off by default, which leaves the comment the
    /// agent's own for the human to answer.
    pub as_human: Option<bool>,
    /// The project to act on: its folder name from `review_status`, or its
    /// path. Omit it for the project the human is looking at.
    pub project: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
pub struct AddCommentResponse {
    pub id: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct DeleteCommentParams {
    /// The comment to delete, from `get_comments` or `add_comment`.
    pub id: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct EditCommentParams {
    /// The comment to rewrite, from `get_comments` or `add_comment`.
    pub id: String,
    pub body: String,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
pub struct StopParams {
    /// The comment id of the stop this replaces, from `get_walkthrough`. Pass
    /// it to keep that stop's thread; omit it for a new stop.
    pub id: Option<String>,
    /// A label of two to five words naming what the stop is about, no verb;
    /// the sidebar shows about thirty characters.
    pub title: String,
    /// `path#symbol` where a symbol exists, `path:start-end` where none does,
    /// `path:line` for one line, a bare `path` for a whole file, or omit for
    /// a stop with no anchor.
    pub anchor: Option<String>,
    /// Markdown: two or three short bullets on what we chose and why, in full
    /// sentences, every identifier in backticks, plain verbs for code (raise,
    /// return, check) and no metaphor. A `mermaid` or `callstack` fence draws
    /// a diagram.
    pub body: String,
    /// Extra remarks on this same stop: a second point about another part of
    /// its region, or a diagram beside the prose. Each becomes its own comment
    /// in the stop's slide.
    pub notes: Option<Vec<NoteParams>>,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
pub struct NoteParams {
    /// The comment id of the note this replaces, from `get_walkthrough`. Pass
    /// it to keep that note's thread; omit it for a new note.
    pub id: Option<String>,
    /// `path:line` or `path:start-end` in the stop's own file, or omit to
    /// anchor the note at the start of the stop's region.
    pub anchor: Option<String>,
    pub body: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct PublishWalkthroughParams {
    /// The walkthrough to revise, from `get_walkthrough` or `review_status`.
    /// Omit to publish a new one of its own.
    pub id: Option<String>,
    /// The walkthrough's name, as the status screen lists it.
    pub title: String,
    pub stops: Vec<StopParams>,
    /// One line on what you left out and why.
    pub skipped: Option<String>,
    /// What the reader meets first: one short paragraph saying what the
    /// change does, plus one diagram of the simplest shape that explains it,
    /// five to eight nodes, participants or frames, naming real files or
    /// functions. Pick the kind for what you are showing: a `mermaid`
    /// `flowchart` for a branch, a state, or data moving through steps; a
    /// `mermaid` `sequenceDiagram` for who calls whom over time, with
    /// `link B: label @ path#symbol` tying participant `B` to its code; a
    /// `callstack` fence for how a call path changed, one frame per line, two
    /// spaces of indent per depth, `+ `/`- ` right before an added or removed
    /// frame's label, and an optional ` @ path#symbol` after it. Never a list
    /// of the stops or a repeat of their titles. Omit for a walkthrough with
    /// no summary.
    pub summary: Option<String>,
    /// The project to act on: its folder name from `review_status`, or its
    /// path. Omit it for the project the human is looking at.
    pub project: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct OpenProjectParams {
    /// Path of a git repository, absolute or starting with `~`.
    pub path: String,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct FocusParams {
    /// A comment id (from `get_comments`, `add_comment` or `get_walkthrough`) or a
    /// walkthrough id. Takes the human to it in whichever review holds it.
    pub id: Option<String>,
    /// Repo-relative path to show, when you pass no `id`.
    pub file: Option<String>,
    /// New-side line to put the cursor on; omit for the top of the file.
    #[schemars(with = "Option<Count>")]
    pub line: Option<u32>,
    /// Last line of an inclusive range starting at `line`, banded on screen.
    #[schemars(with = "Option<Count>")]
    pub line_end: Option<u32>,
    /// The review to show `file` in: `working`, `commit:<rev>`,
    /// `range:<oldest>..<newest>` (both commits included), `pr:<number>`,
    /// `against:<rev>`, or a `source` from `list_reviews`. Omit it to use the
    /// review on screen when it holds the file, else the working tree, else
    /// the file as it is on disk.
    pub review: Option<String>,
    /// A few words the human reads as their view moves, e.g. "the retry loop
    /// you asked about".
    pub note: Option<String>,
    /// The project to act on: its folder name from `review_status`, or its
    /// path. Omit it for the project the human is looking at; an `id` finds
    /// its own project.
    pub project: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct GetWalkthroughParams {
    /// The walkthrough to fetch, from `review_status`. Omit for the newest.
    pub id: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct ReportActivityParams {
    /// Short plain phrase for what you're doing right now, e.g. "writing the
    /// walkthrough" or "fixing the failing test". Keep it to a few words;
    /// the bar cuts a long one.
    pub focus: String,
    /// The file this is about, if any.
    pub file: Option<String>,
}

#[derive(Debug, serde::Deserialize, schemars::JsonSchema)]
pub struct WaitForFeedbackParams {
    /// Return once the feedback epoch exceeds this value. Defaults to the
    /// current epoch, i.e. wait for the next human send.
    #[schemars(with = "Option<Count>")]
    pub since_epoch: Option<u64>,
    /// Long-poll timeout in seconds (default 25), capped at 55; call again
    /// to keep waiting.
    #[schemars(with = "Option<Count>")]
    pub timeout_seconds: Option<u64>,
}

/// Unsigned ints derive `format: "uint*"`, which JSON Schema does not register
/// and strict validators warn on. rmcp hardcodes its generator, so we opt each
/// field out with `#[schemars(with = "Count")]`.
struct Count;

impl schemars::JsonSchema for Count {
    fn inline_schema() -> bool {
        true
    }

    fn schema_name() -> std::borrow::Cow<'static, str> {
        "Count".into()
    }

    fn schema_id() -> std::borrow::Cow<'static, str> {
        "diffler::mcp::Count".into()
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({ "type": "integer", "minimum": 0 })
    }
}

pub const fn comment_status_name(status: CommentStatus) -> &'static str {
    match status {
        CommentStatus::Open => "open",
        CommentStatus::Replied => "replied",
        CommentStatus::Resolved => "resolved",
    }
}

pub const fn file_status_name(status: FileStatus) -> &'static str {
    match status {
        FileStatus::Added => "added",
        FileStatus::Modified => "modified",
        FileStatus::Deleted => "deleted",
        FileStatus::Renamed => "renamed",
        FileStatus::Untracked => "untracked",
        FileStatus::Unchanged => "unchanged",
    }
}

pub fn render_unified(model: &DiffModel, file: Option<&str>) -> Result<String, String> {
    use std::fmt::Write as _;

    if let Some(path) = file
        && !model.files.iter().any(|f| f.path == path)
    {
        return Err(format!("unknown file: {path}"));
    }
    let mut out = String::new();
    for f in &model.files {
        if file.is_some_and(|path| path != f.path) {
            continue;
        }
        let old = match f.status {
            FileStatus::Added | FileStatus::Untracked => "/dev/null".to_owned(),
            _ => format!("a/{}", f.old_path.as_deref().unwrap_or(&f.path)),
        };
        let new = match f.status {
            FileStatus::Deleted => "/dev/null".to_owned(),
            _ => format!("b/{}", f.path),
        };
        let _ = writeln!(out, "--- {old}");
        let _ = writeln!(out, "+++ {new}");
        if f.binary {
            out.push_str("Binary files differ\n");
            continue;
        }
        for hunk in &f.hunks {
            let _ = writeln!(out, "{}", hunk.header());
            for line in &hunk.lines {
                let _ = writeln!(out, "{}{}", line.kind.origin(), line.text);
            }
        }
    }
    Ok(out)
}

pub fn comment_info(comment: &Comment, model: &DiffModel, source: &ReviewSource) -> CommentInfo {
    let anchor = &comment.anchor;
    // outdated detection reads a range's end line, but we start the snippet at
    // its first line so it reads top-down
    let context = anchor
        .line
        .and_then(|line| feedback::context_snippet(model, &anchor.file, line, anchor.on_old_side))
        .map(|snippet| {
            snippet
                .iter()
                .map(|(origin, text)| format!("{origin}{text}"))
                .collect::<Vec<_>>()
                .join("\n")
        });
    let outdated = anchor.is_outdated(model);
    CommentInfo {
        id: comment.id.clone(),
        project: None,
        source: source.key(),
        source_label: source.label(),
        file: anchor.file.clone(),
        line: anchor.line,
        line_end: anchor.line_end,
        side: if anchor.on_old_side { "old" } else { "new" }.to_owned(),
        body: comment.body.clone(),
        status: comment_status_name(comment.status).to_owned(),
        author: comment.author.clone(),
        replies: comment
            .replies
            .iter()
            .map(|r| ReplyInfo {
                author: r.author.clone(),
                body: r.body.clone(),
            })
            .collect(),
        outdated,
        context,
    }
}

/// MCP tool handler: forwards every call to the app over the event channel
/// and holds a feedback-epoch receiver for the long poll.
#[derive(Clone)]
pub struct DifflerMcp {
    tx: UnboundedSender<AppEvent>,
    feedback_rx: watch::Receiver<u64>,
    tool_router: ToolRouter<Self>,
    prompt_router: PromptRouter<Self>,
}

fn mismatch() -> ErrorData {
    ErrorData::internal_error("unexpected response from the diffler app", None)
}

fn parse_status(status: &str) -> Result<CommentStatus, ErrorData> {
    match status {
        "open" => Ok(CommentStatus::Open),
        "replied" => Ok(CommentStatus::Replied),
        "resolved" => Ok(CommentStatus::Resolved),
        other => Err(ErrorData::invalid_params(
            format!("unknown status {other:?} (expected open, replied, or resolved)"),
            None,
        )),
    }
}

impl DifflerMcp {
    pub fn new(tx: UnboundedSender<AppEvent>, feedback_rx: watch::Receiver<u64>) -> Self {
        Self {
            tx,
            feedback_rx,
            tool_router: Self::tool_router(),
            prompt_router: Self::prompt_router(),
        }
    }

    async fn request(&self, kind: McpRequestKind) -> Result<McpResponse, ErrorData> {
        self.request_with_timeout(kind, None, REQUEST_TIMEOUT).await
    }

    /// [`Self::request`] for a call that acts on one project's tab.
    async fn request_in(
        &self,
        project: Option<String>,
        kind: McpRequestKind,
    ) -> Result<McpResponse, ErrorData> {
        self.request_with_timeout(kind, project, REQUEST_TIMEOUT)
            .await
    }

    async fn request_with_timeout(
        &self,
        kind: McpRequestKind,
        project: Option<String>,
        timeout: Duration,
    ) -> Result<McpResponse, ErrorData> {
        let (reply, response) = oneshot::channel();
        self.tx
            .send(AppEvent::Mcp(McpRequest {
                kind,
                project,
                reply,
            }))
            .map_err(|_| ErrorData::internal_error("the diffler TUI is not running", None))?;
        match tokio::time::timeout(timeout, response).await {
            Ok(Ok(McpResponse::Error(message))) => Err(ErrorData::invalid_params(message, None)),
            Ok(Ok(response)) => Ok(response),
            Ok(Err(_)) => Err(ErrorData::internal_error(
                "the diffler TUI dropped the request",
                None,
            )),
            Err(_) => Err(ErrorData::internal_error(
                "diffler is busy (editor open or loop stalled), retry",
                None,
            )),
        }
    }
}

#[tool_router]
impl DifflerMcp {
    #[tool(
        description = "Current review state: repo, branch, changed files with viewed marks, comment counts, and the feedback epoch for wait_for_feedback."
    )]
    async fn review_status(&self) -> Result<Json<ReviewStatusResponse>, ErrorData> {
        match self.request(McpRequestKind::ReviewStatus).await? {
            McpResponse::Status(status) => Ok(Json(status)),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Unified diff text of the working tree under review, optionally restricted to one file."
    )]
    async fn get_diff(
        &self,
        Parameters(params): Parameters<GetDiffParams>,
    ) -> Result<Json<DiffResponse>, ErrorData> {
        let kind = McpRequestKind::GetDiff { file: params.file };
        match self.request_in(params.project, kind).await? {
            McpResponse::Diff(diff) => Ok(Json(DiffResponse { diff })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Review comments across every review (working tree, commits, ranges), each tagged with its source and source_label; anchors, diff context, and threads included. Optionally filtered by status (open, replied, resolved)."
    )]
    async fn get_comments(
        &self,
        Parameters(params): Parameters<GetCommentsParams>,
    ) -> Result<Json<CommentsResponse>, ErrorData> {
        let status = params.status.as_deref().map(parse_status).transpose()?;
        match self.request(McpRequestKind::GetComments { status }).await? {
            McpResponse::Comments(comments) => Ok(Json(CommentsResponse { comments })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "List every review the human has: the working tree, individual commits, and commit ranges, each with its comment counts, so you can tell where feedback came from."
    )]
    async fn list_reviews(&self) -> Result<Json<ReviewsResponse>, ErrorData> {
        match self.request(McpRequestKind::ListReviews).await? {
            McpResponse::Reviews(reviews) => Ok(Json(ReviewsResponse { reviews })),
            _ => Err(mismatch()),
        }
    }

    #[tool(description = "Answer a review comment in place; the human sees the reply immediately.")]
    async fn reply_comment(
        &self,
        Parameters(params): Parameters<ReplyCommentParams>,
    ) -> Result<Json<ReplyResponse>, ErrorData> {
        let kind = McpRequestKind::ReplyComment {
            id: params.id,
            body: params.body,
        };
        match self.request(kind).await? {
            McpResponse::Replied { status } => Ok(Json(ReplyResponse { ok: true, status })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Flag a comment as addressed: marks it replied. Writes nothing into the thread, so call it after reply_comment rather than repeating the answer. The optional note is used only when you did not reply. Only the human can resolve it, in the TUI."
    )]
    async fn propose_resolve(
        &self,
        Parameters(params): Parameters<ProposeResolveParams>,
    ) -> Result<Json<ReplyResponse>, ErrorData> {
        let kind = McpRequestKind::ProposeResolve {
            id: params.id,
            note: params.note,
        };
        match self.request(kind).await? {
            McpResponse::Replied { status } => Ok(Json(ReplyResponse { ok: true, status })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Mark a file as viewed in the review the human is currently looking at (working tree, or the open commit/range diff)."
    )]
    async fn mark_viewed(
        &self,
        Parameters(params): Parameters<MarkViewedParams>,
    ) -> Result<Json<OkResponse>, ErrorData> {
        let kind = McpRequestKind::MarkViewed { file: params.file };
        match self.request_in(params.project, kind).await? {
            McpResponse::Ok => Ok(Json(OkResponse { ok: true })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Write a review comment on a line or an inclusive line range in the review the human has open: the working tree, or the commit, range or PR on screen. To comment on another review, `focus` it first. The comment is anchored like the human's own, so it shows as outdated once its line changes. It is the agent's comment, for the human to answer in its thread; `as_human` makes it the human's own, sent with their next submitted review. Returns its `id`."
    )]
    async fn add_comment(
        &self,
        Parameters(params): Parameters<AddCommentParams>,
    ) -> Result<Json<AddCommentResponse>, ErrorData> {
        let kind = McpRequestKind::AddComment {
            file: params.file,
            line: params.line,
            line_end: params.line_end,
            body: params.body,
            as_human: params.as_human.unwrap_or(false),
        };
        match self.request_in(params.project, kind).await? {
            McpResponse::Added { id } => Ok(Json(AddCommentResponse { id })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Delete a comment, yours or the human's. Refused for one already posted to the forge, for one someone else has replied to (edit it instead), and for a walkthrough stop or note, which `publish_walkthrough` revises."
    )]
    async fn delete_comment(
        &self,
        Parameters(params): Parameters<DeleteCommentParams>,
    ) -> Result<Json<OkResponse>, ErrorData> {
        let kind = McpRequestKind::DeleteComment { id: params.id };
        match self.request(kind).await? {
            McpResponse::Ok => Ok(Json(OkResponse { ok: true })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Replace a comment's body, yours or the human's, keeping its author, status, replies and anchor. Refused for one already posted to the forge, and for a walkthrough stop or note, which `publish_walkthrough` revises."
    )]
    async fn edit_comment(
        &self,
        Parameters(params): Parameters<EditCommentParams>,
    ) -> Result<Json<OkResponse>, ErrorData> {
        let kind = McpRequestKind::EditComment {
            id: params.id,
            body: params.body,
        };
        match self.request(kind).await? {
            McpResponse::Ok => Ok(Json(OkResponse { ok: true })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Publish a walkthrough: the order a reader should take through a change. Use one stop per real decision, as few as the change needs (five is common; more than ten means the change wants splitting). Each stop says why, never what the diff already shows, and becomes an agent comment the human answers in its thread. It describes the review open now, pinned to the commit checked out. Pass `id` to revise one in place, with each surviving stop's and note's `id` from `get_walkthrough`; any left out are deleted. Returns the walkthrough's `id` and receipts; a refusal names what to fix. Limits: 20 stops, 8 KB per body, 64 KB in all."
    )]
    async fn publish_walkthrough(
        &self,
        Parameters(params): Parameters<PublishWalkthroughParams>,
    ) -> Result<Json<WalkthroughPublished>, ErrorData> {
        let kind = McpRequestKind::PublishWalkthrough {
            id: params.id,
            title: params.title,
            stops: params.stops,
            skipped: params.skipped,
            summary: params.summary,
        };
        match self.request_in(params.project, kind).await? {
            McpResponse::WalkthroughPublished(published) => Ok(Json(published)),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "The walkthrough `id` names (from review_status), or the newest one when `id` is omitted, or null when the review has none."
    )]
    async fn get_walkthrough(
        &self,
        Parameters(params): Parameters<GetWalkthroughParams>,
    ) -> Result<Json<GetWalkthroughResponse>, ErrorData> {
        match self
            .request(McpRequestKind::GetWalkthrough { id: params.id })
            .await?
        {
            McpResponse::Walkthrough(walkthrough) => {
                Ok(Json(GetWalkthroughResponse { walkthrough }))
            }
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Show what you are doing in the human's status bar: a few words (\"writing the walkthrough\") and the file it is about, if any. Every other tool call already shows on its own, so call this before work no call covers, such as reading code or writing tests, or when a call's own label says too little."
    )]
    async fn report_activity(
        &self,
        Parameters(params): Parameters<ReportActivityParams>,
    ) -> Result<Json<OkResponse>, ErrorData> {
        let kind = McpRequestKind::ReportActivity {
            focus: params.focus,
            file: params.file,
        };
        match self.request(kind).await? {
            McpResponse::Ok => Ok(Json(OkResponse { ok: true })),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Open a git repository as a project tab in the human's diffler, so they can review its changes beside the others. Call it for every repository you changed outside the one diffler started in. Comments and feedback then cover it too, and `project` targets a call at it."
    )]
    async fn open_project(
        &self,
        Parameters(params): Parameters<OpenProjectParams>,
    ) -> Result<Json<ProjectInfo>, ErrorData> {
        let kind = McpRequestKind::OpenProject { path: params.path };
        match self.request(kind).await? {
            McpResponse::ProjectOpened(project) => Ok(Json(project)),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Take the human's diffler to a place: a comment or walkthrough by `id`, or a `file` and line range in any review. It switches to the project's tab and opens that review with the cursor on the place. Use it when the human asks where something is, and after `publish_walkthrough` to open the walkthrough. To point at code with a remark, call `add_comment`, then focus the `id` it returns. Refused while the human is typing a comment or answering a dialog; a pull request that still has to load answers `waiting` and opens once it does."
    )]
    async fn focus(
        &self,
        Parameters(params): Parameters<FocusParams>,
    ) -> Result<Json<FocusResponse>, ErrorData> {
        let target = match (params.id, params.file) {
            (Some(id), None) => FocusTarget::Id(id),
            (None, Some(file)) => FocusTarget::Code {
                file,
                line: params.line,
                line_end: params.line_end,
                review: params.review,
            },
            _ => {
                return Err(ErrorData::invalid_params("pass either id or file", None));
            }
        };
        let kind = McpRequestKind::Focus {
            target,
            note: params.note,
        };
        match self.request_in(params.project, kind).await? {
            McpResponse::Focused(focused) => Ok(Json(focused)),
            _ => Err(mismatch()),
        }
    }

    #[tool(
        description = "Wait until the human sends feedback: a comment, a reply, or the send key. Returns the new epoch and every open or replied comment, or `timed_out` while they are still reviewing; call again with the returned epoch to keep waiting. A reply on a walkthrough stop arrives as a reply on that stop's comment, so its id names the stop."
    )]
    async fn wait_for_feedback(
        &self,
        Parameters(params): Parameters<WaitForFeedbackParams>,
    ) -> Result<Json<WaitForFeedbackResponse>, ErrorData> {
        let mut rx = self.feedback_rx.clone();
        let since = params.since_epoch.unwrap_or_else(|| *rx.borrow());
        let timeout = Duration::from_secs(
            params
                .timeout_seconds
                .unwrap_or(DEFAULT_WAIT_SECONDS)
                .min(MAX_WAIT_SECONDS),
        );
        // we tell the app before blocking, since the poll sends no request
        // until the human answers
        let _ = self.tx.send(AppEvent::McpWaiting {
            until: Instant::now() + timeout,
        });
        let waited = tokio::time::timeout(timeout, rx.wait_for(|epoch| *epoch > since))
            .await
            // copy the epoch out so the watch borrow ends before the match
            .map(|result| result.map(|epoch| *epoch));
        let (epoch, timed_out) = match waited {
            Ok(Ok(epoch)) => (epoch, false),
            Ok(Err(_)) => {
                return Err(ErrorData::internal_error(
                    "the diffler TUI is not running",
                    None,
                ));
            }
            Err(_) => (*rx.borrow(), true),
        };
        if timed_out {
            return Ok(Json(WaitForFeedbackResponse {
                epoch,
                timed_out: true,
                comments: Vec::new(),
            }));
        }
        match self.request(McpRequestKind::Feedback).await? {
            McpResponse::Feedback { comments } => Ok(Json(WaitForFeedbackResponse {
                epoch,
                timed_out: false,
                comments,
            })),
            _ => Err(mismatch()),
        }
    }
}

/// A skill file's prose with its YAML frontmatter dropped. We normalise CRLF
/// first, since on a Windows checkout `\n` matches no frontmatter and we would
/// ship the YAML header to the agent.
fn skill_body(doc: &str) -> String {
    let doc = doc.replace("\r\n", "\n");
    let body = doc
        .strip_prefix("---\n")
        .and_then(|rest| rest.split_once("\n---\n"))
        .map_or(doc.as_str(), |(_, body)| body);
    body.trim().to_owned()
}

// a published crate carries only its own directory, so the prompts live here
// and `agent_command_sync` pins them to the skill files the plugin ships
const DF_SKILL: &str = include_str!("../prompts/df.md");

const DFA_SKILL: &str = include_str!("../prompts/dfa.md");

const DFR_SKILL: &str = include_str!("../prompts/dfr.md");

#[prompt_router]
impl DifflerMcp {
    #[prompt(
        name = "review",
        description = "Check the diffler review: read the human's open comments, address them in code, reply, and wait for the next round."
    )]
    async fn review(&self) -> Vec<PromptMessage> {
        vec![PromptMessage::new_text(Role::User, skill_body(DF_SKILL))]
    }

    #[prompt(
        name = "walkthrough",
        description = "Walk the human through a change: publish a walkthrough, one stop per real decision, and answer their comments."
    )]
    async fn walkthrough(&self) -> Vec<PromptMessage> {
        vec![PromptMessage::new_text(Role::User, skill_body(DFA_SKILL))]
    }

    #[prompt(
        name = "critique",
        description = "Review a change in diffler: read the diff and leave comments on real problems, one per issue, and never submit."
    )]
    async fn critique(&self) -> Vec<PromptMessage> {
        vec![PromptMessage::new_text(Role::User, skill_body(DFR_SKILL))]
    }
}

#[tool_handler(router = self.tool_router)]
#[prompt_handler(router = self.prompt_router)]
impl ServerHandler for DifflerMcp {
    fn get_info(&self) -> ServerConfig {
        ServerConfig::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .build(),
        )
        .with_instructions(
            "diffler code review: get_comments reads the human's diff comments, \
             reply_comment answers them in place, propose_resolve flags an \
             answered one as addressed without adding text, and \
             wait_for_feedback long-polls until the human sends \
             new feedback. open_project opens another repository you \
             changed as a tab in the same diffler; comments and feedback \
             cover every open project, each tagged with its project. focus \
             takes the human to a comment, a walkthrough, or a file and \
             line in any review. The review prompt packages that loop as a \
             command.",
        )
    }
}

pub struct McpHandle {
    /// Actual bound port: the configured one, or an ephemeral fallback.
    pub port: u16,
    pub handle: JoinHandle<()>,
}

// SO_REUSEADDR lets a restart reclaim the port while the old socket lingers in
// TIME_WAIT. Unix only: on Windows it instead allows hijacking a live port and
// errors WSAEACCES, defeating the busy-port fallback.
fn bind_reusable(addr: SocketAddr) -> std::io::Result<tokio::net::TcpListener> {
    let socket = tokio::net::TcpSocket::new_v4()?;
    #[cfg(unix)]
    socket.set_reuseaddr(true)?;
    socket.bind(addr)?;
    socket.listen(1024)
}

/// Serves `127.0.0.1:{port}/mcp`, or an ephemeral port when `port` is taken;
/// the handle carries the port that bound.
pub fn spawn_mcp(
    tx: UnboundedSender<AppEvent>,
    feedback_rx: watch::Receiver<u64>,
    port: u16,
) -> std::io::Result<McpHandle> {
    let listener = match bind_reusable(SocketAddr::from(([127, 0, 0, 1], port))) {
        Ok(listener) => listener,
        Err(e) if e.kind() == ErrorKind::AddrInUse => {
            bind_reusable(SocketAddr::from(([127, 0, 0, 1], 0)))?
        }
        Err(e) => return Err(e),
    };
    let port = listener.local_addr()?.port();
    let service: StreamableHttpService<DifflerMcp, LocalSessionManager> =
        StreamableHttpService::new(
            move || Ok(DifflerMcp::new(tx.clone(), feedback_rx.clone())),
            std::sync::Arc::default(),
            StreamableHttpServerConfig::default(),
        );
    let router = axum::Router::new().nest_service("/mcp", service);
    let handle = tokio::spawn(async move {
        // serve only ends on listener errors; the TUI aborts this task on quit
        let _ = axum::serve(listener, router).await;
    });
    Ok(McpHandle { port, handle })
}

const ENDPOINT_FILE: &str = "mcp.json";

fn endpoint_path(repo_root: &Path) -> PathBuf {
    repo_root.join(".diffler").join(ENDPOINT_FILE)
}

#[derive(Serialize)]
struct EndpointFile {
    port: u16,
    url: String,
    pid: u32,
}

/// The stdio proxy reads the bound port from `.diffler/mcp.json`, or from the
/// per-user registry when it starts outside any repo.
pub fn write_endpoint(repo_root: &Path, port: u16) -> std::io::Result<()> {
    let pid = std::process::id();
    let body = serde_json::to_string_pretty(&EndpointFile {
        port,
        url: format!("http://127.0.0.1:{port}/mcp"),
        pid,
    })
    .map_err(std::io::Error::other)?;
    diffler_core::store::write_file(repo_root, ENDPOINT_FILE, &body)?;
    write_registry_entry(repo_root, port, pid);
    Ok(())
}

/// We remove the file only while it names our port, since a second instance
/// in the same repo overwrites it and still needs it after we exit.
pub fn clear_endpoint(repo_root: &Path, port: u16) {
    let path = endpoint_path(repo_root);
    if let Ok(body) = std::fs::read_to_string(&path) {
        let current_owner = serde_json::from_str::<serde_json::Value>(&body)
            .ok()
            .and_then(|v| v.get("port").and_then(serde_json::Value::as_u64));
        if current_owner == Some(u64::from(port)) {
            let _ = std::fs::remove_file(&path);
        }
    }
    clear_registry_entry(repo_root, port);
}

#[derive(Serialize)]
struct RegistryEntry<'a> {
    repo: &'a str,
    port: u16,
    pid: u32,
    url: String,
}

/// `$XDG_STATE_HOME/diffler/instances`, defaulting to `~/.local/state`.
/// Tests set `DIFFLER_STATE_DIR` so they never touch the real home directory.
fn registry_dir() -> Option<PathBuf> {
    let base = if let Some(dir) = non_empty_env("DIFFLER_STATE_DIR") {
        PathBuf::from(dir)
    } else if let Some(dir) = non_empty_env("XDG_STATE_HOME") {
        PathBuf::from(dir)
    } else {
        PathBuf::from(non_empty_env("HOME")?)
            .join(".local")
            .join("state")
    };
    Some(base.join("diffler").join("instances"))
}

fn non_empty_env(key: &str) -> Option<std::ffi::OsString> {
    std::env::var_os(key).filter(|v| !v.is_empty())
}

/// Best-effort: a same-repo proxy still finds `.diffler/mcp.json`, so we
/// ignore write failures here.
fn write_registry_entry(repo_root: &Path, port: u16, pid: u32) {
    let Some(dir) = registry_dir() else {
        return;
    };
    if std::fs::create_dir_all(&dir).is_err() {
        return;
    }
    let repo = canonical_repo(repo_root);
    let Some(repo) = repo.to_str() else {
        return;
    };
    let Ok(body) = serde_json::to_string_pretty(&RegistryEntry {
        repo,
        port,
        pid,
        url: format!("http://127.0.0.1:{port}/mcp"),
    }) else {
        return;
    };
    let _ = std::fs::write(dir.join(registry_file(repo_root, port)), body);
}

pub(crate) fn canonical_repo(repo_root: &Path) -> PathBuf {
    repo_root
        .canonicalize()
        .unwrap_or_else(|_| repo_root.to_path_buf())
}

/// One entry per project, since one diffler serves all its tabs on one port.
fn registry_file(repo_root: &Path, port: u16) -> String {
    let mut hasher = std::hash::DefaultHasher::new();
    std::hash::Hash::hash(&canonical_repo(repo_root), &mut hasher);
    format!("{port}-{:016x}.json", std::hash::Hasher::finish(&hasher))
}

/// Same owner check as `clear_endpoint`.
fn clear_registry_entry(repo_root: &Path, port: u16) {
    let Some(dir) = registry_dir() else {
        return;
    };
    let path = dir.join(registry_file(repo_root, port));
    let Ok(body) = std::fs::read_to_string(&path) else {
        return;
    };
    let owner_port = serde_json::from_str::<serde_json::Value>(&body)
        .ok()
        .and_then(|v| v.get("port").and_then(serde_json::Value::as_u64));
    if owner_port == Some(u64::from(port)) {
        let _ = std::fs::remove_file(&path);
    }
}

#[cfg(test)]
mod tests {
    use diffler_core::model::{DiffLine, FileDiff, Hunk, HunkId, LineKind};
    use diffler_core::session::{Anchor, Session};

    use super::*;

    fn diff_line(kind: LineKind, old_no: Option<u32>, new_no: Option<u32>, text: &str) -> DiffLine {
        DiffLine::new(kind, old_no, new_no, text.to_owned())
    }

    fn sample_model() -> DiffModel {
        DiffModel {
            files: vec![
                FileDiff {
                    path: "src/auth.py".into(),
                    old_path: None,
                    status: FileStatus::Modified,
                    binary: false,
                    old_text: None,
                    new_text: Some("one\nTWO\nthree\n".into()),
                    hunks: vec![Hunk {
                        id: HunkId("h1".into()),
                        old_start: 1,
                        old_lines: 3,
                        new_start: 1,
                        new_lines: 3,
                        context: String::new(),
                        lines: vec![
                            diff_line(LineKind::Context, Some(1), Some(1), "one"),
                            diff_line(LineKind::Deleted, Some(2), None, "two"),
                            diff_line(LineKind::Added, None, Some(2), "TWO"),
                            diff_line(LineKind::Context, Some(3), Some(3), "three"),
                        ],
                    }],
                    hashes: diffler_core::model::HashCache::default(),
                    blobs: diffler_core::model::BlobIds::default(),
                },
                FileDiff {
                    path: "logo.png".into(),
                    old_path: None,
                    status: FileStatus::Added,
                    binary: true,
                    old_text: None,
                    new_text: None,
                    hunks: vec![],
                    hashes: diffler_core::model::HashCache::default(),
                    blobs: diffler_core::model::BlobIds::default(),
                },
            ],
        }
    }

    fn anchor(file: &str, line: Option<u32>) -> Anchor {
        Anchor {
            file: file.to_owned(),
            line,
            line_end: None,
            on_old_side: false,
            line_text: None,
        }
    }

    #[test]
    fn render_unified_emits_headers_hunks_and_origins() {
        let text = render_unified(&sample_model(), None).unwrap();
        assert!(text.contains("--- a/src/auth.py\n+++ b/src/auth.py\n"));
        assert!(text.contains("@@ -1,3 +1,3 @@\n one\n-two\n+TWO\n three\n"));
        assert!(text.contains("--- /dev/null\n+++ b/logo.png\nBinary files differ\n"));
    }

    #[test]
    fn render_unified_filters_to_one_file() {
        let text = render_unified(&sample_model(), Some("src/auth.py")).unwrap();
        assert!(text.contains("src/auth.py"));
        assert!(!text.contains("logo.png"));
    }

    #[test]
    fn render_unified_unknown_file_is_an_error() {
        let err = render_unified(&sample_model(), Some("nope.rs")).unwrap_err();
        assert!(err.contains("nope.rs"));
    }

    #[test]
    fn render_unified_marks_deleted_files_with_dev_null() {
        let mut model = sample_model();
        model.files[0].status = FileStatus::Deleted;
        let text = render_unified(&model, Some("src/auth.py")).unwrap();
        assert!(text.contains("--- a/src/auth.py\n+++ /dev/null\n"));
    }

    #[test]
    fn render_unified_renamed_file_pairs_old_and_new_paths() {
        let mut model = sample_model();
        model.files[0].status = FileStatus::Renamed;
        model.files[0].old_path = Some("src/auth_v1.py".to_owned());
        let text = render_unified(&model, Some("src/auth.py")).unwrap();
        assert!(
            text.contains("--- a/src/auth_v1.py\n+++ b/src/auth.py\n"),
            "rename header must pair both paths: {text}"
        );
    }

    #[test]
    fn render_unified_empty_model_is_an_empty_diff() {
        let model = DiffModel { files: vec![] };
        assert_eq!(render_unified(&model, None).unwrap(), "");
    }

    #[test]
    fn comment_info_old_side_anchor_reports_side_and_context() {
        let mut session = Session::default();
        let mut a = anchor("src/auth.py", Some(2));
        a.on_old_side = true;
        a.line_text = Some("two".to_owned());
        session.add_comment(a, "human", "what was wrong with two?");
        let info = comment_info(
            &session.comments[0],
            &sample_model(),
            &ReviewSource::WorkingTree,
        );
        assert_eq!(info.side, "old");
        assert_eq!(info.line, Some(2));
        assert_eq!(info.line_end, None);
        assert!(!info.outdated, "the deleted line is still in the diff");
        assert_eq!(info.context.as_deref(), Some(" one\n-two\n+TWO"));
    }

    #[test]
    fn comment_info_carries_context_and_thread() {
        let mut session = Session::default();
        let mut a = anchor("src/auth.py", Some(2));
        a.line_text = Some("TWO".to_owned());
        let id = session.add_comment(a, "human", "why uppercase?").id.clone();
        session.reply(&id, AGENT_AUTHOR, "legacy API");
        let info = comment_info(
            &session.comments[0],
            &sample_model(),
            &ReviewSource::WorkingTree,
        );
        assert_eq!(info.file, "src/auth.py");
        assert_eq!(info.line, Some(2));
        assert_eq!(info.side, "new");
        assert_eq!(info.status, "replied");
        assert_eq!(info.context.as_deref(), Some("-two\n+TWO\n three"));
        assert!(!info.outdated);
        assert_eq!(info.replies.len(), 1);
        assert_eq!(info.replies[0].author, AGENT_AUTHOR);
    }

    #[test]
    fn comment_info_flags_departed_lines_outdated() {
        let mut session = Session::default();
        session.add_comment(anchor("src/auth.py", Some(99)), "human", "moved on");
        let info = comment_info(
            &session.comments[0],
            &sample_model(),
            &ReviewSource::WorkingTree,
        );
        assert!(info.outdated);
        assert_eq!(info.context, None);
    }

    #[test]
    fn comment_info_flags_drifted_line_text_outdated() {
        let mut session = Session::default();
        let mut a = anchor("src/auth.py", Some(2));
        a.line_text = Some("old text".to_owned());
        session.add_comment(a, "human", "stale");
        let info = comment_info(
            &session.comments[0],
            &sample_model(),
            &ReviewSource::WorkingTree,
        );
        assert!(info.outdated);
        assert!(info.context.is_some(), "context still renders");
    }

    #[test]
    fn file_level_comment_outdated_only_when_file_left_the_diff() {
        let mut session = Session::default();
        session.add_comment(anchor("src/auth.py", None), "human", "overall");
        session.add_comment(anchor("gone.py", None), "human", "gone");
        let model = sample_model();
        assert!(!comment_info(&session.comments[0], &model, &ReviewSource::WorkingTree).outdated);
        assert!(comment_info(&session.comments[1], &model, &ReviewSource::WorkingTree).outdated);
    }

    #[test]
    fn range_comment_not_outdated_when_end_line_matches() {
        let mut session = Session::default();
        // comment spans new lines 1-3; line_text snapshots line 3 ("three")
        let mut a = Anchor {
            file: "src/auth.py".to_owned(),
            line: Some(1),
            line_end: Some(3),
            on_old_side: false,
            line_text: Some("three".to_owned()),
        };
        assert_ne!(a.line_text.as_deref(), Some("one"));
        session.add_comment(a.clone(), "human", "range comment");
        let info = comment_info(
            &session.comments[0],
            &sample_model(),
            &ReviewSource::WorkingTree,
        );
        assert!(
            !info.outdated,
            "end line text matches snapshot: must NOT be outdated"
        );
        a.line_text = Some("changed".to_owned());
        session.comments[0].anchor = a;
        let info2 = comment_info(
            &session.comments[0],
            &sample_model(),
            &ReviewSource::WorkingTree,
        );
        assert!(info2.outdated, "end line text drifted: must be outdated");
    }

    #[tokio::test]
    async fn request_times_out_when_app_does_not_answer() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let (_feedback_tx, feedback_rx) = tokio::sync::watch::channel(0u64);
        let handler = DifflerMcp::new(tx, feedback_rx);
        let err = handler
            .request_with_timeout(
                McpRequestKind::ReviewStatus,
                None,
                Duration::from_millis(50),
            )
            .await
            .unwrap_err();
        assert!(
            err.message.contains("busy"),
            "error should mention busy: {err:?}"
        );
    }

    // a paused clock jumps to the next timer, so elapsed time is the effective timeout
    #[tokio::test(start_paused = true)]
    async fn wait_for_feedback_clamps_the_timeout_to_the_cap() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let (_feedback_tx, feedback_rx) = tokio::sync::watch::channel(0u64);
        let handler = DifflerMcp::new(tx, feedback_rx);
        let started = tokio::time::Instant::now();
        let Json(response) = handler
            .wait_for_feedback(Parameters(WaitForFeedbackParams {
                since_epoch: None,
                timeout_seconds: Some(MAX_WAIT_SECONDS * 10),
            }))
            .await
            .unwrap();
        assert!(response.timed_out, "no feedback ever arrives");
        assert_eq!(
            started.elapsed(),
            Duration::from_secs(MAX_WAIT_SECONDS),
            "a timeout above the cap must clamp to {MAX_WAIT_SECONDS}s"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn wait_for_feedback_defaults_inside_the_client_request_timeout() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let (_feedback_tx, feedback_rx) = tokio::sync::watch::channel(0u64);
        let handler = DifflerMcp::new(tx, feedback_rx);
        let started = tokio::time::Instant::now();
        let Json(response) = handler
            .wait_for_feedback(Parameters(WaitForFeedbackParams {
                since_epoch: None,
                timeout_seconds: None,
            }))
            .await
            .unwrap();
        assert!(response.timed_out, "no feedback ever arrives");
        assert!(
            started.elapsed() + REQUEST_TIMEOUT < Duration::from_secs(120),
            "the wait plus the reply it still owes must beat the client's 120 s cut"
        );
    }

    #[test]
    fn a_capped_wait_and_its_round_trip_fit_the_client_ceiling() {
        assert!(MAX_WAIT_SECONDS + REQUEST_TIMEOUT.as_secs() < 120);
    }

    #[tokio::test]
    async fn wait_for_feedback_answers_with_the_reviews_comments() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
        let (feedback_tx, feedback_rx) = tokio::sync::watch::channel(0u64);
        feedback_tx.send_modify(|epoch| *epoch += 1);
        let handler = DifflerMcp::new(tx, feedback_rx);
        let requests = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let counted = requests.clone();
        tokio::spawn(async move {
            while let Some(event) = rx.recv().await {
                let AppEvent::Mcp(request) = event else {
                    continue;
                };
                counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let response = match request.kind {
                    McpRequestKind::Feedback => McpResponse::Feedback {
                        comments: Vec::new(),
                    },
                    _ => McpResponse::Ok,
                };
                let _ = request.reply.send(response);
            }
        });
        let Json(response) = handler
            .wait_for_feedback(Parameters(WaitForFeedbackParams {
                since_epoch: Some(0),
                timeout_seconds: None,
            }))
            .await
            .unwrap();
        assert!(!response.timed_out);
        assert_eq!(
            requests.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "the success path makes exactly one app request after the wait"
        );
    }

    // `DIFFLER_STATE_DIR` is process-global, so registry tests serialize on this lock.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[allow(unsafe_code)]
    fn with_state_dir<T>(dir: &Path, f: impl FnOnce() -> T) -> T {
        let _guard = ENV_LOCK.lock().unwrap();
        // SAFETY: ENV_LOCK serializes every test that reads or writes this var.
        unsafe { std::env::set_var("DIFFLER_STATE_DIR", dir) };
        let result = f();
        unsafe { std::env::remove_var("DIFFLER_STATE_DIR") };
        result
    }

    #[test]
    fn endpoint_file_publishes_the_port_and_clears() {
        let dir = tempfile::tempdir().expect("tempdir");
        let state = tempfile::tempdir().expect("tempdir");
        with_state_dir(state.path(), || {
            write_endpoint(dir.path(), 8417).expect("write");
            let path = dir.path().join(".diffler/mcp.json");
            let body = std::fs::read_to_string(&path).expect("read");
            assert!(body.contains("\"port\": 8417"), "{body}");
            assert!(body.contains("http://127.0.0.1:8417/mcp"), "{body}");
            assert!(body.contains("\"pid\""), "{body}");
            // the .diffler dir self-gitignores like the session store
            let gitignore =
                std::fs::read_to_string(dir.path().join(".diffler/.gitignore")).expect("gitignore");
            assert_eq!(gitignore, "*\n");
            clear_endpoint(dir.path(), 8417);
            assert!(!path.exists(), "endpoint file removed on shutdown");
        });
    }

    #[test]
    fn clear_endpoint_leaves_a_newer_owner_alone() {
        let dir = tempfile::tempdir().expect("tempdir");
        let state = tempfile::tempdir().expect("tempdir");
        with_state_dir(state.path(), || {
            write_endpoint(dir.path(), 1111).expect("write first instance");
            // a second diffler instance in the same repo overwrites the file
            write_endpoint(dir.path(), 2222).expect("write second instance");

            // the first instance shuts down and clears its own (stale) port
            clear_endpoint(dir.path(), 1111);

            let path = dir.path().join(".diffler/mcp.json");
            let body = std::fs::read_to_string(&path)
                .expect("file survives: it names the still-running instance");
            assert!(body.contains("\"port\": 2222"), "{body}");
        });
    }

    #[test]
    fn write_endpoint_registers_the_instance_for_cross_repo_discovery() {
        let dir = tempfile::tempdir().expect("tempdir");
        let state = tempfile::tempdir().expect("tempdir");
        with_state_dir(state.path(), || {
            write_endpoint(dir.path(), 8417).expect("write");
            let entry_path = state
                .path()
                .join("diffler/instances")
                .join(registry_file(dir.path(), 8417));
            let body = std::fs::read_to_string(&entry_path).expect("registry entry written");
            // we parse the entry because JSON escapes a Windows path's separators
            let entry: serde_json::Value =
                serde_json::from_str(&body).expect("registry entry is json");
            let repo = dir.path().canonicalize().expect("canonicalize");
            assert_eq!(entry["repo"].as_str(), repo.to_str(), "{body}");
            assert_eq!(entry["port"].as_u64(), Some(8417), "{body}");
            assert_eq!(
                entry["pid"].as_u64(),
                Some(u64::from(std::process::id())),
                "{body}"
            );
            assert_eq!(
                entry["url"].as_str(),
                Some("http://127.0.0.1:8417/mcp"),
                "{body}"
            );
        });
    }

    #[test]
    fn clear_endpoint_removes_only_its_own_registry_entry() {
        let dir = tempfile::tempdir().expect("tempdir");
        let state = tempfile::tempdir().expect("tempdir");
        with_state_dir(state.path(), || {
            write_endpoint(dir.path(), 1111).expect("write first instance");
            write_endpoint(dir.path(), 2222).expect("write second instance");
            let instances = state.path().join("diffler/instances");

            clear_endpoint(dir.path(), 1111);

            assert!(
                !instances.join(registry_file(dir.path(), 1111)).exists(),
                "the cleared instance's own registry entry is gone"
            );
            assert!(
                instances.join(registry_file(dir.path(), 2222)).exists(),
                "a different instance's registry entry survives"
            );
        });
    }

    #[test]
    fn one_diffler_registers_every_project_it_serves() {
        let (first, second) = (
            tempfile::tempdir().expect("tempdir"),
            tempfile::tempdir().expect("tempdir"),
        );
        let state = tempfile::tempdir().expect("tempdir");
        with_state_dir(state.path(), || {
            write_endpoint(first.path(), 3333).expect("first project");
            write_endpoint(second.path(), 3333).expect("second project");
            let instances = state.path().join("diffler/instances");
            assert_eq!(std::fs::read_dir(&instances).expect("registry").count(), 2);
            clear_endpoint(second.path(), 3333);
            assert!(instances.join(registry_file(first.path(), 3333)).exists());
            assert!(!instances.join(registry_file(second.path(), 3333)).exists());
        });
    }

    #[test]
    fn tool_schemas_use_no_unregistered_format() {
        for tool in DifflerMcp::tool_router().list_all() {
            for (part, schema) in [
                ("input", Some(&*tool.input_schema)),
                ("output", tool.output_schema.as_deref()),
            ] {
                let Some(schema) = schema else { continue };
                let text = serde_json::to_string(schema).expect("schema serializes");
                assert!(
                    !text.contains("\"format\""),
                    "{} {part} schema carries a format keyword: {text}",
                    tool.name
                );
            }
        }
    }

    #[tokio::test]
    async fn spawn_mcp_fallback_on_addr_in_use() {
        let holder = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .unwrap();
        let busy_port = holder.local_addr().unwrap().port();
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let (_feedback_tx, feedback_rx) = tokio::sync::watch::channel(0u64);
        let handle = spawn_mcp(tx, feedback_rx, busy_port).unwrap();
        assert_ne!(
            handle.port, busy_port,
            "should have bound to a different ephemeral port"
        );
        handle.handle.abort();
    }
}

#[cfg(test)]
mod agent_command_sync {
    fn body(doc: &str) -> String {
        let doc = doc.replace("\r\n", "\n");
        let after_frontmatter = doc
            .strip_prefix("---\n")
            .and_then(|rest| rest.split_once("\n---\n"))
            .map_or(doc.as_str(), |(_, body)| body);
        after_frontmatter.trim().to_owned()
    }

    #[test]
    fn a_skill_loses_its_frontmatter_whatever_its_line_endings() {
        assert_eq!(
            super::skill_body("---\r\nname: df\r\n---\r\n\r\nthe body\r\n"),
            "the body"
        );
        assert_eq!(
            super::skill_body("---\nname: df\n---\n\nthe body\n"),
            "the body"
        );
    }

    /// Every agent command ships as a Claude Code skill, an `OpenCode` command
    /// and a crate prompt, with only the frontmatter allowed to differ.
    #[test]
    fn both_agent_command_files_teach_the_same_loop() {
        const DF_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/df/SKILL.md"
        ));
        const DF_OPENCODE: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../.opencode/commands/df.md"
        ));
        const DFA_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/dfa/SKILL.md"
        ));
        const DFA_OPENCODE: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../.opencode/commands/dfa.md"
        ));
        const DFR_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/dfr/SKILL.md"
        ));
        const DFR_OPENCODE: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../.opencode/commands/dfr.md"
        ));
        for (name, skill, opencode, prompt) in [
            ("df", DF_SKILL, DF_OPENCODE, super::DF_SKILL),
            ("dfa", DFA_SKILL, DFA_OPENCODE, super::DFA_SKILL),
            ("dfr", DFR_SKILL, DFR_OPENCODE, super::DFR_SKILL),
        ] {
            assert_eq!(
                body(skill),
                body(opencode),
                "skills/{name}/SKILL.md and .opencode/commands/{name}.md have drifted; \
                 edit both or neither"
            );
            assert_eq!(
                body(skill),
                body(prompt),
                "skills/{name}/SKILL.md and crates/diffler/prompts/{name}.md have drifted; \
                 the crate ships its own copy because a published crate carries only \
                 its own directory"
            );
        }
    }

    fn write_for_the_card(doc: &str) -> &str {
        const HEADING: &str = "## Write for the card";
        let Some(start) = doc.find(HEADING) else {
            return "";
        };
        let after = &doc[start..];
        let end = after[HEADING.len()..]
            .find("\n## ")
            .map_or(after.len(), |offset| offset + HEADING.len());
        after[..end].trim()
    }

    /// All three skills write a card in the same pane, so they share its writing rules.
    #[test]
    fn every_skill_writes_the_card_the_same_way() {
        const DF_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/df/SKILL.md"
        ));
        const DFA_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/dfa/SKILL.md"
        ));
        const DFR_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/dfr/SKILL.md"
        ));
        let df = write_for_the_card(DF_SKILL);
        let dfa = write_for_the_card(DFA_SKILL);
        let dfr = write_for_the_card(DFR_SKILL);
        assert!(
            !df.is_empty(),
            "df must have a '## Write for the card' section"
        );
        assert_eq!(
            df, dfa,
            "the '## Write for the card' section must be identical in df and dfa"
        );
        assert_eq!(
            df, dfr,
            "the '## Write for the card' section must be identical in df and dfr"
        );
    }

    /// Each MCP prompt must be its skill file's steps, verbatim.
    #[tokio::test]
    async fn the_prompts_are_their_skills_bodies() {
        const DF_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/df/SKILL.md"
        ));
        const DFA_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/dfa/SKILL.md"
        ));
        const DFR_SKILL: &str = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../skills/dfr/SKILL.md"
        ));
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        let (_feedback_tx, feedback_rx) = tokio::sync::watch::channel(0u64);
        let handler = super::DifflerMcp::new(tx, feedback_rx);
        for (messages, skill) in [
            (handler.review().await, DF_SKILL),
            (handler.walkthrough().await, DFA_SKILL),
            (handler.critique().await, DFR_SKILL),
        ] {
            let text = &messages[0]
                .content
                .as_text()
                .expect("prompt carries text")
                .text;
            assert_eq!(*text, body(skill));
        }
    }
}