jumperless-mcp 0.1.0

MCP server for the Jumperless V5 — persistent USB-serial bridge exposing the firmware API to LLMs
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
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
//! Resident library installation protocol for Jumperless MCP.
//!
//! On each connect, the MCP server checks whether the device has the
//! current library installed at `/python_scripts/lib/jumperless_mcp/`.
//! If missing or outdated, it writes the embedded library files to the
//! device. Subsequent ceremony invocations use:
//!   `import jumperless_mcp; jumperless_mcp._ceremony_connect()`
//! which runs entirely on the device via standard MicroPython `import`.
//!
//! The library version follows SemVer 2.0 with build-metadata-as-date:
//! `0.2.0+20260510`. Bumping the version triggers reinstall on next
//! connect.

use std::io::{Read, Write};

use crate::base::McpError;
use crate::repl;

/// Library version — SemVer 2.0 compliant. Build metadata after `+` is
/// the install-date, useful for trace correlation.
///
/// Bumped to 0.2.0 for the Phase A+B+C rewrite: package layout migration
/// to `/python_scripts/lib/jumperless_mcp/` + ceremony-via-import.
/// Bumped to 0.2.1 for ceremony correctness fixes: disconnect now force-saves
/// the cleared overlay state (defeats autosave race causing bracket persistence
/// across reboot), and marquee renders text in natural L→R order regardless
/// of sweep direction.
/// Bumped to 0.2.2 for marquee UX polish: L2R sweep now reverses word order so
/// the first word of the input enters the visible area first (word-entry order
/// matches direction of travel); marquee() switched from fill-then-carve to
/// pre-compute-then-paint (collects letter pixel set before any overlay_set_pixel
/// calls) eliminating the one-frame solid-banner flicker on continuous LED render.
/// Bumped to 0.2.3 reverting v0.2.2 pre-compute: MicroPython set-lookup at 300+
/// checks/frame was slower than the LED render cadence, producing MORE flicker
/// and pushing the marquee past the 10s ceremony timeout. Reverted to fill-then-
/// carve; atomic-frame via pause_core2 is the future path (deferred). Also
/// removed wipe_edges + 800ms hold preamble from _ceremony_connect — the marquee
/// IS the banner; the two-step preamble read as disjointed visual events.
/// Bumped to 0.2.4 for the bracket-unbracket disconnect strategy (Sam's insight):
/// instead of fighting Kevin's autosave with overlay_clear_all + nodes_save (never
/// worked), the disconnect ceremony now paints `corner_frame(0x000000)` — same
/// pixels, black color. Autosave still does its job (preserve overlay state);
/// the saved state IS visually empty. Disconnect ceremony also made symmetric
/// with connect (wipe_edges + sleep removed for matching shape).
/// Bumped to 0.2.5 for atomic-frame rendering via `pause_core2`. Each frame's
/// clear+paint in `marquee_scroll` is now wrapped in `pause_core2(True/False)`
/// so core 2 (LED-refresh core) cannot observe intermediate "all-cleared" or
/// "fully-filled-banner-without-carved-letters" states. Also wraps `corner_frame`
/// and per-frame paints in `wipe_edges`. Eliminates the visible tear + 1-frame
/// blink that produced the v0.2.4 flicker. Live-verified after firmware-source
/// dive + 4-corner pixel probe that pinned the compiled coord system
/// (first-arg=horizontal-col 1-30, second-arg=vertical-hole 1-10) — source
/// comments were stale; see project_jumperless_atomic_frame_pattern.md.
/// Bumped to 0.2.6 for bulk-write marquee via `overlay_set`. BROKEN: had
/// wrong colors-array layout (assumed colors[(x-1)*10+y_idx] but actual
/// firmware layout is row-major colors[(y-1)*30+(x-1)] — see modjumperless.c
/// binding-arg-swap at lines 5695-5698, found by firmware-source review).
/// Symptom: marquee scrolled VERTICALLY + TypeError on long sweeps (memory
/// pressure from per-frame 300-element list allocation).
/// Bumped to 0.2.7: bulk-write marquee with CORRECT row-major layout
/// (colors[(y-1)*30 + (x-1)], width=30, height=10 — full board in one call,
/// no wrap). Colors buffer pre-allocated once per marquee_scroll and mutated
/// in place per frame (eliminates 100x per-ceremony allocations). Per-frame
/// paint cost: ~3-6ms. Single markDirty per frame so autosave debounce stays
/// settled. Verified via firmware-source scout citing modjumperless.c:5695-5698.
/// Bumped to 0.2.8: force-render-black (0x010101) for non-banner pixels.
/// v0.2.7 was missing letter cutouts because the renderer at
/// `GraphicOverlays.cpp:319` skips color==0 pixels (transparent). With the
/// overlay persisting across frames, transparent pixels kept their previous
/// LED-buffer value, leaving banner trails that filled the whole board over
/// the sweep. Painting non-banner pixels with 0x010101 (perceptually black
/// at WS2812's 1/255 floor) forces the renderer to paint over the trail.
/// Bumped to 0.2.9: slice-assign reset from pre-built _BLACK_TEMPLATE
/// (C-level memcpy) instead of `for i in range(300): colors[i] = FORCE_BLACK`
/// (Python loop). Measured 145x faster: 100us vs 15ms per 300-element pass.
/// v0.2.8 paint cost was ~11ms/frame (dominated by the Python-loop pre-fill);
/// v0.2.9 paint cost should drop to ~3-5ms/frame, finally making bulk-write
/// faster than v0.2.5's per-pixel approach in practice (not just in theory).
/// Bumped to 0.2.10: replace FORCE_BLACK (0x010101) with TRUE transparent (0)
/// for non-banner pixels + add `overlay_clear("_MARQUEE_")` before each frame's
/// `overlay_set`. Matches v0.2.5's pattern (overlay removal + recreation)
/// scoped to just _MARQUEE_ overlay. Eliminates the perceptible 1/255-white
/// tint at non-banner positions — letters and gaps now appear TRUE black
/// (showing the underlying unlit-LED state through the renderer's skip-zero
/// transparency). Trade-off: 2 markDirty per frame (overlay_clear adds one)
/// vs v0.2.9's 1. Author's design intuition: bulk-write the banner, "carve
/// letters off-style" via transparent pixels, accept the markDirty cost.
/// Bumped to 0.2.11: Python-work optimizations in _fill_marquee_frame.
/// (1) Banner fill uses per-row C-level slice-assign (10 slice-assigns vs
/// up to 300 Python list-element writes). (2) Letter carving iterates a
/// pre-computed `_FONT_CARVE` table (only the LIT pixels per glyph) instead
/// of the 3×5 bit-check loop. Expected paint cost drop from ~10ms to ~3-5ms
/// per frame. No firmware/coord changes — purely a Python-side speedup.
/// Bumped to 0.2.12: minimalist positive-space marquee. Replaces the
/// negative-space "banner with carved letters" approach with a positive-space
/// renderer (_build_minimalist_frame) that paints ONLY letter glyph pixels
/// (in `color`, additive via _FONT_CARVE) + two 3-pixel direction-of-travel
/// chevrons (quarter-brightness: `(color >> 2) & 0x3F3F3F`). All other
/// pixels stay transparent (0). The overlay_clear + overlay_set per-frame
/// pattern from v0.2.10/0.2.11 is preserved — fresh overlay each frame,
/// no trails. _fill_marquee_frame retained for historical reference;
/// marquee_scroll now delegates to _build_minimalist_frame.
pub const LIBRARY_VERSION: &str = "0.2.12+20260512";

/// Source for `font.py` — embedded at compile time. Written to [`FONT_PATH`] during install.
pub const FONT_PY: &str = include_str!("../python/font.py");
/// Source for `effects.py` — embedded at compile time. Written to [`EFFECTS_PATH`] during install.
pub const EFFECTS_PY: &str = include_str!("../python/effects.py");
/// Source for `__init__.py` — embedded at compile time. Written to [`INIT_PATH`] during install.
pub const INIT_PY: &str = include_str!("../python/__init__.py");

/// Library install root on device.
/// Lives under /python_scripts/lib/ which is on sys.path at firmware init
/// (confirmed Python_Proper.cpp:4706). `import jumperless_mcp` resolves here.
pub const LIBRARY_ROOT: &str = "/python_scripts/lib/jumperless_mcp/";
/// Parent of `LIBRARY_ROOT`; on `sys.path` at firmware init.
pub const PYTHON_SCRIPTS_LIB: &str = "/python_scripts/lib/";
/// Grandparent directory; created first if absent during install.
pub const PYTHON_SCRIPTS: &str = "/python_scripts/";
/// Device path for the installed version sentinel file.
pub const VERSION_PATH: &str = "/python_scripts/lib/jumperless_mcp/VERSION";
/// Device path for the installed font module.
pub const FONT_PATH: &str = "/python_scripts/lib/jumperless_mcp/font.py";
/// Device path for the installed effects module.
pub const EFFECTS_PATH: &str = "/python_scripts/lib/jumperless_mcp/effects.py";
/// Device path for the installed package init module.
pub const INIT_PATH: &str = "/python_scripts/lib/jumperless_mcp/__init__.py";

// ── Compile-time invariant checks ─────────────────────────────────────────────

// HIGH-2: triple-quote invariant enforced at compile time for both library files
// so the release-mode safety gap (debug_assert compiles out) is closed entirely.
// A library file containing ''' would corrupt the python_repr output.
const _: () = {
    let bytes = FONT_PY.as_bytes();
    let needle = b"'''";
    let mut i = 0;
    while i + 3 <= bytes.len() {
        assert!(
            !(bytes[i] == needle[0] && bytes[i + 1] == needle[1] && bytes[i + 2] == needle[2]),
            "FONT_PY must not contain triple-single-quotes (would corrupt python_repr output)"
        );
        i += 1;
    }
};

const _: () = {
    let bytes = EFFECTS_PY.as_bytes();
    let needle = b"'''";
    let mut i = 0;
    while i + 3 <= bytes.len() {
        assert!(
            !(bytes[i] == needle[0] && bytes[i + 1] == needle[1] && bytes[i + 2] == needle[2]),
            "EFFECTS_PY must not contain triple-single-quotes (would corrupt python_repr output)"
        );
        i += 1;
    }
};

const _: () = {
    let bytes = INIT_PY.as_bytes();
    let needle = b"'''";
    let mut i = 0;
    while i + 3 <= bytes.len() {
        assert!(
            !(bytes[i] == needle[0] && bytes[i + 1] == needle[1] && bytes[i + 2] == needle[2]),
            "INIT_PY must not contain triple-single-quotes (would corrupt python_repr output)"
        );
        i += 1;
    }
};

// MEDIUM-H: LIBRARY_VERSION must not contain whitespace. A stray space or
// newline (e.g. from a build-system injection) would cause read_installed_version
// to strip it, making up_to_date always false → reinstall every connect.
const _: () = {
    let bytes = LIBRARY_VERSION.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        assert!(
            b != b' ' && b != b'\t' && b != b'\n' && b != b'\r',
            "LIBRARY_VERSION must not contain whitespace (causes spurious version mismatch)"
        );
        i += 1;
    }
};

// MEDIUM-J: LIBRARY_VERSION must contain '+' (SemVer 2.0 build metadata).
// A version without '+' would cause the build-date tracing to be meaningless
// and also indicates someone accidentally dropped the build metadata suffix.
const _: () = {
    let b = LIBRARY_VERSION.as_bytes();
    let mut has_plus = false;
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'+' {
            has_plus = true;
        }
        i += 1;
    }
    assert!(
        has_plus,
        "LIBRARY_VERSION must include SemVer 2.0 +build metadata (e.g., 0.1.0+20260510)"
    );
};

/// Approximate library footprint on device (informational; for README docs).
#[allow(dead_code)]
pub const LIBRARY_SIZE_BYTES_APPROX: usize =
    FONT_PY.len() + EFFECTS_PY.len() + INIT_PY.len() + LIBRARY_VERSION.len();

/// Per-operation timeout for library file operations (verify, dump, read_installed_version,
/// fs_write_chunked). V5 firmware 5.6.6.2 can take >10 s on the FIRST operation after USB
/// reconnect due to cold filesystem init (flash block-table rebuild). 30 s gives generous
/// headroom while still failing within a reasonable window if something is genuinely wrong.
///
/// **Do not change the global repl timeout.** Library ops are the only known hot-path that
/// needs extra time on cold FS; other exec_code users (ceremony, ping) are unaffected.
pub const LIBRARY_FILE_OP_TIMEOUT_MS: u64 = 30_000;

/// Maximum bytes passed as the size argument to `jumperless.jfs.read(f, size)`.
///
/// Why 8192:
/// - Matches the actual per-call cap in `jfs_file_read` (firmware
///   `modjumperless.c:4274-4277`, confirmed by OS-integration audit 2026-05-10).
/// - Covers all our library files with headroom (largest is effects.py ~6 KB).
/// - 64 KB was tried first and triggered `OSError: [Errno 12] ENOMEM` live on the
///   V5 — 64 KB allocation exceeds what MicroPython's ~128 KB heap can satisfy
///   contiguously with other allocations in flight. 8192 allocates reliably AND
///   matches the firmware's actual per-call read cap (passing larger values is
///   pointless — the binding doesn't return more than 8192 per call).
/// - `jfs.read(f)` with NO size arg uses `jl_fs_available()` internally which
///   returns a misleading value (live-observed: ~1022 bytes returned for a 5 KB
///   file). ALWAYS pass an explicit size.
///
/// If a library file ever grows beyond 8192 bytes, switch to chunked reads:
/// loop calling `jfs.read(f, 8192)` until a short return signals EOF, then
/// concatenate on the host side. Don't bump this constant past 8192.
pub const JFS_READ_MAX_BYTES: usize = 8192;

/// Maximum bytes per exec_code call for chunked writes.
///
/// Must fit comfortably within MicroPython's REPL input buffer (typically
/// 1024-4096 bytes on embedded targets). Set conservatively at 768 to leave
/// headroom for the per-chunk Python wrapper overhead:
///
/// - Init:   `_ygg_assembly = '''<chunk>'''` = 19 + CHUNK_SIZE + 3 = 22 + CHUNK_SIZE bytes
/// - Append: `_ygg_assembly = _ygg_assembly + '''<chunk>'''` = 35 + CHUNK_SIZE + 3 = 38 + CHUNK_SIZE bytes
///
/// At CHUNK_SIZE=768 the largest payload (append) is ~806 bytes — well within a
/// 1024-byte REPL buffer with margin. At CHUNK_SIZE=1024 the append payload is
/// ~1062 bytes, which overflows tight 1024-byte REPL buffers on some V5
/// firmware variants.
///
/// Live-observed during Phase 0b.5 Stage 1.B.4 (2026-05-10): silenced
/// device-side MemoryError mid-concat produced a corrupt file; CHUNK_SIZE
/// overflow was the proximate cause that drove MicroPython past its
/// string-concat budget.
const CHUNK_SIZE: usize = 768;

// HIGH-2: compile-time assertion that CHUNK_SIZE + max wrapper overhead + safety margin
// fits in a 1024-byte REPL buffer. Catches any future CHUNK_SIZE increase that would
// overflow before it reaches hardware.
const _: () = {
    let init_overhead = "_ygg_assembly = '''".len() + "'''".len(); // 19+3 = 22
    let append_overhead = "_ygg_assembly = _ygg_assembly + '''".len() + "'''".len(); // 35+3 = 38
    let max_overhead = if append_overhead > init_overhead {
        append_overhead
    } else {
        init_overhead
    };
    assert!(
        CHUNK_SIZE + max_overhead + 8 <= 1024,
        "CHUNK_SIZE + max wrapper overhead + 8-byte safety margin must fit in 1024-byte REPL buffer"
    );
};

/// Result of `check_installation`.
#[derive(Debug, Clone)]
pub struct InstallationStatus {
    /// True when ALL three library files are present AND a version is readable.
    /// A partial install (some files present, some missing) yields `installed=false`.
    pub installed: bool,
    /// True when at least one file is present but at least one is missing.
    /// Callers can use this to distinguish "never installed" from "interrupted install".
    pub partial: bool,
    /// Version string read from the device's `VERSION` file, or `None` if unreadable.
    pub installed_version: Option<String>,
    /// Version embedded in this binary (`LIBRARY_VERSION`).
    pub current_version: &'static str,
    /// True when `installed_version == current_version` (trimmed comparison).
    pub up_to_date: bool,
    /// Device paths of the library files that are present.
    pub files_present: Vec<&'static str>,
    /// Device paths of the library files that are absent.
    pub files_missing: Vec<&'static str>,
}

/// Structured result returned by `uninstall`.
///
/// `jfs.remove` is confirmed bound on V5 firmware (modjumperless.c:4763-4771,
/// audit 2026-05-10), so physical removal is always attempted. The old
/// `fs_remove_unbound` fallback and VERSION-clearing workaround have been
/// removed.
#[derive(Debug, Clone)]
pub struct UninstallResult {
    /// Number of files targeted for removal (length of the known-paths list).
    pub attempted: usize,
    /// Number of remove operations actually sent to the device (may be < `attempted`
    /// if the loop exits early due to a fatal error).
    pub attempted_actual: usize,
    /// Number of files successfully removed (or already absent).
    pub removed: usize,
    /// Per-file error messages for non-OSError failures (unexpected exceptions).
    pub errors: Vec<String>,
}

// ── Chunking helper ────────────────────────────────────────────────────────────

/// Split `s` into chunks whose byte length is at most `target_size`.
///
/// All split points fall on UTF-8 character boundaries. For ASCII content
/// (which all our Python library files are), this is equivalent to
/// `s.as_bytes().chunks(target_size)` but is safe for any UTF-8 string.
///
/// **Quote-boundary safety:** Each chunk is wrapped on the device side as
/// `'''<chunk>'''`. If a chunk ends with `'` or `\`, the boundary collides
/// with the wrapper:
///   - chunk ending `...x'` + wrapper `'''` = `...x''''` (4 apostrophes →
///     ambiguous parse, MicroPython raises SyntaxError)
///   - chunk ending `...x\` + wrapper `'''` = `...x\'''` (backslash escapes
///     the first closing quote → string never closes, SyntaxError)
///
/// To prevent this, we back off the chunk boundary by up to `MAX_BACKOFF`
/// chars until the chunk's last byte is neither `'` nor `\`. The backed-off
/// chars become the start of the next chunk. In the pathological case where
/// the trailing run exceeds MAX_BACKOFF, we accept the unsafe boundary —
/// but for our Python library files (no runs of >8 apostrophes/backslashes
/// at chunk boundaries) this is effectively unreachable.
///
/// **Origin:** 2026-05-10. Live install of v0.2.2 effects.py failed at
/// chunk 9 because the chunk boundary landed mid-"ceremony's" → trailing `'`
/// produced `''''` SyntaxError. Filed as `feedback_chunk_boundary_quote_collision.md`.
fn chunk_at_char_boundaries(s: &str, target_size: usize) -> Vec<&str> {
    if s.is_empty() {
        return vec![];
    }
    let mut chunks = Vec::new();
    let mut start = 0;

    while start < s.len() {
        // Walk forward until we've accumulated at least target_size bytes
        // OR we've reached the end. We track the last valid char boundary
        // that keeps the chunk within target_size.
        let remaining = &s[start..];
        if remaining.len() <= target_size {
            // Everything left fits in one chunk.
            chunks.push(remaining);
            break;
        }

        // Find the largest prefix whose byte length is <= target_size.
        // char_indices yields (byte_offset, char) where byte_offset is the
        // byte position of the char within `remaining`. We include a char only
        // if its LAST byte still fits within target_size, i.e.
        // byte_offset + ch.len_utf8() <= target_size.
        let mut end = start;
        for (byte_offset, ch) in remaining.char_indices() {
            let char_end = byte_offset + ch.len_utf8();
            if char_end > target_size {
                // Including this char would exceed the limit — stop here.
                break;
            }
            end = start + char_end;
        }

        // Sanity: if end == start we have a single char longer than target_size
        // (pathological multi-byte edge). Advance by one char to avoid infinite loop.
        if end == start {
            let ch = remaining.chars().next().unwrap();
            end = start + ch.len_utf8();
        }

        // Quote-boundary safety: back off if the chunk would end with `'` or `\`,
        // since both collide with the device-side `'''<chunk>'''` wrapper.
        // See function docstring for the collision math.
        const MAX_BACKOFF: usize = 8;
        let mut backoff = 0;
        while end > start && backoff < MAX_BACKOFF {
            let last_byte = s.as_bytes()[end - 1];
            if last_byte != b'\'' && last_byte != b'\\' {
                break;
            }
            // Walk back to the previous char boundary.
            let mut new_end = end - 1;
            while new_end > start && !s.is_char_boundary(new_end) {
                new_end -= 1;
            }
            if new_end == start {
                // Can't back off further — accept the unsafe boundary.
                break;
            }
            end = new_end;
            backoff += 1;
        }

        chunks.push(&s[start..end]);
        start = end;
    }

    chunks
}

// ── Cleanup helper ─────────────────────────────────────────────────────────────

/// Execute a library exec_code call with Ctrl-C + drain cleanup on failure.
///
/// On any error from `repl::exec_code`, this function:
/// 1. Sends `0x03` (Ctrl-C) via `write_all` to abort any half-parsed device
///    code (best-effort; ignores write errors).
/// 2. Sleeps 10 ms to let the device process the interrupt.
/// 3. Logs the failure with the given `op_name` tag.
/// 4. Returns a `McpError::Protocol` wrapping the original error.
///
/// This mirrors the Wave 0 Ctrl-C+drain pattern used in the connect/disconnect
/// ceremony match arms (main.rs §HIGH-3 + HIGH-4), but is adapted to the
/// `Read + Write + ?Sized` bound that library functions carry. The
/// `drain_read_buffer` helper from `repl` requires `&mut dyn SerialPort` and
/// therefore cannot be called here; we rely on the Ctrl-C interrupt to quiesce
/// the device and accept that stale bytes will be consumed (or cause an early
/// EOF) on the next exec_code attempt.
///
/// **Blocking.** Same semantics as `repl::exec_code`.
pub(crate) fn exec_with_cleanup<P: Read + Write + ?Sized>(
    port: &mut P,
    code: &str,
    op_name: &str,
) -> Result<repl::ReplResponse, McpError> {
    match repl::exec_code(port, code) {
        Ok(resp) => {
            // HIGH-1: check resp.is_error() so Python-side exceptions (MemoryError
            // mid-concat, fs_write internal exception, etc.) surface as Err rather
            // than being silently absorbed. An Ok(resp) where resp.is_error()==true
            // means the device executed our code but MicroPython raised an exception.
            // Without this check the caller sees success while the device may have
            // written a partial/corrupt file.
            if resp.is_error() {
                tracing::warn!(
                    op = op_name,
                    stderr = %resp.stderr.trim(),
                    "library op returned device-side exception; sending Ctrl-C abort"
                );
                let _ = port.write_all(&[0x03]);
                let _ = port.flush();
                std::thread::sleep(std::time::Duration::from_millis(10));
                return Err(McpError::Protocol(format!(
                    "{op_name}: device-side exception: {}",
                    resp.stderr.trim()
                )));
            }
            Ok(resp)
        }
        Err(e) => {
            tracing::warn!(op = op_name, err = %e, "library op failed; sending Ctrl-C abort");
            // Send Ctrl-C byte (0x03) to abort any partially-parsed device code.
            // Best-effort: ignore errors (the device may already be in a broken
            // state; failing to send Ctrl-C is not worse than not trying).
            let _ = port.write_all(&[0x03]);
            let _ = port.flush();
            // Brief settle: let the device process the interrupt before the next op.
            std::thread::sleep(std::time::Duration::from_millis(10));
            Err(McpError::Protocol(format!("{op_name}: {e}")))
        }
    }
}

// ── Chunked write helper ───────────────────────────────────────────────────────

/// Write a file to the device using an open/write/close sequence to avoid
/// V5 firmware's `fs_write` per-call truncation at ~4096 bytes (one flash
/// sector boundary).
///
/// Live verification on firmware 5.6.6.2 showed that `fs_write(path, s)` silently
/// truncates content at ~4087 bytes regardless of string length. The previous
/// `_ygg_assembly` strategy (accumulate all chunks in a device-side variable then
/// call `fs_write` once) hit this limit for effects.py (5703 bytes after
/// CRLF→LF), dropping the last 1616 bytes mid-file with no error.
///
/// New strategy: open the file once with `_ygg_f = open(path, 'w')`, write each
/// chunk via `_ygg_f.write(chunk_repr)`, then close with `_ygg_f.close()`. Each
/// `write()` call is a separate ≤CHUNK_SIZE filesystem operation — no single call
/// ever exceeds one sector, and the data accumulates on-device across calls.
///
/// The content is still split into chunks of at most `CHUNK_SIZE` bytes
/// (UTF-8-safe boundaries) so that each REPL exec_code payload stays well under
/// the ~1024-byte REPL input buffer.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
fn fs_write_chunked<P: Read + Write + ?Sized>(
    port: &mut P,
    path: &str,
    content: &str,
) -> Result<(), McpError> {
    let chunks = chunk_at_char_boundaries(content, CHUNK_SIZE);

    if chunks.is_empty() {
        // Empty content: write an empty file directly.
        let code = format!("fs_write('{path}', '')");
        exec_with_cleanup(
            port,
            &code,
            &format!("fs_write_chunked({path}): empty write"),
        )?;
        return Ok(());
    }

    // Diagnostic: log total chunk count + raw content byte length before starting.
    // Content is the raw (potentially CRLF) string; python_repr normalizes it
    // to LF before sending, so the on-device byte count will be
    // expected_lf_size (computed below), not content.len(). Log both for clarity.
    tracing::info!(
        path = path,
        chunk_count = chunks.len(),
        total_bytes = content.len(),
        "fs_write_chunked starting"
    );

    // Open file for write (truncates existing content). Use text mode ('w') since
    // chunks are str. The handle name `_ygg_f` is deliberately collision-free.
    exec_with_cleanup(
        port,
        &format!("_ygg_f = open('{path}', 'w')"),
        &format!("fs_write_chunked({path}): open"),
    )?;

    // Write each chunk via the persistent file handle. Each payload is
    // ≤ CHUNK_SIZE + a small wrapper (~16 bytes), well under the REPL input buffer.
    for (i, chunk) in chunks.iter().enumerate() {
        // Diagnostic: log per-chunk byte length so truncation is locatable.
        // chunk.len() is the raw chunk size (pre-python_repr normalization).
        tracing::info!(
            path = path,
            chunk_idx = i,
            chunk_bytes = chunk.len(),
            "fs_write_chunked writing chunk"
        );
        let chunk_repr = python_repr(chunk);
        exec_with_cleanup(
            port,
            &format!("_ygg_f.write({chunk_repr})"),
            &format!("fs_write_chunked({path}): chunk {i}"),
        )?;
        // NOTE: f.flush() is intentionally NOT called here.
        // Scout audit (2026-05-10) confirmed that `flush` is NOT in the JFS module
        // globals table (modjumperless.c:4941-4972). The earlier flush() calls were
        // silent no-ops — `jfs` file objects don't expose flush. The open/write/close
        // pattern works correctly without per-chunk flush; close() commits all data.
    }

    // Close the file handle — flushes buffered data and releases the fd.
    exec_with_cleanup(
        port,
        "_ygg_f.close()",
        &format!("fs_write_chunked({path}): close"),
    )?;

    // Diagnostic: post-write size verification — re-read the file from device
    // via jfs to confirm on-disk byte count matches the expected LF-normalized
    // content length. This gives a definitive log entry immediately after each
    // install without waiting for a separate verify run.
    //
    // expected_lf_size: apply the same \r\n → \n normalization that python_repr
    // applies before sending, so the expected count matches what the device sees.
    let expected_lf_size = content.replace("\r\n", "\n").replace('\r', "\n").len();
    let read_back_code = format!(
        "try:\n\
         \x20\x20\x20\x20import jumperless\n\
         \x20\x20\x20\x20_ygg_rf = jumperless.jfs.open('{path}', 'r')\n\
         \x20\x20\x20\x20try:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20_ygg_rb = jumperless.jfs.read(_ygg_rf, {JFS_READ_MAX_BYTES})\n\
         \x20\x20\x20\x20except TypeError:\n\
         \x20\x20\x20\x20\x20\x20\x20\x20# Older firmware: jfs.read takes no size arg. Fall back; may truncate.\n\
         \x20\x20\x20\x20\x20\x20\x20\x20_ygg_rb = jumperless.jfs.read(_ygg_rf)\n\
         \x20\x20\x20\x20jumperless.jfs.close(_ygg_rf)\n\
         \x20\x20\x20\x20del _ygg_rf\n\
         \x20\x20\x20\x20print(len(_ygg_rb))\n\
         \x20\x20\x20\x20del _ygg_rb\n\
         except (NameError, AttributeError):\n\
         \x20\x20\x20\x20print(len(fs_read('{path}')))\n\
         except Exception as e:\n\
         \x20\x20\x20\x20print('ERR:' + str(e))"
    );
    match repl::exec_code(port, &read_back_code) {
        Ok(resp) if !resp.is_error() => {
            let out = resp.stdout.trim();
            if let Ok(actual_size) = out.parse::<usize>() {
                tracing::info!(
                    path = path,
                    expected_bytes_after_normalization = expected_lf_size,
                    actual_bytes_on_device = actual_size,
                    "fs_write_chunked complete; post-write size verification"
                );
            } else {
                // Device returned an ERR: token or unparseable output — log at warn.
                tracing::warn!(
                    path = path,
                    device_output = out,
                    expected_bytes_after_normalization = expected_lf_size,
                    "fs_write_chunked post-write size read returned unexpected output"
                );
            }
        }
        Ok(resp) => {
            tracing::warn!(
                path = path,
                stderr = %resp.stderr.trim(),
                "fs_write_chunked post-write size read produced device-side exception"
            );
        }
        Err(e) => {
            tracing::warn!(
                path = path,
                error = %e,
                "fs_write_chunked post-write size read failed at protocol level"
            );
        }
    }

    // HIGH-3: Cleanup: delete the file handle variable (best-effort).
    // Log device-side exceptions at debug (likely already deleted or never set due
    // to an earlier error) and protocol errors at debug (port may be degraded).
    // Both cases are safe — the handle variable is purely ephemeral and any
    // residual leak resolves at REPL reset or next connect.
    match repl::exec_code(port, "del _ygg_f") {
        Ok(resp) if resp.is_error() => {
            tracing::debug!(
                stderr = %resp.stderr.trim(),
                "del _ygg_f produced device exception (likely already deleted; safe)"
            );
        }
        Ok(_) => {}
        Err(e) => {
            tracing::debug!(
                error = %e,
                "del _ygg_f failed at protocol level (best-effort cleanup; safe)"
            );
        }
    }

    Ok(())
}

// ── Public API ─────────────────────────────────────────────────────────────────

/// Read the installed library version by importing `jumperless_mcp`.
///
/// Returns:
/// - `Ok(Some(version))` if the package imports successfully and exposes `__version__`.
/// - `Ok(None)` if `import jumperless_mcp` raises `ImportError` (not installed).
/// - `Err(McpError)` if the exec_code call fails (protocol-level error) or the
///   device raises an unexpected exception.
///
/// Using `import` instead of file-read means the version check also validates that
/// the package is actually importable (not just that a VERSION file exists).
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn read_installed_version<P: Read + Write + ?Sized>(
    port: &mut P,
) -> Result<Option<String>, McpError> {
    // Import jumperless_mcp and read __version__. ImportError → not installed (Ok(None)).
    // Other exceptions → propagate as Err (unexpected; the package may be corrupt).
    //
    // Soft-reset concern (scout note): import may fail immediately after jfs.mkdir on a
    // fresh device if VFS hasn't settled. The retry below (100ms sleep) handles this.
    // Read VERSION file directly via jfs — DO NOT import jumperless_mcp here.
    //
    // Rationale: MicroPython's sys.modules persists across raw-REPL sessions on V5
    // (REPL state is sticky until device reboot). If we import jumperless_mcp during
    // version check on a partial-install state (e.g. namespace-package with no
    // __init__.py), MP caches that incomplete module. After install writes the real
    // __init__.py, subsequent `import jumperless_mcp` calls see the CACHED partial
    // version and miss `_ceremony_connect` / other definitions. File-based version
    // read avoids the cache entirely. Ceremony scripts handle their own cache
    // invalidation explicitly via sys.modules.pop.
    let code = r#"
try:
    import jumperless
    _vf = jumperless.jfs.open('/python_scripts/lib/jumperless_mcp/VERSION', 'r')
    _v = jumperless.jfs.read(_vf, 64)
    jumperless.jfs.close(_vf)
    if isinstance(_v, str):
        print(_v.strip())
    else:
        print(_v.decode('utf-8').strip())
    del _vf
    del _v
except OSError:
    print('')
except Exception as e:
    print('ERR:' + str(e))
"#;
    let resp = repl::exec_code(port, code)
        .map_err(|e| McpError::Protocol(format!("read_installed_version: {e}")))?;
    // MemoryError or KeyboardInterrupt may escape the try/except (BaseException).
    // Surface as Err so callers don't misread it as "not installed".
    if resp.is_error() {
        return Err(McpError::Protocol(format!(
            "read_installed_version: device-side exception: {}",
            resp.stderr.trim()
        )));
    }
    let v = resp.stdout.trim();
    if v.is_empty() {
        Ok(None)
    } else if let Some(msg) = v.strip_prefix("ERR:") {
        // Unexpected exception from inside the device try block.
        Err(McpError::Protocol(format!(
            "read_installed_version: device error: {msg}"
        )))
    } else {
        Ok(Some(v.to_string()))
    }
}

/// Check installation: which files are present, what version, whether up-to-date.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn check_installation<P: Read + Write + ?Sized>(
    port: &mut P,
) -> Result<InstallationStatus, McpError> {
    // MEDIUM-C: read_installed_version now returns Result<Option<String>, McpError>.
    // Protocol errors (e.g. serial I/O failure) propagate as Err; file-missing is Ok(None).
    let installed_version = read_installed_version(port)?;

    let mut files_present = Vec::new();
    let mut files_missing = Vec::new();

    for path in &[VERSION_PATH, FONT_PATH, EFFECTS_PATH, INIT_PATH] {
        let code = format!("print(int(fs_exists('{path}')))");
        let resp = exec_with_cleanup(
            port,
            &code,
            &format!("check_installation: fs_exists({path})"),
        )?;
        if resp.stdout.trim() == "1" {
            files_present.push(*path);
        } else {
            files_missing.push(*path);
        }
    }

    // HIGH-1: installed requires ALL files present, not just one.
    // Partial install (some files missing) is a distinct state: `installed=false, partial=true`.
    let installed = files_missing.is_empty() && installed_version.is_some();
    let partial = !files_present.is_empty() && !files_missing.is_empty();
    let up_to_date = installed_version.as_deref() == Some(LIBRARY_VERSION);

    Ok(InstallationStatus {
        installed,
        partial,
        installed_version,
        current_version: LIBRARY_VERSION,
        up_to_date,
        files_present,
        files_missing,
    })
}

/// Install the library to `/python_scripts/lib/jumperless_mcp/`.
///
/// Directory layout (must exist before files can be written):
///   /python_scripts/          — may not exist on fresh V5
///   /python_scripts/lib/      — may not exist on fresh V5
///   /python_scripts/lib/jumperless_mcp/  — always created here
///
/// mkdir calls are forgiving: `try/except OSError: pass` tolerates
/// "already exists" without error (OSError EEXIST is expected on
/// subsequent installs).
///
/// Writes (in order — VERSION last so interrupted install is detectable):
///   font.py      — pixel font table
///   effects.py   — visual effects functions
///   __init__.py  — package entry point + ceremony functions
///   VERSION      — plain text version sentinel
///
/// Large files (font.py, effects.py, __init__.py) are written via
/// `fs_write_chunked` to avoid overflowing the MicroPython REPL input
/// buffer. VERSION is small enough to use a direct exec_code write.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn install<P: Read + Write + ?Sized>(port: &mut P) -> Result<(), McpError> {
    // Ensure parent directories exist (best-effort mkdir, tolerate EEXIST).
    // /python_scripts/ may not exist on a fresh V5 — scout confirmed it is
    // created on demand by the first script/package install (FilesystemStuff.cpp).
    // Use try/except OSError: pass to handle the "already exists" case gracefully.
    let mkdir_code = format!(
        r#"try:
    import jumperless
    jumperless.jfs.mkdir('{PYTHON_SCRIPTS}')
except OSError:
    pass
try:
    import jumperless
    jumperless.jfs.mkdir('{PYTHON_SCRIPTS_LIB}')
except OSError:
    pass
try:
    import jumperless
    jumperless.jfs.mkdir('{LIBRARY_ROOT}')
except OSError:
    pass"#
    );
    exec_with_cleanup(
        port,
        &mkdir_code,
        "install: mkdir /python_scripts/lib/jumperless_mcp",
    )?;

    // font.py — pixel font table
    fs_write_chunked(port, FONT_PATH, FONT_PY)?;
    // effects.py — visual effects functions (depends on FONT from font.py)
    fs_write_chunked(port, EFFECTS_PATH, EFFECTS_PY)?;
    // __init__.py — package entry point + ceremony functions
    fs_write_chunked(port, INIT_PATH, INIT_PY)?;

    // VERSION is tiny (<30 bytes) — write directly.
    // Written last: a missing/stale VERSION → check_installation returns installed=false
    // → install_if_needed retries. This makes interrupted installs self-healing.
    let code = format!("fs_write('{VERSION_PATH}', '{LIBRARY_VERSION}\\n')");
    exec_with_cleanup(port, &code, "install: write VERSION")?;

    Ok(())
}

/// Idempotent install: only writes if missing or version mismatch.
///
/// Returns `true` if an install was performed, `false` if already up-to-date.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn install_if_needed<P: Read + Write + ?Sized>(port: &mut P) -> Result<bool, McpError> {
    let status = check_installation(port)?;
    if status.installed && status.up_to_date {
        return Ok(false);
    }
    install(port)?;
    Ok(true)
}

/// Forced reinstall: removes existing files (best-effort) then installs fresh.
///
/// Returns a `ReinstallResult` carrying the pre-install uninstall outcome so
/// callers can surface whether the unbound-fallback path was used, without
/// having to read tracing logs. The `Err` path propagates from `install` only
/// — uninstall failures are best-effort and never abort the reinstall.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn reinstall<P: Read + Write + ?Sized>(port: &mut P) -> Result<ReinstallResult, McpError> {
    let pre_uninstall = uninstall_best_effort(port);
    install(port)?;
    Ok(ReinstallResult {
        pre_uninstall,
        installed_version: LIBRARY_VERSION,
    })
}

/// Uninstall the library: removes `/python_scripts/lib/jumperless_mcp/` files
/// and (best-effort) the directory itself. Returns a structured `UninstallResult`.
///
/// `jfs.remove` is confirmed bound on V5 firmware ≥5.6.6.2 (modjumperless.c:4763-4771,
/// audit 2026-05-10). No UNBOUND fallback — use `jfs.remove` directly.
///
/// ## Exception classification
///
/// - `OSError` → file already absent; counted as already-removed (no-op success).
/// - Any other exception → unexpected; logged at `warn!`; counted as error.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn uninstall<P: Read + Write + ?Sized>(port: &mut P) -> Result<UninstallResult, McpError> {
    let files = [FONT_PATH, EFFECTS_PATH, INIT_PATH, VERSION_PATH];
    let attempted = files.len();
    let mut attempted_actual = 0usize;
    let mut removed = 0usize;
    let mut errors: Vec<String> = Vec::new();

    for path in &files {
        attempted_actual += 1;

        // jfs.remove is confirmed bound on V5 firmware (audit 2026-05-10).
        // OSError → already absent (counted as success).
        // Other exceptions → logged as error, iteration continues.
        let code = format!(
            r#"try:
    import jumperless
    jumperless.jfs.remove('{path}')
    print('OK')
except OSError:
    print('ABSENT')
except Exception as e:
    print('ERR:' + str(e))"#
        );

        match repl::exec_code(port, &code) {
            Err(e) => {
                errors.push(format!("{path}: exec failed: {e}"));
            }
            Ok(resp) => {
                // Check is_error() BEFORE token classification: a MemoryError
                // mid-print leaves is_error=true and stdout empty. Without this
                // guard the empty token falls through producing a misleading error.
                if resp.is_error() {
                    tracing::warn!(path = path, stderr = %resp.stderr.trim(), "uninstall device-side exception");
                    errors.push(format!(
                        "{path}: device-side exception: {}",
                        resp.stderr.trim()
                    ));
                    continue;
                }
                let token = resp.stdout.trim();
                match token {
                    "OK" => {
                        removed += 1;
                    }
                    "ABSENT" => {
                        removed += 1;
                    } // already gone — counts as success
                    other if other.starts_with("ERR:") => {
                        tracing::warn!(
                            path = path,
                            detail = other,
                            "unexpected uninstall exception"
                        );
                        errors.push(format!("{path}: {other}"));
                    }
                    _ => {
                        tracing::warn!(
                            path = path,
                            token = token,
                            "unrecognised uninstall response token"
                        );
                        errors.push(format!("{path}: unrecognised token '{token}'"));
                    }
                }
            }
        }
    }

    // Best-effort directory removal. jfs.rmdir is confirmed bound on V5 firmware.
    // Ignores device-side exceptions (non-empty dir, already absent, etc.).
    let dir_code = format!(
        r#"try:
    import jumperless
    jumperless.jfs.rmdir('{LIBRARY_ROOT}')
except Exception:
    pass"#
    );
    if let Err(e) = repl::exec_code(port, &dir_code) {
        tracing::debug!(error = %e, "fs_rmdir best-effort cleanup failed at protocol level (safe — files already handled)");
    }

    Ok(UninstallResult {
        attempted,
        attempted_actual,
        removed,
        errors,
    })
}

/// Convenience wrapper for callers that need the structured `UninstallResult`
/// but must not abort on uninstall failure (e.g. `reinstall`).
///
/// Returns `Some(r)` when `uninstall` returns `Ok(r)` — the result is also
/// logged internally when it contains issues. Returns `None` when `uninstall`
/// returns `Err` — the error is logged at `error!` and the caller proceeds
/// (best-effort semantic: uninstall failure doesn't block a fresh install).
fn uninstall_best_effort<P: Read + Write + ?Sized>(port: &mut P) -> Option<UninstallResult> {
    match uninstall(port) {
        Ok(r) => {
            if !r.errors.is_empty() {
                tracing::warn!(
                    attempted = r.attempted,
                    removed = r.removed,
                    errors = ?r.errors,
                    "uninstall completed with issues"
                );
            }
            Some(r)
        }
        // MEDIUM-H: error! not warn! — a best-effort wrapper that silently hides
        // Err is the failure mode that caused the 1.B.4 investigation. Use error!
        // to ensure this is visible in production logs even at reduced verbosity.
        Err(e) => {
            tracing::error!(error = %e, "uninstall returned Err (ignored for reinstall path)");
            None
        }
    }
}

/// Result of a `reinstall` operation. Carries the pre-install uninstall
/// outcome (for operator visibility) and the installed version.
pub struct ReinstallResult {
    /// Outcome of the pre-install uninstall step.
    /// `None` if `uninstall` returned `Err` (error logged; install proceeded anyway).
    /// `Some(r)` carries the structured result including removed count and `errors`.
    pub pre_uninstall: Option<UninstallResult>,
    /// The version string that was just installed.
    pub installed_version: &'static str,
}

// ── Verify types and impl ──────────────────────────────────────────────────────

/// Per-file verification result returned by `verify_installation`.
#[derive(Debug, Clone)]
pub struct FileVerification {
    /// Path on the device (e.g. `/jumperless_mcp/effects.py`).
    pub path: String,
    /// File size read from device, or `None` if the file is missing.
    pub device_size: Option<usize>,
    /// Expected size from the embedded source.
    pub source_size: usize,
    /// Hex SHA-256 from device, or `None` if the file is missing or hashlib
    /// was unavailable on this firmware. The sentinel `"NO_HASHLIB"` is
    /// translated to `None` with `hash_available_on_device = false`.
    pub device_sha256: Option<String>,
    /// Hex SHA-256 computed host-side from the embedded source bytes.
    pub source_sha256: String,
    /// `true` if the device ran hashlib successfully and returned a hash.
    /// `false` if the device is missing hashlib (size-only verification).
    pub hash_available_on_device: bool,
    /// `true` when sizes match AND (hashes match OR hash unavailable on device).
    /// `false` when sizes differ OR hashes differ.
    pub matched: bool,
}

/// Aggregate result returned by `verify_installation`.
#[derive(Debug)]
pub struct VerifyResult {
    /// Per-file results, in the order `[font.py, effects.py, VERSION]`.
    pub files: Vec<FileVerification>,
    /// Library version string from the embedded source (not read from device).
    pub library_version: &'static str,
    /// `true` when every file's `matched` field is `true`.
    pub all_match: bool,
}

/// Device-side script that reads a file's size and SHA-256 (or size only when
/// hashlib is not available on this firmware build).
///
/// Outputs one or two `key:value` lines on stdout:
///   `size:N`         — byte length of the file (N is an integer)
///   `sha256:HEXHEX`  — lower-hex SHA-256 digest (when hashlib available)
///   `sha256:NO_HASHLIB` — when hashlib is not importable
///   `size:MISSING`   — when the file does not exist (OSError)
///   `sha256:MISSING` — paired with size:MISSING
///   `error:MSG`      — protocol-level error; whole verify for this file should surface as Err
fn device_verify_script(path: &str) -> String {
    // Read via jfs (MicroPython heap, no 4096-byte cap) with fallback to fs_read.
    // This is the CRITICAL fix: effects.py is >4KB so fs_read silently truncated
    // it, producing false SHA-256 MISMATCHes on files that were correctly installed.
    //
    // Structure: read content first via jfs-with-fallback, OSError propagates if
    // missing (caught by outer except OSError). Then hash. The NameError branch
    // handles "hashlib not available" — content is already in scope from the read
    // at the top of the outer try block (Python scoping: variable assigned above
    // the NameError-raising `import hashlib` line remains visible in the handler).
    format!(
        r#"try:
    try:
        import jumperless
        _ygg_rf = jumperless.jfs.open('{path}', 'r')
        try:
            content = jumperless.jfs.read(_ygg_rf, {JFS_READ_MAX_BYTES})
        except TypeError:
            # Older firmware: jfs.read takes no size arg. Fall back; may truncate.
            content = jumperless.jfs.read(_ygg_rf)
        jumperless.jfs.close(_ygg_rf)
        del _ygg_rf
    except (NameError, AttributeError):
        content = fs_read('{path}')
    if isinstance(content, str):
        content = content.encode('utf-8')
    import hashlib
    print('size:' + str(len(content)))
    try:
        h = hashlib.sha256(content).hexdigest()
    except AttributeError:
        try:
            import binascii
            h = binascii.hexlify(hashlib.sha256(content).digest()).decode()
        except Exception:
            h = 'NO_HEX_AVAILABLE'
    print('sha256:' + h)
except NameError as e:
    if 'hashlib' in str(e):
        print('size:' + str(len(content)))
        print('sha256:NO_HASHLIB')
    else:
        print('error:' + str(e))
except OSError:
    print('size:MISSING')
    print('sha256:MISSING')
except Exception as e:
    print('error:' + str(e))"#
    )
}

/// Parse the stdout produced by `device_verify_script` into a
/// `(device_size, device_sha256_raw, hash_available)` triple.
///
/// Returns `Err(String)` with a human-readable description when the device
/// returned an `error:` line or when the output is unparseable.
///
/// `device_sha256_raw` is the raw string from the device — callers convert
/// `"NO_HASHLIB"` to `hash_available = false, device_sha256 = None`.
pub(crate) fn parse_device_verify_output(
    stdout: &str,
) -> Result<(Option<usize>, Option<String>, bool), String> {
    let mut size_line: Option<&str> = None;
    let mut sha256_line: Option<&str> = None;
    let mut error_msg: Option<String> = None;

    for line in stdout.lines() {
        let line = line.trim();
        if let Some(val) = line.strip_prefix("size:") {
            size_line = Some(val);
        } else if let Some(val) = line.strip_prefix("sha256:") {
            sha256_line = Some(val);
        } else if let Some(msg) = line.strip_prefix("error:") {
            // Capture the error but keep iterating — a size: line may have
            // already been emitted before the error: line (e.g. hashlib
            // AttributeError fires after print('size:...') succeeds).
            error_msg = Some(msg.to_string());
        }
        // Ignore blank or unrecognised lines (tracing noise from MicroPython).
    }

    let size_str = size_line.unwrap_or("");
    let sha256_str = sha256_line.unwrap_or("");

    if size_str == "MISSING" {
        // File absent on device — both fields are "missing", not an error.
        return Ok((None, None, false));
    }

    if size_str.is_empty() {
        // No size line and no useful info — surface the error if we have one.
        return match error_msg {
            Some(msg) => Err(msg),
            None => Err("device returned no size or error".to_string()),
        };
    }

    let device_size = size_str
        .parse::<usize>()
        .map(Some)
        .map_err(|_| format!("could not parse size value: '{size_str}'"))?;

    // If an error was emitted after the size line (e.g. hexdigest AttributeError)
    // or sha256 is a sentinel meaning "hash not available", treat as size-only.
    let hash_failed = error_msg.is_some();
    let (device_sha256, hash_available) = match sha256_str {
        "" | "NO_HASHLIB" | "NO_HEX_AVAILABLE" => (None, false),
        _ if hash_failed => (None, false),
        hex => (Some(hex.to_string()), true),
    };

    Ok((device_size, device_sha256, hash_available))
}

/// Verify that each resident library file on the device matches the embedded
/// source. For each of `font.py`, `effects.py`, and `VERSION`:
///
/// 1. Reads the device-side file size.
/// 2. Attempts a SHA-256 hash via MicroPython's `hashlib` module; falls back
///    to size-only verification when `hashlib` is unavailable (sentinel
///    `"NO_HASHLIB"` returned from device-side script).
/// 3. Computes the expected size and SHA-256 from the embedded source.
/// 4. Reports match/mismatch per file.
///
/// This function **never attempts auto-install** — it is diagnostic only.
/// Use it with `new_for_library_cli` on the CLI path so connect() doesn't
/// race with the explicit library op.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn verify_installation<P: Read + Write + ?Sized>(
    port: &mut P,
) -> Result<VerifyResult, McpError> {
    use sha2::{Digest, Sha256};

    // The three files to check, paired with their embedded source content.
    // VERSION content is `LIBRARY_VERSION` + `"\n"` (matching the write in install()).
    let version_content = format!("{LIBRARY_VERSION}\n");
    let targets: &[(&str, &str)] = &[
        (FONT_PATH, FONT_PY),
        (EFFECTS_PATH, EFFECTS_PY),
        (INIT_PATH, INIT_PY),
        (VERSION_PATH, &version_content),
    ];

    let mut file_results: Vec<FileVerification> = Vec::with_capacity(targets.len());
    let mut all_match = true;

    for (path, source_content) in targets {
        // Normalize CRLF → LF before measuring size and hashing.
        //
        // include_str! on Windows does NOT normalize line endings (rust-lang/rust
        // PR #63681 was rejected). FONT_PY and EFFECTS_PY may contain CRLF when
        // the repo is checked out with Git autocrlf=true. However, python_repr()
        // (used in the install path) normalizes \r\n → \n before sending to the
        // device, so the file stored on device is LF-only. Without this step the
        // host SHA/size measured CRLF bytes while the device file has LF bytes →
        // permanent mismatch on Windows even for correctly-installed files.
        //
        // Apply the same two-step normalization as python_repr so the host and
        // device measurements are computed over the same byte stream. VERSION is
        // always LF-only (format string literal) so this is a no-op there, but
        // applying consistently keeps the logic uniform across all three targets.
        let normalized = source_content.replace("\r\n", "\n").replace('\r', "\n");
        // Compute host-side reference values.
        let source_size = normalized.len();
        let digest_bytes = Sha256::digest(normalized.as_bytes());
        let source_sha256: String = digest_bytes.iter().map(|b| format!("{b:02x}")).collect();

        let script = device_verify_script(path);
        let resp = exec_with_cleanup(port, &script, &format!("verify({path})"))?;

        let parse_result = parse_device_verify_output(&resp.stdout);

        let fv = match parse_result {
            Err(e) => {
                // Device returned `error:MSG` — treat as a non-fatal per-file error.
                // We produce a FileVerification with matched=false and no device values.
                tracing::warn!(path = path, error = %e, "device verify script reported error");
                let fv = FileVerification {
                    path: path.to_string(),
                    device_size: None,
                    source_size,
                    device_sha256: None,
                    source_sha256,
                    hash_available_on_device: false,
                    matched: false,
                };
                all_match = false;
                fv
            }
            Ok((device_size, device_sha256_raw, hash_available)) => {
                // Determine match:
                // - sizes must agree (both present and equal)
                // - if hash is available, hashes must also agree
                let sizes_match = device_size == Some(source_size);
                let hashes_match = if hash_available {
                    device_sha256_raw.as_deref() == Some(source_sha256.as_str())
                } else {
                    // No hashlib: size-only comparison — if sizes match we call it
                    // a match with a note that hash was unavailable.
                    true
                };
                let matched = sizes_match && hashes_match;
                if !matched {
                    all_match = false;
                }
                FileVerification {
                    path: path.to_string(),
                    device_size,
                    source_size,
                    device_sha256: device_sha256_raw,
                    source_sha256,
                    hash_available_on_device: hash_available,
                    matched,
                }
            }
        };

        file_results.push(fv);
    }

    Ok(VerifyResult {
        files: file_results,
        library_version: LIBRARY_VERSION,
        all_match,
    })
}

// ── Dump types and impl ────────────────────────────────────────────────────────

/// Result returned by `dump_device_file`.
#[derive(Debug)]
pub struct DumpResult {
    /// The path that was requested.
    pub path: String,
    /// Byte length reported by the device, or `None` if the file is missing.
    pub size: Option<usize>,
    /// Raw bytes decoded from the device hex dump, or `None` if missing.
    pub content: Option<Vec<u8>>,
    /// `true` when the device reported the file does not exist.
    pub missing: bool,
}

/// Generate the device-side MicroPython script for a raw byte dump via
/// `binascii.hexlify`. Confirmed available on V5 firmware 5.6.6.2.
///
/// Output lines:
///   `size:N`       — byte length of the file
///   `hex:HEXHEX`   — lowercase hex of the file contents
///   `size:MISSING` + `hex:MISSING` — when the file does not exist (OSError)
///   `error:MSG`    — any other exception
fn device_dump_script(path: &str) -> String {
    // Read via jfs (MicroPython heap, no 4096-byte cap) with fallback to fs_read.
    format!(
        r#"try:
    try:
        import jumperless
        _ygg_rf = jumperless.jfs.open('{path}', 'r')
        try:
            content = jumperless.jfs.read(_ygg_rf, {JFS_READ_MAX_BYTES})
        except TypeError:
            # Older firmware: jfs.read takes no size arg. Fall back; may truncate.
            content = jumperless.jfs.read(_ygg_rf)
        jumperless.jfs.close(_ygg_rf)
        del _ygg_rf
    except (NameError, AttributeError):
        content = fs_read('{path}')
    if isinstance(content, str):
        content = content.encode('utf-8')
    import binascii
    print('size:' + str(len(content)))
    print('hex:' + binascii.hexlify(content).decode())
except OSError:
    print('size:MISSING')
    print('hex:MISSING')
except Exception as e:
    print('error:' + str(e))"#
    )
}

/// Decode a lowercase or uppercase hex string into bytes.
///
/// Returns `Err(String)` if the input length is odd or any byte pair is
/// not valid hex. Accepts both lowercase and uppercase hex digits.
pub(crate) fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
    if hex.len() % 2 != 0 {
        return Err(format!(
            "hex string has odd length {}; expected even number of nibbles",
            hex.len()
        ));
    }
    let mut out = Vec::with_capacity(hex.len() / 2);
    for i in (0..hex.len()).step_by(2) {
        let pair = &hex[i..i + 2];
        let byte = u8::from_str_radix(pair, 16)
            .map_err(|_| format!("invalid hex pair '{pair}' at offset {i}"))?;
        out.push(byte);
    }
    Ok(out)
}

/// Parse the stdout produced by `device_dump_script` into a
/// `(size, content_bytes)` pair.
///
/// Returns:
/// - `Ok((None, None))` when the file is missing on device.
/// - `Ok((Some(size), Some(bytes)))` on success.
/// - `Err(String)` when the device returned an `error:` line or output is unparseable.
pub(crate) fn parse_dump_output(stdout: &str) -> Result<(Option<usize>, Option<Vec<u8>>), String> {
    let mut size_val: Option<&str> = None;
    let mut hex_val: Option<&str> = None;
    let mut error_msg: Option<String> = None;

    for line in stdout.lines() {
        let line = line.trim();
        if let Some(v) = line.strip_prefix("size:") {
            size_val = Some(v);
        } else if let Some(v) = line.strip_prefix("hex:") {
            hex_val = Some(v);
        } else if let Some(msg) = line.strip_prefix("error:") {
            error_msg = Some(msg.to_string());
        }
    }

    // Surface device-reported errors first.
    if let Some(msg) = error_msg {
        return Err(msg);
    }

    let size_str = size_val.unwrap_or("");
    let hex_str = hex_val.unwrap_or("");

    if size_str == "MISSING" {
        return Ok((None, None));
    }

    if size_str.is_empty() {
        return Err("device returned no size or error".to_string());
    }

    let size = size_str
        .parse::<usize>()
        .map_err(|_| format!("could not parse size value: '{size_str}'"))?;

    if hex_str.is_empty() {
        return Err("device returned size but no hex content".to_string());
    }

    let bytes = hex_to_bytes(hex_str)?;
    Ok((Some(size), Some(bytes)))
}

/// Read a file from the device and return its raw bytes.
///
/// Uses `binascii.hexlify` (confirmed on V5 5.6.6.2) to transfer the binary
/// content safely over the text-oriented MicroPython REPL.
///
/// This is a **debug/diagnostic** function — it does NOT install, modify, or
/// remove any files on the device. Use it after `verify_installation` reports
/// a mismatch to get byte-level visibility into what was actually written.
///
/// **Blocking.** Wrap in `tokio::task::spawn_blocking` when called from async context.
pub fn dump_device_file<P: Read + Write + ?Sized>(
    port: &mut P,
    path: &str,
) -> Result<DumpResult, McpError> {
    let script = device_dump_script(path);
    let resp = exec_with_cleanup(port, &script, &format!("dump({path})"))?;

    match parse_dump_output(&resp.stdout) {
        Ok((None, None)) => Ok(DumpResult {
            path: path.to_string(),
            size: None,
            content: None,
            missing: true,
        }),
        Ok((size, content)) => Ok(DumpResult {
            path: path.to_string(),
            size,
            content,
            missing: false,
        }),
        Err(e) => Err(McpError::Protocol(format!("dump({path}): {e}"))),
    }
}

// ── Internal helpers ───────────────────────────────────────────────────────────

/// Format a Rust string as a Python triple-single-quoted literal.
///
/// Only backslashes need escaping inside `'''...'''` — single quotes are safe
/// unless they appear consecutively as `'''`, which is guarded by the
/// compile-time const assertions on FONT_PY and EFFECTS_PY above.
///
/// MEDIUM-C: single-quote escaping removed. A literal `\'` in the source
/// would produce `\\\'` via the old double-escape chain, which is incorrect.
/// Triple-quoted Python strings tolerate bare single quotes; we trust the
/// compile-time triple-quote check instead of escaping them away.
///
/// Example output: `'''def foo():\n    return 42\n'''`
fn python_repr(s: &str) -> String {
    // Normalize line endings to LF-only BEFORE wrapping. Source files checked
    // out on Windows with Git autocrlf=true have CRLF (\r\n) on disk; include_str!
    // reads those raw bytes. When sent through python_repr → triple-quoted
    // string → MicroPython's parser, the CR characters cause line-counting
    // skew or mishandle CRLF inside triple-quoted strings. The result is a
    // SyntaxError reported at a line number that does not match the source —
    // e.g. SyntaxError at line 86 of the device-stored file when source line
    // 86 is innocent.
    //
    // Live-observed during library-install development (2026-05-10).
    // Normalizing here is more robust than relying on .gitattributes alone:
    // future contributors with non-standard Git config still get LF-clean
    // device files.
    let normalized = s.replace("\r\n", "\n").replace('\r', "\n");
    // Escape backslashes only (must be the sole escape in a triple-quoted context).
    let escaped = normalized.replace('\\', "\\\\");
    format!("'''{escaped}'''")
}

// ── Tests ──────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::VecDeque;
    use std::io::{self, Read, Write};

    // ── Minimal MockPort for library tests ─────────────────────────────────────
    //
    // We need Read + Write (not the full serialport::SerialPort trait) because
    // all library functions take `&mut P: Read + Write + ?Sized`.
    struct MockPort {
        read_data: VecDeque<u8>,
        pub write_data: Vec<u8>,
    }

    impl MockPort {
        /// Build a mock that returns a sequence of exec_code responses.
        ///
        /// Each element in `responses` is the raw frame bytes for one exec_code
        /// call. Frames are concatenated; the exec_code framing (OK + delimiters)
        /// must be included by the caller.
        fn with_responses(responses: &[&[u8]]) -> Self {
            let mut buf = Vec::new();
            for r in responses {
                buf.extend_from_slice(r);
            }
            MockPort {
                read_data: VecDeque::from(buf),
                write_data: Vec::new(),
            }
        }

        /// Successful exec_code response frame (no stdout, no error).
        fn ok_frame() -> Vec<u8> {
            b"OK\x04\x04>".to_vec()
        }

        /// Successful exec_code response returning a single printed line.
        fn ok_with_stdout(line: &str) -> Vec<u8> {
            let mut v = b"OK".to_vec();
            v.extend_from_slice(line.as_bytes());
            v.push(b'\n');
            v.extend_from_slice(b"\x04\x04>");
            v
        }
    }

    impl Read for MockPort {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            let n = buf.len().min(self.read_data.len());
            if n == 0 {
                return Err(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "MockPort: no more scripted bytes",
                ));
            }
            for (dst, src) in buf[..n].iter_mut().zip(self.read_data.drain(..n)) {
                *dst = src;
            }
            Ok(n)
        }
    }

    impl Write for MockPort {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            self.write_data.extend_from_slice(buf);
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    // ── Version + size tests ───────────────────────────────────────────────────

    #[test]
    fn library_version_is_semver_2_with_build_metadata() {
        assert!(LIBRARY_VERSION.contains('+'));
        let (semver, _build) = LIBRARY_VERSION.split_once('+').unwrap();
        // Crude SemVer check: three dot-separated numbers
        assert_eq!(semver.split('.').count(), 3);
        for part in semver.split('.') {
            assert!(
                part.parse::<u32>().is_ok(),
                "semver part must be numeric: {part}"
            );
        }
    }

    #[test]
    #[allow(clippy::assertions_on_constants)] // intentional: enforces compile-time size budget as a runtime-visible test
    fn library_size_is_under_limit() {
        // Sanity guard against pathological library bloat. V5 flash has megabytes
        // free — this limit is set generously to catch unintended runaway growth
        // (e.g., embedding a megabyte of test data by accident), not to enforce
        // a hardware constraint. Bumped from 16KB → 24KB in v0.2.6 to accommodate
        // the bulk-write marquee refactor (_build_marquee_frame function + docs).
        // Bumped from 24KB → 32KB in v0.2.12 to accommodate _build_minimalist_frame
        // (new positive-space renderer) + its geometry/placement docstring.
        assert!(
            LIBRARY_SIZE_BYTES_APPROX < 32_000,
            "Library size {LIBRARY_SIZE_BYTES_APPROX} exceeds 32KB sanity budget"
        );
    }

    #[test]
    fn font_py_and_effects_py_are_non_empty() {
        assert!(!FONT_PY.is_empty(), "FONT_PY must not be empty");
        assert!(!EFFECTS_PY.is_empty(), "EFFECTS_PY must not be empty");
    }

    #[test]
    fn library_version_matches_font_py_header() {
        // font.py header comment should reference the version
        let (semver, _) = LIBRARY_VERSION.split_once('+').unwrap();
        assert!(
            FONT_PY.contains(semver),
            "font.py header should contain the library version semver {semver}"
        );
    }

    #[test]
    fn library_version_matches_effects_py_header() {
        let (semver, _) = LIBRARY_VERSION.split_once('+').unwrap();
        assert!(
            EFFECTS_PY.contains(semver),
            "effects.py header should contain the library version semver {semver}"
        );
    }

    // ── python_repr tests ──────────────────────────────────────────────────────

    #[test]
    fn python_repr_roundtrip_simple() {
        let s = "hello\nworld";
        let r = python_repr(s);
        assert!(r.starts_with("'''"), "repr must start with '''");
        assert!(r.ends_with("'''"), "repr must end with '''");
        // Raw newlines are preserved inside triple-quoted string
        assert!(r.contains("hello\nworld"));
    }

    /// MEDIUM-C: single quotes must pass through unchanged inside triple-quoted context.
    /// The old impl double-escaped them ('→\' via replace, then that \ got doubled),
    /// producing \\' for a bare apostrophe.
    #[test]
    fn python_repr_does_not_escape_single_quotes() {
        let s = "it's a test";
        let r = python_repr(s);
        assert!(
            r.contains("it's"),
            "single quotes must pass through unchanged inside triple-quoted string; got: {r}"
        );
        assert!(
            !r.contains("\\'"),
            "python_repr must not escape single quotes (triple-quote context is safe); got: {r}"
        );
    }

    #[test]
    fn python_repr_escapes_backslashes() {
        let s = "path\\to\\file";
        let r = python_repr(s);
        assert!(r.contains("\\\\"), "backslashes must be doubled");
    }

    /// Stage 1.B.3 fix: source files checked out with CRLF (Windows + Git
    /// autocrlf) must be normalized to LF-only before being sent through
    /// python_repr. Live-observed SyntaxError when MicroPython parsed CRLF
    /// inside the triple-quoted wrapper.
    #[test]
    fn python_repr_normalizes_crlf_to_lf() {
        let s = "line1\r\nline2\r\nline3";
        let r = python_repr(s);
        assert!(!r.contains('\r'), "CR (0x0D) must be stripped; got: {r:?}");
        assert!(
            r.contains("line1\nline2\nline3"),
            "lines must be joined with LF only; got: {r:?}"
        );
    }

    /// Bare CR (Mac classic line endings) is rare but the normalizer should
    /// handle it as well — convert to LF.
    #[test]
    fn python_repr_normalizes_bare_cr_to_lf() {
        let s = "a\rb\rc";
        let r = python_repr(s);
        assert!(!r.contains('\r'));
        assert!(r.contains("a\nb\nc"));
    }

    /// Real-world: FONT_PY and EFFECTS_PY embedded via include_str! may
    /// contain CRLF when checked out on Windows. Confirm the python_repr
    /// output of these constants is LF-only.
    #[test]
    fn python_repr_of_embedded_files_is_lf_only() {
        let font_repr = python_repr(FONT_PY);
        assert!(
            !font_repr.contains('\r'),
            "FONT_PY repr must be LF-only after normalization"
        );
        let effects_repr = python_repr(EFFECTS_PY);
        assert!(
            !effects_repr.contains('\r'),
            "EFFECTS_PY repr must be LF-only after normalization"
        );
    }

    #[test]
    fn python_repr_font_py_does_not_contain_unescaped_triple_quotes() {
        let r = python_repr(FONT_PY);
        // The only ''' in the output should be the wrapping delimiters at pos 0 and end
        let inner = &r[3..r.len() - 3];
        assert!(
            !inner.contains("'''"),
            "font.py repr inner must not contain '''"
        );
    }

    #[test]
    fn python_repr_effects_py_does_not_contain_unescaped_triple_quotes() {
        let r = python_repr(EFFECTS_PY);
        let inner = &r[3..r.len() - 3];
        assert!(
            !inner.contains("'''"),
            "effects.py repr inner must not contain '''"
        );
    }

    // ── chunk_at_char_boundaries tests ────────────────────────────────────────

    #[test]
    fn chunk_empty_string_returns_empty_vec() {
        let chunks = chunk_at_char_boundaries("", 1024);
        assert!(chunks.is_empty(), "empty string should produce no chunks");
    }

    #[test]
    fn chunk_string_shorter_than_limit_returns_one_chunk() {
        let s = "hello world";
        let chunks = chunk_at_char_boundaries(s, 1024);
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0], s);
    }

    #[test]
    fn chunk_string_exactly_limit_returns_one_chunk() {
        let s = "a".repeat(1024);
        let chunks = chunk_at_char_boundaries(&s, 1024);
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0], s.as_str());
    }

    #[test]
    fn chunk_string_one_over_limit_returns_two_chunks() {
        let s = "a".repeat(1025);
        let chunks = chunk_at_char_boundaries(&s, 1024);
        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].len(), 1024);
        assert_eq!(chunks[1].len(), 1);
    }

    #[test]
    fn chunk_preserves_total_content() {
        let s = "the quick brown fox jumps over the lazy dog. ".repeat(100);
        let chunks = chunk_at_char_boundaries(&s, 1024);
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, s,
            "reassembled chunks must equal original string"
        );
    }

    #[test]
    fn chunk_all_chunks_within_size_limit() {
        let s = "x".repeat(8192);
        let chunks = chunk_at_char_boundaries(&s, 1024);
        for (i, chunk) in chunks.iter().enumerate() {
            assert!(
                chunk.len() <= 1024,
                "chunk {i} has length {} which exceeds limit 1024",
                chunk.len()
            );
        }
    }

    /// Regression test for 2026-05-10 bug: v0.2.2 effects.py install failed at
    /// chunk 9 because the chunk boundary landed mid-"ceremony's" and the
    /// trailing apostrophe collided with the `'''<chunk>'''` wrapper to produce
    /// `''''` (ambiguous parse, SyntaxError on device). The chunker must back
    /// off such boundaries.
    #[test]
    fn chunk_boundary_apostrophe_is_avoided() {
        // String of length exactly target_size, ending with `'`.
        // Without the fix, chunk[0] would be 10 chars ending in `'`.
        // With the fix, chunk[0] backs off so it does NOT end in `'`.
        let s = "abcdefghi'extra";
        let chunks = chunk_at_char_boundaries(s, 10);
        assert!(chunks.len() >= 2, "should split into 2+ chunks");
        for (i, chunk) in chunks.iter().enumerate() {
            // Last chunk is allowed to end with anything (no wrapper boundary
            // collision because there's no next chunk).
            if i == chunks.len() - 1 {
                continue;
            }
            let last = chunk.as_bytes().last().copied();
            assert_ne!(
                last,
                Some(b'\''),
                "chunk {i} ends with `'` which would collide with `'''<chunk>'''` wrapper: {chunk:?}"
            );
        }
        // Content must still reassemble exactly.
        let reassembled: String = chunks.concat();
        assert_eq!(reassembled, s);
    }

    /// Same regression-class test for trailing backslash. `\` at chunk end
    /// escapes the first quote of the closing `'''` → string never closes.
    #[test]
    fn chunk_boundary_backslash_is_avoided() {
        let s = "abcdefghi\\extra";
        let chunks = chunk_at_char_boundaries(s, 10);
        assert!(chunks.len() >= 2);
        for (i, chunk) in chunks.iter().enumerate() {
            if i == chunks.len() - 1 {
                continue;
            }
            let last = chunk.as_bytes().last().copied();
            assert_ne!(
                last,
                Some(b'\\'),
                "chunk {i} ends with `\\` which would escape the closing quote: {chunk:?}"
            );
        }
        let reassembled: String = chunks.concat();
        assert_eq!(reassembled, s);
    }

    /// Realistic regression test using a snippet that mimics the actual
    /// effects.py chunk 9 problem (ceremony's apostrophe at boundary).
    #[test]
    fn chunk_boundary_real_world_apostrophe_pattern() {
        // Mimics the failing pattern: text with apostrophe-in-quoted-word
        // followed by more content, with chunk size landing such that the
        // boundary would otherwise fall on the apostrophe.
        let s = "Used as ceremony's transition from idle to active state. \
                 direction 'L2R' or 'R2L' determines sweep direction.";
        // Pick a chunk size that would naturally land on the apostrophe in "ceremony's"
        let target = 16; // "Used as ceremony" = 16 chars, next char is `'`
        let chunks = chunk_at_char_boundaries(s, target);
        // Verify no inner chunk ends with `'`.
        for (i, chunk) in chunks.iter().enumerate() {
            if i == chunks.len() - 1 {
                continue;
            }
            let last = chunk.as_bytes().last().copied();
            assert_ne!(
                last,
                Some(b'\''),
                "chunk {i} would collide with wrapper: {chunk:?}"
            );
        }
        let reassembled: String = chunks.concat();
        assert_eq!(reassembled, s);
    }

    #[test]
    fn chunk_effects_py_all_chunks_within_size_limit() {
        // effects.py is 5372 chars — the exact file that caused Bug 1 + Bug 2.
        let chunks = chunk_at_char_boundaries(EFFECTS_PY, CHUNK_SIZE);
        assert!(
            chunks.len() >= 2,
            "effects.py ({} chars) should require multiple chunks at CHUNK_SIZE={CHUNK_SIZE}",
            EFFECTS_PY.len()
        );
        for (i, chunk) in chunks.iter().enumerate() {
            assert!(
                chunk.len() <= CHUNK_SIZE,
                "effects.py chunk {i} has {} bytes, exceeds CHUNK_SIZE={CHUNK_SIZE}",
                chunk.len()
            );
        }
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, EFFECTS_PY,
            "chunked+reassembled effects.py must equal original"
        );
    }

    #[test]
    fn chunk_font_py_all_chunks_within_size_limit() {
        let chunks = chunk_at_char_boundaries(FONT_PY, CHUNK_SIZE);
        for (i, chunk) in chunks.iter().enumerate() {
            assert!(
                chunk.len() <= CHUNK_SIZE,
                "font.py chunk {i} has {} bytes, exceeds CHUNK_SIZE={CHUNK_SIZE}",
                chunk.len()
            );
        }
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, FONT_PY,
            "chunked+reassembled font.py must equal original"
        );
    }

    #[test]
    fn chunk_utf8_boundary_safety() {
        // 3-byte UTF-8 sequence: '€' is 0xE2 0x82 0xAC (3 bytes).
        // Build a string of 341 '€' chars = 1023 bytes, then add one ASCII 'x' = 1024 bytes.
        // With target_size=1022, the split must not land inside the 3-byte sequence.
        let euro_seq: String = "".repeat(341); // 1023 bytes
        let s = format!("{euro_seq}x"); // 1024 bytes total
        let chunks = chunk_at_char_boundaries(&s, 1022);
        // Every chunk must be valid UTF-8 (it is &str so this is guaranteed by Rust).
        // Additionally, every chunk must have byte length <= 1022.
        for (i, chunk) in chunks.iter().enumerate() {
            assert!(
                chunk.len() <= 1022,
                "UTF-8 boundary chunk {i} has {} bytes, exceeds limit 1022",
                chunk.len()
            );
        }
        let reassembled: String = chunks.concat();
        assert_eq!(
            reassembled, s,
            "UTF-8 chunked reassembly must equal original"
        );
    }

    // ── exec_with_cleanup tests ────────────────────────────────────────────────

    #[test]
    fn exec_with_cleanup_returns_ok_on_success() {
        let mut port = MockPort::with_responses(&[&MockPort::ok_frame()]);
        let resp = exec_with_cleanup(&mut port, "pass", "test_op").unwrap();
        assert!(!resp.is_error());
    }

    #[test]
    fn exec_with_cleanup_sends_ctrl_c_on_error() {
        // MockPort with NO scripted bytes → exec_code will return Err (UnexpectedEof).
        let mut port = MockPort::with_responses(&[]);
        let err = exec_with_cleanup(&mut port, "fail_op", "test_cleanup_op").unwrap_err();
        assert!(
            matches!(err, McpError::Protocol(_)),
            "expected McpError::Protocol, got: {err:?}"
        );
        // After the error, Ctrl-C (0x03) should appear in the written bytes.
        // The write_data will contain: "fail_op\x04" (from exec_code write_all) + 0x03 (Ctrl-C).
        assert!(
            port.write_data.contains(&0x03),
            "exec_with_cleanup must send Ctrl-C (0x03) on error; write_data={:?}",
            port.write_data
        );
    }

    #[test]
    fn exec_with_cleanup_wraps_error_with_op_name() {
        let mut port = MockPort::with_responses(&[]);
        let err = exec_with_cleanup(&mut port, "bad_code", "my_op_label").unwrap_err();
        match &err {
            McpError::Protocol(msg) => {
                assert!(
                    msg.starts_with("my_op_label:"),
                    "error message should be prefixed with op_name; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    // ── install (chunked) tests ────────────────────────────────────────────────

    /// Verify that fs_write_chunked sends the correct exec_code sequence when
    /// content exceeds CHUNK_SIZE and requires multiple chunks.
    ///
    /// Pattern for N chunks (open/write/close — no flush):
    ///   _ygg_f = open('<path>', 'w')     (open)
    ///   _ygg_f.write('''<chunk0>''')     (write chunk 0)
    ///   ...repeated N times...
    ///   _ygg_f.close()                   (close)
    ///   del _ygg_f                       (cleanup)
    ///
    /// Total exec_code calls: N + 3 (open + N writes + close + del).
    /// flush() is NOT called: jfs.flush is not in the JFS module globals table
    /// (modjumperless.c:4941-4972, confirmed audit 2026-05-10). The previous
    /// per-chunk flush() was a silent no-op; removing it is correct.
    #[test]
    fn fs_write_chunked_sends_assembly_sequence() {
        // 2100 bytes of ASCII → 3 chunks at CHUNK_SIZE=768: [768, 768, 564]
        let content: String = "x".repeat(2100);
        let path = "/test/file.py";

        let n_chunks = chunk_at_char_boundaries(&content, CHUNK_SIZE).len();
        assert_eq!(
            n_chunks, 3,
            "sanity: 2100-char content should split into 3 chunks at CHUNK_SIZE={CHUNK_SIZE}"
        );

        // exec_code calls: 1 open + 3 writes + 1 close + 1 del = N+3
        let frames: Vec<Vec<u8>> = (0..(n_chunks + 3)).map(|_| MockPort::ok_frame()).collect();
        let frame_refs: Vec<&[u8]> = frames.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);

        fs_write_chunked(&mut port, path, &content).unwrap();

        let written = String::from_utf8_lossy(&port.write_data);

        // Open call must be present.
        assert!(
            written.contains(&format!("_ygg_f = open('{path}', 'w')")),
            "should contain open call; written (truncated)={:.200}",
            &written
        );
        // write() calls must be present (multi-chunk).
        assert!(
            written.contains("_ygg_f.write("),
            "should contain _ygg_f.write() calls for multi-chunk content"
        );
        // Close call must be present.
        assert!(
            written.contains("_ygg_f.close()"),
            "should contain _ygg_f.close() call"
        );
        // Cleanup del.
        assert!(
            written.contains("del _ygg_f"),
            "should contain cleanup del _ygg_f"
        );
        // Phase C: flush() must NOT be called — jfs.flush is not bound on device.
        assert!(
            !written.contains("_ygg_f.flush()"),
            "must NOT call _ygg_f.flush() — jfs.flush is not in JFS globals table \
             (modjumperless.c:4941-4972). Phase C removes the silent no-op flush."
        );
        // Old _ygg_assembly pattern must NOT appear.
        assert!(
            !written.contains("_ygg_assembly"),
            "must not use old _ygg_assembly pattern"
        );
        // Old single-shot fs_write must NOT appear.
        assert!(
            !written.contains(&format!("fs_write('{path}',")),
            "must not call fs_write() directly — replaced by open/write/close"
        );
    }

    /// Verify that fs_write_chunked handles single-chunk content correctly:
    /// open + exactly one write + close + del (no flush).
    #[test]
    fn fs_write_chunked_single_chunk_no_appends() {
        // Content smaller than CHUNK_SIZE: fits in one chunk.
        let content = "short content here";
        let path = "/test/short.py";

        let n_chunks = chunk_at_char_boundaries(content, CHUNK_SIZE).len();
        assert_eq!(n_chunks, 1, "short content should produce exactly 1 chunk");

        // exec_code calls: 1 open + 1 write + 1 close + 1 del = 4 (N+3 = 1+3 = 4)
        let frames: Vec<Vec<u8>> = (0..4).map(|_| MockPort::ok_frame()).collect();
        let frame_refs: Vec<&[u8]> = frames.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);

        fs_write_chunked(&mut port, path, content).unwrap();

        let written = String::from_utf8_lossy(&port.write_data);

        // Must open the file.
        assert!(
            written.contains(&format!("_ygg_f = open('{path}', 'w')")),
            "single-chunk: should open with _ygg_f"
        );
        // Exactly one write call — count occurrences of the write marker.
        let write_count = written.matches("_ygg_f.write(").count();
        assert_eq!(
            write_count, 1,
            "single-chunk: must have exactly one _ygg_f.write() call, got {write_count}"
        );
        // Must close.
        assert!(
            written.contains("_ygg_f.close()"),
            "single-chunk: should close with _ygg_f.close()"
        );
        // Phase C: flush must NOT appear.
        assert!(
            !written.contains("_ygg_f.flush()"),
            "single-chunk: must NOT call _ygg_f.flush() — jfs.flush is not bound"
        );
        // Must del.
        assert!(
            written.contains("del _ygg_f"),
            "single-chunk: should cleanup del _ygg_f"
        );
        // Old patterns must not appear.
        assert!(
            !written.contains("_ygg_assembly"),
            "single-chunk: must not use old _ygg_assembly pattern"
        );
    }

    #[test]
    fn install_chunked_succeeds_for_effects_py_sized_content() {
        // Simulate an install with a >5KB string to confirm the chunking logic
        // produces a valid sequence. We use a synthetic string the same length as
        // effects.py (5703 bytes after CRLF→LF) rather than the real embedded file
        // to keep the test hermetic w.r.t. content escaping.
        let big_content: String = "x".repeat(5703);
        let path = "/python_scripts/lib/jumperless_mcp/effects.py";

        let n_chunks = chunk_at_char_boundaries(&big_content, CHUNK_SIZE).len();
        // 5703 / 768 = 7 full chunks (5376) + 1 remainder (327) = 8 chunks
        assert!(
            n_chunks >= 2,
            "5703-char string should require ≥2 chunks at CHUNK_SIZE={CHUNK_SIZE}"
        );

        // ok_frames: open(1) + writes(n) + close(1) + del(1) = n+3 (no flush)
        let frames: Vec<Vec<u8>> = (0..(n_chunks + 3)).map(|_| MockPort::ok_frame()).collect();
        let frame_refs: Vec<&[u8]> = frames.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);

        fs_write_chunked(&mut port, path, &big_content).unwrap();

        let written = String::from_utf8_lossy(&port.write_data);
        // Must use open/write/close protocol (no flush), never old fs_write(_ygg_assembly).
        assert!(
            written.contains(&format!("_ygg_f = open('{path}', 'w')")),
            "5KB+ write must open file with _ygg_f"
        );
        assert!(
            written.contains("_ygg_f.write("),
            "5KB+ write must use _ygg_f.write() calls"
        );
        // Phase C: no flush — jfs.flush is not bound.
        assert!(
            !written.contains("_ygg_f.flush()"),
            "5KB+ write must NOT call _ygg_f.flush() — jfs.flush is not in JFS globals"
        );
        assert!(
            written.contains("_ygg_f.close()"),
            "5KB+ write must close with _ygg_f.close()"
        );
        assert!(
            !written.contains("_ygg_assembly"),
            "5KB+ write must not use old _ygg_assembly pattern"
        );
        // Verify write count matches n_chunks.
        let write_count = written.matches("_ygg_f.write(").count();
        assert_eq!(
            write_count, n_chunks,
            "write call count ({write_count}) must equal chunk count ({n_chunks})"
        );
    }

    // ── check_installation tests (MockPort) ────────────────────────────────────

    #[test]
    fn check_installation_all_present_and_current() {
        // Responses for: read_installed_version (1 call), then 4 fs_exists calls
        // (VERSION, font.py, effects.py, __init__.py)
        let responses: &[&[u8]] = &[
            // read_installed_version: import jumperless_mcp; print(__version__)
            &MockPort::ok_with_stdout(LIBRARY_VERSION),
            // fs_exists(VERSION_PATH) → 1
            &MockPort::ok_with_stdout("1"),
            // fs_exists(FONT_PATH) → 1
            &MockPort::ok_with_stdout("1"),
            // fs_exists(EFFECTS_PATH) → 1
            &MockPort::ok_with_stdout("1"),
            // fs_exists(INIT_PATH) → 1
            &MockPort::ok_with_stdout("1"),
        ];
        let mut port = MockPort::with_responses(responses);
        let status = check_installation(&mut port).unwrap();
        assert!(status.installed);
        assert!(!status.partial, "all files present → partial=false");
        assert!(status.up_to_date);
        assert_eq!(status.installed_version.as_deref(), Some(LIBRARY_VERSION));
        assert_eq!(status.current_version, LIBRARY_VERSION);
        assert_eq!(status.files_missing.len(), 0);
        assert_eq!(status.files_present.len(), 4);
    }

    #[test]
    fn check_installation_not_installed_all_missing() {
        // read_installed_version returns empty (ImportError → not installed)
        // 4 fs_exists calls all return 0
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout(""),  // ImportError → not installed
            &MockPort::ok_with_stdout("0"), // VERSION missing
            &MockPort::ok_with_stdout("0"), // font.py missing
            &MockPort::ok_with_stdout("0"), // effects.py missing
            &MockPort::ok_with_stdout("0"), // __init__.py missing
        ];
        let mut port = MockPort::with_responses(responses);
        let status = check_installation(&mut port).unwrap();
        assert!(!status.installed);
        assert!(!status.up_to_date);
        assert!(status.installed_version.is_none());
        assert_eq!(status.files_present.len(), 0);
        assert_eq!(status.files_missing.len(), 4);
    }

    #[test]
    fn check_installation_stale_version() {
        // All four files present but VERSION reports old version.
        // installed=true (all files present + version readable), up_to_date=false.
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout("0.1.0+20260510"), // old version
            &MockPort::ok_with_stdout("1"),
            &MockPort::ok_with_stdout("1"),
            &MockPort::ok_with_stdout("1"),
            &MockPort::ok_with_stdout("1"),
        ];
        let mut port = MockPort::with_responses(responses);
        let status = check_installation(&mut port).unwrap();
        assert!(
            status.installed,
            "stale version with all files present → installed=true"
        );
        assert!(!status.partial, "all files present → partial=false");
        assert!(!status.up_to_date); // version mismatch
        assert_eq!(status.installed_version.as_deref(), Some("0.1.0+20260510"));
    }

    /// HIGH-1: partial install (1 of 4 files present) must yield installed=false, partial=true.
    #[test]
    fn check_installation_partial_install_is_not_installed() {
        // Only VERSION present (the first file checked); others missing.
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout(LIBRARY_VERSION), // version readable
            &MockPort::ok_with_stdout("1"),             // VERSION present
            &MockPort::ok_with_stdout("0"),             // font.py missing
            &MockPort::ok_with_stdout("0"),             // effects.py missing
            &MockPort::ok_with_stdout("0"),             // __init__.py missing
        ];
        let mut port = MockPort::with_responses(responses);
        let status = check_installation(&mut port).unwrap();
        assert!(
            !status.installed,
            "partial install must NOT report installed=true"
        );
        assert!(status.partial, "partial install must set partial=true");
        assert_eq!(status.files_present.len(), 1);
        assert_eq!(status.files_missing.len(), 3);
    }

    // ── install_if_needed tests (MockPort) ─────────────────────────────────────

    #[test]
    fn install_if_needed_skips_when_up_to_date() {
        // check returns current version + all 4 files present → no install
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout(LIBRARY_VERSION),
            &MockPort::ok_with_stdout("1"),
            &MockPort::ok_with_stdout("1"),
            &MockPort::ok_with_stdout("1"),
            &MockPort::ok_with_stdout("1"),
        ];
        let mut port = MockPort::with_responses(responses);
        let installed = install_if_needed(&mut port).unwrap();
        assert!(!installed, "should return false when already up-to-date");
    }

    #[test]
    fn install_if_needed_installs_when_missing() {
        // check: not installed; then install via chunked writes.
        // Frame accounting (Phase A+B+C):
        //   check_installation: 1 (version read) + 4 (fs_exists for VERSION/font/effects/init) = 5 reads
        //   install:
        //     mkdir: 1 frame (3 mkdir calls in one script)
        //     font.py chunked: n_font+3 (open + N writes + close + del) + 1 (readback) frames
        //     effects.py chunked: n_effects+3 + 1 readback frames
        //     __init__.py chunked: n_init+3 + 1 readback frames
        //     VERSION direct: 1 frame
        //
        // Phase C removed per-chunk flush: frame count is N+3 (not 2N+3 as before).
        let n_font = chunk_at_char_boundaries(FONT_PY, CHUNK_SIZE).len();
        let n_effects = chunk_at_char_boundaries(EFFECTS_PY, CHUNK_SIZE).len();
        let n_init = chunk_at_char_boundaries(INIT_PY, CHUNK_SIZE).len();

        let mut responses: Vec<Vec<u8>> = vec![
            // check_installation (5 frames: version + 4 fs_exists)
            MockPort::ok_with_stdout(""), // version empty (ImportError → not installed)
            MockPort::ok_with_stdout("0"), // VERSION missing
            MockPort::ok_with_stdout("0"), // font.py missing
            MockPort::ok_with_stdout("0"), // effects.py missing
            MockPort::ok_with_stdout("0"), // __init__.py missing
        ];
        // install: mkdir (1 frame for the combined mkdir script)
        responses.push(MockPort::ok_frame());
        // install: font.py chunked (open(1) + N writes + close(1) + del(1) + readback(1) = N+4 frames)
        for _ in 0..(n_font + 3) {
            responses.push(MockPort::ok_frame());
        }
        responses.push(MockPort::ok_with_stdout("1000")); // readback: simulated byte count
                                                          // install: effects.py chunked (n_effects+3 + 1 readback)
        for _ in 0..(n_effects + 3) {
            responses.push(MockPort::ok_frame());
        }
        responses.push(MockPort::ok_with_stdout("5000")); // readback: simulated byte count
                                                          // install: __init__.py chunked (n_init+3 + 1 readback)
        for _ in 0..(n_init + 3) {
            responses.push(MockPort::ok_frame());
        }
        responses.push(MockPort::ok_with_stdout("2000")); // readback: simulated byte count
                                                          // install: VERSION direct (1 frame)
        responses.push(MockPort::ok_frame());

        let frame_refs: Vec<&[u8]> = responses.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);
        let installed = install_if_needed(&mut port).unwrap();
        assert!(installed, "should return true when install was performed");
    }

    // ── uninstall tests (MockPort) ─────────────────────────────────────────────

    #[test]
    fn uninstall_returns_summary_all_ok() {
        // 4 file remove calls + 1 fs_rmdir = 5 exec_code calls total.
        // Phase C: no UNBOUND token, no VERSION-clear fallback.
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout("OK"), // font.py → removed
            &MockPort::ok_with_stdout("OK"), // effects.py → removed
            &MockPort::ok_with_stdout("OK"), // __init__.py → removed
            &MockPort::ok_with_stdout("OK"), // VERSION → removed
            &MockPort::ok_frame(),           // fs_rmdir (best-effort)
        ];
        let mut port = MockPort::with_responses(responses);
        let result = uninstall(&mut port).unwrap();
        assert_eq!(result.attempted, 4);
        assert_eq!(result.attempted_actual, 4);
        assert_eq!(result.removed, 4);
        assert!(
            result.errors.is_empty(),
            "no errors expected; got: {:?}",
            result.errors
        );
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(
            written.contains("jumperless.jfs.remove"),
            "uninstall must call jumperless.jfs.remove; got: {written}"
        );
        // Phase C: no legacy fs_remove fallback, no VERSION-clear workaround.
        assert!(
            !written.contains("fs_write") || !written.contains("''"),
            "uninstall must NOT use VERSION-clearing fallback (Phase C removed it)"
        );
    }

    #[test]
    fn uninstall_no_unbound_token_in_script() {
        // Phase C: the simplified uninstall script must not classify UNBOUND.
        // jfs.remove is confirmed bound — no fallback needed.
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout("OK"),
            &MockPort::ok_with_stdout("OK"),
            &MockPort::ok_with_stdout("OK"),
            &MockPort::ok_with_stdout("OK"),
            &MockPort::ok_frame(),
        ];
        let mut port = MockPort::with_responses(responses);
        uninstall(&mut port).unwrap();
        let written = String::from_utf8_lossy(&port.write_data);
        assert!(
            !written.contains("UNBOUND"),
            "uninstall must NOT classify UNBOUND (Phase C: jfs.remove is confirmed bound); got: {written}"
        );
    }

    /// OSError (file absent) counts as already-removed: removed increments, no error.
    #[test]
    fn uninstall_counts_absent_file_as_removed() {
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout("ABSENT"), // font.py already gone
            &MockPort::ok_with_stdout("OK"),     // effects.py removed
            &MockPort::ok_with_stdout("OK"),     // __init__.py removed
            &MockPort::ok_with_stdout("ABSENT"), // VERSION already gone
            &MockPort::ok_frame(),               // fs_rmdir
        ];
        let mut port = MockPort::with_responses(responses);
        let result = uninstall(&mut port).unwrap();
        assert_eq!(result.removed, 4, "ABSENT + OK + OK + ABSENT = 4 removes");
        assert_eq!(result.attempted_actual, 4, "all 4 files attempted");
        assert!(result.errors.is_empty());
    }

    /// Unexpected exception token: captured in errors, not counted as removed.
    #[test]
    fn uninstall_captures_unexpected_errors() {
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout("ERR:IOError something weird"), // font.py → unexpected
            &MockPort::ok_with_stdout("OK"),                          // effects.py → removed
            &MockPort::ok_with_stdout("OK"),                          // __init__.py → removed
            &MockPort::ok_with_stdout("OK"),                          // VERSION → removed
            &MockPort::ok_frame(),                                    // fs_rmdir
        ];
        let mut port = MockPort::with_responses(responses);
        let result = uninstall(&mut port).unwrap();
        assert_eq!(result.removed, 3, "OK+OK+OK = 3 removes; ERR doesn't count");
        assert_eq!(
            result.attempted_actual, 4,
            "ERR doesn't break the loop; all 4 attempted"
        );
        assert_eq!(
            result.errors.len(),
            1,
            "unexpected exception → 1 error entry"
        );
        assert!(result.errors[0].contains("ERR:IOError"));
    }

    // ── Constants tests ────────────────────────────────────────────────────────

    #[test]
    fn library_paths_start_with_library_root() {
        assert!(FONT_PATH.starts_with(LIBRARY_ROOT));
        assert!(EFFECTS_PATH.starts_with(LIBRARY_ROOT));
        assert!(INIT_PATH.starts_with(LIBRARY_ROOT));
        assert!(VERSION_PATH.starts_with(LIBRARY_ROOT));
    }

    #[test]
    fn install_paths_are_under_python_scripts_lib() {
        // Phase A: all install paths must be under /python_scripts/lib/
        assert!(
            LIBRARY_ROOT.starts_with(PYTHON_SCRIPTS_LIB),
            "LIBRARY_ROOT must be under /python_scripts/lib/ (sys.path); got: {LIBRARY_ROOT}"
        );
        assert!(
            FONT_PATH.starts_with(PYTHON_SCRIPTS_LIB),
            "FONT_PATH must be under /python_scripts/lib/; got: {FONT_PATH}"
        );
        assert!(
            EFFECTS_PATH.starts_with(PYTHON_SCRIPTS_LIB),
            "EFFECTS_PATH must be under /python_scripts/lib/; got: {EFFECTS_PATH}"
        );
        assert!(
            INIT_PATH.starts_with(PYTHON_SCRIPTS_LIB),
            "INIT_PATH must be under /python_scripts/lib/; got: {INIT_PATH}"
        );
        assert!(
            VERSION_PATH.starts_with(PYTHON_SCRIPTS_LIB),
            "VERSION_PATH must be under /python_scripts/lib/; got: {VERSION_PATH}"
        );
    }

    #[test]
    fn init_py_contains_version_string() {
        // Phase A/B: __init__.py must embed the version so import-based version
        // detection works without reading a separate VERSION file. The version
        // string must match LIBRARY_VERSION (the Rust-side source of truth) so
        // host and device agree on what's installed.
        assert!(
            INIT_PY.contains(LIBRARY_VERSION),
            "INIT_PY must contain LIBRARY_VERSION ({LIBRARY_VERSION}); got INIT_PY start: {:.100}",
            INIT_PY
        );
        assert!(
            INIT_PY.contains("__version__"),
            "INIT_PY must define __version__"
        );
    }

    #[test]
    fn init_py_contains_ceremony_functions() {
        // Phase B: __init__.py must define both ceremony entry points.
        assert!(
            INIT_PY.contains("def _ceremony_connect"),
            "INIT_PY must define _ceremony_connect()"
        );
        assert!(
            INIT_PY.contains("def _ceremony_disconnect"),
            "INIT_PY must define _ceremony_disconnect()"
        );
    }

    #[test]
    fn font_py_contains_font_dict() {
        assert!(
            FONT_PY.contains("FONT = {"),
            "font.py must define FONT dict"
        );
    }

    #[test]
    fn effects_py_contains_key_functions() {
        assert!(
            EFFECTS_PY.contains("def marquee("),
            "effects.py must define marquee"
        );
        assert!(
            EFFECTS_PY.contains("def marquee_scroll("),
            "effects.py must define marquee_scroll"
        );
        assert!(
            EFFECTS_PY.contains("def corner_frame("),
            "effects.py must define corner_frame"
        );
        assert!(
            EFFECTS_PY.contains("def wipe_edges("),
            "effects.py must define wipe_edges"
        );
    }

    #[test]
    fn effects_py_defines_nasa_orange() {
        assert!(
            EFFECTS_PY.contains("NASA_ORANGE = 0xFC4C00"),
            "effects.py must define NASA_ORANGE constant"
        );
    }

    #[test]
    fn font_py_covers_mcp_connected_chars() {
        for ch in &[
            "\"M\"", "\"C\"", "\"P\"", "\"O\"", "\"N\"", "\"E\"", "\"T\"", "\"D\"", "\" \"",
        ] {
            assert!(
                FONT_PY.contains(ch),
                "font.py FONT dict must include key {} (needed for 'MCP CONNECTED')",
                ch
            );
        }
    }

    #[test]
    fn font_py_covers_mcp_disconnected_chars() {
        // "MCP DISCONNECTED" needs: M, C, P, D, I, S, O, N, E, T + space
        for ch in &["\"I\"", "\"S\""] {
            assert!(
                FONT_PY.contains(ch),
                "font.py FONT dict must include key {} (needed for 'MCP DISCONNECTED')",
                ch
            );
        }
    }

    // ── HIGH-1: exec_with_cleanup resp.is_error() propagation tests ───────────

    /// HIGH-1: exec_with_cleanup must convert a device-side exception (is_error()==true)
    /// into McpError::Protocol, not silently return Ok(resp).
    ///
    /// This is the core gap: before the fix, fs_write_chunked would call exec_with_cleanup
    /// and trust that Ok(resp) meant success, even when resp.stderr was non-empty and
    /// resp.is_error() returned true (MicroPython raised an exception device-side).
    /// A MemoryError mid-concat → install appears to succeed → corrupt file on disk.
    #[test]
    fn exec_with_cleanup_rejects_device_side_exception() {
        // Build a response frame that looks like a device-side exception:
        // "OK" prefix + empty stdout + non-empty stderr + prompt.
        // Format: b"OK" + stdout_bytes + b"\x04" + stderr_bytes + b"\x04>"
        let stderr_msg = b"MemoryError: memory allocation failed";
        let mut frame = b"OK".to_vec();
        // stdout portion is empty
        frame.push(b'\x04');
        // stderr portion has the exception
        frame.extend_from_slice(stderr_msg);
        frame.push(b'\x04');
        frame.push(b'>');

        let mut port = MockPort::with_responses(&[frame.as_slice()]);
        let result = exec_with_cleanup(
            &mut port,
            "big_concat_op()",
            "fs_write_chunked(x): chunk 1 (append)",
        );

        // Must be Err, not Ok
        assert!(
            result.is_err(),
            "exec_with_cleanup must return Err when resp.is_error() is true; \
             got Ok (device exception silently absorbed)"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("device-side exception"),
                    "error must mention device-side exception; got: {msg}"
                );
                assert!(
                    msg.contains("MemoryError"),
                    "error must include the device stderr content; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
        // Ctrl-C (0x03) should have been sent after the device-side exception.
        assert!(
            port.write_data.contains(&0x03),
            "exec_with_cleanup must send Ctrl-C after device-side exception; write_data={:?}",
            port.write_data
        );
    }

    // ── HIGH-3: del cleanup match tests ───────────────────────────────────────

    /// HIGH-3: del cleanup — device-side exception should be logged at debug, not propagate.
    /// This tests that fs_write_chunked doesn't return Err from the cleanup `del _ygg_f`.
    #[test]
    fn fs_write_chunked_del_cleanup_device_exception_does_not_propagate() {
        let content = "short content";
        let path = "/test/file.py";

        // Frames: open (ok), write (ok), close (ok), del (device exception — should be absorbed)
        let del_exception_frame = {
            let mut frame = b"OK".to_vec();
            frame.push(b'\x04');
            frame.extend_from_slice(b"NameError: name '_ygg_f' is not defined");
            frame.push(b'\x04');
            frame.push(b'>');
            frame
        };

        // We can't use an inline responses slice due to lifetime issues (del_exception_frame
        // is owned; we need Vec<Vec<u8>> for the refs to be valid).
        // Single-chunk: open + 1 write + 1 flush + close + del = 5 frames (2N+3 = 2*1+3 = 5).
        let frames: Vec<Vec<u8>> = vec![
            MockPort::ok_frame(), // open
            MockPort::ok_frame(), // write chunk 0
            MockPort::ok_frame(), // flush chunk 0
            MockPort::ok_frame(), // close
            del_exception_frame,  // del _ygg_f — device exception, must be absorbed
        ];
        let frame_refs: Vec<&[u8]> = frames.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);

        // fs_write_chunked should return Ok(()) even when del cleanup has a device exception.
        let result = fs_write_chunked(&mut port, path, content);
        assert!(
            result.is_ok(),
            "del _ygg_f device exception must not propagate from fs_write_chunked; got: {result:?}"
        );
    }

    // ── MEDIUM-C: read_installed_version Result<Option<String>> tests ─────────

    /// MEDIUM-C: read_installed_version returns Ok(Some(version)) when file present.
    #[test]
    fn read_installed_version_returns_some_when_present() {
        let mut port = MockPort::with_responses(&[&MockPort::ok_with_stdout(LIBRARY_VERSION)]);
        let result = read_installed_version(&mut port);
        assert!(result.is_ok(), "should succeed; got: {result:?}");
        assert_eq!(result.unwrap(), Some(LIBRARY_VERSION.to_string()));
    }

    /// MEDIUM-C: read_installed_version returns Ok(None) when file missing (empty stdout).
    #[test]
    fn read_installed_version_returns_none_when_missing() {
        let mut port = MockPort::with_responses(&[&MockPort::ok_with_stdout("")]);
        let result = read_installed_version(&mut port);
        assert!(
            result.is_ok(),
            "empty stdout = missing file; should be Ok(None)"
        );
        assert_eq!(result.unwrap(), None);
    }

    /// MEDIUM-C: read_installed_version returns Err on protocol-level failure (no bytes).
    #[test]
    fn read_installed_version_returns_err_on_protocol_failure() {
        // Empty MockPort → exec_code returns Err(UnexpectedEof).
        let mut port = MockPort::with_responses(&[]);
        let result = read_installed_version(&mut port);
        assert!(
            result.is_err(),
            "protocol-level failure must be Err, not Ok(None); got: {result:?}"
        );
    }

    // ── MEDIUM-D: attempted_actual reflects actual loop iterations ────────────

    /// Phase C: reinstall returns ReinstallResult carrying pre_uninstall info.
    /// With jfs.remove confirmed bound, all 4 files are removed before install.
    #[test]
    fn reinstall_result_carries_pre_uninstall_info() {
        // Sequence for reinstall:
        //   uninstall phase: 4 file removes (OK) + fs_rmdir
        //   install phase:
        //     check_installation: read_version(empty) + 4×fs_exists(0)
        //     install: mkdir(1) + font(n+3+1) + effects(n+3+1) + init(n+3+1) + VERSION(1)
        let n_font = chunk_at_char_boundaries(FONT_PY, CHUNK_SIZE).len();
        let n_effects = chunk_at_char_boundaries(EFFECTS_PY, CHUNK_SIZE).len();
        let n_init = chunk_at_char_boundaries(INIT_PY, CHUNK_SIZE).len();

        let mut responses: Vec<Vec<u8>> = vec![
            // uninstall: 4 files + rmdir
            MockPort::ok_with_stdout("OK"), // font.py
            MockPort::ok_with_stdout("OK"), // effects.py
            MockPort::ok_with_stdout("OK"), // __init__.py
            MockPort::ok_with_stdout("OK"), // VERSION
            MockPort::ok_frame(),           // fs_rmdir
            // check_installation (5 frames)
            MockPort::ok_with_stdout(""),  // version empty
            MockPort::ok_with_stdout("0"), // VERSION missing
            MockPort::ok_with_stdout("0"), // font.py missing
            MockPort::ok_with_stdout("0"), // effects.py missing
            MockPort::ok_with_stdout("0"), // __init__.py missing
        ];
        // mkdir (1 frame)
        responses.push(MockPort::ok_frame());
        // font.py: open + N writes + close + del + readback
        for _ in 0..(n_font + 3) {
            responses.push(MockPort::ok_frame());
        }
        responses.push(MockPort::ok_with_stdout("1000"));
        // effects.py
        for _ in 0..(n_effects + 3) {
            responses.push(MockPort::ok_frame());
        }
        responses.push(MockPort::ok_with_stdout("5000"));
        // __init__.py
        for _ in 0..(n_init + 3) {
            responses.push(MockPort::ok_frame());
        }
        responses.push(MockPort::ok_with_stdout("2000"));
        // VERSION direct
        responses.push(MockPort::ok_frame());

        let frame_refs: Vec<&[u8]> = responses.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);

        let result = reinstall(&mut port).unwrap();
        assert_eq!(result.installed_version, LIBRARY_VERSION);
        let pre = result.pre_uninstall.expect("pre_uninstall should be Some");
        assert_eq!(
            pre.removed, 4,
            "all 4 files should be removed in pre-uninstall"
        );
        assert!(pre.errors.is_empty(), "clean uninstall has no errors");
    }

    /// MEDIUM-D: attempted_actual tracks actual loop iterations.
    #[test]
    fn uninstall_attempted_actual_reflects_actual_iterations() {
        // All 4 files attempted — no early break (no UNBOUND path in Phase C).
        let responses: &[&[u8]] = &[
            &MockPort::ok_with_stdout("OK"),     // font.py → removed
            &MockPort::ok_with_stdout("OK"),     // effects.py → removed
            &MockPort::ok_with_stdout("ABSENT"), // __init__.py already gone
            &MockPort::ok_with_stdout("OK"),     // VERSION → removed
            &MockPort::ok_frame(),               // fs_rmdir
        ];
        let mut port = MockPort::with_responses(responses);
        let result = uninstall(&mut port).unwrap();
        assert_eq!(result.attempted, 4, "attempted = intent (4 files)");
        assert_eq!(result.attempted_actual, 4, "all 4 files attempted");
        assert_eq!(result.removed, 4, "OK+OK+ABSENT+OK = 4 removes");
    }

    // ── Fix 4: read_installed_version is_error() check ────────────────────────

    /// Fix 4: read_installed_version must return Err when resp.is_error()==true,
    /// not silently treat the empty stdout as "file missing". Real triggers:
    /// MemoryError during parse (OOMs before try block runs) and KeyboardInterrupt
    /// (BaseException subclass, not caught by except Exception).
    #[test]
    fn read_installed_version_returns_err_on_device_side_exception() {
        // Build a frame with is_error()==true: empty stdout, non-empty stderr.
        // Format: b"OK" + empty_stdout + \x04 + stderr_bytes + \x04>
        let stderr_msg = b"MemoryError: memory allocation failed, allocating 16 bytes";
        let mut frame = b"OK".to_vec();
        frame.push(b'\x04');
        frame.extend_from_slice(stderr_msg);
        frame.push(b'\x04');
        frame.push(b'>');

        let mut port = MockPort::with_responses(&[frame.as_slice()]);
        let result = read_installed_version(&mut port);

        assert!(
            result.is_err(),
            "read_installed_version must return Err when resp.is_error()==true; \
             got Ok (device exception silently treated as file-missing)"
        );
        match result.unwrap_err() {
            McpError::Protocol(msg) => {
                assert!(
                    msg.contains("device-side exception"),
                    "error must contain 'device-side exception'; got: {msg}"
                );
                assert!(
                    msg.contains("MemoryError"),
                    "error must include device stderr content; got: {msg}"
                );
            }
            other => panic!("expected McpError::Protocol, got: {other:?}"),
        }
    }

    // ── Fix 5: uninstall per-file is_error() check ────────────────────────────

    /// Fix 5: when a per-file exec_code returns Ok(resp) with is_error()==true
    /// (e.g. MemoryError mid-print), the error must surface in UninstallResult.errors
    /// with the stderr content — not fall through to the `_ =>` arm as an empty-token
    /// "unrecognised token ''" message that hides the real cause.
    ///
    /// Scenario: 4 files. File 1 OK, file 2 device exception, file 3 OK, file 4 OK.
    /// The device-exception does NOT break the loop, so remaining files are still attempted.
    #[test]
    fn uninstall_per_file_device_exception_surfaces_in_errors() {
        // Build a frame with is_error()==true for the second file.
        let exception_frame = {
            let mut frame = b"OK".to_vec();
            frame.push(b'\x04');
            frame.extend_from_slice(b"MemoryError: out of memory printing token");
            frame.push(b'\x04');
            frame.push(b'>');
            frame
        };
        let frames: Vec<Vec<u8>> = vec![
            MockPort::ok_with_stdout("OK"), // font.py → removed
            exception_frame,                // effects.py → device exception
            MockPort::ok_with_stdout("OK"), // __init__.py → removed
            MockPort::ok_with_stdout("OK"), // VERSION → removed
            MockPort::ok_frame(),           // fs_rmdir (best-effort)
        ];
        let frame_refs: Vec<&[u8]> = frames.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);
        let result = uninstall(&mut port).unwrap();

        // Three files successfully removed (font.py + __init__.py + VERSION).
        assert_eq!(
            result.removed, 3,
            "font.py + __init__.py + VERSION should be removed; got {}",
            result.removed
        );
        // The exception entry must appear in errors.
        assert!(
            !result.errors.is_empty(),
            "device exception must surface in errors; got empty errors"
        );
        assert!(
            result
                .errors
                .iter()
                .any(|e| e.contains("device-side exception") && e.contains("MemoryError")),
            "errors must contain 'device-side exception' + stderr content; got: {:?}",
            result.errors
        );
        assert_eq!(
            result.attempted_actual, 4,
            "exception doesn't break loop; all 4 attempted"
        );
    }

    // ── CHUNK_SIZE payload-fits-in-buffer property test ───────────────────────

    /// HIGH-2: verify that the largest possible chunk payload (append wrapper)
    /// fits within a 1024-byte REPL buffer including the 8-byte safety margin.
    /// This is the runtime companion to the compile-time const assertion.
    #[test]
    fn chunk_size_payload_fits_in_repl_buffer() {
        let append_wrapper = "_ygg_assembly = _ygg_assembly + ''''''".len(); // 38 bytes for wrappers
        let max_payload = CHUNK_SIZE + append_wrapper;
        assert!(
            max_payload + 8 <= 1024,
            "CHUNK_SIZE={CHUNK_SIZE} + append wrapper ({append_wrapper}) + 8 safety = {} \
             must fit in 1024-byte REPL buffer",
            max_payload + 8
        );
    }

    // ── LIBRARY_VERSION + metadata test ───────────────────────────────────────

    /// MEDIUM-J: LIBRARY_VERSION must contain '+' (SemVer 2.0 build metadata).
    /// The compile-time const assertion enforces this; this test documents it as a
    /// specification test visible in test output.
    #[test]
    fn library_version_contains_build_metadata_marker() {
        assert!(
            LIBRARY_VERSION.contains('+'),
            "LIBRARY_VERSION must contain '+' for SemVer 2.0 build metadata; got: {LIBRARY_VERSION}"
        );
    }

    // ── parse_device_verify_output tests ──────────────────────────────────────

    /// Happy path: device returns size + SHA-256 (hashlib available).
    #[test]
    fn parse_verify_size_and_hash_present() {
        let stdout =
            "size:5372\nsha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890\n";
        let (size, sha, hash_avail) = parse_device_verify_output(stdout).unwrap();
        assert_eq!(size, Some(5372));
        assert_eq!(
            sha.as_deref(),
            Some("abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890")
        );
        assert!(
            hash_avail,
            "hash_available should be true when a hex sha256 is returned"
        );
    }

    /// hashlib unavailable: device returns `sha256:NO_HASHLIB` sentinel.
    /// Parser must set hash_available=false and device_sha256=None.
    #[test]
    fn parse_verify_no_hashlib_sentinel() {
        let stdout = "size:234\nsha256:NO_HASHLIB\n";
        let (size, sha, hash_avail) = parse_device_verify_output(stdout).unwrap();
        assert_eq!(size, Some(234));
        assert!(
            sha.is_none(),
            "NO_HASHLIB sentinel must produce None device_sha256"
        );
        assert!(
            !hash_avail,
            "hash_available must be false when NO_HASHLIB returned"
        );
    }

    /// File missing on device: device returns `size:MISSING` + `sha256:MISSING`.
    /// Parser must return Ok with all-None (not an error — just absent).
    #[test]
    fn parse_verify_missing_file() {
        let stdout = "size:MISSING\nsha256:MISSING\n";
        let (size, sha, hash_avail) = parse_device_verify_output(stdout).unwrap();
        assert!(size.is_none(), "size must be None for MISSING file");
        assert!(sha.is_none(), "sha256 must be None for MISSING file");
        assert!(!hash_avail, "hash_available must be false for MISSING file");
    }

    /// Device script returned `error:` line with NO preceding size: — must surface as Err.
    /// (The file was likely unreadable before any output was produced.)
    #[test]
    fn parse_verify_error_line_returns_err() {
        let stdout = "error:OSError: [Errno 2] ENOENT\n";
        let result = parse_device_verify_output(stdout);
        assert!(result.is_err(), "error: line with no size must produce Err");
        let msg = result.unwrap_err();
        assert!(
            msg.contains("ENOENT"),
            "error message must include device error text; got: {msg}"
        );
    }

    /// Live failure mode (Sam's V5 5.6.6.2 firmware): size: is emitted successfully,
    /// then the script hits `AttributeError: 'sha256' object has no attribute 'hexdigest'`
    /// and emits error:.  Parser must preserve the size and treat hash as unavailable,
    /// NOT discard the file as an error.
    #[test]
    fn parse_verify_size_present_with_error_after() {
        let stdout = "size:5372\nerror:'sha256' object has no attribute 'hexdigest'\n";
        let (size, sha, hash_avail) = parse_device_verify_output(stdout).unwrap();
        assert_eq!(
            size,
            Some(5372),
            "size must be preserved even when error: follows"
        );
        assert!(sha.is_none(), "sha256 must be None when hash errored");
        assert!(
            !hash_avail,
            "hash_available must be false when hash errored"
        );
    }

    /// hexlify fallback sentinel: device emits `sha256:NO_HEX_AVAILABLE` when both
    /// `.hexdigest()` and `binascii.hexlify()` failed.  Parser must treat it as
    /// size-only (hash_available=false, device_sha256=None).
    #[test]
    fn parse_verify_no_hex_available_sentinel() {
        let stdout = "size:234\nsha256:NO_HEX_AVAILABLE\n";
        let (size, sha, hash_avail) = parse_device_verify_output(stdout).unwrap();
        assert_eq!(size, Some(234));
        assert!(
            sha.is_none(),
            "NO_HEX_AVAILABLE sentinel must produce None device_sha256"
        );
        assert!(
            !hash_avail,
            "hash_available must be false for NO_HEX_AVAILABLE sentinel"
        );
    }

    // ── parse_dump_output + hex_to_bytes tests ────────────────────────────────

    /// Happy path: device returns `size:N` + `hex:HEXHEX` — parse into (Some(size), Some(bytes)).
    #[test]
    fn parse_dump_output_happy_path() {
        // "Hello" = 0x48 0x65 0x6c 0x6c 0x6f (5 bytes)
        let stdout = "size:5\nhex:48656c6c6f\n";
        let (size, content) = parse_dump_output(stdout).unwrap();
        assert_eq!(size, Some(5), "size must be 5");
        assert_eq!(
            content.as_deref(),
            Some(b"Hello".as_ref()),
            "decoded bytes must equal b\"Hello\""
        );
    }

    /// Missing file: device returns `size:MISSING` + `hex:MISSING` — parse into (None, None).
    #[test]
    fn parse_dump_output_missing_file() {
        let stdout = "size:MISSING\nhex:MISSING\n";
        let (size, content) = parse_dump_output(stdout).unwrap();
        assert!(size.is_none(), "size must be None for missing file");
        assert!(content.is_none(), "content must be None for missing file");
    }

    /// hex_to_bytes round-trips 0x00..=0xff correctly and tolerates uppercase hex.
    #[test]
    fn hex_to_bytes_round_trip() {
        // Build bytes 0x00..=0xff.
        let all_bytes: Vec<u8> = (0u8..=255u8).collect();
        // Encode lowercase.
        let hex_lower: String = all_bytes.iter().map(|b| format!("{b:02x}")).collect();
        let decoded_lower = hex_to_bytes(&hex_lower).expect("lowercase hex must decode cleanly");
        assert_eq!(
            decoded_lower, all_bytes,
            "lowercase hex round-trip must recover all 256 byte values"
        );
        // Encode uppercase.
        let hex_upper: String = all_bytes.iter().map(|b| format!("{b:02X}")).collect();
        let decoded_upper = hex_to_bytes(&hex_upper).expect("uppercase hex must decode cleanly");
        assert_eq!(
            decoded_upper, all_bytes,
            "uppercase hex round-trip must recover all 256 byte values"
        );
    }

    // ── jfs read path tests ────────────────────────────────────────────────────

    /// device_verify_script must use jfs (jumperless.jfs.open) instead of bare
    /// fs_read so that files >4KB are read without truncation (firmware 5.6.6.2
    /// static 4096-byte buffer in JumperlessMicroPythonAPI.cpp).
    /// Must pass an explicit size arg to bypass the no-args default truncation.
    #[test]
    fn device_verify_script_uses_jfs_pattern() {
        let script = device_verify_script("/jumperless_mcp/effects.py");
        assert!(
            script.contains("jumperless.jfs.open"),
            "device_verify_script must use jfs for read; got:\n{script}"
        );
        assert!(
            script.contains(&format!(
                "jumperless.jfs.read(_ygg_rf, {JFS_READ_MAX_BYTES})"
            )),
            "device_verify_script must pass explicit size to jfs.read; got:\n{script}"
        );
        assert!(
            script.contains("except (NameError, AttributeError)"),
            "device_verify_script must include jfs-fallback handler; got:\n{script}"
        );
        assert!(
            script.contains("fs_read("),
            "device_verify_script must retain fs_read as fallback; got:\n{script}"
        );
    }

    /// device_dump_script must use jfs for the same reason, with explicit size arg.
    #[test]
    fn device_dump_script_uses_jfs_pattern() {
        let script = device_dump_script("/jumperless_mcp/effects.py");
        assert!(
            script.contains("jumperless.jfs.open"),
            "device_dump_script must use jfs for read; got:\n{script}"
        );
        assert!(
            script.contains(&format!(
                "jumperless.jfs.read(_ygg_rf, {JFS_READ_MAX_BYTES})"
            )),
            "device_dump_script must pass explicit size to jfs.read; got:\n{script}"
        );
        assert!(
            script.contains("except (NameError, AttributeError)"),
            "device_dump_script must include jfs-fallback handler; got:\n{script}"
        );
        assert!(
            script.contains("fs_read("),
            "device_dump_script must retain fs_read as fallback; got:\n{script}"
        );
    }

    /// verify and dump scripts must include a `try/except TypeError` fallback
    /// for the jfs.read(f, size) call, so older firmware variants degrade gracefully.
    /// Ceremony scripts no longer use jfs.read (Phase B: switched to import), so
    /// they do NOT need this fallback.
    #[test]
    fn jfs_read_with_size_has_typeerror_fallback_in_generated_scripts() {
        // device_verify_script: still reads files via jfs.read, needs TypeError fallback.
        let verify_script = device_verify_script("/python_scripts/lib/jumperless_mcp/effects.py");
        assert!(
            verify_script.contains("except TypeError:"),
            "device_verify_script must have except TypeError fallback for jfs.read size arg; got:\n{verify_script}"
        );
        assert!(
            verify_script.contains("jumperless.jfs.read(_ygg_rf)"),
            "device_verify_script TypeError fallback must call no-arg jfs.read; got:\n{verify_script}"
        );

        // device_dump_script: same.
        let dump_script = device_dump_script("/python_scripts/lib/jumperless_mcp/effects.py");
        assert!(
            dump_script.contains("except TypeError:"),
            "device_dump_script must have except TypeError fallback for jfs.read size arg; got:\n{dump_script}"
        );
        assert!(
            dump_script.contains("jumperless.jfs.read(_ygg_rf)"),
            "device_dump_script TypeError fallback must call no-arg jfs.read; got:\n{dump_script}"
        );

        // Phase B: ceremony scripts use `import jumperless_mcp` — no jfs.read, no TypeError needed.
        use crate::ceremony::{CEREMONY_CONNECT_SCRIPT, CEREMONY_DISCONNECT_SCRIPT};
        assert!(
            !CEREMONY_CONNECT_SCRIPT.contains("jfs.read"),
            "CEREMONY_CONNECT_SCRIPT must NOT use jfs.read (Phase B: import replaces it); got:\n{CEREMONY_CONNECT_SCRIPT}"
        );
        assert!(
            !CEREMONY_DISCONNECT_SCRIPT.contains("jfs.read"),
            "CEREMONY_DISCONNECT_SCRIPT must NOT use jfs.read (Phase B: import replaces it); got:\n{CEREMONY_DISCONNECT_SCRIPT}"
        );
    }

    /// Fallback path: when the device returns NameError/AttributeError on the
    /// `import jumperless` line, the script falls back to fs_read and still
    /// returns content. Verify the parser handles output from both code paths.
    ///
    /// This test simulates what happens when jfs is unavailable by using
    /// parse_device_verify_output and parse_dump_output — the parsers don't
    /// care which code path produced the output, only the format.
    #[test]
    fn jfs_fallback_output_is_parseable_by_verify_parser() {
        // Device falls back to fs_read → same output format as jfs path.
        let stdout =
            "size:234\nsha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890\n";
        let (size, sha, hash_avail) = parse_device_verify_output(stdout).unwrap();
        assert_eq!(size, Some(234));
        assert!(sha.is_some(), "sha256 must be present in fallback output");
        assert!(hash_avail, "hash_available must be true");
    }

    #[test]
    fn jfs_fallback_output_is_parseable_by_dump_parser() {
        // Device falls back to fs_read → same output format as jfs path.
        let stdout = "size:5\nhex:48656c6c6f\n";
        let (size, content) = parse_dump_output(stdout).unwrap();
        assert_eq!(size, Some(5));
        assert_eq!(content.as_deref(), Some(b"Hello".as_ref()));
    }

    // ── Bug A: verify normalizes CRLF host content ────────────────────────────

    /// verify_installation computes source_size + source_sha256 over the
    /// LF-normalized content, not over the raw (potentially CRLF) bytes.
    ///
    /// include_str! does NOT normalize line endings on Windows (rust-lang/rust
    /// PR #63681 rejected). python_repr() normalizes \r\n → \n before sending,
    /// so the device always stores LF-only files. Without this fix the host
    /// measures CRLF bytes while the device has LF bytes → permanent size
    /// mismatch on every Windows checkout even for correctly-installed files.
    #[test]
    fn verify_source_normalization_handles_crlf() {
        use sha2::{Digest, Sha256};

        // Build a synthetic source string with CRLF line endings.
        let crlf_source = "line1\r\nline2\r\nline3\r\n";
        // The LF-only version (what the device stores after python_repr normalization).
        let lf_source = "line1\nline2\nline3\n";

        // The verify fix: normalize then measure.
        let normalized = crlf_source.replace("\r\n", "\n").replace('\r', "\n");

        // Normalized content must equal the LF-only variant.
        assert_eq!(
            normalized, lf_source,
            "normalization must produce LF-only content"
        );

        // Size must be measured over normalized content, not CRLF bytes.
        let normalized_size = normalized.len();
        let crlf_size = crlf_source.len();
        assert!(
            normalized_size < crlf_size,
            "LF-normalized size ({normalized_size}) must be less than CRLF size ({crlf_size})"
        );
        assert_eq!(
            normalized_size,
            lf_source.len(),
            "normalized size must match pure-LF variant"
        );

        // SHA-256 must be computed over normalized content.
        let sha_of_normalized: String = Sha256::digest(normalized.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        let sha_of_lf: String = Sha256::digest(lf_source.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        let sha_of_crlf: String = Sha256::digest(crlf_source.as_bytes())
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();

        assert_eq!(
            sha_of_normalized, sha_of_lf,
            "SHA of normalized content must equal SHA of LF-only content"
        );
        assert_ne!(
            sha_of_normalized, sha_of_crlf,
            "SHA of normalized content must differ from SHA of raw CRLF content \
             (confirming the normalization actually changes the hash)"
        );
    }

    // ── Fix 1: device script byte-counting (isinstance + encode) ─────────────

    /// Fix 1 (device_verify_script): the generated script must contain the
    /// `isinstance(content, str)` guard and `content.encode('utf-8')` call.
    ///
    /// When `jfs.read()` returns a `str` (text-mode read on MicroPython), `len()`
    /// returns the char count, NOT the byte count. Multi-byte UTF-8 chars (e.g.
    /// em-dashes in comments) produce a char count smaller than the byte count,
    /// causing SHAs to match while sizes differ — the impossible-looking mismatch
    /// observed live: "727 bytes ≠ 731 bytes ✗ MISMATCH" with identical SHAs.
    ///
    /// The fix normalizes content to bytes after the read step so `len()` and
    /// `sha256()` both operate on the byte stream consistently.
    #[test]
    fn device_verify_script_contains_isinstance_encode_guard() {
        let script = device_verify_script("/jumperless_mcp/font.py");
        assert!(
            script.contains("if isinstance(content, str):"),
            "device_verify_script must contain isinstance(content, str) guard; script:\n{script}"
        );
        assert!(
            script.contains("content = content.encode('utf-8')"),
            "device_verify_script must contain content.encode('utf-8') call; script:\n{script}"
        );
    }

    /// Fix 1 (device_dump_script): the generated script must also contain the
    /// `isinstance` guard so `binascii.hexlify(content)` always receives bytes.
    ///
    /// Without this, `hexlify(str)` raises `TypeError` on MicroPython (hexlify
    /// requires bytes-like object) and the dump reports `error:TypeError` instead
    /// of the actual file content.
    #[test]
    fn device_dump_script_contains_isinstance_encode_guard() {
        let script = device_dump_script("/jumperless_mcp/effects.py");
        assert!(
            script.contains("if isinstance(content, str):"),
            "device_dump_script must contain isinstance(content, str) guard; script:\n{script}"
        );
        assert!(
            script.contains("content = content.encode('utf-8')"),
            "device_dump_script must contain content.encode('utf-8') call; script:\n{script}"
        );
    }

    // ── Phase C: no flush calls ───────────────────────────────────────────────

    /// Phase C: fs_write_chunked must NOT emit any `_ygg_f.flush()` calls.
    ///
    /// Scout audit (2026-05-10) confirmed that `flush` is NOT in the JFS module
    /// globals table (modjumperless.c:4941-4972). The earlier flush() calls were
    /// silent no-ops. Frame count is now N+3 (open + N writes + close + del),
    /// not the old 2N+3 (which included a flush after each write).
    #[test]
    fn fs_write_chunked_no_flush_calls() {
        let content: String = "y".repeat(2000); // → 3 chunks at CHUNK_SIZE=768
        let path = "/python_scripts/lib/jumperless_mcp/test.py";
        let n_chunks = chunk_at_char_boundaries(&content, CHUNK_SIZE).len();

        // N+3 frames: open + N writes + close + del (no flush frames)
        let frames: Vec<Vec<u8>> = (0..(n_chunks + 3)).map(|_| MockPort::ok_frame()).collect();
        let frame_refs: Vec<&[u8]> = frames.iter().map(|v| v.as_slice()).collect();
        let mut port = MockPort::with_responses(&frame_refs);

        fs_write_chunked(&mut port, path, &content).unwrap();

        let written = String::from_utf8_lossy(&port.write_data);
        let flush_count = written.matches("_ygg_f.flush()").count();

        assert_eq!(
            flush_count, 0,
            "Phase C: fs_write_chunked must not emit any flush() calls \
             (jfs.flush is not in the JFS module globals table)"
        );
    }
}