tailscale-mcp 2.0.3

MCP server for Tailscale: the local node through the CLI, the tailnet through the control-plane API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
//! Every tool, checked the same way.
//!
//! The point of a table-driven contract is that adding a tool is not enough:
//! the tool has to say what a successful call and a failed call look like, or
//! the suite fails. What is asserted here is what a client can see — the tier,
//! the toolset, the annotations, and one call of each kind through a real
//! session — so a tool cannot pass by being right on the inside.
#![allow(clippy::expect_used, clippy::unwrap_used)]

mod harness;

use std::collections::BTreeSet;

use serde_json::{Value, json};
use tailscale_cli::stub::Reply;
use tailscale_mcp::gating::Preset;
use tailscale_mcp::meta::{Tier, ToolMeta};
use tailscale_rest::fake::Response;

use harness::Setup;

/// What one tool needs to be answered with for one call.
#[derive(Default)]
struct Arrangement {
    /// Answers the fake `tailscale` should give, matched on an argument prefix.
    cli: Vec<(Vec<&'static str>, Reply)>,
    /// Answers the fake control plane should give.
    api: Vec<(&'static str, &'static str, Response)>,
}

impl Arrangement {
    fn cli(mut self, argv: &[&'static str], reply: Reply) -> Self {
        self.cli.push((argv.to_vec(), reply));
        self
    }

    fn api(mut self, method: &'static str, path: &'static str, response: Response) -> Self {
        self.api.push((method, path, response));
        self
    }
}

/// One tool's contract: what it does when it works, and when it does not.
struct Contract {
    tool: &'static str,
    /// A call that should succeed, and what the world looks like when it does.
    success: (Value, Arrangement),
    /// A call that should fail, and the code it should fail with.
    failure: (Value, Arrangement, &'static str),
}

/// The contract for every tool in the table.
///
/// A tool with no row here fails [`every_tool_has_a_contract`], which is the
/// mechanism that keeps this list complete as the table grows.
fn contracts() -> Vec<Contract> {
    /// One row, written the way it reads: the tool, the call, the answer
    /// arranged for it, and the code the same tool gives when it goes wrong.
    macro_rules! contract {
        (
            $tool:literal,
            ok: $ok_args:tt on $ok_argv:expr => $ok_reply:expr,
            err: $err_args:tt on $err_argv:expr => $err_reply:expr, $code:literal
        ) => {
            Contract {
                tool: $tool,
                success: (
                    json!($ok_args),
                    Arrangement::default().cli(&$ok_argv, $ok_reply),
                ),
                failure: (
                    json!($err_args),
                    Arrangement::default().cli(&$err_argv, $err_reply),
                    $code,
                ),
            }
        };
    }

    /// The same row for a tool on the tailnet surface, where the arrangement
    /// is a route on the fake control plane rather than an argument list.
    ///
    /// The failure case is a 404 throughout: it is the one status every
    /// endpoint here can produce, it maps to a code of its own rather than to
    /// the catch-all, and arranging it needs no knowledge of what each
    /// endpoint validates.
    macro_rules! api_contract {
        (
            $tool:literal,
            ok: $ok_args:tt on $method:literal $path:literal => $answer:expr,
            err: $err_args:tt
        ) => {
            Contract {
                tool: $tool,
                success: (
                    json!($ok_args),
                    Arrangement::default().api($method, $path, $answer),
                ),
                failure: (
                    json!($err_args),
                    Arrangement::default().api(
                        $method,
                        $path,
                        Response::status(404, json!({"message": "not found"})),
                    ),
                    "not_found",
                ),
            }
        };
        (
            $tool:literal,
            ok: $ok_args:tt on $method:literal $path:literal => $answer:expr,
            err: $err_args:tt also $fallback:literal
        ) => {
            Contract {
                tool: $tool,
                success: (
                    json!($ok_args),
                    Arrangement::default().api($method, $path, $answer),
                ),
                failure: (
                    json!($err_args),
                    // Both spellings refused: these tools retry a 404 at the
                    // other path, and whatever *it* answers is what the caller
                    // gets. Arranging only one would test the fake's fallback
                    // rather than the tool's.
                    Arrangement::default()
                        .api(
                            $method,
                            $path,
                            Response::status(404, json!({"message": "not found"})),
                        )
                        .api(
                            $method,
                            $fallback,
                            Response::status(404, json!({"message": "not found"})),
                        ),
                    "not_found",
                ),
            }
        };
    }

    /// A recorded answer from `tests/fixtures`.
    macro_rules! printed {
        ($name:literal) => {
            Reply::ok(harness::fixture($name))
        };
    }

    vec![
        contract!(
            "tailscale_status",
            ok: {} on ["status"] => printed!("status.json"),
            err: {} on ["status"] => Reply::Unavailable, "backend_unavailable"
        ),
        contract!(
            "tailscale_ip",
            ok: {} on ["ip"] => printed!("ip.txt"),
            err: {"target": "missing"} on ["ip"] =>
                Reply::failed(1, "no such host: missing"), "not_found"
        ),
        contract!(
            "tailscale_netcheck",
            ok: {} on ["netcheck"] => printed!("netcheck.json"),
            err: {} on ["netcheck"] =>
                Reply::failed(1, "netcheck: the probe could not be run"), "cli_failed"
        ),
        contract!(
            "tailscale_ping",
            ok: {"target": "laptop"} on ["ping"] => printed!("ping.txt"),
            err: {"target": "missing"} on ["ping"] =>
                Reply::failed(1, "ping \"missing\": unknown peer"), "not_found"
        ),
        contract!(
            "tailscale_whois",
            ok: {"address": "100.64.0.2"} on ["whois"] => printed!("whois.json"),
            err: {"address": "203.0.113.9"} on ["whois"] =>
                Reply::failed(1, "whois: 203.0.113.9 is outside the tailnet"), "cli_failed"
        ),
        contract!(
            "tailscale_whoami",
            ok: {} on ["whoami"] => printed!("whoami.json"),
            // A command added after our floor: an old binary refuses it by not
            // knowing it, and the caller is told which release added it.
            err: {} on ["whoami"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"whoami\""), "unsupported_version"
        ),
        contract!(
            "tailscale_version",
            ok: {} on ["version"] => printed!("tailscale-version.txt"),
            err: {} on ["version"] =>
                Reply::failed(1, "failed to connect to local tailscaled"), "cli_failed"
        ),
        contract!(
            "tailscale_licenses",
            ok: {} on ["licenses"] => printed!("licenses.txt"),
            err: {} on ["licenses"] =>
                Reply::failed(1, "licenses: this build carries no licence index"), "cli_failed"
        ),
        contract!(
            "tailscale_bugreport",
            ok: {"note": "slow handshake"} on ["bugreport"] => printed!("bugreport.txt"),
            err: {} on ["bugreport"] =>
                Reply::failed(1, "bugreport: the log service could not be reached"), "cli_failed"
        ),
        contract!(
            "tailscale_appc_routes",
            ok: {"all": true} on ["appc-routes"] => printed!("appc-routes.txt"),
            err: {} on ["appc-routes"] =>
                Reply::failed(1, "appc-routes: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_routecheck",
            ok: {} on ["routecheck"] => printed!("routecheck.json"),
            err: {} on ["routecheck"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"routecheck\""),
                "unsupported_version"
        ),
        contract!(
            "tailscale_wait",
            ok: {"timeout_seconds": 1} on ["wait"] => Reply::ok(""),
            err: {"timeout_seconds": 1} on ["wait"] => Reply::Unavailable, "backend_unavailable"
        ),
        contract!(
            "tailscale_dns_status",
            ok: {} on ["dns", "status"] => printed!("dns-status.json"),
            err: {} on ["dns", "status"] =>
                Reply::failed(1, "dns status: the resolver configuration could not be read"),
                "cli_failed"
        ),
        contract!(
            "tailscale_dns_query",
            ok: {"name": "laptop.example-tailnet.ts.net"} on ["dns", "query"] =>
                printed!("dns-query.json"),
            err: {"name": "absent.example-tailnet.ts.net"} on ["dns", "query"] =>
                Reply::failed(1, "dns query: the resolver answered NXDOMAIN"), "cli_failed"
        ),
        contract!(
            "tailscale_exit_node_list",
            ok: {} on ["exit-node", "list"] => printed!("exit-node-list.txt"),
            // Having no exit nodes is an answer, so the failure this tool can
            // still have is being refused outright.
            err: {} on ["exit-node", "list"] =>
                Reply::failed(1, "Access denied: this operation requires the operator"),
                "needs_operator"
        ),
        contract!(
            "tailscale_exit_node_suggest",
            ok: {} on ["exit-node", "suggest"] => printed!("exit-node-suggest.txt"),
            err: {} on ["exit-node", "suggest"] => Reply::Unavailable, "backend_unavailable"
        ),
        contract!(
            "tailscale_metrics_print",
            ok: {} on ["metrics", "print"] => printed!("metrics.txt"),
            err: {} on ["metrics", "print"] =>
                Reply::failed(1, "metrics: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_service_list",
            ok: {} on ["service", "list"] => printed!("service-list.json"),
            err: {} on ["service", "list"] =>
                Reply::failed(1, "tailscale service: unknown subcommand \"list\""),
                "unsupported_version"
        ),
        contract!(
            "tailscale_syspolicy_list",
            ok: {} on ["syspolicy", "list"] => printed!("syspolicy-list.json"),
            err: {} on ["syspolicy", "list"] =>
                Reply::failed(1, "syspolicy: the policy store could not be read"), "cli_failed"
        ),
        contract!(
            "tailscale_lock_status",
            ok: {} on ["lock", "status"] => printed!("lock-status.json"),
            err: {} on ["lock", "status"] =>
                Reply::failed(1, "lock: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_lock_log",
            ok: {} on ["lock", "log"] => printed!("lock-log.json"),
            err: {} on ["lock", "log"] =>
                Reply::failed(1, "lock log: the key authority is unreachable"), "cli_failed"
        ),
        contract!(
            "tailscale_serve_status",
            ok: {} on ["serve", "status"] => printed!("serve-status.json"),
            err: {} on ["serve", "status"] =>
                Reply::failed(1, "serve: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_funnel_status",
            ok: {} on ["funnel", "status"] => printed!("funnel-status.json"),
            err: {} on ["funnel", "status"] =>
                Reply::failed(1, "funnel: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_configure_sysext_status",
            ok: {} on ["configure", "sysext", "status"] => printed!("sysext-status.txt"),
            err: {} on ["configure", "sysext", "status"] =>
                Reply::failed(1, "configure sysext: the extension could not be queried"),
                "cli_failed"
        ),
        contract!(
            "tailscale_switch_list",
            ok: {} on ["switch"] => printed!("switch-list.json"),
            err: {} on ["switch"] =>
                Reply::failed(1, "switch: the profile store could not be read"), "cli_failed"
        ),
        contract!(
            "tailscale_prefs_get",
            ok: {} on ["get"] => printed!("prefs.json"),
            err: {} on ["get"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"get\""), "unsupported_version"
        ),
        contract!(
            "tailscale_prefs_set",
            ok: {"hostname": "workstation"} on ["set"] => Reply::ok(""),
            err: {"shields_up": true} on ["set"] =>
                Reply::failed(1, "set: shields-up is managed by policy"), "cli_failed"
        ),
        contract!(
            "tailscale_up",
            ok: {} on ["up"] => printed!("up-running.json"),
            err: {} on ["up"] => Reply::Unavailable, "backend_unavailable"
        ),
        contract!(
            "tailscale_down",
            ok: {} on ["down"] => Reply::ok(""),
            err: {} on ["down"] =>
                Reply::failed(1, "down: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_login",
            ok: {} on ["login"] => printed!("login.txt"),
            // Logging in changes the node's identity, which an unprivileged
            // caller is not allowed to do.
            err: {} on ["login"] =>
                Reply::failed(1, "Access denied: this operation requires the operator"),
                "needs_operator"
        ),
        contract!(
            "tailscale_logout",
            ok: {} on ["logout"] => Reply::ok(""),
            err: {} on ["logout"] =>
                Reply::failed(1, "logout: the profile could not be cleared"), "cli_failed"
        ),
        contract!(
            "tailscale_switch_profile",
            ok: {"account": "example-tailnet.ts.net"} on ["switch"] => Reply::ok(""),
            err: {"account": "nobody"} on ["switch"] =>
                Reply::failed(1, "switch: profile \"nobody\" not found"), "not_found"
        ),
        contract!(
            "tailscale_switch_remove",
            ok: {"account": "example-tailnet.ts.net"} on ["switch", "remove"] => Reply::ok(""),
            err: {"account": "nobody"} on ["switch", "remove"] =>
                Reply::failed(1, "switch remove: the profile store is read-only"), "cli_failed"
        ),
        contract!(
            "tailscale_serve_set",
            ok: {"target": "3000"} on ["serve"] => printed!("serve-set.txt"),
            err: {"target": "3000", "http": 80, "https": 443} on ["serve"] =>
                Reply::ok(""), "invalid_args"
        ),
        contract!(
            "tailscale_serve_off",
            ok: {"https": 8443} on ["serve"] => Reply::ok(""),
            err: {"https": 8443} on ["serve"] =>
                Reply::failed(1, "error: failed to remove web serve: handler does not exist"),
                "not_found"
        ),
        contract!(
            "tailscale_serve_reset",
            ok: {} on ["serve", "reset"] => Reply::ok(""),
            err: {} on ["serve", "reset"] =>
                Reply::failed(1, "reset: the daemon refused the request"), "cli_failed"
        ),
        contract!(
            "tailscale_serve_drain",
            ok: {"service": "svc:web"} on ["serve", "drain"] => Reply::ok(""),
            err: {"service": "svc:web"} on ["serve", "drain"] =>
                Reply::failed(1, "drain: no such service"), "not_found"
        ),
        contract!(
            "tailscale_serve_clear",
            ok: {"service": "svc:web"} on ["serve", "clear"] => Reply::ok(""),
            err: {"service": "svc:web"} on ["serve", "clear"] =>
                Reply::failed(1, "clear: the configuration could not be written"), "cli_failed"
        ),
        contract!(
            "tailscale_serve_advertise",
            ok: {"service": "svc:web"} on ["serve", "advertise"] => Reply::ok(""),
            err: {"service": "svc:web"} on ["serve", "advertise"] =>
                Reply::failed(1, "advertise: no such service"), "not_found"
        ),
        contract!(
            "tailscale_serve_get_config",
            ok: {"all": true} on ["serve", "get-config"] => printed!("serve-config.json"),
            err: {} on ["serve", "get-config"] => Reply::ok(""), "invalid_args"
        ),
        contract!(
            "tailscale_serve_set_config",
            ok: {"all": true, "configuration": {"version": "0.0.1"}} on ["serve", "set-config"] =>
                Reply::ok(""),
            err: {"all": true, "service": "svc:web", "configuration": {}}
                on ["serve", "set-config"] => Reply::ok(""), "invalid_args"
        ),
        contract!(
            "tailscale_funnel_set",
            ok: {"target": "3000"} on ["funnel"] => printed!("serve-set.txt"),
            err: {"target": "3000"} on ["funnel"] =>
                Reply::hung_after("Funnel is not enabled on your tailnet."), "timeout"
        ),
        contract!(
            "tailscale_funnel_off",
            ok: {"https": 8443} on ["funnel"] => Reply::ok(""),
            err: {"https": 8443} on ["funnel"] =>
                Reply::failed(1, "error: failed to remove funnel: handler does not exist"),
                "not_found"
        ),
        contract!(
            "tailscale_file_cp",
            ok: {"files": ["/tmp/notes.txt"], "target": "laptop"} on ["file", "cp"] =>
                Reply::ok("notes.txt: 4.1 kB\n"),
            err: {"files": ["/tmp/notes.txt"], "target": "missing"} on ["file", "cp"] =>
                Reply::failed(1, "error looking up IP of \"missing\": lookup missing: no such host"),
                "not_found"
        ),
        contract!(
            "tailscale_file_targets",
            ok: {} on ["file", "cp"] => printed!("file-targets.txt"),
            err: {} on ["file", "cp"] =>
                Reply::failed(1, "file cp: not logged in"), "cli_failed"
        ),
        contract!(
            "tailscale_file_get",
            ok: {"directory": "/tmp/inbox"} on ["file", "get"] => Reply::ok("notes.txt\n"),
            err: {"directory": "/tmp/inbox"} on ["file", "get"] =>
                Reply::failed(1, "\"/tmp/inbox\" is not a directory"), "cli_failed"
        ),
        contract!(
            "tailscale_cert",
            ok: {
                "domain": "workstation.example-tailnet.ts.net",
                "cert_file": "/tmp/node.crt",
                "key_file": "/tmp/node.key"
            } on ["cert"] => Reply::ok(""),
            err: {
                "domain": "workstation.example-tailnet.ts.net",
                "cert_file": "/tmp/node.crt",
                "key_file": "/tmp/node.key"
            } on ["cert"] =>
                Reply::failed(1, "500 Internal Server Error: invalid domain"), "cli_failed"
        ),
        contract!(
            "tailscale_metrics_write",
            ok: {"path": "/tmp/tailscaled.prom"} on ["metrics", "write"] => Reply::ok(""),
            err: {"path": "/tmp/tailscaled.prom"} on ["metrics", "write"] =>
                Reply::failed(1, "error writing metrics: read-only file system"), "cli_failed"
        ),
        contract!(
            "tailscale_configure_kubeconfig",
            ok: {"hostname": "cluster"} on ["configure", "kubeconfig"] => Reply::ok(""),
            err: {"hostname": "cluster"} on ["configure", "kubeconfig"] =>
                Reply::failed(1, "no such host: cluster"), "not_found"
        ),
        contract!(
            "tailscale_syspolicy_reload",
            ok: {} on ["syspolicy", "reload"] => printed!("syspolicy-reload.json"),
            err: {} on ["syspolicy", "reload"] =>
                Reply::failed(1, "syspolicy: the policy store could not be reloaded"),
                "cli_failed"
        ),
        contract!(
            "tailscale_drive_list",
            ok: {} on ["drive", "list"] => printed!("drive-list.txt"),
            // The macOS GUI packaging carries the subcommand and refuses it,
            // which is a fact about the build rather than about the call.
            err: {} on ["drive", "list"] => Reply::failed(
                1,
                "Taildrive CLI commands are not supported when using the macOS GUI app."
            ), "unsupported_platform"
        ),
        contract!(
            "tailscale_drive_share",
            ok: {"name": "docs", "path": "/srv/docs"} on ["drive", "share"] => Reply::ok(""),
            err: {"name": "docs", "path": "/srv/docs"} on ["drive", "share"] =>
                Reply::failed(1, "drive share: \"/srv/docs\" is not a directory"), "cli_failed"
        ),
        contract!(
            "tailscale_drive_rename",
            ok: {"name": "docs", "new_name": "handbook"} on ["drive", "rename"] => Reply::ok(""),
            err: {"name": "docs", "new_name": "handbook"} on ["drive", "rename"] =>
                Reply::failed(1, "share \"docs\" does not exist"), "not_found"
        ),
        contract!(
            "tailscale_drive_unshare",
            ok: {"name": "docs"} on ["drive", "unshare"] => Reply::ok(""),
            err: {"name": "docs"} on ["drive", "unshare"] =>
                Reply::failed(1, "share \"docs\" does not exist"), "not_found"
        ),
        // Tailnet lock. Every key here is a documentation value: a real
        // `tlpub:` key names a real signing node, and none belongs in a repo.
        contract!(
            "tailscale_lock_init",
            ok: {"trusted_keys": [TLPUB]} on ["lock", "init"] =>
                Reply::ok("disablement-secret:00112233445566778899aabbccddeeff\n"),
            err: {"trusted_keys": [TLPUB]} on ["lock", "init"] => Reply::failed(
                1,
                "the tailnet lock key of the current node must be one of the trusted keys during initialization"
            ), "cli_failed"
        ),
        contract!(
            "tailscale_lock_add",
            ok: {"keys": [TLPUB]} on ["lock", "add"] => Reply::ok(""),
            err: {"keys": [TLPUB]} on ["lock", "add"] =>
                Reply::failed(1, "tailnet lock is not enabled"), "cli_failed"
        ),
        contract!(
            "tailscale_lock_remove",
            ok: {"keys": [TLPUB]} on ["lock", "remove"] => Reply::ok(""),
            err: {"keys": [TLPUB]} on ["lock", "remove"] =>
                Reply::failed(1, "tailnet lock is not enabled"), "cli_failed"
        ),
        contract!(
            "tailscale_lock_sign",
            ok: {"key": NODEKEY} on ["lock", "sign"] => Reply::ok(""),
            err: {"key": NODEKEY} on ["lock", "sign"] => Reply::failed(
                1,
                "error: 500 Internal Server Error: signing failed: tailnet-lock is not active"
            ), "cli_failed"
        ),
        contract!(
            "tailscale_lock_disable",
            ok: {"secret": DISABLEMENT_SECRET} on ["lock", "disable"] => Reply::ok(""),
            err: {"secret": DISABLEMENT_SECRET} on ["lock", "disable"] => Reply::failed(
                1,
                "error: 400 Bad Request: tailnet-lock disable failed: tailnet-lock is not active"
            ), "cli_failed"
        ),
        contract!(
            "tailscale_lock_disablement_kdf",
            ok: {"secret": DISABLEMENT_HEX} on ["lock", "disablement-kdf"] =>
                Reply::ok("disablement:756fe19f200fbfc9ad431e75c7942b82\n"),
            err: {"secret": DISABLEMENT_HEX} on ["lock", "disablement-kdf"] =>
                Reply::failed(1, "encoding/hex: invalid byte: U+007A 'z'"), "cli_failed"
        ),
        contract!(
            "tailscale_lock_local_disable",
            ok: {} on ["lock", "local-disable"] => Reply::ok(""),
            err: {} on ["lock", "local-disable"] => Reply::failed(
                1,
                "error: 400 Bad Request: tailnet-lock local disable failed: tailnet-lock is not active"
            ), "cli_failed"
        ),
        contract!(
            "tailscale_lock_revoke_keys",
            ok: {"keys": [TLPUB]} on ["lock", "revoke-keys"] =>
                Reply::ok("run this on the next signing node\n"),
            err: {"keys": [TLPUB]} on ["lock", "revoke-keys"] => Reply::failed(
                1,
                "generation of recovery AUM failed: sending generate-recovery-aum: 500 Internal Server Error: tailnet-lock is not active"
            ), "cli_failed"
        ),
        // The debug toolset. Every payload here is a documentation value: the
        // real commands print this node's keys, addresses and peers, and none
        // of that belongs in a repo.
        contract!(
            "tailscale_debug_derp_map",
            ok: {} on ["debug", "derp-map"] => Reply::ok(r#"{"Regions":{}}"#),
            err: {} on ["debug", "derp-map"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_netmap",
            ok: {} on ["debug", "netmap"] => Reply::ok(r#"{"Peers":[]}"#),
            err: {} on ["debug", "netmap"] =>
                Reply::failed(1, "netmap is not available: not logged in"), "cli_failed"
        ),
        contract!(
            "tailscale_debug_hostinfo",
            ok: {} on ["debug", "hostinfo"] => Reply::ok(r#"{"OS":"macOS","Hostname":"example"}"#),
            err: {} on ["debug", "hostinfo"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_control_knobs",
            ok: {} on ["debug", "control-knobs"] => Reply::ok(r#"{"DisableUPnP":false}"#),
            err: {} on ["debug", "control-knobs"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"control-knobs\""), "unsupported_version"
        ),
        contract!(
            "tailscale_debug_daemon_goroutines",
            ok: {} on ["debug", "daemon-goroutines"] =>
                Reply::ok("goroutine 1 [running]:\nmain.main()\n"),
            err: {} on ["debug", "daemon-goroutines"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_daemon_bus_graph",
            ok: {} on ["debug", "daemon-bus-graph", "--format=json"] =>
                Reply::ok(r#"{"nodes":[],"edges":[]}"#),
            err: {"format": "dot"} on ["debug", "daemon-bus-graph", "--format=dot"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_daemon_bus_queues",
            ok: {} on ["debug", "daemon-bus-queues"] => Reply::ok(r#"{"queues":[]}"#),
            err: {} on ["debug", "daemon-bus-queues"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_metrics",
            ok: {} on ["debug", "metrics"] =>
                Reply::ok("# TYPE tailscaled_inbound_packets_total counter\ntailscaled_inbound_packets_total 0\n"),
            err: {} on ["debug", "metrics"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_statedir",
            ok: {} on ["debug", "statedir"] => Reply::ok("/var/lib/tailscale\n"),
            err: {} on ["debug", "statedir"] =>
                Reply::failed(1, "no state directory is configured"), "cli_failed"
        ),
        contract!(
            "tailscale_debug_go_buildinfo",
            ok: {} on ["debug", "go-buildinfo"] => Reply::ok(r#"{"GoVersion":"go1.24.0"}"#),
            err: {} on ["debug", "go-buildinfo"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"go-buildinfo\""), "unsupported_version"
        ),
        contract!(
            "tailscale_debug_peer_relay_servers",
            ok: {} on ["debug", "peer-relay-servers"] => Reply::ok("[]\n"),
            err: {} on ["debug", "peer-relay-servers"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"peer-relay-servers\""), "unsupported_version"
        ),
        contract!(
            "tailscale_debug_peer_relay_sessions",
            ok: {} on ["debug", "peer-relay-sessions"] =>
                Reply::ok("Server port: not configured\nSessions count: 0\n"),
            err: {} on ["debug", "peer-relay-sessions"] =>
                Reply::failed(1, "tailscale: unknown subcommand \"peer-relay-sessions\""), "unsupported_version"
        ),
        contract!(
            "tailscale_debug_file_list",
            ok: {} on ["debug", "--file=get"] => Reply::ok("null\n"),
            err: {} on ["debug", "--file=get"] =>
                Reply::failed(1, "Taildrop is not enabled on this node"), "cli_failed"
        ),
        contract!(
            "tailscale_debug_stat",
            ok: {"paths": ["/etc/hosts"]} on ["debug", "stat", "/etc/hosts"] =>
                Reply::ok("/etc/hosts: -rw-r--r--, 213\n"),
            err: {"paths": ["/etc/nope"]} on ["debug", "stat", "/etc/nope"] =>
                Reply::failed(1, "stat /etc/nope: no such file or directory"), "not_found"
        ),
        contract!(
            "tailscale_debug_via",
            ok: {"site_id": 7, "prefix": "10.1.0.0/16"} on ["debug", "via", "7", "10.1.0.0/16"] =>
                Reply::ok("fd7a:115c:a1e0:b1a:0:7:a01:0/112\n"),
            err: {"site_id": 7, "prefix": "10.1.0.0/16", "route": "fd7a::/112"}
                on ["debug", "via"] => Reply::ok(""), "invalid_args"
        ),
        contract!(
            "tailscale_debug_watch_ipn",
            ok: {"count": 1} on ["debug", "watch-ipn", "--count=1"] =>
                Reply::ok("{\"Version\":\"1.102.2\"}\n"),
            err: {"count": 0} on ["debug", "watch-ipn"] => Reply::ok(""), "invalid_args"
        ),
        contract!(
            "tailscale_debug_peer_endpoint_changes",
            ok: {"peer": "laptop"} on ["debug", "peer-endpoint-changes", "laptop"] =>
                Reply::ok(r#"{"changes":[]}"#),
            err: {"peer": "missing"} on ["debug", "peer-endpoint-changes", "missing"] =>
                Reply::failed(1, "error looking up IP of \"missing\": no such host"), "not_found"
        ),
        contract!(
            "tailscale_debug_resolve",
            ok: {"host": "example.com"} on ["debug", "resolve", "example.com"] =>
                Reply::ok("203.0.113.10\n"),
            err: {"host": "missing.invalid"} on ["debug", "resolve", "missing.invalid"] =>
                Reply::failed(1, "lookup missing.invalid: no such host"), "not_found"
        ),
        contract!(
            "tailscale_debug_dial_types",
            ok: {"host": "example.com", "port": 443} on ["debug", "dial-types", "example.com", "443"] =>
                Reply::ok("tcp dial to example.com:443 succeeded\n"),
            err: {"host": "example.com", "port": 443} on ["debug", "dial-types"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_derp",
            ok: {} on ["debug", "derp"] => Reply::ok("derp region 1: ok\n"),
            err: {} on ["debug", "derp"] =>
                Reply::failed(1, "no DERP map is available"), "cli_failed"
        ),
        contract!(
            "tailscale_debug_ts2021",
            ok: {} on ["debug", "ts2021"] => Reply::ok("did noise handshake\n"),
            err: {} on ["debug", "ts2021"] =>
                Reply::failed(1, "fetching keys: dial tcp: connection refused"), "cli_failed"
        ),
        contract!(
            "tailscale_debug_portmap",
            ok: {} on ["debug", "portmap", "--duration=5s"] =>
                Reply::ok("portmapper: no port mapping services were found\n"),
            err: {"gateway_addr": "192.0.2.1"} on ["debug", "portmap"] =>
                Reply::ok(""), "invalid_args"
        ),
        // The knobs. Each needs the write tier as well as the toolset.
        contract!(
            "tailscale_debug_component_logs",
            ok: {"component": "magicsock"}
                on ["debug", "component-logs", "--for=3600s", "magicsock"] => Reply::ok(""),
            err: {"component": "nonsense"} on ["debug", "component-logs"] =>
                Reply::failed(1, "unknown component \"nonsense\""), "cli_failed"
        ),
        contract!(
            "tailscale_debug_restun",
            ok: {} on ["debug", "restun"] => Reply::ok(""),
            err: {} on ["debug", "restun"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_rebind",
            ok: {} on ["debug", "rebind"] => Reply::ok(""),
            err: {} on ["debug", "rebind"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_rotate_disco_key",
            ok: {} on ["debug", "rotate-disco-key"] => Reply::ok(""),
            err: {} on ["debug", "rotate-disco-key"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_derp_unset_on_demand",
            ok: {} on ["debug", "derp-unset-on-demand"] => Reply::ok(""),
            err: {} on ["debug", "derp-unset-on-demand"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_pick_new_derp",
            ok: {} on ["debug", "pick-new-derp"] => Reply::ok("now using derp region 2\n"),
            err: {} on ["debug", "pick-new-derp"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            "tailscale_debug_force_prefer_derp",
            ok: {"region_id": 0} on ["debug", "force-prefer-derp", "0"] => Reply::ok(""),
            err: {"region_id": 99} on ["debug", "force-prefer-derp", "99"] =>
                Reply::failed(1, "region 99 is not in the DERP map"), "cli_failed"
        ),
        contract!(
            "tailscale_debug_force_netmap_update",
            ok: {} on ["debug", "force-netmap-update"] => Reply::ok(""),
            err: {} on ["debug", "force-netmap-update"] =>
                Reply::failed(1, "Access denied: cannot debug without operator access"), "needs_operator"
        ),
        contract!(
            // Its session runs at the tier of its row, which is the read floor,
            // so the failing call is a command the floor does not reach. That
            // is the passthrough's own contract rather than an accident of the
            // harness: what it may run is decided by the command.
            "tailscale_run",
            ok: {"args": ["version"]} on ["version"] => printed!("tailscale-version.txt"),
            err: {"args": ["down"]} on ["down"] => Reply::ok(""), "not_permitted"
        ),
        // ---- tailnet: devices -------------------------------------------
        api_contract!(
            "tailnet_device_list",
            ok: {} on "GET" "/api/v2/tailnet/-/devices" =>
                Response::json(json!({"devices": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_device_get",
            ok: {"device_id": "n1111111CNTRL"} on "GET" "/api/v2/device/n1111111CNTRL" =>
                Response::json(json!({"nodeId": "n1111111CNTRL", "name": "example-node"})),
            err: {"device_id": "n1111111CNTRL"}
        ),
        // `n2222222CNTRL` from here on for the six tools that sever when they
        // are aimed at us: the fake `tailscale status` names `n1111111CNTRL`
        // as this node, so a row using that would be exercising the
        // confirmation rather than the call. The confirmation is
        // `tailnet_surface.rs`'s to assert (Q83).
        api_contract!(
            "tailnet_device_delete",
            ok: {"device_id": "n2222222CNTRL"} on "DELETE" "/api/v2/device/n2222222CNTRL" =>
                Response::empty(),
            err: {"device_id": "n2222222CNTRL"}
        ),
        api_contract!(
            "tailnet_device_expire",
            ok: {"device_id": "n2222222CNTRL"} on "POST" "/api/v2/device/n2222222CNTRL/expire" =>
                Response::empty(),
            err: {"device_id": "n2222222CNTRL"}
        ),
        api_contract!(
            "tailnet_device_authorize",
            ok: {"device_id": "n2222222CNTRL", "authorized": true}
                on "POST" "/api/v2/device/n2222222CNTRL/authorized" => Response::empty(),
            err: {"device_id": "n2222222CNTRL", "authorized": true}
        ),
        api_contract!(
            // A peer, not this node: the fake status names `n1111111CNTRL` as
            // ourselves, and a rename aimed at ourselves asks to be confirmed.
            "tailnet_device_rename",
            ok: {"device_id": "n2222222CNTRL", "name": "example-node"}
                on "POST" "/api/v2/device/n2222222CNTRL/name" => Response::empty(),
            err: {"device_id": "n2222222CNTRL", "name": "example-node"}
        ),
        api_contract!(
            "tailnet_device_tags_set",
            ok: {"device_id": "n2222222CNTRL", "tags": ["tag:example"]}
                on "POST" "/api/v2/device/n2222222CNTRL/tags" => Response::empty(),
            err: {"device_id": "n2222222CNTRL", "tags": ["tag:example"]}
        ),
        api_contract!(
            "tailnet_device_key_expiry_set",
            ok: {"device_id": "n1111111CNTRL", "key_expiry_disabled": true}
                on "POST" "/api/v2/device/n1111111CNTRL/key" => Response::empty(),
            err: {"device_id": "n1111111CNTRL", "key_expiry_disabled": true}
        ),
        api_contract!(
            "tailnet_device_ip_set",
            ok: {"device_id": "n2222222CNTRL", "ipv4": "100.64.0.9"}
                on "POST" "/api/v2/device/n2222222CNTRL/ip" => Response::empty(),
            err: {"device_id": "n2222222CNTRL", "ipv4": "100.64.0.9"}
        ),
        api_contract!(
            "tailnet_device_routes_get",
            ok: {"device_id": "n1111111CNTRL"} on "GET" "/api/v2/device/n1111111CNTRL/routes" =>
                Response::json(json!({"advertisedRoutes": [], "enabledRoutes": []})),
            err: {"device_id": "n1111111CNTRL"}
        ),
        api_contract!(
            "tailnet_device_routes_set",
            ok: {"device_id": "n2222222CNTRL", "routes": ["10.0.0.0/24"]}
                on "POST" "/api/v2/device/n2222222CNTRL/routes" =>
                Response::json(json!({"advertisedRoutes": ["10.0.0.0/24"],
                                      "enabledRoutes": ["10.0.0.0/24"]})),
            err: {"device_id": "n2222222CNTRL", "routes": ["10.0.0.0/24"]}
        ),
        api_contract!(
            "tailnet_device_attributes_get",
            ok: {"device_id": "n1111111CNTRL"} on "GET" "/api/v2/device/n1111111CNTRL/attributes" =>
                Response::json(json!({"attributes": {}, "expiries": {}})),
            err: {"device_id": "n1111111CNTRL"}
        ),
        api_contract!(
            "tailnet_device_attribute_set",
            ok: {"device_id": "n1111111CNTRL", "attribute_key": "custom:example", "value": true}
                on "POST" "/api/v2/device/n1111111CNTRL/attributes/custom:example" => Response::empty(),
            err: {"device_id": "n1111111CNTRL", "attribute_key": "custom:example", "value": true}
        ),
        api_contract!(
            "tailnet_device_attribute_delete",
            ok: {"device_id": "n1111111CNTRL", "attribute_key": "custom:example"}
                on "DELETE" "/api/v2/device/n1111111CNTRL/attributes/custom:example" => Response::empty(),
            err: {"device_id": "n1111111CNTRL", "attribute_key": "custom:example"}
        ),
        api_contract!(
            "tailnet_device_attributes_update",
            ok: {"nodes": {"n1111111CNTRL": {"custom:example": true}}}
                on "PATCH" "/api/v2/tailnet/-/device-attributes" => Response::empty(),
            err: {"nodes": {"n1111111CNTRL": {"custom:example": true}}}
        ),
        // ---- tailnet: posture -------------------------------------------
        api_contract!(
            "tailnet_posture_integration_list",
            ok: {} on "GET" "/api/v2/tailnet/-/posture/integrations" =>
                Response::json(json!({"integrations": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_posture_integration_get",
            ok: {"integration_id": "pi-example"}
                on "GET" "/api/v2/posture/integrations/pi-example" =>
                Response::json(json!({"id": "pi-example", "provider": "falcon"})),
            err: {"integration_id": "pi-example"}
        ),
        api_contract!(
            "tailnet_posture_integration_create",
            ok: {"provider": "falcon", "client_secret": "example-secret"}
                on "POST" "/api/v2/tailnet/-/posture/integrations" =>
                Response::json(json!({"id": "pi-example", "provider": "falcon"})),
            err: {"provider": "falcon", "client_secret": "example-secret"}
        ),
        api_contract!(
            "tailnet_posture_integration_update",
            ok: {"integration_id": "pi-example", "client_id": "example-client"}
                on "PATCH" "/api/v2/posture/integrations/pi-example" =>
                Response::json(json!({"id": "pi-example", "provider": "falcon"})),
            err: {"integration_id": "pi-example", "client_id": "example-client"}
        ),
        api_contract!(
            "tailnet_posture_integration_delete",
            ok: {"integration_id": "pi-example"}
                on "DELETE" "/api/v2/posture/integrations/pi-example" => Response::empty(),
            err: {"integration_id": "pi-example"}
        ),
        // ---- tailnet: DNS ------------------------------------------------
        api_contract!(
            "tailnet_dns_nameservers_get",
            ok: {} on "GET" "/api/v2/tailnet/-/dns/nameservers" =>
                Response::json(json!({"dns": ["8.8.8.8"]})),
            err: {}
        ),
        api_contract!(
            "tailnet_dns_nameservers_replace",
            ok: {"dns": ["8.8.8.8"]} on "POST" "/api/v2/tailnet/-/dns/nameservers" =>
                Response::json(json!({"dns": ["8.8.8.8"], "magicDNS": true})),
            err: {"dns": ["8.8.8.8"]}
        ),
        api_contract!(
            "tailnet_dns_preferences_get",
            ok: {} on "GET" "/api/v2/tailnet/-/dns/preferences" =>
                Response::json(json!({"magicDNS": true})),
            err: {}
        ),
        api_contract!(
            "tailnet_dns_preferences_set",
            ok: {"magic_dns": true} on "POST" "/api/v2/tailnet/-/dns/preferences" =>
                Response::json(json!({"magicDNS": true})),
            err: {"magic_dns": true}
        ),
        api_contract!(
            "tailnet_dns_search_paths_get",
            ok: {} on "GET" "/api/v2/tailnet/-/dns/searchpaths" =>
                Response::json(json!({"searchPaths": ["example.com"]})),
            err: {}
        ),
        api_contract!(
            "tailnet_dns_search_paths_replace",
            ok: {"search_paths": ["example.com"]}
                on "POST" "/api/v2/tailnet/-/dns/searchpaths" =>
                Response::json(json!({"searchPaths": ["example.com"]})),
            err: {"search_paths": ["example.com"]}
        ),
        api_contract!(
            "tailnet_dns_split_get",
            ok: {} on "GET" "/api/v2/tailnet/-/dns/split-dns" =>
                Response::json(json!({"example.com": ["10.0.0.1"]})),
            err: {}
        ),
        api_contract!(
            "tailnet_dns_split_update",
            ok: {"domains": {"example.com": ["10.0.0.1"]}}
                on "PATCH" "/api/v2/tailnet/-/dns/split-dns" =>
                Response::json(json!({"example.com": ["10.0.0.1"]})),
            err: {"domains": {"example.com": ["10.0.0.1"]}}
        ),
        api_contract!(
            "tailnet_dns_split_replace",
            ok: {"domains": {"example.com": ["10.0.0.1"]}}
                on "PUT" "/api/v2/tailnet/-/dns/split-dns" =>
                Response::json(json!({"example.com": ["10.0.0.1"]})),
            err: {"domains": {"example.com": ["10.0.0.1"]}}
        ),
        api_contract!(
            "tailnet_dns_configuration_get",
            ok: {} on "GET" "/api/v2/tailnet/-/dns/configuration" =>
                Response::json(json!({"nameservers": [], "searchPaths": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_dns_configuration_replace",
            ok: {"configuration": {"nameservers": [], "searchPaths": []}}
                on "POST" "/api/v2/tailnet/-/dns/configuration" =>
                Response::json(json!({"nameservers": [], "searchPaths": []})),
            err: {"configuration": {"nameservers": [], "searchPaths": []}}
        ),
        // ---- tailnet: policy ---------------------------------------------
        api_contract!(
            "tailnet_policy_get",
            ok: {} on "GET" "/api/v2/tailnet/-/acl" =>
                Response::text("application/hujson", "{\n  // a policy\n  \"acls\": [],\n}"),
            err: {}
        ),
        api_contract!(
            "tailnet_policy_set",
            ok: {"policy": "{\"acls\": []}", "etag": "\"e0b2816b418\""}
                on "POST" "/api/v2/tailnet/-/acl" =>
                Response::text("application/hujson", "{\"acls\": []}"),
            err: {"policy": "{\"acls\": []}", "etag": "\"e0b2816b418\""}
        ),
        api_contract!(
            "tailnet_policy_preview",
            ok: {"policy": {"acls": []}, "subject_type": "user",
                 "preview_for": "someone@example.com"}
                on "POST" "/api/v2/tailnet/-/acl/preview" =>
                Response::json(json!({"matches": [], "type": "user",
                                      "previewFor": "someone@example.com"})),
            err: {"policy": {"acls": []}, "subject_type": "user",
                  "preview_for": "someone@example.com"}
        ),
        api_contract!(
            "tailnet_policy_validate",
            ok: {"tests": [{"src": "someone@example.com", "accept": ["10.0.0.1:80"]}]}
                on "POST" "/api/v2/tailnet/-/acl/validate" => Response::empty(),
            err: {"tests": [{"src": "someone@example.com", "accept": ["10.0.0.1:80"]}]}
        ),
        // ---- tailnet: keys -----------------------------------------------
        api_contract!(
            "tailnet_key_list",
            ok: {} on "GET" "/api/v2/tailnet/-/keys" => Response::json(json!({"keys": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_key_get",
            ok: {"key_id": "kexample1"} on "GET" "/api/v2/tailnet/-/keys/kexample1" =>
                Response::json(json!({"id": "kexample1", "keyType": "auth"})),
            err: {"key_id": "kexample1"}
        ),
        api_contract!(
            "tailnet_key_create",
            ok: {"key_type": "auth", "description": "example"}
                on "POST" "/api/v2/tailnet/-/keys" =>
                Response::json(json!({"id": "kexample1", "keyType": "auth"})),
            err: {"key_type": "auth", "description": "example"}
        ),
        api_contract!(
            "tailnet_key_update",
            ok: {"key_id": "kexample1", "key_type": "client", "scopes": ["devices:core:read"]}
                on "PUT" "/api/v2/tailnet/-/keys/kexample1" =>
                Response::json(json!({"id": "kexample1", "keyType": "client"})),
            err: {"key_id": "kexample1", "key_type": "client", "scopes": ["devices:core:read"]}
        ),
        api_contract!(
            "tailnet_key_delete",
            ok: {"key_id": "kexample1"} on "DELETE" "/api/v2/tailnet/-/keys/kexample1" =>
                Response::empty(),
            err: {"key_id": "kexample1"}
        ),
        // ---- tailnet: users ----------------------------------------------
        api_contract!(
            "tailnet_user_list",
            ok: {} on "GET" "/api/v2/tailnet/-/users" => Response::json(json!({"users": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_user_get",
            ok: {"user_id": "uexample1"} on "GET" "/api/v2/users/uexample1" =>
                Response::json(json!({"id": "uexample1", "role": "member"})),
            err: {"user_id": "uexample1"}
        ),
        api_contract!(
            "tailnet_user_role_set",
            ok: {"user_id": "uexample1", "role": "admin"}
                on "POST" "/api/v2/users/uexample1/role" => Response::empty(),
            err: {"user_id": "uexample1", "role": "admin"}
        ),
        api_contract!(
            "tailnet_user_approve",
            ok: {"user_id": "uexample1"} on "POST" "/api/v2/users/uexample1/approve" =>
                Response::empty(),
            err: {"user_id": "uexample1"}
        ),
        api_contract!(
            "tailnet_user_suspend",
            ok: {"user_id": "uexample1"} on "POST" "/api/v2/users/uexample1/suspend" =>
                Response::empty(),
            err: {"user_id": "uexample1"}
        ),
        api_contract!(
            "tailnet_user_restore",
            ok: {"user_id": "uexample1"} on "POST" "/api/v2/users/uexample1/restore" =>
                Response::empty(),
            err: {"user_id": "uexample1"}
        ),
        api_contract!(
            "tailnet_user_delete",
            ok: {"user_id": "uexample1"} on "POST" "/api/v2/users/uexample1/delete" =>
                Response::empty(),
            err: {"user_id": "uexample1"}
        ),
        // ---- tailnet: invitations ----------------------------------------
        api_contract!(
            "tailnet_device_invite_list",
            ok: {"device_id": "n1111111CNTRL"}
                on "GET" "/api/v2/device/n1111111CNTRL/device-invites" =>
                Response::json(json!([])),
            err: {"device_id": "n1111111CNTRL"}
        ),
        api_contract!(
            "tailnet_device_invite_create",
            ok: {"device_id": "n1111111CNTRL", "invites": [{"multiUse": true}]}
                on "POST" "/api/v2/device/n1111111CNTRL/device-invites" =>
                Response::json(json!([{"id": "di-example"}])),
            err: {"device_id": "n1111111CNTRL", "invites": [{"multiUse": true}]}
        ),
        api_contract!(
            "tailnet_device_invite_get",
            ok: {"invite_id": "di-example"} on "GET" "/api/v2/device-invites/di-example" =>
                Response::json(json!({"id": "di-example"})),
            err: {"invite_id": "di-example"}
        ),
        api_contract!(
            "tailnet_device_invite_delete",
            ok: {"invite_id": "di-example"} on "DELETE" "/api/v2/device-invites/di-example" =>
                Response::empty(),
            err: {"invite_id": "di-example"}
        ),
        api_contract!(
            "tailnet_device_invite_resend",
            ok: {"invite_id": "di-example"}
                on "POST" "/api/v2/device-invites/di-example/resend" => Response::empty(),
            err: {"invite_id": "di-example"}
        ),
        api_contract!(
            "tailnet_device_invite_accept",
            ok: {"invite": "example-invite-code"}
                on "POST" "/api/v2/device-invites/-/accept" =>
                Response::json(json!({"device": {"id": "1"}})),
            err: {"invite": "example-invite-code"}
        ),
        api_contract!(
            "tailnet_user_invite_list",
            ok: {} on "GET" "/api/v2/tailnet/-/user-invites" => Response::json(json!([])),
            err: {}
        ),
        api_contract!(
            "tailnet_user_invite_create",
            ok: {"invites": [{"role": "member"}]}
                on "POST" "/api/v2/tailnet/-/user-invites" =>
                Response::json(json!([{"id": "ui-example"}])),
            err: {"invites": [{"role": "member"}]}
        ),
        api_contract!(
            "tailnet_user_invite_get",
            ok: {"invite_id": "ui-example"} on "GET" "/api/v2/user-invites/ui-example" =>
                Response::json(json!({"id": "ui-example"})),
            err: {"invite_id": "ui-example"}
        ),
        api_contract!(
            "tailnet_user_invite_delete",
            ok: {"invite_id": "ui-example"} on "DELETE" "/api/v2/user-invites/ui-example" =>
                Response::empty(),
            err: {"invite_id": "ui-example"}
        ),
        api_contract!(
            "tailnet_user_invite_resend",
            ok: {"invite_id": "ui-example"}
                on "POST" "/api/v2/user-invites/ui-example/resend" => Response::empty(),
            err: {"invite_id": "ui-example"}
        ),
        // ---- tailnet: contacts and settings ------------------------------
        api_contract!(
            "tailnet_contacts_get",
            ok: {} on "GET" "/api/v2/tailnet/-/contacts" =>
                Response::json(json!({"account": {"email": "someone@example.com"}})),
            err: {}
        ),
        api_contract!(
            "tailnet_contact_update",
            ok: {"contact_type": "security", "email": "someone@example.com"}
                on "PATCH" "/api/v2/tailnet/-/contacts/security" => Response::empty(),
            err: {"contact_type": "security", "email": "someone@example.com"}
        ),
        api_contract!(
            "tailnet_contact_verification_resend",
            ok: {"contact_type": "security"}
                on "POST" "/api/v2/tailnet/-/contacts/security/resend-verification-email" =>
                Response::empty(),
            err: {"contact_type": "security"}
        ),
        api_contract!(
            "tailnet_settings_get",
            ok: {} on "GET" "/api/v2/tailnet/-/settings" =>
                Response::json(json!({"devicesApprovalOn": true})),
            err: {}
        ),
        api_contract!(
            "tailnet_settings_update",
            ok: {"settings": {"devicesApprovalOn": true}}
                on "PATCH" "/api/v2/tailnet/-/settings" => Response::empty(),
            err: {"settings": {"devicesApprovalOn": true}}
        ),
        // --- Ticket 20: webhooks -------------------------------------------
        api_contract!(
            "tailnet_webhook_list",
            ok: {} on "GET" "/api/v2/tailnet/-/webhooks"
                => Response::json(json!({"webhooks": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_webhook_create",
            ok: {"endpoint_url": "https://example.com/hook", "subscriptions": ["nodeCreated"]}
                on "POST" "/api/v2/tailnet/-/webhooks"
                => Response::json(json!({"endpointId": "whk-example", "secret": "tskey-webhook-redacted"})),
            err: {"endpoint_url": "https://example.com/hook", "subscriptions": ["nodeCreated"]}
        ),
        api_contract!(
            "tailnet_webhook_get",
            ok: {"endpoint_id": "whk-example"} on "GET" "/api/v2/webhooks/whk-example"
                => Response::json(json!({"endpointId": "whk-example"})),
            err: {"endpoint_id": "whk-example"}
        ),
        api_contract!(
            "tailnet_webhook_subscriptions_replace",
            ok: {"endpoint_id": "whk-example", "subscriptions": ["nodeCreated", "nodeDeleted"]}
                on "PATCH" "/api/v2/webhooks/whk-example"
                => Response::json(json!({"endpointId": "whk-example"})),
            err: {"endpoint_id": "whk-example", "subscriptions": ["nodeCreated"]}
        ),
        api_contract!(
            "tailnet_webhook_delete",
            ok: {"endpoint_id": "whk-example"} on "DELETE" "/api/v2/webhooks/whk-example"
                => Response::empty(),
            err: {"endpoint_id": "whk-example"}
        ),
        api_contract!(
            "tailnet_webhook_test",
            ok: {"endpoint_id": "whk-example"} on "POST" "/api/v2/webhooks/whk-example/test"
                => Response::empty(),
            err: {"endpoint_id": "whk-example"}
        ),
        api_contract!(
            "tailnet_webhook_secret_rotate",
            ok: {"endpoint_id": "whk-example"} on "POST" "/api/v2/webhooks/whk-example/rotate"
                => Response::json(json!({"endpointId": "whk-example", "secret": "tskey-webhook-redacted"})),
            err: {"endpoint_id": "whk-example"}
        ),
        // --- Ticket 20: services -------------------------------------------
        api_contract!(
            "tailnet_service_list",
            ok: {} on "GET" "/api/v2/tailnet/-/services"
                => Response::json(json!({"vipServices": []})),
            err: {} also "/api/v2/tailnet/-/vip-services"
        ),
        api_contract!(
            "tailnet_service_get",
            ok: {"service_name": "svc:example"} on "GET" "/api/v2/tailnet/-/services/svc:example"
                => Response::json(json!({"name": "svc:example"})),
            err: {"service_name": "svc:example"} also "/api/v2/tailnet/-/vip-services/svc:example"
        ),
        api_contract!(
            "tailnet_service_replace",
            ok: {"service_name": "svc:example", "service": {"name": "svc:example"}}
                on "PUT" "/api/v2/tailnet/-/services/svc:example"
                => Response::json(json!({"name": "svc:example"})),
            err: {"service_name": "svc:example", "service": {"name": "svc:example"}} also "/api/v2/tailnet/-/vip-services/svc:example"
        ),
        api_contract!(
            "tailnet_service_delete",
            ok: {"service_name": "svc:example"} on "DELETE" "/api/v2/tailnet/-/services/svc:example"
                => Response::empty(),
            err: {"service_name": "svc:example"} also "/api/v2/tailnet/-/vip-services/svc:example"
        ),
        api_contract!(
            "tailnet_service_devices_list",
            ok: {"service_name": "svc:example"}
                on "GET" "/api/v2/tailnet/-/services/svc:example/devices"
                // `hosts` is the envelope the description gives this one, even
                // though the path is `/devices`; forwarded as it arrives.
                => Response::json(json!({"hosts": []})),
            err: {"service_name": "svc:example"} also "/api/v2/tailnet/-/vip-services/svc:example/devices"
        ),
        api_contract!(
            "tailnet_service_approval_get",
            ok: {"service_name": "svc:example", "device_id": "n1111111CNTRL"}
                on "GET" "/api/v2/tailnet/-/services/svc:example/device/n1111111CNTRL/approved"
                => Response::json(json!({"approved": true})),
            err: {"service_name": "svc:example", "device_id": "n1111111CNTRL"} also "/api/v2/tailnet/-/vip-services/svc:example/device/n1111111CNTRL/approved"
        ),
        api_contract!(
            "tailnet_service_approval_set",
            ok: {"service_name": "svc:example", "device_id": "n1111111CNTRL", "approved": true}
                on "POST" "/api/v2/tailnet/-/services/svc:example/device/n1111111CNTRL/approved"
                => Response::json(json!({"approved": true})),
            // `approved: true`: withdrawing is refused by the tier floor
            // before a request is made, which is `tailnet_surface.rs`'s to
            // assert rather than this table's.
            err: {"service_name": "svc:example", "device_id": "n1111111CNTRL", "approved": true} also "/api/v2/tailnet/-/vip-services/svc:example/device/n1111111CNTRL/approved"
        ),
        // --- Ticket 20: OAuth apps -----------------------------------------
        api_contract!(
            "tailnet_oauth_app_list",
            ok: {} on "GET" "/api/v2/tailnet/-/oauth-apps"
                => Response::json(json!({"oauthApps": []})),
            err: {}
        ),
        api_contract!(
            "tailnet_oauth_app_create",
            ok: {
                "name": "my-oauth-app",
                "redirect_uris": ["https://example.com/oauth/callback"],
                "scopes": ["auth_keys:create"]
            } on "POST" "/api/v2/tailnet/-/oauth-apps"
                => Response::json(json!({"id": "a111111CNTRL", "name": "my-oauth-app"})),
            err: {
                "name": "my-oauth-app",
                "redirect_uris": ["https://example.com/oauth/callback"],
                "scopes": ["auth_keys:create"]
            }
        ),
        api_contract!(
            "tailnet_oauth_app_get",
            ok: {"app_id": "a111111CNTRL"} on "GET" "/api/v2/tailnet/-/oauth-apps/a111111CNTRL"
                => Response::json(json!({"id": "a111111CNTRL"})),
            err: {"app_id": "a111111CNTRL"}
        ),
        api_contract!(
            "tailnet_oauth_app_update",
            ok: {
                "app_id": "a111111CNTRL",
                "name": "my-oauth-app",
                "redirect_uris": ["https://example.com/oauth/callback"],
                "scopes": ["auth_keys:create"]
            } on "PUT" "/api/v2/tailnet/-/oauth-apps/a111111CNTRL"
                => Response::json(json!({"id": "a111111CNTRL"})),
            err: {
                "app_id": "a111111CNTRL",
                "name": "my-oauth-app",
                "redirect_uris": ["https://example.com/oauth/callback"],
                "scopes": ["auth_keys:create"]
            }
        ),
        api_contract!(
            "tailnet_oauth_app_delete",
            ok: {"app_id": "a111111CNTRL"} on "DELETE" "/api/v2/tailnet/-/oauth-apps/a111111CNTRL"
                => Response::empty(),
            err: {"app_id": "a111111CNTRL"}
        ),
        // --- Ticket 20: logging --------------------------------------------
        api_contract!(
            "tailnet_audit_log_list",
            ok: {"start": "2023-12-19T16:39:57-08:00", "end": "2023-12-22T02:15:23-08:00"}
                on "GET" "/api/v2/tailnet/-/logging/configuration"
                => Response::json(json!({"logs": []})),
            err: {"start": "2023-12-19T16:39:57-08:00", "end": "2023-12-22T02:15:23-08:00"}
        ),
        api_contract!(
            "tailnet_network_log_list",
            ok: {"start": "2023-12-19T16:39:57-08:00", "end": "2023-12-22T02:15:23-08:00"}
                on "GET" "/api/v2/tailnet/-/logging/network"
                => Response::json(json!({"logs": []})),
            err: {"start": "2023-12-19T16:39:57-08:00", "end": "2023-12-22T02:15:23-08:00"}
        ),
        api_contract!(
            "tailnet_log_stream_get",
            ok: {"log_type": "configuration"}
                on "GET" "/api/v2/tailnet/-/logging/configuration/stream"
                => Response::json(json!({"destinationType": "elastic"})),
            err: {"log_type": "configuration"}
        ),
        api_contract!(
            "tailnet_log_stream_status_get",
            ok: {"log_type": "network"}
                on "GET" "/api/v2/tailnet/-/logging/network/stream/status"
                => Response::json(json!({"lastActivity": "2023-12-19T16:39:57-08:00"})),
            err: {"log_type": "network"}
        ),
        api_contract!(
            "tailnet_log_stream_replace",
            ok: {
                "log_type": "configuration",
                "configuration": {"destinationType": "elastic", "url": "https://example.com/logs"}
            } on "PUT" "/api/v2/tailnet/-/logging/configuration/stream"
                => Response::json(json!({"destinationType": "elastic"})),
            err: {
                "log_type": "configuration",
                "configuration": {"destinationType": "elastic", "url": "https://example.com/logs"}
            }
        ),
        api_contract!(
            "tailnet_log_stream_delete",
            ok: {"log_type": "network"}
                on "DELETE" "/api/v2/tailnet/-/logging/network/stream" => Response::empty(),
            err: {"log_type": "network"}
        ),
        api_contract!(
            "tailnet_aws_external_id_create",
            ok: {"reusable": true} on "POST" "/api/v2/tailnet/-/aws-external-id"
                => Response::json(json!({
                    "externalId": "00000000-0000-0000-0000-000000000000",
                    "tailscaleAwsAccountId": "000000000000"
                })),
            err: {"reusable": true}
        ),
        api_contract!(
            "tailnet_aws_trust_policy_validate",
            ok: {
                "external_id": "00000000-0000-0000-0000-000000000000",
                "role_arn": "arn:aws:iam::000000000000:role/tailscale-log-writer"
            } on "POST"
                "/api/v2/tailnet/-/aws-external-id/00000000-0000-0000-0000-000000000000/validate-aws-trust-policy"
                => Response::empty(),
            err: {
                "external_id": "00000000-0000-0000-0000-000000000000",
                "role_arn": "arn:aws:iam::000000000000:role/tailscale-log-writer"
            }
        ),
        // --- Ticket 20: organisation ---------------------------------------
        api_contract!(
            "tailnet_organization_tailnet_list",
            ok: {"organization": "example.com"}
                on "GET" "/api/v2/organizations/example.com/tailnets"
                => Response::json(json!({"tailnets": [], "totalCount": 0})),
            err: {"organization": "example.com"}
        ),
        api_contract!(
            "tailnet_organization_tailnet_create",
            ok: {"organization": "example.com", "display_name": "Production staging"}
                on "POST" "/api/v2/organizations/example.com/tailnets"
                => Response::json(json!({"id": "T111111CNTRL", "displayName": "Production staging"})),
            err: {"organization": "example.com", "display_name": "Production staging"}
        ),
        api_contract!(
            "tailnet_organization_tailnet_delete",
            ok: {"tailnet": "T111111CNTRL"} on "DELETE" "/api/v2/tailnet/T111111CNTRL"
                => Response::empty(),
            err: {"tailnet": "T111111CNTRL"}
        ),
    ]
}

/// A tailnet-lock key that names nobody.
const TLPUB: &str = "tlpub:0000000000000000000000000000000000000000000000000000000000000000";
/// A node key that names nobody.
const NODEKEY: &str = "nodekey:0000000000000000000000000000000000000000000000000000000000000000";
/// A disablement secret in the two shapes the two commands want it in.
const DISABLEMENT_SECRET: &str = "disablement-secret:00112233445566778899aabbccddeeff";
const DISABLEMENT_HEX: &str = "00112233445566778899aabbccddeeff";

/// Build a session in which `meta`'s tool is on offer, arranged as the case says.
async fn session(meta: &ToolMeta, arrangement: &Arrangement) -> harness::Harness {
    let mut setup = Setup::new().toolsets(meta.toolset.as_str()).tier(meta.tier);
    for (argv, reply) in &arrangement.cli {
        setup = setup.cli_answers(argv, reply.clone());
    }
    for (method, path, response) in &arrangement.api {
        setup = setup.api_answers(method, path, response.clone()).await;
    }
    setup.start().await
}

/// The arguments a call is made with, plus the confirmation the tool requires.
fn arguments(meta: &ToolMeta, args: &Value) -> Value {
    let mut args = args.clone();
    if meta.requires_confirmation
        && let Some(object) = args.as_object_mut()
    {
        object.insert("confirm".to_owned(), json!(true));
    }
    args
}

fn table() -> Vec<ToolMeta> {
    tailscale_mcp::tools::entries()
        .into_iter()
        .map(|e| e.meta)
        .collect()
}

fn contract_for(name: &str) -> Contract {
    contracts()
        .into_iter()
        .find(|c| c.tool == name)
        .unwrap_or_else(|| panic!("no contract for `{name}`"))
}

#[test]
fn every_tool_has_a_contract() {
    let declared: BTreeSet<&str> = table().iter().map(|m| m.name).collect();
    let covered: BTreeSet<&str> = contracts().iter().map(|c| c.tool).collect();

    let uncovered: Vec<&&str> = declared.difference(&covered).collect();
    assert!(
        uncovered.is_empty(),
        "these tools have no contract row, so nothing checks what they do: {uncovered:?}"
    );

    let invented: Vec<&&str> = covered.difference(&declared).collect();
    assert!(
        invented.is_empty(),
        "these contract rows name tools that do not exist: {invented:?}"
    );
}

#[tokio::test]
async fn every_tool_is_named_for_the_surface_it_acts_on() {
    for meta in table() {
        assert!(
            meta.name.starts_with(meta.surface().prefix()),
            "`{}` belongs to the {} surface but is not named for it",
            meta.name,
            meta.surface().as_str()
        );
    }
}

#[tokio::test]
async fn every_tool_describes_itself_the_way_its_tier_says() {
    for meta in table() {
        let harness = session(&meta, &Arrangement::default()).await;
        let tool = harness
            .tool(meta.name)
            .await
            .unwrap_or_else(|| panic!("`{}` is not offered by its own toolset", meta.name));

        assert!(
            tool.description.as_deref().is_some_and(|d| !d.is_empty()),
            "`{}` has no description, so a model cannot choose it",
            meta.name
        );

        let annotations = tool
            .annotations
            .unwrap_or_else(|| panic!("`{}` is not annotated", meta.name));
        // A tool whose row is a floor rather than its whole tier is annotated
        // at its worst case: a client reading `read_only` cannot learn from
        // the annotation that this one depends on the arguments.
        let (read_only, destructive) = if meta.varying_tier {
            (false, true)
        } else {
            (meta.tier == Tier::Read, meta.tier == Tier::Destructive)
        };
        assert_eq!(
            annotations.read_only_hint,
            Some(read_only),
            "`{}` is at the {} tier",
            meta.name,
            meta.tier
        );
        assert_eq!(
            annotations.destructive_hint,
            Some(destructive),
            "`{}` is at the {} tier",
            meta.name,
            meta.tier
        );
        assert_eq!(
            annotations.idempotent_hint,
            Some(meta.idempotent),
            "`{}` declares idempotent: {}",
            meta.name,
            meta.idempotent
        );
        assert_eq!(annotations.open_world_hint, Some(true), "{}", meta.name);

        harness.shutdown().await;
    }
}

#[tokio::test]
async fn every_tool_answers_its_success_case() {
    for meta in table() {
        let contract = contract_for(meta.name);
        let (args, arrangement) = contract.success;
        let harness = session(&meta, &arrangement).await;

        if !meta.runs_here() {
            // The table is the same on every platform, so a tool whose command
            // only exists elsewhere is still listed and still has a contract.
            // What it owes a caller here is the reason, not the answer.
            let error = harness.call_err(meta.name, arguments(&meta, &args)).await;
            assert_eq!(
                error["code"],
                "unsupported_platform",
                "`{}` does not exist on {} and should say so: {error:#}",
                meta.name,
                std::env::consts::OS
            );
            harness.shutdown().await;
            continue;
        }

        let answer = harness.call_ok(meta.name, arguments(&meta, &args)).await;
        assert!(
            answer.is_object(),
            "`{}` answered with something a client cannot destructure: {answer}",
            meta.name
        );

        harness.shutdown().await;
    }
}

#[tokio::test]
async fn every_tool_answers_its_failure_case_with_the_code_it_promised() {
    for meta in table() {
        let contract = contract_for(meta.name);
        let (args, arrangement, code) = contract.failure;
        let code = if meta.runs_here() {
            code
        } else {
            "unsupported_platform"
        };
        let harness = session(&meta, &arrangement).await;

        let error = harness.call_err(meta.name, arguments(&meta, &args)).await;
        assert_eq!(
            error["code"], code,
            "`{}` failed with the wrong code: {error:#}",
            meta.name
        );
        assert!(
            error["message"].as_str().is_some_and(|m| !m.is_empty()),
            "`{}` failed without a message: {error:#}",
            meta.name
        );

        harness.shutdown().await;
    }
}

#[tokio::test]
async fn every_tool_that_needs_confirming_refuses_without_it() {
    for meta in table().into_iter().filter(|m| m.requires_confirmation) {
        let contract = contract_for(meta.name);
        let (args, arrangement) = contract.success;
        let harness = session(&meta, &arrangement).await;

        // The same call that succeeds above, minus the confirmation.
        let error = harness.call_err(meta.name, args).await;
        assert_eq!(
            error["code"], "confirmation_required",
            "`{}` ran without being confirmed",
            meta.name
        );

        harness.shutdown().await;
    }
}

#[tokio::test]
async fn each_preset_offers_more_than_the_one_below_it() {
    // The presets are meant to nest, so an operator moving up never loses a
    // tool they had. Checked against the real table, at every tier.
    for tier in [Tier::Read, Tier::Write, Tier::Destructive] {
        let mut previous: Option<(&str, BTreeSet<String>)> = None;
        for preset in Preset::ALL {
            let harness = Setup::new()
                .preset(preset.as_str())
                .tier(tier)
                .start()
                .await;
            let offered: BTreeSet<String> = harness.tool_names().await.into_iter().collect();

            if let Some((smaller, below)) = &previous {
                let lost: Vec<&String> = below.difference(&offered).collect();
                assert!(
                    lost.is_empty(),
                    "moving from {smaller} to {} at the {tier} tier loses {lost:?}",
                    preset.as_str()
                );
            }
            previous = Some((preset.as_str(), offered));
            harness.shutdown().await;
        }
    }
}

#[tokio::test]
async fn no_tool_is_reachable_from_a_session_that_did_not_ask_for_its_toolset() {
    // A session that selected some other toolset cannot see or call this tool,
    // even at the destructive tier. A zero-tool session cannot start, so the
    // session is built from every *other* toolset that has tools in it.
    let occupied: BTreeSet<&str> = table().iter().map(|m| m.toolset.as_str()).collect();

    for meta in table() {
        let elsewhere: Vec<&str> = occupied
            .iter()
            .copied()
            .filter(|t| *t != meta.toolset.as_str())
            .collect();
        if elsewhere.is_empty() {
            // Nothing else has tools yet, so there is no session to build.
            continue;
        }

        let harness = Setup::new()
            .toolsets(&elsewhere.join(","))
            .tier(Tier::Destructive)
            .start()
            .await;

        assert!(
            harness.tool(meta.name).await.is_none(),
            "`{}` is offered by a session that did not select {}",
            meta.name,
            meta.toolset.as_str()
        );
        let error = harness.call_err(meta.name, json!({})).await;
        assert_eq!(error["code"], "not_permitted", "{}", meta.name);

        harness.shutdown().await;
    }
}

/// The debug toolset is opt-in, and "every toolset" does not include it.
///
/// A caller reaching it has said `local-debug` out loud, which is the statement
/// that it accepts output the client itself calls unstable. A preset is the
/// opposite kind of choice — a name for a sensible default — so no preset, not
/// even the largest, may carry one of these.
#[tokio::test]
async fn no_preset_offers_a_debug_tool_at_any_tier() {
    let debug: BTreeSet<&str> = table()
        .iter()
        .filter(|m| m.toolset == tailscale_mcp::meta::Toolset::LocalDebug)
        .map(|m| m.name)
        .collect();
    assert_eq!(debug.len(), 30, "the debug toolset is thirty tools");

    for preset in [Preset::Minimal, Preset::Core, Preset::Full] {
        for tier in [Tier::Read, Tier::Write, Tier::Destructive] {
            let harness = Setup::new()
                .preset(preset.as_str())
                .tier(tier)
                .start()
                .await;
            let offered: BTreeSet<String> = harness.tool_names().await.into_iter().collect();
            let leaked: Vec<&&str> = debug
                .iter()
                .filter(|name| offered.contains(**name))
                .collect();
            assert!(
                leaked.is_empty(),
                "the {} preset at the {tier} tier offers {leaked:?}",
                preset.as_str()
            );
            harness.shutdown().await;
        }
    }
}

/// The toolset and the tier are separate keys to the same door.
///
/// Adding `local-debug` at the read tier buys the twenty-two readers and none
/// of the eight knobs: a reader asks the daemon what it believes, and a knob
/// makes it do something over again.
#[tokio::test]
async fn the_knobs_need_the_write_tier_as_well_as_the_toolset() {
    let readers: BTreeSet<&str> = table()
        .iter()
        .filter(|m| m.toolset == tailscale_mcp::meta::Toolset::LocalDebug && m.tier == Tier::Read)
        .map(|m| m.name)
        .collect();
    let knobs: BTreeSet<&str> = table()
        .iter()
        .filter(|m| m.toolset == tailscale_mcp::meta::Toolset::LocalDebug && m.tier == Tier::Write)
        .map(|m| m.name)
        .collect();
    assert_eq!((readers.len(), knobs.len()), (22, 8));

    let harness = Setup::new()
        .toolsets("local-debug")
        .tier(Tier::Read)
        .start()
        .await;
    let offered: BTreeSet<String> = harness.tool_names().await.into_iter().collect();
    for reader in &readers {
        assert!(offered.contains(*reader), "`{reader}` is a read-tier tool");
    }
    for knob in &knobs {
        assert!(!offered.contains(*knob), "`{knob}` needs the write tier");
        let error = harness.call_err(knob, json!({})).await;
        assert_eq!(error["code"], "not_permitted", "{knob}");
    }
    harness.shutdown().await;

    let harness = Setup::new()
        .toolsets("local-debug")
        .tier(Tier::Write)
        .start()
        .await;
    let offered: BTreeSet<String> = harness.tool_names().await.into_iter().collect();
    for knob in &knobs {
        assert!(
            offered.contains(*knob),
            "`{knob}` is on offer at the write tier"
        );
    }
    harness.shutdown().await;
}

/// The arguments a tool needs to get as far as spawning, read off its own
/// schema.
///
/// Every required property gets the emptiest value its type allows. The point
/// is never to make a meaningful call — the fake refuses most of these — but to
/// get past argument validation so that the client is actually reached and the
/// argument list is recorded.
fn minimal_arguments(tool: &rmcp::model::Tool) -> Value {
    let schema = &tool.input_schema;
    let properties = schema.get("properties").and_then(Value::as_object);
    let required = schema
        .get("required")
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();

    let mut args = serde_json::Map::new();
    for name in required.iter().filter_map(Value::as_str) {
        let property = properties.and_then(|p| p.get(name));
        args.insert(name.to_owned(), emptiest_value(property));
    }
    Value::Object(args)
}

/// The emptiest value a schema will accept, by type.
fn emptiest_value(property: Option<&Value>) -> Value {
    // A nullable property is written `["string", "null"]`, so the first named
    // type is the one to satisfy.
    let kind = property
        .and_then(|p| p.get("type"))
        .map(|t| match t {
            Value::Array(types) => types
                .iter()
                .filter_map(Value::as_str)
                .find(|t| *t != "null")
                .unwrap_or("string")
                .to_owned(),
            other => other.as_str().unwrap_or("string").to_owned(),
        })
        .unwrap_or_else(|| "string".to_owned());

    match kind.as_str() {
        "integer" | "number" => json!(1),
        "boolean" => json!(false),
        "array" => json!([emptiest_value(
            property
                .and_then(|p| p.get("items"))
                .filter(|i| i.is_object())
        )]),
        _ => json!("x"),
    }
}

/// Every debug tool is called, and none of them runs an excluded command.
///
/// This is what the ticket's third criterion actually asks of the registry.
/// Its sibling below proves that no tool is *named* for an excluded path,
/// which is a weaker claim than it looks: `debug prefs` is excluded precisely
/// because a command's name does not tell you what it does, so a check on
/// names alone would not catch a tool that quietly ran one. This one drives
/// every debug tool through a real session and reads back the argument lists
/// the fake `tailscale` was given.
///
/// The other half of the criterion — the passthrough refusing the same list —
/// belongs to the passthrough, and is ticket 14.
#[tokio::test]
async fn no_debug_tool_runs_an_excluded_subcommand() {
    let harness = Setup::new()
        .toolsets("local-debug")
        .tier(Tier::Destructive)
        .start()
        .await;

    // `debug via` takes either a route or a site and a prefix, and refuses
    // before spawning when given a lone one, so the generator cannot reach it.
    let route = json!({"route": "fd7a:115c:a1e0:b1a:0:7:a01:0/112"});

    let mut called = 0;
    for tool in harness.tools().await {
        let name = tool.name.to_string();
        assert!(
            name.starts_with("tailscale_debug_"),
            "only debug tools should be on offer here, and `{name}` is not one"
        );
        let arguments = if name == "tailscale_debug_via" {
            route.clone()
        } else {
            minimal_arguments(&tool)
        };

        let before = harness.cli_calls().len();
        // Whether the call succeeded is beside the point; what it ran is not.
        let _ = harness.call(&name, arguments.clone()).await;
        let calls = harness.cli_calls();
        assert!(
            calls.len() > before,
            "`{name}` answered without reaching the client, so nothing was \
             proved about what it runs; it was called with {arguments}"
        );

        for argv in &calls[before..] {
            for excluded in tailscale_mcp::tools::local_debug::EXCLUDED {
                // Word by word, so that a future `debug prefsomething` is not
                // mistaken for `debug prefs`.
                let words: Vec<String> = excluded.path.split(' ').map(str::to_owned).collect();
                assert!(
                    !argv.starts_with(&words),
                    "`{name}` ran `{}`, which is the excluded `{}`",
                    argv.join(" "),
                    excluded.path
                );
            }
        }
        called += 1;
    }

    assert_eq!(called, 30, "every debug tool has to be exercised, not most");
    harness.shutdown().await;
}

/// No excluded `debug` subcommand is a tool name.
///
/// A weaker claim than its sibling above, and kept because it is the one a
/// caller can check: the name they would guess is not there, and calling it
/// says so plainly.
#[tokio::test]
async fn no_excluded_debug_subcommand_is_reachable_as_a_tool() {
    let harness = Setup::new()
        .toolsets("local-debug")
        .tier(Tier::Destructive)
        .start()
        .await;
    let offered: BTreeSet<String> = harness.tool_names().await.into_iter().collect();

    for excluded in tailscale_mcp::tools::local_debug::EXCLUDED {
        // `debug foo-bar` would have been `tailscale_debug_foo_bar`.
        let name = format!("tailscale_{}", excluded.path.replace([' ', '-'], "_"));
        assert!(
            !offered.contains(&name),
            "`{}` is excluded but `{name}` is on offer",
            excluded.path
        );
        // `not_found`, not `not_permitted`: a gated tool exists and a switch
        // would reach it, while these do not exist at all. Telling a caller to
        // enable something that would never appear would be the wrong answer.
        let error = harness.call_err(&name, json!({})).await;
        assert_eq!(error["code"], "not_found", "{name}");
    }
    harness.shutdown().await;
}

// ---------------------------------------------------------------------------
// the passthrough
// ---------------------------------------------------------------------------

/// A session with the passthrough on offer and nothing else.
async fn passthrough(tier: Tier, answers: &[(&[&str], Reply)]) -> harness::Harness {
    let mut setup = Setup::new().toolsets("local-passthrough").tier(tier);
    for (argv, reply) in answers {
        setup = setup.cli_answers(argv, reply.clone());
    }
    setup.start().await
}

#[tokio::test]
async fn the_passthrough_is_reached_by_naming_it_and_no_other_way() {
    // `full` means every toolset a preset is willing to imply, and this is not
    // one of them: the switch that turns it on is naming it.
    let broad = Setup::new()
        .preset("full")
        .tier(Tier::Destructive)
        .start()
        .await;
    assert!(
        !broad
            .tool_names()
            .await
            .contains(&"tailscale_run".to_owned()),
        "`full` offered the passthrough"
    );
    broad.shutdown().await;

    let named = Setup::new()
        .preset("full")
        .toolsets("+local-passthrough")
        .tier(Tier::Destructive)
        .start()
        .await;
    assert!(
        named
            .tool_names()
            .await
            .contains(&"tailscale_run".to_owned()),
        "adding the toolset did not offer the passthrough"
    );
    named.shutdown().await;
}

/// The read tier runs a read command and refuses a destructive one.
#[tokio::test]
async fn at_the_read_tier_the_command_decides_what_may_run() {
    let harness = passthrough(
        Tier::Read,
        &[(&["status"], Reply::ok(harness::fixture("status.json")))],
    )
    .await;

    let answer = harness
        .call_ok("tailscale_run", json!({"args": ["status", "--json"]}))
        .await;
    assert_eq!(answer["tier"], "read");
    assert_eq!(answer["covered"], true);

    let error = harness
        .call_err("tailscale_run", json!({"args": ["down"]}))
        .await;
    assert_eq!(error["code"], "not_permitted", "{error:#}");
    assert!(
        error["hint"]
            .as_str()
            .is_some_and(|h| h.contains("--allow-destructive")),
        "the refusal should name the switch that would allow it: {error:#}"
    );
    assert!(
        harness
            .cli_calls()
            .iter()
            .all(|argv| argv.first().map(String::as_str) != Some("down")),
        "`down` was refused and should not have run"
    );

    harness.shutdown().await;
}

/// A subcommand no tool covers is destructive, and is refused below that tier.
#[tokio::test]
async fn an_unknown_subcommand_is_judged_at_the_top() {
    for tier in [Tier::Read, Tier::Write] {
        let harness = passthrough(tier, &[]).await;
        let error = harness
            .call_err("tailscale_run", json!({"args": ["nonesuch"]}))
            .await;
        assert_eq!(
            error["code"], "not_permitted",
            "at the {tier} tier: {error:#}"
        );
        assert!(harness.cli_calls().iter().all(|argv| argv != &["nonesuch"]));
        harness.shutdown().await;
    }

    let harness = passthrough(Tier::Destructive, &[(&["nonesuch"], Reply::ok("it ran\n"))]).await;
    let answer = harness
        .call_ok("tailscale_run", json!({"args": ["nonesuch"]}))
        .await;
    assert_eq!(answer["tier"], "destructive");
    assert_eq!(
        answer["covered"], false,
        "an unknown command must say the tier was a refusal to guess: {answer:#}"
    );
    harness.shutdown().await;
}

/// Every excluded command, enumerated, is refused with the permission code.
#[tokio::test]
async fn every_excluded_command_is_refused() {
    let harness = passthrough(Tier::Destructive, &[]).await;

    let mut checked = 0;
    for excluded in tailscale_mcp::tools::passthrough::excluded() {
        let words: Vec<&str> = excluded.path.split(' ').collect();
        let before = harness.cli_calls().len();
        let error = harness
            .call_err("tailscale_run", json!({"args": words}))
            .await;
        assert_eq!(
            error["code"], "not_permitted",
            "`{}` was not refused: {error:#}",
            excluded.path
        );
        assert!(
            error["message"]
                .as_str()
                .is_some_and(|m| m.contains(excluded.reason)),
            "`{}` was refused without its reason: {error:#}",
            excluded.path
        );
        assert!(
            error["hint"].is_null(),
            "`{}` is refused by no switch, so nothing should suggest one: {error:#}",
            excluded.path
        );
        assert_eq!(
            harness.cli_calls().len(),
            before,
            "`{}` reached the client",
            excluded.path
        );
        checked += 1;
    }

    // Nine documented commands and the fourteen hidden ones ticket 13 named.
    assert_eq!(checked, 23, "the whole exclusion list has to be walked");

    // The one `debug` member in neither list stays runnable, which is what
    // makes the list above a list rather than a blanket refusal.
    let runnable = harness
        .call_err("tailscale_run", json!({"args": ["debug", "reload-config"]}))
        .await;
    assert_ne!(
        runnable["code"], "not_permitted",
        "`debug reload-config` is deliberately runnable (DECISIONS Q44): {runnable:#}"
    );

    harness.shutdown().await;
}

/// A command cannot be spelled past the judgement that applies to it.
///
/// Both of these were `/code-review` findings on this ticket, and both are one
/// mistake: reading the argument list as a single spelling when the client
/// reads it as another. What holds them closed is `classify` taking two
/// readings and keeping the stricter; these are the end-to-end proof that the
/// gate, the tables and the handler agree with it.
#[tokio::test]
async fn a_command_cannot_be_disguised_past_its_own_judgement() {
    // The client matches its own subcommands without regard to case, so this
    // is `debug prefs`, excluded for printing the node's private key.
    let harness = passthrough(Tier::Destructive, &[]).await;
    let before = harness.cli_calls().len();
    let error = harness
        .call_err("tailscale_run", json!({"args": ["DEBUG", "PREFS"]}))
        .await;
    assert_eq!(error["code"], "not_permitted", "{error:#}");
    assert_eq!(
        harness.cli_calls().len(),
        before,
        "a shouted `debug prefs` reached the client"
    );
    harness.shutdown().await;

    // `tailscale serve --bg reset` runs `serve reset`, which is destructive and
    // wants a confirmation. Read as `serve`, it is a write needing neither.
    let harness = passthrough(Tier::Write, &[]).await;
    let before = harness.cli_calls().len();
    let error = harness
        .call_err("tailscale_run", json!({"args": ["serve", "--bg", "reset"]}))
        .await;
    assert_eq!(error["code"], "not_permitted", "{error:#}");
    assert_eq!(
        harness.cli_calls().len(),
        before,
        "a write-tier session reset the serve configuration"
    );
    harness.shutdown().await;

    // And at the tier that does allow it, the confirmation is still owed.
    let harness = passthrough(Tier::Destructive, &[]).await;
    let before = harness.cli_calls().len();
    let error = harness
        .call_err("tailscale_run", json!({"args": ["serve", "--bg", "reset"]}))
        .await;
    assert_eq!(error["code"], "confirmation_required", "{error:#}");
    assert_eq!(
        harness.cli_calls().len(),
        before,
        "the serve configuration was reset without a confirmation"
    );
    harness.shutdown().await;
}

/// An argument full of shell syntax is one argument.
#[tokio::test]
async fn nothing_a_caller_writes_is_parsed_by_a_shell() {
    let awkward = "; rm -rf / & $(whoami) `id` | tee /tmp/x #'\"";
    let harness = passthrough(Tier::Read, &[(&["ping"], Reply::ok("pong\n"))]).await;

    harness
        .call_ok("tailscale_run", json!({"args": ["ping", awkward]}))
        .await;

    let ran = harness
        .cli_calls()
        .into_iter()
        .find(|argv| argv.first().map(String::as_str) == Some("ping"))
        .expect("`ping` ran");
    assert_eq!(
        ran,
        vec!["ping".to_owned(), awkward.to_owned()],
        "the argument was split, quoted or expanded on its way to the client"
    );

    harness.shutdown().await;
}

/// Arguments the schema-derived generator cannot satisfy, written out.
///
/// Each of these validates its input before spawning — a key has a prefix, a
/// selector is required, `set` refuses to change nothing — so the emptiest
/// value its type allows never reaches the client.
fn hand_written_arguments(name: &str) -> Option<Value> {
    Some(match name {
        "tailscale_debug_via" => json!({"route": "fd7a:115c:a1e0:b1a:0:7:a01:0/112"}),
        "tailscale_lock_add" => json!({"keys": [TLPUB]}),
        "tailscale_lock_remove" => json!({"keys": [TLPUB]}),
        "tailscale_lock_init" => json!({"trusted_keys": [TLPUB], "confirm": true}),
        "tailscale_lock_disable" => json!({"secret": DISABLEMENT_SECRET, "confirm": true}),
        "tailscale_lock_disablement_kdf" => json!({"secret": DISABLEMENT_HEX}),
        "tailscale_lock_revoke_keys" => json!({"keys": [TLPUB], "confirm": true}),
        "tailscale_lock_sign" => json!({"key": NODEKEY}),
        "tailscale_prefs_set" => json!({"nickname": "workstation"}),
        "tailscale_serve_get_config" => json!({"all": true}),
        "tailscale_serve_set_config" => json!({"all": true, "configuration": {}}),
        _ => return None,
    })
}

/// The passthrough's table of covered commands is the typed tools' own terms.
///
/// [`COVERED`](tailscale_mcp::tools::passthrough::COVERED) is eighty-seven
/// hand-written rows claiming to state, for each command, the tier and
/// confirmation of the tool that runs it. Nothing about a hand-written table
/// stays true on its own, so this drives every typed tool through a real
/// session, reads back the command each one actually ran, and re-derives the
/// table from that. Both directions are checked: no row is weaker than a tool
/// that runs its command, and no row is stronger than every tool that does.
#[tokio::test]
async fn the_covered_table_follows_the_tools_it_claims_to_follow() {
    use std::collections::BTreeMap;
    use tailscale_mcp::tools::passthrough::{COVERED, Known, classify};

    let harness = Setup::new()
        .preset("full")
        .toolsets("+local-debug")
        .tier(Tier::Destructive)
        .start()
        .await;

    // What the tools say, path by path: the highest tier any of them runs the
    // command at, and whether any of them requires a confirmation.
    let mut derived: BTreeMap<String, (Tier, bool)> = BTreeMap::new();
    // The paths whose only tool belongs to another platform, so nothing here
    // can say what terms they run on.
    let mut elsewhere: std::collections::BTreeSet<String> = Default::default();

    for meta in table() {
        if meta.name == "tailscale_run" {
            // The tool doing the judging; it has no fixed command to judge.
            continue;
        }
        if meta.surface() == tailscale_mcp::meta::Surface::Tailnet {
            // `COVERED` is about `tailscale` subcommands, and the tailnet
            // surface runs none: it reaches the control plane over HTTP. A
            // tool with no command to read cannot contribute a row, and asking
            // it for one is what this loop would otherwise do.
            continue;
        }
        if !meta.runs_here() {
            // The command exists on another operating system, so a tool for it
            // refuses before spawning and there is no argument list to read
            // back — `every_tool_answers_its_success_case` checks the refusal.
            // Its contract row names the command, which is enough to know the
            // path exists; what it runs on has to be judged where it runs.
            let contract = contract_for(meta.name);
            let argv: Vec<String> = contract.success.1.cli[0]
                .0
                .iter()
                .map(|word| (*word).to_owned())
                .collect();
            let (path, _) = classify(&argv).unwrap_or_else(|e| {
                panic!(
                    "`{}` is contracted to run `{}`, which the passthrough refuses to read: {e:?}",
                    meta.name,
                    argv.join(" ")
                )
            });
            elsewhere.insert(path);
            continue;
        }
        let tool = harness
            .tool(meta.name)
            .await
            .unwrap_or_else(|| panic!("`{}` was not offered", meta.name));
        let mut arguments =
            hand_written_arguments(meta.name).unwrap_or_else(|| minimal_arguments(&tool));
        if meta.requires_confirmation
            && let Some(object) = arguments.as_object_mut()
        {
            object.insert("confirm".to_owned(), json!(true));
        }

        let before = harness.cli_calls().len();
        let _ = harness.call(meta.name, arguments.clone()).await;
        let calls = harness.cli_calls();
        let ran = &calls[before..];
        assert_eq!(
            ran.len(),
            1,
            "`{}` ran {} commands, and this test reads one; it was called with \
             {arguments}",
            meta.name,
            ran.len()
        );
        let argv = &ran[0];

        if meta.name == "tailscale_debug_file_list" {
            // The one tool whose command is not a subcommand: `debug --file=get`
            // is a flag on the parent, so there is no path to put in the table.
            // The passthrough refuses it rather than reading `debug` and
            // guessing, which is why this tool exists.
            assert_eq!(argv, &["debug", "--file=get"]);
            let error = classify(argv).expect_err("a bare `debug` cannot be judged");
            assert_eq!(error.code, tailscale_mcp::error::ErrorCode::InvalidArgs);
            continue;
        }

        let (path, known) = classify(argv).unwrap_or_else(|e| {
            panic!(
                "`{}` ran `{}`, which the passthrough refuses to read: {e:?}",
                meta.name,
                argv.join(" ")
            )
        });
        let Known::Covered(row) = known else {
            panic!(
                "`{}` runs `tailscale {path}`, which is in no row of COVERED",
                meta.name
            );
        };
        assert!(
            row.tier >= meta.tier,
            "`tailscale {path}` is {} in COVERED but `{}` runs it at {}",
            row.tier,
            meta.name,
            meta.tier
        );
        assert!(
            row.confirm >= meta.requires_confirmation,
            "`{}` confirms and `tailscale {path}` does not",
            meta.name
        );

        let entry = derived.entry(path).or_insert((Tier::Read, false));
        entry.0 = entry.0.max(meta.tier);
        entry.1 |= meta.requires_confirmation;
    }

    for row in COVERED {
        let Some(&(tier, confirm)) = derived.get(row.path) else {
            assert!(
                elsewhere.contains(row.path),
                "no tool runs `tailscale {}`, so its row states nobody's terms",
                row.path
            );
            // The row is real and its tool is real; both are judged on the
            // platform that has the command (Q105).
            continue;
        };
        assert_eq!(
            (row.tier, row.confirm),
            (tier, confirm),
            "`tailscale {}` is stricter in COVERED than every tool that runs it",
            row.path
        );
    }

    harness.shutdown().await;
}