nord-cli 0.6.0

Your Nord from the terminal: inspect, edit and move the sounds in Nord files and on a connected instrument
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
2347
2348
2349
2350
2351
2352
2353
2354
2355
//! The operations that talk to an attached instrument.
//!
//! Each one is parameterised by object class: the same code drives a program and a set
//! list, differing only in the class the session opened.
//!
//! Read-only queries (`status`, `get`, `info`, `deps`) and the non-destructive `select`
//! need no confirmation; the mutating actions (`put`, `move`, `delete`, `rename`,
//! `duplicate`) each describe what they will touch and then refuse to proceed without
//! `--yes`.

use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;

use nord_format::accept::{Acceptance, Family};
use nord_usb::op;
use nord_usb::transport::{Transport, UsbTransport};
use nord_usb::wire::{Bank, Location, ProgramInfo, Status};
use nord_usb::{op as usb_op, Device, Geometry, ObjectClass, Session};

use crate::slot::{addr, noun, shown};
use crate::ui::Ui;

/// Where to get the exchange from.
pub enum Source {
    /// A real instrument over USB.
    Usb,
    /// A recorded exchange. Lets the whole path be demonstrated with no hardware —
    /// and is how this command is exercised under Wine, qemu and in CI.
    Replay(PathBuf),
}

pub fn status(ui: &Ui, source: Source, json: bool) -> Result<(), String> {
    let report = match source {
        Source::Usb => {
            let mut device = open_usb()?;
            transact(&mut device, "device status", |d| {
                nord_usb::block_on(op::inventory(d.transport()))
            })
            .map_err(|e| e.to_string())?
        }
        Source::Replay(path) => {
            let text =
                std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
            let mut transport = nord_usb::ReplayTransport::from_script(&text)
                .map_err(|e| e.to_string())?
                .lenient();
            collect(&mut transport)?
        }
    };

    // An empty report means every class refused, not that every class is empty: a
    // failed connection is an error of its own and never arrives here.
    if report.is_empty() {
        return Err(
            "every object class refused — the instrument is not in a usable session \
             state, and a power cycle clears it. `nord device info` shows what is on \
             the bus."
                .into(),
        );
    }

    if json {
        print_json(ui, &report);
    } else {
        print_table(ui, &report);
    }
    Ok(())
}

/// Report the attached instrument itself: what is on the bus, not what is stored on it.
///
/// Answered entirely from the USB descriptors, so it works before any transaction is
/// opened and is the right first thing to run when nothing else responds.
pub fn info(ui: &Ui) -> Result<(), String> {
    let devices = nord_usb::transport::usb::list().map_err(|e| e.to_string())?;
    if devices.is_empty() {
        return Err("no Clavia device found".into());
    }
    let mut unreachable = None;
    for (i, d) in devices.iter().enumerate() {
        if i > 0 {
            ui.out("");
        }
        ui.out(format!(
            "  product:   {}",
            d.product_string().unwrap_or("(none reported)")
        ));
        ui.out(format!(
            "  vendor:    {} ({:#06x})",
            d.manufacturer_string().unwrap_or("(none reported)"),
            d.vendor_id(),
        ));
        ui.out(format!("  product id: {:#06x}", d.product_id()));
        ui.out(format!(
            "  serial:    {}",
            d.serial_number().unwrap_or("(none reported)")
        ));
        // The protocol requires the vendor-specific interface, not USB-MIDI alone.
        let vendor_iface = d.interfaces().any(|i| i.class() == 0xff);
        ui.out(format!(
            "  protocol:  {}",
            if vendor_iface {
                "vendor interface present"
            } else {
                "no vendor interface — this tool cannot drive it"
            }
        ));

        // Endpoint 0, so this needs no transaction and still answers on an instrument
        // that has stopped serving the bulk protocol.
        if vendor_iface {
            match nord_usb::transport::UsbTransport::open(d).and_then(|t| t.identity()) {
                Ok(id) => {
                    ui.out(format!(
                        "  firmware:  {}",
                        crate::summary::version_label(u32::from(id.firmware))
                    ));
                    ui.out(format!("  build:     {}", id.build));
                    ui.out(format!("  max xfer:  {} bytes", id.max_transfer));
                }
                Err(e) => {
                    ui.out(format!("  firmware:  {}", ui.dim(e.to_string())));
                    unreachable.get_or_insert_with(|| e.to_string());
                }
            }
        }
    }
    // This is what a caller runs to find out whether the instrument can be reached at
    // all, so the exit code has to carry that answer and not just the printed lines.
    match unreachable {
        Some(e) => Err(format!("could not identify the instrument: {e}")),
        None => Ok(()),
    }
}

fn collect<T: Transport>(transport: &mut T) -> Result<Vec<Status>, String> {
    nord_usb::block_on(op::inventory(transport)).map_err(|e| e.to_string())
}

fn print_table(ui: &Ui, report: &[Status]) {
    ui.out(ui.dim(format!(
        "{:<10} {:>20} {:>7} {:>14}  {}",
        "class", "used", "full", "free", "of"
    )));
    let mut any_dirty = false;
    for s in report {
        let (used, free, of) = match s.slots() {
            Some(slots) => (
                format!("{} / {} slots", s.count, slots),
                u64::from(slots)
                    .saturating_sub(u64::from(s.count))
                    .to_string(),
                format!("{} bytes each", s.bytes_per_item().unwrap_or(0)),
            ),
            // ⚠️ What a write can reach is `available`, not `free`: a delete parks its
            // blocks in the dirty pool, and a partition reporting no free space at all
            // is still writable once the cleaning pass has run.
            None => {
                let unit = if s.class.is_library() {
                    "blocks"
                } else {
                    "bytes"
                };
                (
                    format!("{} / {} {unit}", s.used, s.total()),
                    match s.dirty {
                        0 => s.available().to_string(),
                        dirty => {
                            any_dirty = true;
                            format!("{} ({dirty} dirty)", s.available())
                        }
                    },
                    format!("{} items", s.count),
                )
            }
        };
        ui.out(format!(
            "{:<10} {:>20} {:>6.1}% {:>14}  {}",
            s.class.label(),
            used,
            s.used_percent(),
            free,
            ui.dim(of),
        ));
    }
    let mut footnotes: Vec<&str> = Vec::new();
    if report.iter().any(|s| s.class.is_library()) {
        footnotes.push("a block is the library partition's own allocation unit, and");
        footnotes.push("`nord device geometry` reports its size; the slot classes count bytes");
    }
    if any_dirty {
        footnotes.push("dirty blocks hold deleted content and are not free yet — a write that");
        footnotes.push("needs them reclaims exactly the shortfall first");
    }
    if !footnotes.is_empty() {
        ui.note("");
        let last = footnotes.len() - 1;
        for (i, line) in footnotes.iter().enumerate() {
            let open = if i == 0 { "(" } else { "" };
            let close = if i == last { ")" } else { "" };
            ui.note(format!("{open}{line}{close}"));
        }
    }
}

fn print_json(ui: &Ui, report: &[Status]) {
    ui.out("[");
    for (i, s) in report.iter().enumerate() {
        let comma = if i + 1 == report.len() { "" } else { "," };
        ui.out(format!(
            "  {{\"class\": \"{}\", \"code\": {}, \"items\": {}, \"used\": {}, \"free\": {}, \"dirty\": {}, \"available\": {}, \"capacity\": {}}}{comma}",
            s.class.label(),
            s.class.to_raw(),
            s.count,
            s.used,
            s.free,
            s.dirty,
            s.available(),
            s.total(),
        ));
    }
    ui.out("]");
}

/// Turn the device's bare status code into something actionable.
///
/// Confirmed on hardware. `0x1` from a vacant slot, `0x3` from an address past the
/// instrument's geometry, `0x4` from a write aimed at an occupied slot.
fn explain(e: nord_usb::Error, at: Location) -> String {
    match e {
        nord_usb::Error::DeviceStatus(1) => {
            format!("{} is empty", shown(at))
        }
        nord_usb::Error::DeviceStatus(3) => {
            format!("{} is out of range for this instrument", shown(at))
        }
        nord_usb::Error::DeviceStatus(4) => {
            format!(
                "{} is occupied, and the instrument does not overwrite in place",
                shown(at)
            )
        }
        other => other.to_string(),
    }
}

/// [`explain`] for a verb with a source and a destination: an empty slot can only be
/// the source, an occupied one only the destination.
fn explain_pair(e: nord_usb::Error, from: Location, to: Location) -> String {
    match e {
        nord_usb::Error::DeviceStatus(1) => explain(e, from),
        nord_usb::Error::DeviceStatus(4) => explain(e, to),
        nord_usb::Error::DeviceStatus(3) => format!(
            "{} or {} is out of range for this instrument",
            shown(from),
            shown(to)
        ),
        other => other.to_string(),
    }
}

/// Turn a refusal from the enumeration walk into something actionable.
///
/// No slot to name here — the failing command is the walk itself.
fn explain_walk(e: nord_usb::Error) -> String {
    match e {
        nord_usb::Error::DeviceStatus(usb_op::ENUMERATION_DISABLED) => {
            "the instrument refused the enumeration request as malformed (status 0x11) \
             — it refuses a cursor request without the direction word after any write \
             since power-up. nord sends the full form, so this should not happen; \
             per-slot `info` still works in the meantime"
                .into()
        }
        other => other.to_string(),
    }
}

/// Where `--record` writes, for the one transport this process opens.
static RECORDING: OnceLock<Option<PathBuf>> = OnceLock::new();

/// Set once, from the parsed global flag, before any command runs.
pub fn set_recording(path: Option<PathBuf>) {
    let _ = RECORDING.set(path);
}

/// What a transaction needs from the transport it runs on beyond moving frames: the
/// `--record` bracket, and the product string the acceptance table reads.
///
/// A [`UsbTransport`] carries both; a replayed exchange records nothing and names no
/// product. Stating that here is what lets [`send`] — the one path that holds a slot's
/// only copy — be driven by a script as well as by an instrument.
trait Recorded {
    fn mark_intent(&mut self, intent: &str);
    fn mark_expect(&mut self, e: &nord_usb::Error);
    fn finish_recording(&mut self) -> nord_usb::Result<()>;
    fn product(&self) -> Option<&str>;
}

/// A replayed exchange records nothing and names no product: the script is the
/// recording, and what the instrument would have called itself is not in it.
#[cfg(test)]
impl Recorded for nord_usb::ReplayTransport {
    fn mark_intent(&mut self, _intent: &str) {}

    fn mark_expect(&mut self, _e: &nord_usb::Error) {}

    fn finish_recording(&mut self) -> nord_usb::Result<()> {
        Ok(())
    }

    fn product(&self) -> Option<&str> {
        None
    }
}

impl Recorded for UsbTransport {
    fn mark_intent(&mut self, intent: &str) {
        UsbTransport::mark_intent(self, intent);
    }

    fn mark_expect(&mut self, e: &nord_usb::Error) {
        UsbTransport::mark_expect(self, e);
    }

    fn finish_recording(&mut self) -> nord_usb::Result<()> {
        UsbTransport::finish_recording(self)
    }

    fn product(&self) -> Option<&str> {
        UsbTransport::product(self)
    }
}

/// Run one transaction on the instrument, recording what it was for and — if it failed —
/// what it produced.
///
/// A recording is replayable only if the script says both, and they cannot be
/// written at the same moment: the intent goes ahead of the frames, the outcome is only
/// known once they are on disk. A success writes nothing, because a section that says
/// nothing expects `ok`.
///
/// A recording that lost frames is reported once the transaction has closed, so a script
/// is never silently short. The transaction's own failure outranks it: that is what the
/// operator asked about.
fn transact<T: Transport + Recorded, R>(
    device: &mut Device<T>,
    intent: impl std::fmt::Display,
    run: impl FnOnce(&mut Device<T>) -> nord_usb::Result<R>,
) -> nord_usb::Result<R> {
    device.transport().mark_intent(&intent.to_string());
    let outcome = run(device);
    if let Err(e) = &outcome {
        device.transport().mark_expect(e);
    }
    let recorded = device.transport().finish_recording();
    outcome.and_then(|value| recorded.map(|()| value))
}

fn open_usb() -> Result<Device<UsbTransport>, String> {
    let transport = UsbTransport::open_first().map_err(|e| e.to_string())?;
    let transport = match RECORDING.get().and_then(Option::as_deref) {
        Some(path) => transport.recording_to(path).map_err(|e| e.to_string())?,
        None => transport,
    };
    Ok(Device::new(transport))
}

/// Cache geometry in its own intent so later recordings contain only their own frames.
fn read_geometry<T: Transport + Recorded>(device: &mut Device<T>) -> Result<&Geometry, String> {
    transact(device, "device geometry", |d| {
        nord_usb::block_on(d.geometry()).map(|_| ())
    })
    .map_err(|e| e.to_string())?;
    nord_usb::block_on(device.geometry()).map_err(|e| e.to_string())
}

fn declared_banks(
    device: &mut Device<UsbTransport>,
    class: ObjectClass,
) -> Result<Vec<Bank>, String> {
    read_geometry(device)?
        .banks(class)
        .map(<[Bank]>::to_vec)
        .map_err(|e| e.to_string())
}

/// One read in its own session: the slot's metadata, then its bytes.
///
/// `body` returns the wire body verbatim; otherwise the bytes are a whole CBIN file.
fn read_object(
    device: &mut Device<UsbTransport>,
    at: Location,
    class: ObjectClass,
    body: bool,
) -> Result<(ProgramInfo, Vec<u8>), String> {
    let verb = if body { "get-body" } else { "get" };
    transact(
        device,
        format!("{} {verb} {}", noun(class), addr(at)),
        |d| {
            nord_usb::block_on(d.read(class, async |s| {
                let info = usb_op::info(s, at).await?;
                let file = if body {
                    usb_op::read_body(s, at).await?
                } else {
                    usb_op::read_program(s, at).await?
                };
                Ok((info, file))
            }))
        },
    )
    .map_err(|e| explain(e, at))
}

/// Read one object off the instrument. Read-only.
///
/// With `out` set, writes the file; otherwise decodes and prints a summary.
///
/// `body` writes the wire body verbatim instead of wrapping it in a CBIN header, for
/// classes whose header layout is not yet known and where wrapping would fabricate a
/// wrong file.
pub fn get(
    ui: &Ui,
    at: Location,
    out: Option<PathBuf>,
    class: ObjectClass,
    body: bool,
) -> Result<(), String> {
    // Before the transport opens: a piano read is minutes long, and finding out at the
    // end that there was nowhere to put it is the worst possible time.
    if body && out.is_none() {
        return Err("--body writes a file; give -o a path".into());
    }
    let mut device = open_usb()?;
    let (info, file) = read_object(&mut device, at, class, body)?;

    if let Some(path) = out {
        crate::edit::replace_file(&path, &file)?;
        ui.note(format!(
            "read {:?} ({} bytes) from {} -> {}",
            info.name,
            file.len(),
            shown(at),
            path.display(),
        ));
        return Ok(());
    }

    let entity = nord_format::from_stream(&mut std::io::Cursor::new(&file)).map_err(|e| {
        format!(
            "{} decoded off the device but did not parse: {e}",
            shown(at)
        )
    })?;

    ui.out(format!(
        "{} {} {:?}  ({}, version {})",
        shown(at),
        ui.dash(),
        info.name,
        info.format,
        info.version
    ));
    crate::summary::print(ui, &entity);
    Ok(())
}

/// Read the same slot once per change the operator makes on the panel, filing each
/// capture under what they say changed. Read-only.
///
/// ⚠️ **The read happens after the answer, not before.** The answer is the operator
/// saying the instrument is now in the state to capture; reading first would file every
/// capture under the change that comes next.
///
/// A failed read is reported and the sweep continues — one fumbled step should not cost
/// the session, and nothing already written is at risk.
///
/// ⚠️ The prompt sits *between* sessions, never inside one. Ctrl-C there ends the process
/// outright ([`Ui::ask`]), and an interrupt taken mid-session would leave the instrument
/// holding its progress label with no way out but a power cycle.
pub fn sweep(
    ui: &Ui,
    at: Location,
    dir: PathBuf,
    class: ObjectClass,
    body: bool,
) -> Result<(), String> {
    std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    let mut device = open_usb()?;
    ui.note(format!(
        "sweeping {} ({}) into {}",
        shown(at),
        class.label(),
        dir.display()
    ));
    ui.note("change one thing on the instrument, then say what it was");
    ui.note("each prompt reopens with your last answer, editable; clear it to finish");

    let mut captured = 0usize;
    // Reuse the last answer because adjacent captures usually differ by one value.
    let mut previous = String::new();
    while let Some(label) = ui.ask("what changed", &previous)? {
        previous = label.clone();
        let stem = match stem(&label) {
            Ok(s) => s,
            Err(e) => {
                ui.warn(e);
                continue;
            }
        };
        // Refuse duplicates before the slow device read.
        if taken(&dir, &stem)? {
            ui.warn(format!(
                "{stem:?} is already captured; give this one another name"
            ));
            continue;
        }

        let (info, file) = match read_object(&mut device, at, class, body) {
            Ok(read) => read,
            Err(e) => {
                ui.warn(e);
                continue;
            }
        };
        // The extension says what the bytes are: a wrapped file carries the device's own
        // format tag, a `--body` dump is a fragment and no format at all.
        let path = dir.join(match body {
            true => format!("{stem}.bin"),
            false => format!("{stem}.{}", info.format),
        });
        let mut output = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
            .map_err(|e| format!("{}: {e}", path.display()))?;
        output
            .write_all(&file)
            .map_err(|e| format!("{}: {e}", path.display()))?;
        captured += 1;
        ui.note(format!("  {} ({} bytes)", path.display(), file.len()));
    }

    ui.note(format!("captured {captured} file(s) in {}", dir.display()));
    Ok(())
}

/// Turn what the operator typed into a filename stem.
///
/// The answer is prose — `split point C4`, `vol 5 -> 6` — and in the corpus directory it
/// is the only record of what the bytes mean, so it stays readable: whitespace runs
/// become one `-`, and only what a path cannot carry is dropped.
fn stem(label: &str) -> Result<String, String> {
    // Defer separators so runs collapse and trailing punctuation disappears.
    let mut owed = false;
    let mut out = String::with_capacity(label.len());
    for c in label.chars() {
        match c {
            '-' => owed = !out.is_empty(),
            _ if c.is_whitespace() => owed = !out.is_empty(),
            // The corpus must remain readable on Windows.
            '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => owed = !out.is_empty(),
            _ if c.is_control() => {}
            _ => {
                if std::mem::take(&mut owed) {
                    out.push('-');
                }
                out.push(c);
            }
        }
    }
    // Trim shell-option prefixes and dots that are hidden or invalid across platforms.
    let out = out.trim_matches(['.', '-']);
    if out.is_empty() {
        return Err(format!("{label:?} leaves nothing usable as a filename"));
    }
    let device = out.split('.').next().unwrap_or(out).to_ascii_uppercase();
    let reserved = matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL")
        || device
            .strip_prefix("COM")
            .or_else(|| device.strip_prefix("LPT"))
            .is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"));
    if reserved {
        return Err(format!("{label:?} is a reserved filename on Windows"));
    }
    Ok(out.to_string())
}

/// Whether a capture under this name already exists, whatever extension it took.
fn taken(dir: &Path, stem: &str) -> Result<bool, String> {
    let entries = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    for entry in entries {
        let entry = entry.map_err(|e| format!("{}: {e}", dir.display()))?;
        let same = Path::new(&entry.file_name())
            .file_stem()
            .is_some_and(|held| held.to_string_lossy().eq_ignore_ascii_case(stem));
        if same {
            return Ok(true);
        }
    }
    Ok(false)
}

/// What the acceptance table says about writing a file into a class on the attached
/// instrument.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admit {
    Takes,
    /// The write goes ahead, and this is what has not been checked.
    Warn(String),
    /// Another family's file. Nothing is written.
    Refuse(String),
}

/// Whether the instrument `product` names takes a `tag` file in `class`.
///
/// ⚠️ Only a tag another family carries is evidence that a file is in the wrong place,
/// so everything short of that — a product string the table does not name, a class it
/// says nothing about, or no product string at all — warns and lets the write proceed.
/// Refusing what is merely unmeasured would put this table in the way of the next
/// measurement.
pub fn admit(product: Option<&str>, class: ObjectClass, tag: &str) -> Admit {
    let Some(product) = product else {
        return Admit::Warn(format!(
            "this transport reports no product string, so nothing here says whether \
             the instrument takes a {tag} file"
        ));
    };
    let (Some(slot), Some(family)) = (class.storage(), Family::from_product(product)) else {
        return Admit::Warn(format!(
            "{product} is not in the acceptance table, so nothing here says whether it \
             takes a {tag} file"
        ));
    };
    match family.accepts(slot, tag) {
        Acceptance::Confirmed => Admit::Takes,
        Acceptance::Inferred => Admit::Warn(format!(
            "this is a {} file and the instrument is a {product}, but no file of this \
             kind has ever been written to one: this write is untried",
            family.label()
        )),
        Acceptance::Unknown => Admit::Warn(format!(
            "nothing here says whether a {product} takes a {tag} file"
        )),
        Acceptance::Refused => Admit::Refuse(match Family::of_tag(tag) {
            Some(owner) => format!(
                "this is a {} file and the instrument is a {product}",
                owner.label()
            ),
            // ⚠️ Unreachable while `accepts` refuses only a tag another family carries;
            // stated rather than unwrapped so a widened table cannot panic here.
            None => format!("a {tag} file is not one a {product} takes"),
        }),
    }
}

/// Write a file into a slot, overwriting it.
pub fn put(
    ui: &Ui,
    path: PathBuf,
    at: Location,
    class: ObjectClass,
    confirmed: bool,
) -> Result<(), String> {
    let file = std::fs::read(&path).map_err(|e| format!("{}: {e}", path.display()))?;
    // Fail before touching the device if the file is not what it claims to be.
    nord_usb::envelope::unwrap(&file).map_err(|e| e.to_string())?;
    // The write carries the slot's name and the file supplies none: the stem is it.
    let stem = path
        .file_stem()
        .map(|s| s.to_string_lossy().to_string())
        .filter(|s| !s.is_empty() && !s.starts_with('.'))
        .ok_or_else(|| {
            format!(
                "{}: the slot takes its name from the file's stem, and this file has none",
                path.display()
            )
        })?;
    // The file's own modification time, as NSM sends.
    let stamp = std::fs::metadata(&path)
        .and_then(|m| m.modified())
        .ok()
        .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|d| u32::try_from(d.as_secs()))
        .transpose()
        .map_err(|_| {
            format!(
                "{}: modification time does not fit the protocol",
                path.display()
            )
        })?;

    send(
        ui,
        &file,
        at,
        class,
        confirmed,
        &path.display().to_string(),
        Some(&stem),
        stamp,
    )
}

/// Send an already-validated file into a slot, describing the target first. Shared with
/// `edit`, which arrives with bytes rather than a path.
///
/// ⚠️ **On most classes an occupied destination is replaced, not overwritten.** The
/// instrument answers status 4 to a write aimed at a slot that already holds something,
/// so this reads the occupant, deletes it, writes, and puts the occupant back if the
/// write fails — the slot is genuinely empty in between, and the only copy of its
/// contents is in this process. The classes that
/// [overwrite in place](ObjectClass::overwrites_in_place) skip the delete and keep the
/// same backup-and-restore guard.
#[allow(clippy::too_many_arguments)]
pub fn send(
    ui: &Ui,
    file: &[u8],
    at: Location,
    class: ObjectClass,
    confirmed: bool,
    what: &str,
    // `None` keeps whatever the slot is already called.
    name: Option<&str>,
    // `None` means now; the device can refuse a timestamp it considers future.
    stamp: Option<u32>,
) -> Result<(), String> {
    send_with(
        ui,
        &mut open_usb()?,
        &std::env::current_dir().unwrap_or_default(),
        file,
        at,
        class,
        confirmed,
        what,
        name,
        stamp,
    )
}

/// [`send`] against an already-open device, spilling a rescue into `spill`.
///
/// The split is what the replay tests drive: every step between the first `INFO` and the
/// write can fail, and what this does with the occupant it is holding is the difference
/// between a failed write and a lost slot.
#[allow(clippy::too_many_arguments)]
fn send_with<T: Transport + Recorded>(
    ui: &Ui,
    device: &mut Device<T>,
    spill_into: &Path,
    file: &[u8],
    at: Location,
    class: ObjectClass,
    confirmed: bool,
    what: &str,
    name: Option<&str>,
    stamp: Option<u32>,
) -> Result<(), String> {
    // Check geometry before the transfer starts.
    let bad = transact(
        device,
        format!("{} check-address {}", noun(class), addr(at)),
        |d| nord_usb::block_on(d.read(class, async |s| usb_op::check_address(s, at).await)),
    )
    .map_err(|e| explain(e, at))?;
    if let Some(reason) = bad {
        return Err(format!("{}: {reason}", shown(at)));
    }

    let timestamp = match stamp {
        Some(stamp) => stamp,
        None => crate::edit::unix_seconds_now()?,
    };

    // Name what is about to be destroyed before destroying it. An empty destination is
    // not a failure: status 1 means the slot is vacant, so there is nothing to report.
    let existing = transact(device, format!("{} info {}", noun(class), addr(at)), |d| {
        nord_usb::block_on(d.read(class, async |s| usb_op::info(s, at).await))
    });

    let existing = match existing {
        Ok(info) => Some(info),
        Err(nord_usb::Error::DeviceStatus(1)) => None,
        Err(e) => return Err(explain(e, at)),
    };

    let in_place = class.overwrites_in_place();
    match &existing {
        Some(info) => {
            ui.note(format!(
                "about to {} {} (currently {:?}) with {what}",
                ui.danger("overwrite"),
                shown(at),
                info.name,
            ));
            let room = match in_place {
                true => format!(
                    "the instrument overwrites {} in place, so nothing is deleted.",
                    shown(at)
                ),
                // The operator is consenting to the slot being empty for a moment, not
                // just to a write, so the delete has to be part of the question.
                false => format!(
                    "{} the instrument will not overwrite in place, so {} is deleted first.",
                    ui.danger("note:"),
                    shown(at),
                ),
            };
            ui.note(format!(
                "  {room} Its {} bytes are read back beforehand and put back if the \
                 write fails.",
                info.body_len,
            ));
        }
        None => ui.note(format!("{} is empty; writing {what}", shown(at))),
    }
    // The write carries the slot's name, so say it up front — and say when the device
    // will drop it, rather than reporting a naming that never happens.
    match name.filter(|n| !n.is_empty()) {
        Some(name) if class.names_its_slots() => {
            ui.note(format!("the slot will be named {name:?}"))
        }
        Some(_) => ui.note(format!(
            "{} keeps its fixed name: this class stores none, so the device discards \
             the write's name argument",
            shown(at),
        )),
        None => {}
    }
    if class == ObjectClass::Settings {
        // Confirmed on hardware.
        ui.warn(
            "a settings write reloads the selected program: panel state that has not \
             been stored is lost, so re-select and re-apply afterwards",
        );
    }
    // The file names its model in its tag and the instrument names its own in the
    // product string, so this is the last thing that can be known before the write.
    // Bytes carrying no tag are nothing the table can be about, and `put` has already
    // refused those.
    if let Some(tag) = tag(file) {
        match admit(device.transport().product(), class, &tag) {
            Admit::Takes => {}
            Admit::Warn(why) => ui.warn(why),
            Admit::Refuse(why) => return Err(format!("{what}: {why}")),
        }
    }
    ui.confirm(confirmed)?;

    // After consent, not before: for a piano this read is minutes long, and nobody should
    // sit through it only to be asked whether they meant it.
    let backup = match &existing {
        Some(_) => Some(
            transact(device, format!("{} read {}", noun(class), addr(at)), |d| {
                nord_usb::block_on(d.read(class, async |s| usb_op::read_program(s, at).await))
            })
            // Nothing is deleted until the backup is in hand.
            .map_err(|e| {
                format!(
                    "could not read {} back before replacing it, so it was left alone: {}",
                    shown(at),
                    explain(e, at)
                )
            })?,
        ),
        None => None,
    };

    // Read before deletion so geometry failure leaves the occupant intact.
    read_geometry(device)?;

    if let (Some(backup), false) = (&backup, in_place) {
        ui.note(format!("deleting {} to make room", shown(at)));
        if let Err(e) = transact(
            device,
            format!("{} delete {}", noun(class), addr(at)),
            |d| nord_usb::block_on(delete_for_replacement(d, class, at)),
        ) {
            // ⚠️ A status is the instrument declining before the DELETE landed, so the
            // occupant is still there. Anything else — a close that would not answer, a read
            // that timed out — can have landed, and this process is then holding the only
            // copy of what the slot held.
            if let nord_usb::Error::DeviceStatus(_) = e {
                return Err(format!("deleting {}: {}", shown(at), explain(e, at)));
            }
            return Err(spill(
                ui,
                spill_into,
                at,
                backup,
                format!("{} may have been deleted: {}", shown(at), explain(e, at)),
            ));
        }
    }

    // What the slot ends up called: the caller's choice, else the occupant's name.
    let write_name = name
        .map(str::to_string)
        .or_else(|| existing.as_ref().map(|i| i.name.clone()))
        .unwrap_or_default();

    let written = if fail_after_delete() {
        // The backup is in hand and the write never happens: exactly the state the
        // restore path exists for, reached without needing a real transport failure.
        Err(nord_usb::Error::Transport(
            "NORD_FAIL_AFTER_DELETE was set, so the write was not attempted".into(),
        ))
    } else {
        transact(
            device,
            put_intent(class, what, at, &write_name, timestamp),
            |d| nord_usb::block_on(d.write(class, at, file, &write_name, timestamp)),
        )
    };

    match (written, backup) {
        (Ok(()), _) => {
            ui.note(format!("wrote {what} -> {}", shown(at)));
            Ok(())
        }
        (Err(e), None) => Err(explain(e, at)),
        // Getting the occupant back matters more than reporting the original error, which
        // is carried along and reported once the slot is whole again.
        (Err(e), Some(backup)) => {
            ui.warn(format!(
                "the write failed and {}; putting the original back",
                aftermath(class, at)
            ));
            // Restoring puts back what the slot was called, not what the caller wanted
            // the replacement named.
            let restore_name = existing
                .as_ref()
                .map(|i| i.name.clone())
                .unwrap_or_else(|| write_name.clone());
            let restore = transact(
                device,
                put_intent(
                    class,
                    &rescue_name(at, &backup),
                    at,
                    &restore_name,
                    timestamp,
                ),
                |d| nord_usb::block_on(d.write(class, at, &backup, &restore_name, timestamp)),
            );
            match restore {
                Ok(()) => {
                    ui.note(format!("restored {}", shown(at)));
                    Err(format!(
                        "{} ({} was restored, and is unchanged)",
                        explain(e, at),
                        shown(at)
                    ))
                }
                Err(restore) => {
                    ui.warn("restoring failed too");
                    Err(spill(
                        ui,
                        spill_into,
                        at,
                        &backup,
                        format!(
                            "{} (restoring failed as well: {}) {}",
                            explain(e, at),
                            explain(restore, at),
                            aftermath(class, at),
                        ),
                    ))
                }
            }
        }
    }
}

/// Whether to skip the write and report a failure, so the restore and rescue paths can
/// be exercised against a real instrument. Test tool: a genuine transport failure at this
/// exact point is otherwise only reachable by pulling the cable mid-operation.
///
/// ⚠️ It leaves the slot deleted, so point it at a scratch slot with a copy on disk.
#[cfg(feature = "fault-injection")]
fn fail_after_delete() -> bool {
    std::env::var_os("NORD_FAIL_AFTER_DELETE").is_some()
}

#[cfg(not(feature = "fault-injection"))]
fn fail_after_delete() -> bool {
    false
}

/// Last resort: the slot's former contents exist only in this process. Put them next to
/// the operator rather than exiting with them, and say where they went.
///
/// Both paths that can leave a slot without them reach this — a delete that may have
/// landed before its transaction failed, and a write whose restore failed too — so what
/// the operator has to do next is worded once.
fn spill(ui: &Ui, dir: &Path, at: Location, backup: &[u8], lost: String) -> String {
    let path = dir.join(rescue_name(at, backup));
    match crate::edit::replace_file(&path, backup) {
        Ok(()) => {
            ui.warn(format!("wrote the original to {}", path.display()));
            format!(
                "{lost}; its former contents were saved to {} — put it back with `nord put`",
                path.display(),
            )
        }
        Err(io) => format!(
            "{lost}, and its former contents could not be saved either ({io}); {} bytes \
             are lost",
            backup.len(),
        ),
    }
}

/// Validate the write allocation before removing an occupant that may need restoring.
async fn delete_for_replacement<T: Transport>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> nord_usb::Result<()> {
    device.geometry().await?.allocation_unit(class)?;
    device
        .destructive(class, async |s| usb_op::delete(s, at).await)
        .await
}

/// What a failed write left in the slot, for the line that reports it.
///
/// The two write paths fail differently: the delete-first composition leaves the slot
/// genuinely empty, while a class that overwrites in place leaves whatever the
/// interrupted write put there. Naming the wrong one tells the operator to take the
/// wrong next step.
fn aftermath(class: ObjectClass, at: Location) -> String {
    match class.overwrites_in_place() {
        true => format!("{} may hold a partly written body", shown(at)),
        false => format!("{} is empty", shown(at)),
    }
}

/// Read one slot's metadata in a throwaway read-only session — used to show what a
/// mutation is about to affect before it happens.
fn peek_info<T: Transport + Recorded>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> nord_usb::Result<ProgramInfo> {
    transact(device, format!("{} info {}", noun(class), addr(at)), |d| {
        nord_usb::block_on(d.read(class, async |s| usb_op::info(s, at).await))
    })
}

/// The same, reduced to the name and the refusal a caller prints.
fn peek<T: Transport + Recorded>(
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
) -> Result<String, String> {
    peek_info(device, class, at)
        .map(|info| info.name)
        .map_err(|e| explain(e, at))
}

/// What the operation does to whatever occupies the destination slot.
enum DestFate {
    /// Replaced, and lost.
    Overwritten,
    /// Exchanged with the source slot's contents. Nothing is lost.
    Swapped,
}

/// Describe what currently occupies a *destination* slot, for the pre-flight line.
///
/// ⚠️ The two fates need different words, and saying "overwriting" for a swap is worse
/// than saying nothing: it invites the reader to delete the destination first to protect
/// it, which destroys the very thing the swap would have preserved.
///
/// Unlike [`peek`] this never fails: `INFO` answers status 1 on an empty destination,
/// which is the normal case here, and the operation itself is a moment away from
/// reporting anything worse. ⚠️ Only that status says the slot is empty — a fault
/// reported as emptiness would have the reader expect a write where a swap is coming.
fn peek_dest<T: Transport + Recorded>(
    ui: &Ui,
    device: &mut Device<T>,
    class: ObjectClass,
    at: Location,
    fate: DestFate,
) -> String {
    match (peek_info(device, class, at), fate) {
        (Ok(info), DestFate::Overwritten) => {
            format!("{} {:?}", ui.danger("OVERWRITING"), info.name)
        }
        (Ok(info), DestFate::Swapped) => format!("{} {:?}", ui.bold("SWAPPING WITH"), info.name),
        (Err(nord_usb::Error::DeviceStatus(1)), _) => "destination reads as empty".into(),
        (Err(e), _) => format!("destination could not be read: {}", explain(e, at)),
    }
}

/// The set lists affected by moving or swapping the target programs.
fn referring_set_lists(
    device: &mut Device<UsbTransport>,
    targets: &[Location],
) -> Result<Vec<op::Referrer>, String> {
    let class = ObjectClass::SetList;
    let banks = declared_banks(device, class)?;
    let where_: Vec<String> = targets.iter().map(|&at| addr(at)).collect();
    let intent = format!("{} referrers {}", noun(class), where_.join(" "));
    transact(device, intent, |d| {
        nord_usb::block_on(d.read(class, async |s| {
            usb_op::set_lists_referencing(s, &banks, targets).await
        }))
    })
    .map_err(|e| e.to_string())
}

/// The pre-flight lines naming set lists a program move will rewrite.
fn set_list_rewrite_lines(ui: &Ui, found: &[op::Referrer]) -> Vec<String> {
    if found.is_empty() {
        return vec!["no set list references either slot".into()];
    }
    let mut lines = vec![format!(
        "the instrument will also rewrite {} set list{} that reference these slots:",
        found.len(),
        if found.len() == 1 { "" } else { "s" }
    )];
    for r in found {
        let refs: Vec<String> = r.programs.iter().map(|&l| addr(l)).collect();
        lines.push(format!(
            "  setlist {} {:?} points at {}",
            addr(r.at),
            r.name,
            refs.join(", "),
        ));
        // ⚠️ Keep the irreversible migration beside the affected set list.
        if r.version == 0 {
            lines.push(format!(
                "    {} {} the rewrite migrates it to version 1, and moving the program",
                ui.danger("VERSION 0"),
                ui.dash(),
            ));
            lines.push("    back does not migrate the set list back".into());
        }
    }
    lines
}

/// Say what a program move will do to the set lists that point at it.
fn describe_set_list_rewrites(
    ui: &Ui,
    device: &mut Device<UsbTransport>,
    targets: &[Location],
) -> Result<(), String> {
    let found = referring_set_lists(device, targets).map_err(|e| {
        format!(
            "could not read which set lists reference these slots ({e}); the move was \
             not attempted"
        )
    })?;
    for line in set_list_rewrite_lines(ui, &found) {
        ui.note(line);
    }
    Ok(())
}

/// Move an object from one slot to another. Requires confirmation: it changes both slots,
/// though an occupied destination is swapped rather than destroyed.
///
/// For programs the pre-flight also names the set lists the instrument will rewrite —
/// objects in another class, which the command line never mentions.
pub fn move_object(
    ui: &Ui,
    from: Location,
    to: Location,
    class: ObjectClass,
    confirmed: bool,
) -> Result<(), String> {
    let mut device = open_usb()?;
    let name = peek(&mut device, class, from)?;
    let dest = peek_dest(ui, &mut device, class, to, DestFate::Swapped);
    ui.note(format!(
        "moving {:?} from {} to {} {} {}",
        name,
        shown(from),
        shown(to),
        ui.dash(),
        dest
    ));
    // Only programs are referenced by slot. A set list's own move disturbs nothing that
    // points at it, and the library classes are referenced by content id, not address.
    if class == ObjectClass::Program {
        describe_set_list_rewrites(ui, &mut device, &[from, to])?;
    }
    ui.confirm(confirmed)?;
    transact(
        &mut device,
        format!("{} move {} {}", noun(class), addr(from), addr(to)),
        |d| {
            nord_usb::block_on(
                d.destructive(class, async |s| usb_op::move_object(s, from, to).await),
            )
        },
    )
    .map_err(|e| explain_pair(e, from, to))?;
    ui.note(format!("moved {} -> {}", shown(from), shown(to)));
    Ok(())
}

/// Delete one or more slots. Destructive; requires confirmation. All items run in one
/// session, exactly as NSM batches a multi-delete.
pub fn delete(
    ui: &Ui,
    slots: &[Location],
    class: ObjectClass,
    confirmed: bool,
) -> Result<(), String> {
    let mut device = open_usb()?;
    for &at in slots {
        let name = peek(&mut device, class, at)?;
        ui.note(format!(
            "{} {:?} at {}",
            ui.danger("deleting"),
            name,
            shown(at)
        ));
    }
    ui.confirm(confirmed)?;
    let addresses: Vec<String> = slots.iter().map(|&at| addr(at)).collect();
    // Each delete lands on the instrument as it is sent: a failure part-way leaves the
    // earlier ones gone, and the report has to say which.
    let mut done = 0;
    let outcome = transact(
        &mut device,
        format!("{} delete {}", noun(class), addresses.join(" ")),
        |d| {
            nord_usb::block_on(d.destructive(class, async |s| {
                for &at in slots {
                    usb_op::delete(s, at).await?;
                    done += 1;
                }
                Ok(())
            }))
        },
    );
    if let Err(e) = outcome {
        // The slot the failure was about: the first one not deleted, or — when the
        // session would not close after the last delete — that last slot.
        let at = slots[done.min(slots.len() - 1)];
        let gone: Vec<String> = slots[..done].iter().map(|&at| shown(at)).collect();
        return Err(match done {
            0 => format!("deleting {}: {}", shown(at), explain(e, at)),
            _ => format!(
                "deleting {}: {}{} already deleted ({}); {} left alone",
                shown(at),
                explain(e, at),
                done,
                gone.join(", "),
                slots.len().saturating_sub(done + 1)
            ),
        });
    }
    ui.note(format!("deleted {} item(s)", slots.len()));
    Ok(())
}

/// Rename the object in a slot. Destructive; requires confirmation.
pub fn rename(
    ui: &Ui,
    at: Location,
    name: String,
    class: ObjectClass,
    confirmed: bool,
) -> Result<(), String> {
    let mut device = open_usb()?;
    let old = peek(&mut device, class, at)?;
    ui.note(format!(
        "renaming {} from {:?} to {:?}",
        shown(at),
        old,
        name
    ));
    ui.confirm(confirmed)?;
    transact(
        &mut device,
        format!("{} rename {} {name:?}", noun(class), addr(at)),
        |d| nord_usb::block_on(d.destructive(class, async |s| usb_op::rename(s, at, &name).await)),
    )
    .map_err(|e| explain(e, at))?;
    ui.note(format!("renamed {} -> {:?}", shown(at), name));
    Ok(())
}

/// Duplicate an object into another slot (a device-internal deep copy). Destructive;
/// requires confirmation.
pub fn duplicate(
    ui: &Ui,
    from: Location,
    to: Location,
    class: ObjectClass,
    confirmed: bool,
) -> Result<(), String> {
    let mut device = open_usb()?;
    let name = peek(&mut device, class, from)?;
    let dest = peek_dest(ui, &mut device, class, to, DestFate::Overwritten);
    ui.note(format!(
        "duplicating {:?} from {} to {} {} {}",
        name,
        shown(from),
        shown(to),
        ui.dash(),
        dest
    ));
    ui.confirm(confirmed)?;
    transact(
        &mut device,
        format!("{} duplicate {} {}", noun(class), addr(from), addr(to)),
        |d| {
            nord_usb::block_on(d.destructive(class, async |s| usb_op::duplicate(s, from, to).await))
        },
    )
    .map_err(|e| explain_pair(e, from, to))?;
    ui.note(format!("duplicated {} -> {}", shown(from), shown(to)));
    Ok(())
}

/// Load an object live on the instrument (double-click in NSM). Non-destructive, so no
/// confirmation is needed.
pub fn select(ui: &Ui, at: Location, class: ObjectClass) -> Result<(), String> {
    let mut device = open_usb()?;
    transact(
        &mut device,
        format!("{} select {}", noun(class), addr(at)),
        |d| nord_usb::block_on(d.read(class, async |s| usb_op::select(s, at).await)),
    )
    .map_err(|e| explain(e, at))?;
    ui.note(format!("selected {} on the instrument", shown(at)));
    Ok(())
}

/// Thousands separators. A nine-digit byte count is otherwise counted by eye.
pub(crate) fn grouped(n: u32) -> String {
    let digits = n.to_string();
    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i).is_multiple_of(3) {
            out.push(',');
        }
        out.push(c);
    }
    out
}

/// Rounded binary size, or `None` below a kibibyte where the byte count already reads.
pub(crate) fn human_size(n: u32) -> Option<String> {
    const UNITS: [&str; 3] = ["KiB", "MiB", "GiB"];
    if n < 1024 {
        return None;
    }
    let mut value = n as f64 / 1024.0;
    let mut unit = 0;
    while value >= 1024.0 && unit + 1 < UNITS.len() {
        value /= 1024.0;
        unit += 1;
    }
    Some(format!("{value:.1} {}", UNITS[unit]))
}

/// List the piano/sample library objects an entity depends on. Read-only.
pub fn deps(ui: &Ui, at: Location, class: ObjectClass) -> Result<(), String> {
    let mut device = open_usb()?;
    let deps = transact(
        &mut device,
        format!("{} deps {}", noun(class), addr(at)),
        |d| nord_usb::block_on(d.read(class, async |s| usb_op::dependencies(s, at).await)),
    )
    .map_err(|e| explain(e, at))?;

    // Unrouted sections still report rows, but they are not live dependencies.
    let (live, idle): (Vec<_>, Vec<_>) = deps.iter().partition(|d| d.flag == 1);
    // Null ids describe unassigned routed sections, not library objects.
    let (live, unassigned): (Vec<_>, Vec<_>) = live.into_iter().partition(|d| d.is_required());

    if live.is_empty() {
        ui.note(format!("{} depends on nothing", shown(at)));
    } else {
        ui.out(ui.dim(format!("{:<8} {:<10} name", "class", "id")));
        for d in &live {
            // Library objects report no slot, so most rows carry no location at all.
            let loc = match d.location.map(shown) {
                Some(at) => format!("  {}", ui.dim(at)),
                None => String::new(),
            };
            ui.out(format!(
                "{:<8} {:<10} {}{loc}",
                d.class.label(),
                crate::summary::dep_id(d.id),
                d.name.trim_end(),
            ));
        }
    }

    if !unassigned.is_empty() {
        let which: Vec<String> = unassigned
            .iter()
            .map(|d| d.class.label().to_string())
            .collect();
        ui.note("");
        ui.note(format!("routed but nothing assigned: {}", which.join(", ")));
    }

    if !idle.is_empty() {
        ui.note("");
        ui.note(format!(
            "{} further row(s) reported but not in use — the section is not routed to a \
             keyboard part, so the instrument names an object this object does not depend on:",
            idle.len()
        ));
        for d in &idle {
            let named = if d.name.trim_end().is_empty() {
                "(no name)".to_string()
            } else {
                d.name.trim_end().to_string()
            };
            ui.note(format!(
                "  {} {} {named}",
                d.class.label(),
                crate::summary::dep_id(d.id)
            ));
        }
    }
    Ok(())
}

/// Release anything an interrupted run left open on the instrument.
pub fn recover(ui: &Ui) -> Result<(), String> {
    let mut device = open_usb()?;
    transact(&mut device, "device recover", |d| {
        nord_usb::block_on(usb_op::recover(d.transport()))
    })
    .map_err(|e| e.to_string())?;
    ui.note("released any session the instrument was still holding");
    ui.note("if slots were reading as empty, re-check them now");
    Ok(())
}

/// Report the instrument's storage layout, from the device's own tables. Read-only.
pub fn geometry(ui: &Ui) -> Result<(), String> {
    let mut device = open_usb()?;
    let geometry = read_geometry(&mut device)?;

    ui.out(ui.dim(format!(
        "{:<4} {:<18} {:>6} {:>7} {:>10}  banks",
        "code", "partition", "banks", "slots", "unit"
    )));
    for (p, banks) in geometry.entries() {
        // The sentinel is not a capacity and must not be summed into one.
        let bounded: Vec<&Bank> = banks.iter().filter(|b| b.is_bounded()).collect();
        let slots = match bounded.len() == banks.len() {
            true => bounded
                .iter()
                .map(|bank| u64::from(bank.slots))
                .sum::<u64>()
                .to_string(),
            false => "".to_string(),
        };
        let names: Vec<&str> = banks.iter().map(|b| b.name.as_str()).collect();
        // The allocation granularity is what `device status` counts in for this
        // partition: a storage block for the libraries, one byte everywhere else.
        let unit = match p.allocation_unit() {
            Ok(unit) if unit.is_bytes() => "byte".to_string(),
            Ok(unit) => format!("{} B", unit.get()),
            Err(e) => e.to_string(),
        };
        ui.out(format!(
            "{:<4} {:<18} {:>6} {:>7} {:>10}  {}",
            p.index,
            p.name,
            banks.len(),
            slots,
            unit,
            ui.dim(names.join(", ")),
        ));
    }
    ui.note("");
    ui.note("the partition index is the object class number; (Native) partitions are a");
    ui.note("second view of the same library, so their capacity is a sentinel, not a size");
    ui.note("the unit is net of the block's own overhead");
    Ok(())
}

/// Deliberately abandon an open session, wedging the instrument. Test tool.
///
/// Behind the `wedge` feature: it breaks the attached instrument on purpose.
///
/// Reproduces the half-open `HELLO` on purpose: opens a transaction and drops it without
/// the closing exchanges. The instrument then answers "empty" for every slot in every
/// class, which survives reopening.
///
/// Exists so recovery can be tested against a *known* wedge rather than one arrived at by
/// accident. Nothing stored is harmed — but until it is cleared, every reading taken from
/// the instrument is a lie, which is worse than an error.
#[cfg(feature = "wedge")]
pub fn wedge(ui: &Ui, class: ObjectClass, yes: bool) -> Result<(), String> {
    if !yes {
        return Err("refusing to wedge the instrument without --yes; \
             clear it afterwards with `nord device recover`"
            .into());
    }
    let mut device = open_usb()?;
    nord_usb::block_on(async {
        let s = Session::open(device.transport(), class).await?;
        s.abort();
        Ok::<(), nord_usb::Error>(())
    })
    .map_err(|e| e.to_string())?;

    ui.note("session abandoned with no GOODBYE — the instrument is now wedged");
    ui.note("every slot will read as empty, and read *successfully*, until you run");
    ui.note("`nord device recover`");
    Ok(())
}

/// Sweep vendor control requests on endpoint 0. Reverse-engineering tool.
///
/// Read-only, and outside the bulk protocol: no session is opened, so nothing here can
/// desync or wedge one. A request the device does not implement stalls the endpoint,
/// which arrives as an error and is reported as a dash rather than as data.
///
/// `len` is the transfer's `wLength`, which the host controller states in 16 bits.
pub fn controls(
    ui: &Ui,
    from: u8,
    to: u8,
    len: u16,
    interface: bool,
    value: u16,
    index: u16,
) -> Result<(), String> {
    if from > to {
        return Err(format!(
            "--from {from:#04x} is above --to {to:#04x}; nothing to sweep"
        ));
    }
    let mut device = open_usb()?;
    let recipient = if interface {
        nord_usb::transport::usb::Recipient::Interface
    } else {
        nord_usb::transport::usb::Recipient::Device
    };

    ui.out(ui.dim(format!("{:<9} {:>5}  {}", "bRequest", "bytes", "response")));
    let mut answered = 0;
    for request in from..=to {
        let got = device.transport().vendor_control_in(
            recipient,
            request,
            value,
            index,
            usize::from(len),
            std::time::Duration::from_millis(500),
        );
        match got {
            Ok(data) if data.is_empty() => {
                answered += 1;
                ui.out(format!(
                    "{request:#04x} ({request:>3}) {:>5}  (accepted, no data)",
                    0
                ));
            }
            Ok(data) => {
                answered += 1;
                // A sweep asks which requests answer at all; the row states the whole
                // length and shows as much of it as one line holds.
                let (hex, text) = dump(&data[..data.len().min(24)]);
                ui.out(format!(
                    "{request:#04x} ({request:>3}) {:>5}  {hex}",
                    data.len(),
                ));
                ui.out(format!("{:>16}  {}", "", ui.dim(text)));
            }
            Err(_) => ui.out(ui.dim(format!("{request:#04x} ({request:>3})     -  —"))),
        }
    }
    ui.note("");
    ui.note(format!(
        "{answered} of {} request(s) answered",
        u16::from(to) - u16::from(from) + 1
    ));
    Ok(())
}

/// Report which object the panel has loaded in this class. Read-only.
pub fn focus(ui: &Ui, class: ObjectClass) -> Result<(), String> {
    let mut device = open_usb()?;
    let (at, info) = transact(&mut device, format!("{} focus", noun(class)), |d| {
        nord_usb::block_on(d.read(class, async |s| {
            let at = usb_op::focus(s).await?;
            // An empty focused slot is possible and is not an error to report as one.
            let info = match usb_op::info(s, at).await {
                Ok(i) => Some(i),
                Err(nord_usb::Error::DeviceStatus(1)) => None,
                Err(e) => return Err(e),
            };
            Ok((at, info))
        }))
    })
    .map_err(|e| e.to_string())?;

    match info {
        Some(info) => ui.out(format!("{}  {:?}", addr(at), info.name)),
        None => ui.out(format!("{}  (empty)", addr(at))),
    }
    Ok(())
}

/// List every occupied slot in a class, with each object's name. Read-only.
///
/// One session: the cursor walk and every `info` share it, so a library of a few hundred
/// items is a few hundred exchanges rather than a few hundred sessions.
pub fn list(ui: &Ui, class: ObjectClass) -> Result<(), String> {
    let mut device = open_usb()?;
    let banks = declared_banks(&mut device, class)?;
    let rows = transact(&mut device, format!("{} walk", noun(class)), |d| {
        nord_usb::block_on(d.read(class, async |s| {
            let mut rows = Vec::new();
            for at in usb_op::occupied_slots(s, &banks).await? {
                // The cursor may return an empty starting address; status 1 is harmless.
                match usb_op::info(s, at).await {
                    Ok(info) => rows.push((at, info)),
                    Err(nord_usb::Error::DeviceStatus(1)) => {}
                    Err(e) => return Err(e),
                }
            }
            Ok(rows)
        }))
    })
    .map_err(explain_walk)?;

    if rows.is_empty() {
        ui.note(format!("no {} on the instrument", class.label()));
        return Ok(());
    }

    ui.out(ui.dim(format!(
        "{:<8} {:<6} {:>9}  name",
        "slot", "format", "bytes"
    )));
    for (at, info) in &rows {
        ui.out(format!(
            "{:<8} {:<6} {:>9}  {}",
            addr(*at),
            info.format,
            info.body_len,
            info.name.trim_end(),
        ));
    }
    ui.note("");
    ui.note(format!("{} {}", rows.len(), class.label()));
    Ok(())
}

/// Send a raw command code and print the reply verbatim. Reverse-engineering tool.
///
/// Interprets nothing: an unknown command's status word and payload are the finding, so
/// both are printed as they arrived. A device that ignores the command is reported as a
/// timeout rather than hanging the caller.
#[allow(clippy::too_many_arguments)]
pub fn probe(
    ui: &Ui,
    class: ObjectClass,
    op: u32,
    args: &[u32],
    wait: u64,
    yes: bool,
    bare: bool,
    service: u32,
    subsystem: u32,
) -> Result<(), String> {
    let mut words = Vec::with_capacity(args.len() * 4);
    for a in args {
        words.extend_from_slice(&a.to_be_bytes());
    }

    // Known wedges: no reply, and a power cycle to recover. A price, not a
    // prohibition, so `--yes` proceeds informed.
    if op == nord_usb::wire::cmd::NOTIFY_READ_WEDGE {
        ui.note(format!(
            "{op:#04x} is known to wedge the instrument (no reply, session lost, \
             power cycle to recover); nothing stored has ever been harmed by it"
        ));
    }

    // The one code that destroys data rather than costing a power cycle. The session's
    // class is what aims it, so the warning names the target it is currently pointed at.
    if op == nord_usb::wire::cmd::ERASE_ALL {
        ui.note(format!(
            "{op:#04x} is reported to erase an ENTIRE PARTITION — as aimed, all of {}. \
             Unlike the wedges this does not cost a power cycle, it costs the data; \
             restoring a library means a backup and a long upload",
            class.label()
        ));
    }

    // The general form of that warning. A code above the answering range is not a
    // spare slot: one of them starts erasing and cannot be talked out of it.
    if op > nord_usb::wire::cmd::HIGHEST_ANSWERING {
        ui.note(format!(
            "{op:#04x} is above {:#04x}, the highest command this instrument has been \
             seen to answer; codes up there are unexplored and at least one is \
             destructive",
            nord_usb::wire::cmd::HIGHEST_ANSWERING
        ));
    }

    ui.note(format!(
        "probing command {op:#04x} on {} with {} argument word(s)",
        class.label(),
        args.len()
    ));
    if !yes {
        return Err("refusing to probe without --yes".into());
    }

    if op == u32::MAX {
        return Err(format!(
            "{op:#x} has no `op + 1` reply code; the command space ends one below it"
        ));
    }

    let svc = nord_usb::Service::from_raw(service);
    let mut device = open_usb()?;

    // Bare probes bypass session machinery that may itself be refusing commands.
    if bare {
        let reply = nord_usb::block_on(async {
            let req = nord_usb::Message::new(svc, subsystem, op, words.clone());
            let t = device.transport();
            let limit = std::time::Duration::from_secs(wait);
            // ⚠️ `--bare` is the path for an instrument that is already refusing
            // commands, and a stalled bulk endpoint blocks a plain write forever: the
            // read timeout below is never reached and the caller hangs with no reason.
            if !t.write_timeout(&req.encode(), limit).await? {
                return Err(nord_usb::Error::Transport(format!(
                    "the device did not accept command {op:#04x} within {wait}s: its bulk \
                     endpoints are stalled, and a power cycle is the only way out"
                )));
            }
            match t
                .read_timeout(nord_usb::transport::READ_BUFFER, limit)
                .await?
            {
                Some(raw) => nord_usb::Message::decode_probe(&raw).map(Some),
                None => Ok(None),
            }
        })
        .map_err(|e: nord_usb::Error| e.to_string())?;

        match reply {
            Some(reply) => report_reply(ui, &reply, op),
            None => ui.out(format!("no reply within {wait}s")),
        }
        return Ok(());
    }

    let (reply, changed, close_failed) = nord_usb::block_on(async {
        let mut s = Session::open(device.transport(), class).await?;
        let r = s
            .probe(
                svc,
                subsystem,
                op,
                &words,
                std::time::Duration::from_secs(wait),
            )
            .await;
        let changed = s.instrument_changed();
        let closed = s
            .commit_with_read_limit(std::time::Duration::from_secs(wait))
            .await;
        // Preserve a probe reply even if that unknown command made the close fail.
        r.map(|reply| (reply, changed, closed.err()))
    })
    .map_err(|e| e.to_string())?;

    if changed {
        ui.note("the instrument reported a change during this session");
    }
    if let Some(e) = close_failed {
        ui.note(format!("the session would not close afterwards: {e}"));
    }

    let Some(reply) = reply else {
        ui.out(format!(
            "no reply within {wait}s — the device ignored command {op:#04x}"
        ));
        return Ok(());
    };

    report_reply(ui, &reply, op);
    Ok(())
}

/// Print a probed reply verbatim: echoed command, status, and a hex/ASCII payload dump.
///
/// Interprets nothing. On an unknown command the status is the finding, and the payload
/// of a non-zero status is uninitialised device memory rather than data — so it is shown
/// as bytes and never decoded.
fn report_reply(ui: &Ui, reply: &nord_usb::Message, op: u32) {
    // `command` is the device's own echo, not an assumption: an unknown code may not
    // answer with `op + 1`, and which code it does answer with is part of the finding.
    ui.out(format!(
        "reply command {:#04x}{}",
        reply.command,
        if reply.command == op + 1 {
            String::new()
        } else {
            format!(" (expected {:#04x} by the +1 rule)", op + 1)
        }
    ));
    match reply.status() {
        Some(0) => ui.out("status  0 (ok)".to_string()),
        Some(code) => ui.out(format!("status  {code} ({code:#x}) — not success")),
        None => ui.out("status  absent — reply too short to carry one".to_string()),
    }

    let payload = reply.payload();
    ui.out(format!("payload {} bytes", payload.len()));
    for (i, chunk) in payload.chunks(16).enumerate() {
        let (hex, text) = dump(chunk);
        ui.out(format!("  {:04x}  {hex:<47}  {text}", i * 16));
    }
}

/// Bytes as hex pairs, and the same bytes as text with everything unprintable shown
/// as `.`.
///
/// ⚠️ Both dumps read one run of bytes: a byte shown in one column and not the other
/// would have the reader lining up different data.
fn dump(bytes: &[u8]) -> (String, String) {
    let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
    let text = bytes
        .iter()
        .map(|&b| {
            if (0x20..0x7f).contains(&b) {
                b as char
            } else {
                '.'
            }
        })
        .collect();
    (hex.join(" "), text)
}

/// Report everything the instrument knows about one slot. Read-only.
///
/// This is `0x1e`: body length, format tag, version, name and CRC-32 — every field of the
/// CBIN header, which is never itself transmitted, plus the name, which no `.ne5p`/`.ne5t`
/// file stores at all.
pub fn slot_info(ui: &Ui, at: Location, class: ObjectClass) -> Result<(), String> {
    let mut device = open_usb()?;
    let info = transact(
        &mut device,
        format!("{} info {}", noun(class), addr(at)),
        |d| nord_usb::block_on(d.read(class, async |s| usb_op::info(s, at).await)),
    )
    .map_err(|e| explain(e, at))?;

    let row = |label: &str, value: String| {
        ui.out(format!("  {}{value}", ui.dim(format!("{label:<11}"))));
    };
    row("location:", shown(info.location));
    row("name:", format!("{:?}", info.name));
    row("format:", info.format.clone());
    row("version:", info.version.to_string());
    row(
        "body:",
        format!(
            "{} bytes{}",
            grouped(info.body_len),
            match human_size(info.body_len) {
                Some(h) => format!("  {}", ui.dim(format!("({h})"))),
                None => String::new(),
            }
        ),
    );
    match info.crc32 {
        // Library content (pianos, samples) reports 0xffffffff: no checksum is kept for
        // objects this large.
        Some(crc) => row("crc32:", format!("{crc:#010x}")),
        None => row(
            "crc32:",
            format!("none {}", ui.dim("(not checksummed for this class)")),
        ),
    }
    Ok(())
}

/// Read one object's bytes with no printing, for `edit`'s read-modify-write.
pub fn fetch(at: Location, class: ObjectClass) -> Result<Vec<u8>, String> {
    let mut device = open_usb()?;
    transact(
        &mut device,
        format!("{} read {}", noun(class), addr(at)),
        |d| nord_usb::block_on(d.read(class, async |s| usb_op::read_program(s, at).await)),
    )
    .map_err(|e| explain(e, at))
}

/// The intent line for a write: the file beside the script, the slot, and the two
/// `BEGIN_WRITE` arguments the file itself does not carry — the name the slot ends up
/// with, and the timestamp the device stores.
fn put_intent(class: ObjectClass, what: &str, at: Location, name: &str, stamp: u32) -> String {
    let file = Path::new(what)
        .file_name()
        .map(|f| f.to_string_lossy().into_owned())
        .unwrap_or_else(|| what.to_string());
    format!("{} put {file} {} {name:?} {stamp}", noun(class), addr(at))
}

/// The four-character format tag a body carries, where those bytes are one.
///
/// ⚠️ Read off the header rather than parsed: this has to answer for a body whose
/// checksum is bad, because that body may be a slot's last remaining copy.
fn tag(body: &[u8]) -> Option<String> {
    body.get(8..12)
        .filter(|tag| tag.iter().all(|b| b.is_ascii_alphanumeric()))
        .map(|tag| String::from_utf8_lossy(tag).into_owned())
}

/// Filename for a rescued slot: the location as the instrument labels it, and the
/// object's own format tag so the file can be handed straight back to `put`.
fn rescue_name(at: Location, backup: &[u8]) -> String {
    let format = tag(backup).unwrap_or_else(|| "bin".to_string());
    format!(
        "nord-rescued-{}-{}.{format}",
        at.user_bank(),
        at.user_slot()
    )
}

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

    #[test]
    fn replacement_refuses_unusable_geometry_before_deleting() {
        use nord_usb::transport::{Direction, ReplayTransport, Script};
        use nord_usb::wire::{cmd, Message, Partition, Service};

        let script = Script::parse(include_str!(
            "../../nord-usb/tests/scripts/device/geometry.script"
        ))
        .unwrap();
        for class in [ObjectClass::Program, ObjectClass::Unknown(9)] {
            let mut steps = script.steps();
            for step in &mut steps {
                if step.direction != Direction::In {
                    continue;
                }
                let mut reply = Message::decode_response(&step.bytes).unwrap();
                if reply.service != Service::Program || reply.command != cmd::PARTITIONS + 1 {
                    continue;
                }
                let partitions = Partition::decode_all(&reply).unwrap();
                reply.args = vec![0, 0, 0, 0, partitions.len() as u8];
                for mut partition in partitions {
                    if partition.index == ObjectClass::Program.to_raw() {
                        partition.fields[..4].fill(0);
                    }
                    reply
                        .args
                        .extend_from_slice(&(partition.name.len() as u32).to_be_bytes());
                    reply.args.extend_from_slice(partition.name.as_bytes());
                    reply.args.extend_from_slice(&partition.fields);
                }
                step.bytes = reply.encode();
            }
            let mut device = Device::new(ReplayTransport::new(steps));
            nord_usb::block_on(async {
                device
                    .geometry()
                    .await
                    .expect("the tables themselves are readable");
                let error =
                    delete_for_replacement(&mut device, class, Location { bank: 0, slot: 0 })
                        .await
                        .expect_err("an unusable write allocation must leave the occupant alone");
                assert!(
                    matches!(error, nord_usb::Error::InvalidArgument(_)),
                    "{class:?}: {error}"
                );
            });
            assert!(
                device.transport().is_exhausted(),
                "{class:?}: the geometry session must close"
            );
        }
    }

    /// A control transfer's `wLength` is 16 bits, and the sweep allocates the buffer
    /// before the request goes out, so a wider count is refused at the flag.
    #[test]
    fn a_control_sweep_cannot_ask_for_more_bytes_than_a_transfer_carries() {
        let sweep = |len: &str| {
            crate::Cli::try_parse_from(["nord", "device", "controls", "--len", len]).is_ok()
        };
        assert!(sweep("65535"));
        assert!(!sweep("65536"));
        assert!(!sweep("4294967296"));
    }

    /// The rescue file is the last copy of a program that no longer exists on the
    /// instrument, so it has to be named something a person can act on.
    #[test]
    fn a_rescued_slot_is_named_for_its_location_and_format() {
        // A minimal CBIN: magic, header type, tag. The checksum is deliberately left
        // wrong — naming must not depend on the backup being intact.
        let mut file = vec![0u8; 45];
        file[0..4].copy_from_slice(b"CBIN");
        file[4..8].copy_from_slice(&1u32.to_le_bytes());
        file[8..12].copy_from_slice(b"ne5p");
        let at = Location { bank: 6, slot: 49 };
        // Wire is zero-indexed, the instrument's labels are not.
        assert_eq!(rescue_name(at, &file), "nord-rescued-7-50.ne5p");
    }

    #[test]
    fn a_move_preflight_names_each_set_list_and_what_it_points_at() {
        let ui = Ui::new(crate::ui::ColorChoice::Never);
        let lines = set_list_rewrite_lines(
            &ui,
            &[
                op::Referrer {
                    at: Location { bank: 0, slot: 42 },
                    name: "Factory Set".into(),
                    version: 1,
                    programs: vec![Location { bank: 0, slot: 6 }],
                },
                op::Referrer {
                    at: Location { bank: 1, slot: 6 },
                    name: "Friday".into(),
                    version: 1,
                    programs: vec![Location { bank: 0, slot: 6 }, Location { bank: 6, slot: 9 }],
                },
            ],
        );
        assert_eq!(lines.len(), 3);
        assert!(lines[0].contains("2 set lists"), "{}", lines[0]);
        assert!(
            lines[1].contains("setlist 1:43 \"Factory Set\""),
            "{}",
            lines[1]
        );
        assert!(lines[1].contains("points at 1:7"), "{}", lines[1]);
        assert!(lines[2].contains("points at 1:7, 7:10"), "{}", lines[2]);
        assert!(!lines.iter().any(|l| l.contains("VERSION 0")));
    }

    #[test]
    fn a_version_zero_set_list_says_the_rewrite_cannot_be_undone() {
        let ui = Ui::new(crate::ui::ColorChoice::Never);
        let lines = set_list_rewrite_lines(
            &ui,
            &[op::Referrer {
                at: Location { bank: 0, slot: 42 },
                name: "Factory Set".into(),
                version: 0,
                programs: vec![Location { bank: 0, slot: 6 }],
            }],
        );
        assert_eq!(lines.len(), 4);
        assert!(lines[0].contains("1 set list "), "{}", lines[0]);
        assert!(
            lines[1].contains("setlist 1:43 \"Factory Set\""),
            "{}",
            lines[1]
        );
        assert!(lines[2].contains("VERSION 0"), "{}", lines[2]);
        assert!(
            lines[2].contains("migrates it to version 1"),
            "{}",
            lines[2]
        );
        assert!(
            lines[3].contains("does not migrate the set list back"),
            "{}",
            lines[3]
        );
    }

    #[test]
    fn no_referrer_is_stated_rather_than_left_silent() {
        let ui = Ui::new(crate::ui::ColorChoice::Never);
        assert_eq!(
            set_list_rewrite_lines(&ui, &[]),
            vec!["no set list references either slot".to_string()]
        );
    }

    #[test]
    fn a_failed_write_says_what_it_left_in_the_slot() {
        let at = Location { bank: 0, slot: 1 };
        assert_eq!(
            aftermath(ObjectClass::Program, at),
            "bank 1 slot 2 is empty"
        );
        assert_eq!(
            aftermath(ObjectClass::Live, at),
            "bank 1 slot 2 may hold a partly written body"
        );
        assert_eq!(
            aftermath(ObjectClass::Settings, at),
            "bank 1 slot 2 may hold a partly written body"
        );
    }

    /// ⚠️ A refusal is a file another family carries the tag of, and nothing else: the
    /// instrument would take the write and store something it cannot play. Both models
    /// are named, because which of the two is wrong is the operator's to decide.
    #[test]
    fn a_write_of_another_familys_file_is_refused_and_names_both() {
        let refused = admit(Some("Nord Electro 5D"), ObjectClass::Program, "ns4p");
        let Admit::Refuse(why) = refused else {
            panic!("{refused:?}");
        };
        assert!(why.contains("Stage 4"), "{why}");
        assert!(why.contains("Nord Electro 5D"), "{why}");
    }

    /// ⚠️ Everything short of another family's tag warns and writes. An unmeasured
    /// combination is not a wrong one, and a table that refused those would stand in
    /// the way of the measurement.
    #[test]
    fn only_a_measured_write_is_silent_and_the_rest_warns() {
        let warning = |product, class, tag| match admit(product, class, tag) {
            Admit::Warn(why) => why,
            other => panic!("{other:?}"),
        };

        assert_eq!(
            admit(Some("Nord Electro 5D"), ObjectClass::Program, "ne5p"),
            Admit::Takes,
            "a row written and read back says nothing"
        );

        let untried = warning(Some("Nord Stage 2 EX"), ObjectClass::Program, "ns2p");
        assert!(untried.contains("untried"), "{untried}");

        let unnamed = warning(Some("Nord Modular G2"), ObjectClass::Program, "ne5p");
        assert!(unnamed.contains("not in the acceptance table"), "{unnamed}");

        // A shared library format is nobody's own, so the table says nothing about it.
        let shared = warning(Some("Nord Electro 5D"), ObjectClass::Program, "npno");
        assert!(shared.contains("npno"), "{shared}");

        let silent = warning(None, ObjectClass::Program, "ne5p");
        assert!(silent.contains("no product string"), "{silent}");
    }

    /// A set list must not land with a program's extension.
    #[test]
    fn the_format_tag_comes_from_the_bytes() {
        let mut file = vec![0u8; 45];
        file[8..12].copy_from_slice(b"ne5t");
        let at = Location { bank: 0, slot: 3 };
        assert_eq!(rescue_name(at, &file), "nord-rescued-1-4.ne5t");
    }

    /// Bytes that do not parse are still the only copy, so they must still get a name.
    #[test]
    fn unparseable_bytes_still_get_rescued() {
        let at = Location { bank: 0, slot: 0 };
        assert_eq!(rescue_name(at, b"nonsense"), "nord-rescued-1-1.bin");
    }

    /// The write path driven by the recorded `nord program put`, with one step of it
    /// made to fail.
    ///
    /// Between the backup read and the write the slot is genuinely empty and this
    /// process holds the only copy of what was in it, so what `send` does with that copy
    /// is the whole difference between a failed write and a lost program.
    mod losing_the_occupant {
        use super::*;
        use nord_usb::transport::{Direction, ReplayTransport, Script, Step};
        use nord_usb::wire::Message;

        const PUT: &str =
            include_str!("../../nord-usb/tests/scripts/program/put_7-10_overwrite.script");
        const FILE: &[u8] = include_bytes!("../../nord-usb/tests/scripts/program/prog_8-14.ne5p");
        const GEOMETRY: &str = include_str!("../../nord-usb/tests/scripts/device/geometry.script");
        const AT: Location = Location { bank: 6, slot: 9 };
        const NAME: &str = "prog-8-14";
        const STAMP: u32 = 0x6a89_f433;

        /// The recorded transactions a put runs through: check-address, info, read,
        /// geometry, delete, write.
        ///
        /// ⚠️ The geometry read is spliced in from its own recording. The put was
        /// captured against a build that already held the partition table, so the
        /// capture has no frames for the transaction this one opens before deleting.
        fn recorded() -> Vec<Vec<Step>> {
            let steps = |text| {
                Script::parse(text)
                    .expect("a recorded exchange parses")
                    .sections
                    .into_iter()
                    .map(|section| section.steps)
                    .filter(|steps: &Vec<Step>| !steps.is_empty())
                    .collect::<Vec<_>>()
            };
            let mut out = steps(PUT);
            out.splice(3..3, steps(GEOMETRY));
            out
        }

        /// The write transaction with its `BEGIN_WRITE` answered by `status`, and the
        /// data frames it would have carried dropped: a refusal leaves the session in
        /// step, so the client closes it and sends nothing else.
        fn refused_write(steps: &[Step], status: u32) -> Vec<Step> {
            let mut refusal = Message::decode_response(&steps[6].bytes).expect("the reply");
            refusal.args[..4].copy_from_slice(&status.to_be_bytes());
            let mut out = steps[..6].to_vec();
            out.push(Step {
                direction: Direction::In,
                bytes: refusal.encode(),
            });
            out.extend_from_slice(&steps[12..]);
            out
        }

        fn send_over(steps: Vec<Step>, spill_into: &Path) -> Result<(), String> {
            let mut device = Device::new(ReplayTransport::new(steps));
            send_with(
                &Ui::piped(),
                &mut device,
                spill_into,
                FILE,
                AT,
                ObjectClass::Program,
                true,
                "prog_8-14.ne5p",
                Some(NAME),
                Some(STAMP),
            )
        }

        fn rescued(dir: &Path) -> Vec<String> {
            std::fs::read_dir(dir)
                .unwrap()
                .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
                .collect()
        }

        /// A refused write puts the occupant back, and the refusal reaches the operator
        /// as what the status means rather than as its number.
        #[test]
        fn a_refused_write_restores_the_occupant() {
            let dir = crate::edit::tests::scratch("send-restored");
            let put = recorded();
            let mut steps: Vec<Step> = put[..5].concat();
            steps.extend(refused_write(&put[5], 4));
            steps.extend(put[5].clone());

            let err = send_over(steps, &dir).unwrap_err();
            assert!(err.contains("is occupied"), "{err}");
            assert!(err.contains("was restored, and is unchanged"), "{err}");
            assert_eq!(rescued(&dir), Vec::<String>::new());
        }

        /// Nothing is left holding the program once the restore is refused too, so it
        /// has to reach the disk before the process exits.
        #[test]
        fn a_refused_restore_leaves_the_occupant_on_disk() {
            let dir = crate::edit::tests::scratch("send-rescued");
            let put = recorded();
            let refused = refused_write(&put[5], 4);
            let mut steps: Vec<Step> = put[..5].concat();
            steps.extend(refused.clone());
            steps.extend(refused);

            let err = send_over(steps, &dir).unwrap_err();
            assert!(err.contains("restoring failed as well"), "{err}");
            assert!(err.contains("were saved to"), "{err}");
            assert_eq!(rescued(&dir), ["nord-rescued-7-10.ne5p"]);
            // The error tells the operator to hand it back to `nord put`, which reads it
            // exactly this way before touching the instrument.
            let saved = std::fs::read(dir.join("nord-rescued-7-10.ne5p")).unwrap();
            assert!(nord_usb::envelope::unwrap(&saved).is_ok());
        }

        /// ⚠️ A delete step that fails after the `DELETE` landed leaves the slot empty
        /// just as surely as a failed write does, so the backup has to be spilled there
        /// too — the restore path is never reached, because no write was attempted.
        #[test]
        fn a_delete_that_fails_after_it_landed_spills_the_occupant() {
            let dir = crate::edit::tests::scratch("send-delete-fails");
            let put = recorded();
            // Through the DELETE's own reply, and nothing for the close to read.
            let mut steps: Vec<Step> = put[..4].concat();
            steps.extend_from_slice(&put[4][..7]);

            let err = send_over(steps, &dir).unwrap_err();
            assert!(err.contains("may have been deleted"), "{err}");
            assert!(err.contains("were saved to"), "{err}");
            assert_eq!(rescued(&dir), ["nord-rescued-7-10.ne5p"]);
        }

        /// A status from the delete step is the instrument declining before the `DELETE`
        /// landed: the occupant is still in the slot, and spilling a copy beside the
        /// operator would invite them to put back what never left.
        #[test]
        fn a_refused_delete_leaves_the_occupant_where_it_is() {
            let dir = crate::edit::tests::scratch("send-delete-refused");
            let put = recorded();
            let mut delete = put[4][..7].to_vec();
            let mut refusal = Message::decode_response(&delete[6].bytes).expect("the reply");
            refusal.args[..4].copy_from_slice(&3u32.to_be_bytes());
            delete[6].bytes = refusal.encode();
            delete.extend_from_slice(&put[4][7..]);
            let mut steps: Vec<Step> = put[..4].concat();
            steps.extend(delete);

            let err = send_over(steps, &dir).unwrap_err();
            assert!(err.contains("out of range"), "{err}");
            assert!(!err.contains("saved to"), "{err}");
            assert_eq!(rescued(&dir), Vec::<String>::new());
        }
    }

    /// The answer is the only description the corpus will ever have of these bytes, so it
    /// survives into the filename rather than being reduced to something opaque.
    #[test]
    fn a_swept_capture_keeps_the_words_it_was_described_with() {
        assert_eq!(stem("split point C4").unwrap(), "split-point-C4");
        assert_eq!(stem("  transpose +1  ").unwrap(), "transpose-+1");
        assert_eq!(stem("organ vol 5 -> 6").unwrap(), "organ-vol-5-6");
    }

    /// The stem is joined to the output directory, so nothing in it may climb out.
    #[test]
    fn a_swept_name_cannot_leave_the_output_directory() {
        assert_eq!(stem("../../etc/passwd").unwrap(), "etc-passwd");
        assert_eq!(stem("rotary:fast").unwrap(), "rotary-fast");
        assert_eq!(stem(".hidden").unwrap(), "hidden");
    }

    /// Rejected, not silently turned into some default — an unnamed capture in a sweep is
    /// indistinguishable from the ones around it.
    #[test]
    fn an_answer_with_no_filename_in_it_is_refused() {
        for bad in ["...", "/", "  ", "?*", "-", "CON", "lpt1.txt"] {
            assert!(stem(bad).is_err(), "{bad:?}");
        }
    }
}