ftts-cli 0.1.10

franken_tts CLI: pure-Rust Qwen3-TTS voice synthesis (`ftts say`), no Python, no GPU
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
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
#![forbid(unsafe_code)]

//! Shared, stateless command-line dispatch for both FrankenTTS binaries.

pub(crate) mod card;
pub mod diagnostics;
mod error;
pub mod resident;
pub mod robot;
pub mod session_protocol;
pub mod style;
pub mod synth;
pub mod talk;

pub use error::{FttsError, FttsExitCode};
pub use robot::{EventType, validate_event, validate_ndjson};

use std::collections::BTreeMap;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{LazyLock, OnceLock};

#[cfg(test)]
use clap::CommandFactory;
use clap::{Parser, Subcommand, ValueEnum};
use ftts_artifacts::census::{ExpectedTensor, WeightsManifest};
use ftts_artifacts::converter::{
    StreamingConversionPlan, TensorConversion, TensorStoragePolicy, convert_safetensors_streaming,
};
use ftts_artifacts::fttsq::{AccessClass, MappedFttsq};
use ftts_artifacts::safetensors::Dtype;
use ftts_core::{NormalizationMode, NormalizationOptions, SynthesisRequest};
use ftts_kernels::mmap::MappedFile;
use serde_json::{Value, json};

const ROBOT_SCHEMA_VERSION: u8 = 1;
const SCAFFOLD_ADMISSION_TEXT_LIMIT_BYTES: usize = 1_048_576;
const MODEL_BASENAME: &str = "qwen3-tts-12hz-0.6b-base.fttsq";

/// Built-in voices: name, one-line character, and the enrolled 1,024-float x-vector.
///
/// "matt" is the out-of-box default when no enrollment exists. Enrolling a real reference
/// always takes precedence over any of them.
const PRESET_VOICES: &[(&str, &str, &[u8])] = &[
    (
        "aria",
        "clear, warm, feminine",
        include_bytes!("../presets/aria.spk"),
    ),
    (
        "ember",
        "the same character a few semitones deeper",
        include_bytes!("../presets/ember.spk"),
    ),
    (
        "james",
        "natural, conversational, masculine",
        include_bytes!("../presets/james.spk"),
    ),
    (
        "matt",
        "warm, easy, masculine — the out-of-box default",
        include_bytes!("../presets/matt.spk"),
    ),
    (
        "leo",
        "relaxed, resonant, masculine",
        include_bytes!("../presets/leo.spk"),
    ),
    (
        "robert",
        "steady, measured, masculine",
        include_bytes!("../presets/robert.spk"),
    ),
    (
        "judy",
        "bright, articulate, feminine",
        include_bytes!("../presets/judy.spk"),
    ),
    (
        "liam",
        "thoughtful, engaging, masculine",
        include_bytes!("../presets/liam.spk"),
    ),
    (
        "anthony",
        "authoritative, articulate, masculine",
        include_bytes!("../presets/anthony.spk"),
    ),
    (
        "russell",
        "rich, warm, masculine",
        include_bytes!("../presets/russell.spk"),
    ),
    (
        "steve",
        "direct, energetic, masculine",
        include_bytes!("../presets/steve.spk"),
    ),
    (
        "daniel",
        "clear, calm, masculine",
        include_bytes!("../presets/daniel.spk"),
    ),
    (
        "meryl",
        "expressive, poised, feminine",
        include_bytes!("../presets/meryl.spk"),
    ),
    (
        "laurence",
        "deep, measured, masculine",
        include_bytes!("../presets/laurence.spk"),
    ),
    (
        "jack",
        "crisp, confident, masculine",
        include_bytes!("../presets/jack.spk"),
    ),
    (
        "michael",
        "warm, dynamic, masculine",
        include_bytes!("../presets/michael.spk"),
    ),
    (
        "jodie",
        "warm, expressive, feminine",
        include_bytes!("../presets/jodie.spk"),
    ),
    (
        "denzel",
        "commanding, charismatic, masculine",
        include_bytes!("../presets/denzel.spk"),
    ),
];

/// The preset used when `--voice`, `FTTS_DEFAULT_VOICE`, and an enrolled default voice
/// (MODEL_DIR/default.ftvoice or legacy default.spk) are all
/// absent, so a fresh install speaks out of the box.
const DEFAULT_PRESET_VOICE: &str = "matt";

/// Names a preset resolves to a temp-materialized `.spk` path the existing voice loaders read.
///
/// Only fires when the value is NOT an existing file, so a file named like a preset still wins.
/// The file is rewritten unconditionally: 4 KB per run is cheaper than trusting stale content.
fn materialize_preset_voice(name: &str) -> Option<Result<PathBuf, FttsError>> {
    let (_, _, bytes) = PRESET_VOICES
        .iter()
        .find(|(preset, _, _)| *preset == name)?;
    let staging_dir = match synth::private_staging_dir() {
        Ok(dir) => dir,
        Err(error) => {
            return Some(Err(FttsError::Generic(format!(
                "cannot create staging directory for preset voice {name}: {error}"
            ))));
        }
    };
    let path = staging_dir.join(format!("ftts-preset-{name}-{}.spk", std::process::id()));
    Some(
        fs::write(&path, bytes)
            .map(|()| path.clone())
            .map_err(|error| {
                FttsError::Generic(format!(
                    "cannot materialize preset voice {name} at {}: {error}",
                    path.display()
                ))
            }),
    )
}

fn preset_names() -> String {
    PRESET_VOICES
        .iter()
        .map(|(name, _, _)| *name)
        .collect::<Vec<_>>()
        .join(", ")
}

/// Materializes a built-in preset voice as an `.spk` path, so evaluation harnesses can
/// condition synthesis on a real speech x-vector without handling voice bytes themselves.
///
/// # Errors
///
/// Unknown preset name, or the staging directory/file could not be written.
pub fn preset_voice_path(name: &str) -> Result<PathBuf, FttsError> {
    match materialize_preset_voice(name) {
        Some(result) => result,
        None => Err(FttsError::Usage(format!(
            "unknown preset voice {name:?}; available presets: {}",
            preset_names()
        ))),
    }
}
const PINNED_MAIN_WEIGHTS_FILENAME: &str = "model.safetensors";
const PINNED_MAIN_WEIGHTS_SHA256: &str =
    "180b3b10eb1c9f1b4db7806d5475bae3071c0243c299d49926bab1da3b6946f6";
const PINNED_MODEL_REVISION: &str = "5d83992436eae1d760afd27aff78a71d676296fc";
const PINNED_MAIN_TENSOR_COUNT: usize = 478;
//  Crate-local pinned copies (`pinned/`): `cargo package` cannot ship files outside the crate
//  root, and these three are compile-time product surfaces (the artifact census, the model-dir
//  pin assertion, and the Apache attribution the binary prints). A unit test asserts each copy is
//  byte-identical to the truth-pack canonical whenever the truth pack is present.
const PINNED_TENSOR_INVENTORY: &str = include_str!("../pinned/TENSOR_INVENTORY.json");
const PINNED_MODEL_CONFIG: &str = include_str!("../pinned/model_config.json");
const APACHE_LICENSE: &str = include_str!("../pinned/QWEN_APACHE_LICENSE");
//  The `ftts pull` download contract: which release assets make a complete model directory, and
//  the exact digest each must carry. Embedded so a shipped binary can fetch and verify the model
//  with no network-served manifest to trust.
const PINNED_MODEL_MANIFEST: &str = include_str!("../pinned/model_manifest.json");
/// Subdirectory of `$HOME/.cache` that `ftts pull` fills and model resolution falls back to.
const DEFAULT_MODEL_CACHE_SUBDIR: &str = ".cache/franken_tts/model";
// The environment snapshot and the agent-facing contract share ONE list —
// `robot::DOCUMENTED_ENVIRONMENT` — so `doctor`, `robot schema`, and the actual readers can
// never disagree about which levers exist (they did: neither list mentioned the resident
// daemon's variables, and each had entries the other lacked).

/// Runs the shared `ftts` / `franken_tts` command-line interface.
pub fn cli_main() -> ExitCode {
    // The optimized route is the DEFAULT everywhere (library-level: see
    // `ftts_kernels::route`). `FTTS_INT8=0` selects the f32 reference route end to end;
    // DISC-003 records the decision and the evidence.

    let cli = match Cli::try_parse() {
        Ok(cli) => cli,
        Err(error) => {
            let exit_code = match error.kind() {
                clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion => {
                    FttsExitCode::Success
                }
                _ => FttsExitCode::Usage,
            };
            let _ = error.print();
            return exit_code.as_exit_code();
        }
    };

    // `talk` owns the process's stdio from BACKGROUND threads (reader/writer), and the
    // std lock guards are reentrant only on their own thread: holding them here for the
    // whole dispatch would deadlock the session the moment its threads try to lock.
    // Dispatch it before any lock exists.
    if let Command::Talk(args) = &cli.command {
        return match run_talk_command(&cli, args, environment()) {
            Ok(()) => FttsExitCode::Success.as_exit_code(),
            Err(error) => {
                let mut stderr = io::stderr().lock();
                let _ = writeln!(stderr, "error: {error}");
                error.exit_code().as_exit_code()
            }
        };
    }

    use std::io::IsTerminal as _;
    let capabilities = IoCapabilities {
        human_output: io::stdout().is_terminal(),
        can_confirm: io::stdin().is_terminal() && io::stdout().is_terminal(),
    };
    let mut stdin = io::stdin().lock();
    let mut stdout = io::stdout().lock();
    let mut stderr = io::stderr().lock();
    // `say` reports its own failures as a `run_error` NDJSON event on stderr — that IS the
    // machine contract, and under `--stream raw` stderr carries nothing but events. The
    // plain-text duplicate below would be a non-JSON line in that same stream, so for `say`
    // it only appears when a human (a terminal) is reading stderr.
    let already_on_contract = matches!(cli.command, Command::Say(_));
    match dispatch(
        cli,
        environment(),
        &mut stdin,
        &mut stdout,
        &mut stderr,
        capabilities,
    ) {
        Ok(()) => FttsExitCode::Success.as_exit_code(),
        Err(error) => {
            if !already_on_contract || io::stderr().is_terminal() {
                let _ = writeln!(stderr, "error: {error}");
            }
            error.exit_code().as_exit_code()
        }
    }
}

#[derive(Debug, Parser)]
#[command(
    name = "ftts",
    version,
    about = "Pure-Rust Qwen3-TTS command-line interface",
    long_about = "FrankenTTS is stateless by default: synthesis history is never persisted. \
                  Use `ftts robot schema` for the versioned NDJSON contract.",
    arg_required_else_help = true
)]
struct Cli {
    /// Execution profile. The default is balanced unless FTTS_PROFILE overrides it.
    #[arg(long, global = true, value_enum)]
    profile: Option<ExecutionProfile>,

    /// Codec packet size in frames. The default is profile-dependent.
    #[arg(long, global = true, value_enum)]
    packet_frames: Option<PacketFrames>,

    /// Math contract used by this invocation.
    #[arg(long, global = true, value_enum)]
    math_mode: Option<MathMode>,

    /// Voice-pack serialization profile used by enrollment.
    #[arg(long, global = true, value_enum)]
    voice_pack: Option<VoicePackProfile>,

    /// Text-normalization policy.
    #[arg(long, global = true, value_enum)]
    normalize: Option<NormalizeMode>,

    /// Request a structured trace from synthesis without default-persisting sensitive text.
    #[arg(long, global = true, value_name = "DIR")]
    trace: Option<PathBuf>,

    /// Reproducibility seed for a future sampler.
    #[arg(long, global = true)]
    seed: Option<u64>,

    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    /// Validate or synthesize text with an optional voice pack.
    ///
    /// Signals: the first SIGINT/SIGTERM stops the run cooperatively — audio already
    /// delivered is finalized (a valid WAV of whatever landed; a compressed encoding
    /// is skipped and the partial WAV kept) — and the run ends with `run_error` kind
    /// "cancelled", exit code 6. A second signal exits immediately.
    Say(SayArgs),
    /// Synthesize text and render a share-ready branded video of it.
    #[command(name = "make-video")]
    MakeVideo(MakeVideoArgs),
    /// Build a consent-bearing voice pack from reference audio.
    Enroll(EnrollArgs),
    /// Inspect a portable voice pack.
    Voice(VoiceArgs),
    /// Export or import a voice card: a picture that carries the voice itself,
    /// interchangeable with the iOS app.
    Card(CardArgs),
    /// Convert pinned source weights into a portable .fttsq artifact.
    Convert(ConvertArgs),
    /// Download and verify the pinned model files into the model directory.
    Pull(PullArgs),
    /// Hold a live conversation session: NDJSON ops on stdin, schema-v2 events on
    /// stdout, raw s16le 24 kHz PCM on fd 3 (Unix) or --pcm-out. One warm model for
    /// the whole exchange; the resident daemon is never involved. See
    /// `ftts robot schema --contract session` for the wire contract.
    Talk(TalkArgs),
    /// Emit versioned, line-oriented robot contract data.
    Robot(RobotArgs),
    /// Report local configuration and readiness without inference.
    Doctor(DoctorArgs),
    /// Internal: run the resident engine daemon. Spawned by `ftts say`; not for direct use.
    #[command(hide = true, name = "resident-daemon")]
    ResidentDaemon(ResidentDaemonArgs),
}

#[derive(Debug, clap::Args)]
struct ResidentDaemonArgs {
    /// Model directory this daemon serves.
    #[arg(long, value_name = "PATH")]
    bundle_root: PathBuf,
}

#[derive(Debug, clap::Args)]
struct SayArgs {
    /// Text to synthesize. Use `-` to read UTF-8 text from stdin.
    #[arg(value_name = "TEXT")]
    text: Option<String>,

    /// Output file (same as -o). Format follows the extension: .wav is written natively;
    /// .m4a, .mp3, and .flac are encoded from the native WAV by the first available system
    /// encoder (afconvert, ffmpeg, lame, flac).
    #[arg(value_name = "OUTPUT", conflicts_with_all = ["stream", "output"])]
    output_positional: Option<PathBuf>,

    /// Read UTF-8 text from PATH. Use `-` for stdin.
    #[arg(long, value_name = "PATH", conflicts_with = "text")]
    file: Option<PathBuf>,

    /// Explicit .fttsq model artifact. No network lookup is performed.
    #[arg(long, value_name = "PATH")]
    model: Option<PathBuf>,

    /// Voice source: a .spk vector, a voice-card image (PNG/JPEG), reference
    /// audio, or a built-in voice name
    /// (matt, james, leo, robert, judy, aria, ember, liam, anthony, russell, steve, daniel, meryl, laurence, jack, michael, jodie, denzel).
    /// Default: the enrolled default voice (MODEL_DIR/default.ftvoice, else legacy
    /// default.spk), else the built-in "matt".
    #[arg(long, value_name = "PATH|NAME")]
    voice: Option<PathBuf>,

    /// Write WAV output here. Mutually exclusive with raw stdout streaming.
    #[arg(short = 'o', long, value_name = "PATH", conflicts_with = "stream")]
    output: Option<PathBuf>,

    /// Stream raw PCM on stdout; robot events then use stderr. Packets are written live,
    /// during synthesis. Raw streaming bypasses the resident engine (whose reply is one
    /// whole buffer after synthesis) and pays the in-process model load instead.
    #[arg(long, value_enum)]
    stream: Option<StreamMode>,

    /// Parse inputs and run the conservative admission preflight without synthesis.
    #[arg(long)]
    check: bool,

    /// Emit the NDJSON event stream even when stdout is a terminal.
    ///
    /// Piped, redirected and CI runs already get NDJSON — nothing but a terminal gets the human
    /// view — so this exists for a person who wants to watch the machine contract directly.
    #[arg(long)]
    robot: bool,

    /// Load the model in this process instead of using the resident engine.
    ///
    /// By default `ftts say` keeps the loaded model in a background process so the next
    /// invocation starts without the multi-second load, unloading itself after ten idle
    /// minutes (FTTS_RESIDENT_IDLE_SECS overrides). This flag, or FTTS_NO_RESIDENT=1,
    /// opts a run out; results are identical either way.
    #[arg(long)]
    no_resident: bool,
}

#[derive(Debug, clap::Args)]
struct MakeVideoArgs {
    /// Text to synthesize. Use `-` to read UTF-8 text from stdin.
    #[arg(value_name = "TEXT")]
    text: Option<String>,

    /// Output video. `.mp4` uses the first available system encoder (ffmpeg);
    /// `.y4m` renders natively with a `.wav` sibling and needs no encoder.
    #[arg(value_name = "OUTPUT", conflicts_with = "output")]
    output_positional: Option<PathBuf>,

    /// Read UTF-8 text from PATH. Use `-` for stdin.
    #[arg(long, value_name = "PATH", conflicts_with = "text")]
    file: Option<PathBuf>,

    /// Explicit .fttsq model artifact. No network lookup is performed.
    #[arg(long, value_name = "PATH")]
    model: Option<PathBuf>,

    /// Voice source: a .spk vector, a voice-card image (PNG/JPEG), reference
    /// audio, or a built-in voice name
    /// (matt, james, leo, robert, judy, aria, ember, liam, anthony, russell, steve, daniel, meryl, laurence, jack, michael, jodie, denzel).
    #[arg(long, value_name = "PATH|NAME")]
    voice: Option<PathBuf>,

    /// Write the video here. Same as the positional OUTPUT.
    #[arg(short = 'o', long, value_name = "PATH")]
    output: Option<PathBuf>,

    /// Skip synthesis and render this existing PCM WAV instead.
    #[arg(long, value_name = "PATH", conflicts_with_all = ["text", "file"])]
    audio: Option<PathBuf>,

    /// Voice name shown on the video. Defaults to the voice's name.
    #[arg(long, value_name = "NAME")]
    label: Option<String>,

    /// Load the model in this process instead of using the resident engine.
    #[arg(long)]
    no_resident: bool,
}

/// How enrollment chooses its conditioning path (bead frankentts-p4-enrollment-en6).
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
enum EnrollMode {
    /// Transcript-backed ICL: verified transcript + codec-encoder tokens land in the pack.
    Quality,
    /// x-vector embedding only; upstream documents possible quality reduction and this CLI
    /// says so in the enrollment output.
    Quick,
    /// QUALITY when a transcript is supplied and verifies, else QUICK with a loud warning.
    #[default]
    Auto,
}

/// The mode enrollment actually ran, decided from [`EnrollMode`] plus what the input allows.
#[derive(Clone, Debug, Eq, PartialEq)]
enum ResolvedEnrollMode {
    Quality,
    Quick {
        /// Why QUICK was chosen despite an AUTO/QUALITY request — printed loudly.
        reason: String,
    },
}

/// Pure mode resolution so the fallback policy is unit-testable without audio or models.
///
/// QUALITY demands a transcript; AUTO degrades to QUICK (loudly) without one; an explicit
/// QUICK never silently upgrades.
fn resolve_enroll_mode(requested: EnrollMode, transcript: Option<&str>) -> ResolvedEnrollMode {
    let verified = transcript.is_some_and(|text| !text.trim().is_empty());
    match requested {
        EnrollMode::Quality if verified => ResolvedEnrollMode::Quality,
        EnrollMode::Quality => ResolvedEnrollMode::Quick {
            reason: "--mode quality needs --transcript-text/--transcript-file; enrolled \
                     x-vector only"
                .to_owned(),
        },
        EnrollMode::Auto if verified => ResolvedEnrollMode::Quality,
        EnrollMode::Auto => ResolvedEnrollMode::Quick {
            reason: "no transcript supplied; AUTO fell back to QUICK (x-vector only)".to_owned(),
        },
        EnrollMode::Quick => ResolvedEnrollMode::Quick {
            reason: "--mode quick enrolls the x-vector only".to_owned(),
        },
    }
}

#[derive(Debug, clap::Args)]
struct EnrollArgs {
    /// Reference audio: WAV/FLAC decode natively; m4a/mp3/aac/ogg/opus route through the first
    /// system decoder found (afconvert on macOS, ffmpeg).
    #[arg(value_name = "REFERENCE_AUDIO")]
    reference_audio: PathBuf,

    /// Explicit model directory or .fttsq model artifact. No network lookup is performed.
    #[arg(long, value_name = "PATH")]
    model: Option<PathBuf>,

    /// Write the enrolled portable `.ftvoice` pack here. Refuses to overwrite an existing file.
    #[arg(short = 'o', long, value_name = "PATH", conflicts_with = "default")]
    output: Option<PathBuf>,

    /// Write MODEL_DIR/default.ftvoice — the enrolled default `ftts say` uses when
    /// `--voice` is absent.
    #[arg(long, conflicts_with = "output")]
    default: bool,

    /// Proceed past a REFUSED enrollment: a reference diagnosed as structurally unusable
    /// (no speech, wall-to-wall clipping) otherwise exits 8 (`enrollment-quality
    /// refusal`). Mere quality WARNINGS never refuse on their own.
    #[arg(long)]
    force: bool,

    /// Replace an existing voice at the destination without asking.
    ///
    /// Interactive runs are asked to confirm instead; this is how a script or an agent gives that
    /// consent up front. The displaced voice is copied to `<path>.bak` either way.
    #[arg(long)]
    overwrite: bool,

    /// Remove late reverberation from the reference before enrolling.
    ///
    /// A room is convolutive, so `--denoise` cannot touch it; this is the lever for a reference
    /// that sounds "wet". It matters because the speaker encoder cannot separate voice from room,
    /// so a reverberant reference enrolls the room as part of the speaker and every utterance the
    /// clone speaks is rendered in it. Off by default: it changes the enrolled identity.
    #[arg(long)]
    dereverb: bool,

    /// Clean stationary noise from the reference before enrolling.
    ///
    /// This is the default whenever the neural denoiser's weights are present (`ftts pull`
    /// fetches them; measured on a static-hiss reference, the cleaned enrollment lands
    /// closer to a clean-source enrollment than the raw recording does). Passing the flag
    /// explicitly additionally engages the classic no-weights spectral subtraction when the
    /// weights are absent, where the automatic path would skip cleanup rather than swap in
    /// a different engine unannounced.
    #[arg(long, overrides_with = "no_denoise")]
    denoise: bool,

    /// Enroll the recording exactly as given, with no noise cleanup.
    #[arg(long, overrides_with = "denoise")]
    no_denoise: bool,
    /// Conditioning path: quality (transcript-backed ICL), quick (x-vector only), or auto
    /// (quality when a usable transcript is supplied, else quick with a loud warning).
    /// The modes are NOT interchangeable equals: continuation-style cloning reproduces
    /// prompt-recording defects, so the quick path says what it skipped.
    #[arg(long, value_enum, default_value_t = EnrollMode::Auto)]
    mode: EnrollMode,

    /// Reference transcript text, verbatim (quality path / AUTO input). The ICL prompt
    /// conditions on exactly these words, so they must match the recording word for word.
    #[arg(long, conflicts_with = "transcript_file", value_name = "TEXT")]
    transcript_text: Option<String>,

    /// Read the reference transcript from a UTF-8 file (one alternative to --transcript-text).
    #[arg(long, value_name = "PATH")]
    transcript_file: Option<PathBuf>,

    /// Affirm recording consent non-interactively; interactive runs are asked instead. The
    /// answer — yes or no — is recorded in the pack either way, because a pack that cannot
    /// state its own consent status is worse than one that states `false`.
    #[arg(long)]
    consent_attest: bool,
}

#[derive(Debug, clap::Args)]
struct VoiceArgs {
    #[command(subcommand)]
    command: VoiceCommand,
}

#[derive(Debug, Subcommand)]
enum VoiceCommand {
    /// Inspect a .ftvoice header without synthesizing.
    Inspect { path: PathBuf },
}

#[derive(Debug, clap::Args)]
struct ConvertArgs {
    /// Pinned source-weight directory or file.
    #[arg(value_name = "SOURCE")]
    source: PathBuf,

    /// Destination .fttsq path. Refuses to overwrite an existing artifact.
    #[arg(short = 'o', long, value_name = "PATH")]
    output: PathBuf,

    /// EXPERIMENTAL: store the 622 MB cold text embedding as Q8 (per-row scales) instead of
    /// bf16, roughly halving it. The loader already reads both forms; bf16 remains the default
    /// until the artifact-v2 gates pass (teacher-forced logit parity on the conformance corpus
    /// plus the equivalence-bound listening protocol — frankentts-6ea1). Browser deployments
    /// stay on bf16 artifacts for now: the playground's provided-rows path is bf16-only.
    #[arg(long)]
    embed_q8: bool,

    /// EXPERIMENTAL: store the microdecoder's per-depth residual embedding tables and
    /// scoring heads (~126 MB of bf16 across thirty tensors) as per-row Q8 instead,
    /// roughly halving that block. The loader dequantizes both forms; bf16 stays the
    /// default until the artifact-v2 gates pass (per-depth teacher-forced logit KL/top-k
    /// plus the equivalence-bound listening protocol — frankentts-x7bt, following the
    /// --embed-q8 precedent of frankentts-6ea1/NE-008).
    #[arg(long)]
    micro_q8: bool,
}

#[derive(Debug, clap::Args)]
struct PullArgs {
    /// Destination model directory. Defaults to FTTS_MODEL_DIR, then ~/.cache/franken_tts/model.
    #[arg(long, value_name = "PATH")]
    model: Option<PathBuf>,

    /// Re-download every file even when it is already present and verified.
    #[arg(long)]
    force: bool,
}

#[derive(Debug, clap::Args)]
struct RobotArgs {
    #[command(subcommand)]
    command: RobotCommand,
}

#[derive(Clone, Debug, Subcommand)]
enum RobotCommand {
    /// Print the versioned NDJSON event schema.
    Schema {
        /// Which contract to print: the one-shot run contract (v1, the default and the shape
        /// every existing consumer validates) or the talk-session contract (v2).
        #[arg(default_value = "run")]
        contract: SchemaContract,
    },
    /// Print a versioned machine-readable readiness event.
    Health,
    /// Print available backend routes without probing model weights.
    Backends,
    /// Print the self-test state; no unavailable kernel is reported as passing.
    Selftest,
}

/// Which wire contract `ftts robot schema` prints.
#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum SchemaContract {
    /// The one-shot run contract (schema v1), frozen by the conformance fixture.
    Run,
    /// The talk-session contract (schema v2).
    Session,
}

#[derive(Debug, clap::Args)]
struct DoctorArgs {
    /// Emit one JSON object on stdout instead of a human-readable report.
    #[arg(long)]
    json: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum ExecutionProfile {
    Interactive,
    Balanced,
    Throughput,
    Strict,
}

impl ExecutionProfile {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Interactive => "interactive",
            Self::Balanced => "balanced",
            Self::Throughput => "throughput",
            Self::Strict => "strict",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum PacketFrames {
    #[value(name = "1")]
    One,
    #[value(name = "2")]
    Two,
    #[value(name = "4")]
    Four,
    Auto,
}

impl PacketFrames {
    const fn as_str(self) -> &'static str {
        match self {
            Self::One => "1",
            Self::Two => "2",
            Self::Four => "4",
            Self::Auto => "auto",
        }
    }

    /// Codec frames carried by one PCM packet.
    ///
    /// `auto` resolves to 4 here. The autotuner that will choose it per machine is
    /// `frankentts-k-packet-tuning-28u`; until it exists, `auto` means "the balanced default"
    /// rather than a number this call site invented on the spot.
    const fn frames_per_packet(self) -> u8 {
        match self {
            Self::One => 1,
            Self::Two => 2,
            Self::Four | Self::Auto => 4,
        }
    }

    /// Samples in one packet: frames times the codec's 1,920 samples per 80 ms frame.
    const fn samples_per_packet(self) -> usize {
        self.frames_per_packet() as usize * ftts_core::audio::SAMPLES_PER_FRAME
    }

    const fn default_for(profile: ExecutionProfile) -> Self {
        match profile {
            ExecutionProfile::Interactive => Self::One,
            ExecutionProfile::Balanced => Self::Four,
            ExecutionProfile::Throughput => Self::Auto,
            ExecutionProfile::Strict => Self::Four,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum MathMode {
    Strict,
    Fast,
}

impl MathMode {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Strict => "strict",
            Self::Fast => "fast",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum VoicePackProfile {
    Portable,
    Private,
    Minimal,
}

impl VoicePackProfile {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Portable => "portable",
            Self::Private => "private",
            Self::Minimal => "minimal",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum NormalizeMode {
    Verbatim,
    Conservative,
    LocaleAware,
}

impl NormalizeMode {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Verbatim => "verbatim",
            Self::Conservative => "conservative",
            Self::LocaleAware => "locale-aware",
        }
    }
}

impl From<NormalizeMode> for NormalizationMode {
    fn from(mode: NormalizeMode) -> Self {
        match mode {
            NormalizeMode::Verbatim => Self::Verbatim,
            NormalizeMode::Conservative => Self::Conservative,
            NormalizeMode::LocaleAware => Self::LocaleAware,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum StreamMode {
    Raw,
}

#[derive(Debug, Default)]
struct Environment {
    values: BTreeMap<&'static str, Option<OsString>>,
    stage_budget_values: BTreeMap<OsString, OsString>,
}

impl Environment {
    fn from_process() -> Self {
        let values = robot::DOCUMENTED_ENVIRONMENT
            .iter()
            .map(|&name| (name, std::env::var_os(name)))
            .collect();
        let stage_budget_values = std::env::vars_os()
            .filter(|(name, _)| {
                name.to_str().is_some_and(|name| {
                    name.starts_with("FTTS_STAGE_BUDGET_") && name.ends_with("_MS")
                })
            })
            .collect();
        Self {
            values,
            stage_budget_values,
        }
    }

    fn value(&self, name: &'static str) -> Option<&str> {
        self.values.get(name)?.as_deref()?.to_str()
    }

    fn documented_values(&self) -> BTreeMap<String, Option<String>> {
        let mut values = self
            .values
            .iter()
            .map(|(name, value)| {
                (
                    (*name).to_owned(),
                    value
                        .as_ref()
                        .map(|value| value.to_string_lossy().into_owned()),
                )
            })
            .collect::<BTreeMap<_, _>>();
        values.insert("FTTS_STAGE_BUDGET_*_MS".to_owned(), None);
        values.extend(self.stage_budget_values.iter().map(|(name, value)| {
            (
                name.to_string_lossy().into_owned(),
                Some(value.to_string_lossy().into_owned()),
            )
        }));
        values
    }
}

fn environment() -> &'static Environment {
    static ENVIRONMENT: OnceLock<Environment> = OnceLock::new();
    ENVIRONMENT.get_or_init(Environment::from_process)
}

#[derive(Debug)]
struct EffectiveSettings {
    profile: ExecutionProfile,
    packet_frames: PacketFrames,
    math_mode: MathMode,
    voice_pack: VoicePackProfile,
    normalize: NormalizeMode,
}

impl EffectiveSettings {
    fn resolve(cli: &Cli, environment: &Environment) -> Result<Self, FttsError> {
        let profile = cli
            .profile
            .or(parse_env_value(
                environment.value("FTTS_PROFILE"),
                "FTTS_PROFILE",
                ExecutionProfile::value_variants(),
            )?)
            .unwrap_or(ExecutionProfile::Balanced);
        let packet_frames = cli
            .packet_frames
            .or(parse_env_value(
                environment.value("FTTS_PACKET_FRAMES"),
                "FTTS_PACKET_FRAMES",
                PacketFrames::value_variants(),
            )?)
            .unwrap_or_else(|| PacketFrames::default_for(profile));
        let math_mode = cli
            .math_mode
            .or(parse_env_value(
                environment.value("FTTS_MATH_MODE"),
                "FTTS_MATH_MODE",
                MathMode::value_variants(),
            )?)
            .unwrap_or(MathMode::Fast);
        let voice_pack = cli.voice_pack.unwrap_or(VoicePackProfile::Portable);
        let normalize = cli.normalize.unwrap_or(NormalizeMode::Verbatim);
        Ok(Self {
            profile,
            packet_frames,
            math_mode,
            voice_pack,
            normalize,
        })
    }

    fn normalization_options(&self) -> NormalizationOptions {
        NormalizationOptions {
            mode: self.normalize.into(),
            ..NormalizationOptions::default()
        }
    }
}

fn parse_env_value<T>(
    value: Option<&str>,
    name: &str,
    variants: &'static [T],
) -> Result<Option<T>, FttsError>
where
    T: ValueEnum + Copy,
{
    match value {
        None => Ok(None),
        Some(value) => T::from_str(value, true).map(Some).map_err(|_| {
            let choices = variants
                .iter()
                .filter_map(|variant| variant.to_possible_value())
                .map(|variant| variant.get_name().to_owned())
                .collect::<Vec<_>>()
                .join(", ");
            FttsError::Usage(format!("invalid {name}={value:?}; use one of: {choices}"))
        }),
    }
}

/// Capabilities of the concrete I/O handles owned by the process entry point.
///
/// Sink-agnostic command functions cannot infer these from `&mut dyn Write`. Keeping them
/// explicit prevents a library call that writes to a buffer from inheriting the parent process's
/// TTY state and accidentally emitting prose, blocking for input, or corrupting NDJSON.
#[derive(Clone, Copy, Debug, Default)]
struct IoCapabilities {
    human_output: bool,
    can_confirm: bool,
}

fn dispatch(
    cli: Cli,
    environment: &Environment,
    stdin: &mut dyn Read,
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
    capabilities: IoCapabilities,
) -> Result<(), FttsError> {
    match &cli.command {
        Command::Say(args) => run_say(&cli, args, environment, stdin, stdout, stderr, capabilities),
        Command::MakeVideo(args) => {
            run_make_video(&cli, args, environment, stdin, stdout, stderr, capabilities)
        }
        Command::Enroll(args) => run_enroll(args, environment, stdin, stdout, capabilities),
        Command::Voice(VoiceArgs {
            command: VoiceCommand::Inspect { path },
        }) => run_voice_inspect(path, stdout),
        Command::Card(args) => run_card(args, stdout),
        Command::Convert(args) => run_convert(&cli, args, environment, stdout, stderr),
        Command::Pull(args) => run_pull(args, environment, stdout),
        // Talk is dispatched in `cli_main` BEFORE the stdio locks exist (see there); by
        // this point it has already run and returned.
        Command::Talk(_) => unreachable!("talk dispatches before the stdio locks are taken"),
        Command::Robot(args) => run_robot(args.command.clone(), environment, stdout),
        Command::Doctor(args) => run_doctor(args, environment, stdout),
        Command::ResidentDaemon(args) => resident::run_daemon(&args.bundle_root),
    }
}

/// `ftts talk`: the live conversation session (bead frankentts-edz0). Model resolution
/// and voice naming reuse `say`'s exact surfaces; transport rules live in `talk`.
fn run_talk_command(
    cli: &Cli,
    args: &TalkArgs,
    environment: &Environment,
) -> Result<(), FttsError> {
    install_talk_signal_handler();
    let model = resolve_model(args.model.as_deref(), environment)?;
    let bundle = synth::ModelBundle::resolve(Path::new(&model))?;
    let voices = |name: &str| -> Result<Vec<f32>, FttsError> {
        let path = match materialize_preset_voice(name) {
            Some(result) => result?,
            None => PathBuf::from(name),
        };
        synth::speaker_from_voice(
            &bundle,
            &path,
            synth::ReferenceCleanup {
                denoise: None,
                dereverb: None,
            },
        )
    };
    let settings = EffectiveSettings::resolve(cli, environment)?;
    talk::run_talk(
        &bundle,
        args.pcm_out.as_ref(),
        &voices,
        settings.normalization_options(),
        cli.seed.unwrap_or(0),
    )
}

#[derive(Debug, clap::Args)]
struct TalkArgs {
    /// Model directory (defaults to the standard cache location).
    #[arg(long, value_name = "DIR")]
    model: Option<PathBuf>,
    /// Write session PCM here (file or FIFO). Default on Unix: inherited fd 3.
    /// Required on Windows, where fd inheritance does not exist.
    #[arg(long, value_name = "PATH")]
    pcm_out: Option<PathBuf>,
}

/// A source tensor pinned by the truth-pack inventory and its reviewed storage policy.
#[derive(Clone, Debug)]
struct PinnedMainTensor {
    name: String,
    dtype: Dtype,
    shape: Vec<usize>,
    access_class: AccessClass,
    storage: TensorStoragePolicy,
}

fn run_convert(
    cli: &Cli,
    args: &ConvertArgs,
    environment: &Environment,
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
) -> Result<(), FttsError> {
    let run = robot::RunContext::generate();
    let outcome = run_convert_events(cli, args, environment, &run, &mut |event| {
        write_json_line(stdout, event)
    });

    if let Err(error) = &outcome {
        let mut event = run.event(robot::EventType::RunError);
        event.insert("exit_code".to_owned(), json!(error.exit_code().as_u8()));
        event.insert("kind".to_owned(), json!(error.exit_code().description()));
        event.insert("message".to_owned(), json!(error.to_string()));
        event.insert("remediation".to_owned(), json!(error.remediation()));
        event.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
        write_json_line(stderr, &Value::Object(event))?;
    }

    outcome
}

/// Converts the pinned main checkpoint and emits the normal run lifecycle receipt.
///
/// The source mapping owns no writable state. The destination is first created under a unique
/// sibling name with `create_new`, then atomically renamed only after the streaming writer, an
/// `fsync`, and a digest-validating mapped re-read all succeed. We deliberately leave a failed
/// staging file in place for diagnosis rather than deleting data behind the caller's back.
fn run_convert_events(
    cli: &Cli,
    args: &ConvertArgs,
    environment: &Environment,
    run: &robot::RunContext,
    emit: &mut dyn FnMut(&Value) -> Result<(), FttsError>,
) -> Result<(), FttsError> {
    let settings = EffectiveSettings::resolve(cli, environment)?;
    let mut start = run.event(robot::EventType::RunStart);
    start.insert("command".to_owned(), json!("convert"));
    start.insert("profile".to_owned(), json!(settings.profile.as_str()));
    start.insert(
        "packet_frames".to_owned(),
        json!(settings.packet_frames.as_str()),
    );
    start.insert("math_mode".to_owned(), json!(settings.math_mode.as_str()));
    start.insert("stateless".to_owned(), json!(true));
    start.insert("seed".to_owned(), json!(cli.seed));
    start.insert("model".to_owned(), Value::Null);
    start.insert("voice".to_owned(), Value::Null);
    emit(&Value::Object(start))?;
    let mut seq = 0_u64;

    emit_stage(run, emit, "source_preflight", "begin", &mut seq)?;
    let source = resolve_pinned_main_source(&args.source)?;
    let mapping = MappedFile::open(&source).map_err(|error| {
        FttsError::Input(format!(
            "cannot memory-map pinned source checkpoint {}: {error}",
            source.display()
        ))
    })?;
    let (manifest, plan) = pinned_main_conversion_plan(args.embed_q8, args.micro_q8)?;
    let staging = conversion_staging_path(&args.output)?;
    emit_stage(run, emit, "source_preflight", "end", &mut seq)?;

    emit_stage(run, emit, "convert", "begin", &mut seq)?;
    let destination = std::fs::File::options()
        .write(true)
        .create_new(true)
        .open(&staging)
        .map_err(|error| {
            FttsError::Input(format!(
                "cannot create conversion staging artifact {}: {error}; the output path is never overwritten",
                staging.display()
            ))
        })?;
    let destination = convert_safetensors_streaming(
        mapping.as_slice(),
        &manifest,
        &plan,
        destination,
    )
    .map_err(|error| {
        FttsError::ArtifactFormat(format!(
            "conversion failed before publication: {error}; staging artifact retained at {}",
            staging.display()
        ))
    })?;
    destination.sync_all().map_err(|error| {
        FttsError::ArtifactFormat(format!(
            "cannot sync converted artifact at {}: {error}; staging artifact retained",
            staging.display()
        ))
    })?;
    drop(destination);
    emit_stage(run, emit, "convert", "end", &mut seq)?;

    emit_stage(run, emit, "verify", "begin", &mut seq)?;
    let verified = MappedFttsq::open(&staging).map_err(|error| {
        FttsError::ArtifactFormat(format!(
            "converted staging artifact did not pass digest re-read: {error}; retained at {}",
            staging.display()
        ))
    })?;
    if verified.reader().source_sha256() != PINNED_MAIN_WEIGHTS_SHA256 {
        return Err(FttsError::ArtifactFormat(format!(
            "converted staging artifact recorded an unexpected source digest {}; retained at {}",
            verified.reader().source_sha256(),
            staging.display()
        )));
    }
    drop(verified);
    std::fs::rename(&staging, &args.output).map_err(|error| {
        FttsError::ArtifactFormat(format!(
            "converted artifact verified but could not be published from {} to {}: {error}; staging artifact retained",
            staging.display(),
            args.output.display()
        ))
    })?;
    emit_stage(run, emit, "verify", "end", &mut seq)?;

    let mut complete = run.event(robot::EventType::RunComplete);
    complete.insert("exit_code".to_owned(), json!(FttsExitCode::Success.as_u8()));
    complete.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
    complete.insert("frames".to_owned(), json!(0));
    complete.insert("audio_bytes".to_owned(), json!(0));
    emit(&Value::Object(complete))
}

fn resolve_pinned_main_source(source: &Path) -> Result<PathBuf, FttsError> {
    let source = if source.is_dir() {
        source.join(PINNED_MAIN_WEIGHTS_FILENAME)
    } else {
        source.to_owned()
    };
    if !source.is_file() {
        return Err(FttsError::Input(format!(
            "pinned main checkpoint {} does not exist or is not a file; pass model.safetensors or its containing directory",
            source.display()
        )));
    }
    if source.file_name().and_then(|name| name.to_str()) != Some(PINNED_MAIN_WEIGHTS_FILENAME) {
        return Err(FttsError::Input(format!(
            "this converter accepts the pinned main checkpoint named {PINNED_MAIN_WEIGHTS_FILENAME}, not {}",
            source.display()
        )));
    }
    Ok(source)
}

fn conversion_staging_path(output: &Path) -> Result<PathBuf, FttsError> {
    if output.exists() {
        return Err(FttsError::Input(format!(
            "refusing to overwrite existing output {}; choose a new -o path",
            output.display()
        )));
    }
    let parent = output.parent().unwrap_or_else(|| Path::new("."));
    let file_name = output
        .file_name()
        .and_then(|name| name.to_str())
        .ok_or_else(|| {
            FttsError::Usage("conversion output must name a file, not a directory".to_owned())
        })?;
    let nonce = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|error| FttsError::Generic(format!("system clock is before UNIX_EPOCH: {error}")))?
        .as_nanos();
    let staging = parent.join(format!(
        ".{file_name}.fttsq-converting-{}-{nonce}",
        std::process::id()
    ));
    Ok(staging)
}

fn pinned_main_conversion_plan(
    embed_q8: bool,
    micro_q8: bool,
) -> Result<(WeightsManifest, StreamingConversionPlan), FttsError> {
    let specs = pinned_main_tensor_specs(embed_q8, micro_q8)?;
    let manifest = WeightsManifest::from_expectations(
        "Qwen/Qwen3-TTS-12Hz-0.6B-Base main checkpoint",
        specs
            .iter()
            .map(|spec| ExpectedTensor::new(&spec.name, spec.shape.clone(), spec.dtype)),
    );
    let model_config = serde_json::from_str(PINNED_MODEL_CONFIG).map_err(|error| {
        FttsError::Generic(format!(
            "checked-in pinned model config is invalid JSON: {error}"
        ))
    })?;
    let q8_count = specs
        .iter()
        .filter(|spec| spec.storage == TensorStoragePolicy::Q8PerOutputChannel)
        .count();
    let mut plan = StreamingConversionPlan::new(
        "qwen3-tts-12hz-0.6b-base",
        PINNED_MAIN_WEIGHTS_SHA256,
    )
    .license_notice(pinned_license_notice())
    .model_config(model_config)
    .quantization_manifest(json!({
        "source": {
            "repository": "Qwen/Qwen3-TTS-12Hz-0.6B-Base",
            "revision": PINNED_MODEL_REVISION,
            "file": PINNED_MAIN_WEIGHTS_FILENAME,
            "sha256": PINNED_MAIN_WEIGHTS_SHA256,
        },
        "q8_recipe": "symmetric per-output-channel int8; zero_point=0; scale=max_abs(row)/127",
        "q8_tensor_count": q8_count,
        "verbatim_tensor_count": specs.len() - q8_count,
        "q8_scope": match (embed_q8, micro_q8) {
            (true, true) => "talker and residual-code-microdecoder attention/MLP projection matrices, plus the cold text embedding (per-64-element-group scales; --embed-q8) and the microdecoder per-depth embedding/head tables (--micro-q8)",
            (true, false) => "talker and residual-code-microdecoder attention/MLP projection matrices, plus the cold text embedding (per-64-element-group scales; --embed-q8)",
            (false, true) => "talker and residual-code-microdecoder attention/MLP projection matrices, plus the microdecoder per-depth embedding/head tables (--micro-q8)",
            (false, false) => "talker and residual-code-microdecoder attention/MLP projection matrices only",
        },
        "verbatim_scope": if embed_q8 || micro_q8 {
            "norms, non-Q8 embeddings and heads, speaker path, and every tensor outside the reviewed Q8 set"
        } else {
            "norms, heads, embeddings, speaker path, and every tensor outside the reviewed Q8 projection set"
        },
        "embedding_q8": embed_q8,
        "micro_tables_q8": micro_q8,
    }));
    for spec in specs {
        let conversion = match spec.storage {
            TensorStoragePolicy::Verbatim => {
                TensorConversion::verbatim(&spec.name, &spec.name, spec.access_class)
            }
            TensorStoragePolicy::Q8PerOutputChannel => {
                TensorConversion::q8_per_output_channel(&spec.name, &spec.name, spec.access_class)
            }
            TensorStoragePolicy::Q8PerGroup64 => {
                TensorConversion::q8_per_group_64(&spec.name, &spec.name, spec.access_class)
            }
        };
        plan = plan.tensor(conversion);
    }
    Ok((manifest, plan))
}

fn pinned_main_tensor_specs(
    embed_q8: bool,
    micro_q8: bool,
) -> Result<Vec<PinnedMainTensor>, FttsError> {
    let inventory: Value = serde_json::from_str(PINNED_TENSOR_INVENTORY).map_err(|error| {
        FttsError::Generic(format!(
            "checked-in tensor inventory is invalid JSON: {error}"
        ))
    })?;
    if inventory.get("source_pin").and_then(Value::as_str)
        != Some(&format!(
            "Qwen/Qwen3-TTS-12Hz-0.6B-Base@{PINNED_MODEL_REVISION}"
        ))
    {
        return Err(FttsError::Generic(
            "checked-in tensor inventory does not name the pinned Qwen3-TTS revision".to_owned(),
        ));
    }
    let records = inventory
        .get("tensors")
        .and_then(Value::as_array)
        .ok_or_else(|| {
            FttsError::Generic("checked-in tensor inventory lacks tensors[]".to_owned())
        })?;
    let mut specs = Vec::new();
    for record in records {
        if record.get("source").and_then(Value::as_str) != Some(PINNED_MAIN_WEIGHTS_FILENAME) {
            continue;
        }
        let name = required_inventory_string(record, "name")?.to_owned();
        let dtype = match required_inventory_string(record, "dtype")? {
            "BF16" => Dtype::Bf16,
            "F32" => Dtype::F32,
            other => {
                return Err(FttsError::Generic(format!(
                    "pinned main inventory has unsupported dtype {other:?} for {name}"
                )));
            }
        };
        let shape = record
            .get("shape")
            .and_then(Value::as_array)
            .ok_or_else(|| {
                FttsError::Generic(format!("pinned inventory tensor {name} lacks shape[]"))
            })?
            .iter()
            .map(|dimension| {
                dimension
                    .as_u64()
                    .and_then(|dimension| usize::try_from(dimension).ok())
                    .ok_or_else(|| {
                        FttsError::Generic(format!(
                            "pinned inventory tensor {name} has a non-usize shape dimension"
                        ))
                    })
            })
            .collect::<Result<Vec<_>, _>>()?;
        // The cold text embedding joins the Q8 set only on explicit request: 47.4% of the
        // artifact (census, frankentts-o461), halved by Q8, but it ships as default only
        // after the artifact-v2 gates (frankentts-6ea1). GROUPED scales, not per-row: the
        // most common tokens' rows measured 23.8 dB SQNR under one row scale (their energy
        // is uneven across the row) and 35.0 dB under 64-element groups, for ~19 MB of
        // scales. The loader reads grouped and per-row forms alike.
        let storage = if is_q8_projection(&name) {
            TensorStoragePolicy::Q8PerOutputChannel
        } else if embed_q8 && name == "talker.model.text_embedding.weight" {
            TensorStoragePolicy::Q8PerGroup64
        } else if micro_q8 && is_micro_table(&name) {
            TensorStoragePolicy::Q8PerOutputChannel
        } else {
            TensorStoragePolicy::Verbatim
        };
        specs.push(PinnedMainTensor {
            access_class: main_access_class(&name)?,
            name,
            dtype,
            shape,
            storage,
        });
    }
    if specs.len() != PINNED_MAIN_TENSOR_COUNT {
        return Err(FttsError::Generic(format!(
            "pinned main inventory contains {} tensors, expected {PINNED_MAIN_TENSOR_COUNT}",
            specs.len()
        )));
    }
    Ok(specs)
}

fn required_inventory_string<'a>(record: &'a Value, field: &str) -> Result<&'a str, FttsError> {
    record.get(field).and_then(Value::as_str).ok_or_else(|| {
        FttsError::Generic(format!(
            "checked-in tensor inventory record lacks string {field:?}"
        ))
    })
}

fn is_q8_projection(name: &str) -> bool {
    (name.starts_with("talker.model.layers.")
        || name.starts_with("talker.code_predictor.model.layers."))
        && [
            ".self_attn.q_proj.weight",
            ".self_attn.k_proj.weight",
            ".self_attn.v_proj.weight",
            ".self_attn.o_proj.weight",
            ".mlp.gate_proj.weight",
            ".mlp.up_proj.weight",
            ".mlp.down_proj.weight",
        ]
        .iter()
        .any(|suffix| name.ends_with(suffix))
}

/// The microdecoder's per-depth residual embedding tables and scoring heads: the ~126 MB
/// bf16 block the census flagged as the second-largest wide surface after the cold text
/// embedding (frankentts-o461). Fifteen `[2048, 1024]` tables each side; `--micro-q8`
/// stores them per-row Q8, which halves them and which [`crate::synth`] consumes
/// natively — heads feed the int8 refine path's coarse pass directly, and the embedding
/// gather dequantizes one row at a time (bead frankentts-x7bt).
fn is_micro_table(name: &str) -> bool {
    (name.starts_with("talker.code_predictor.model.codec_embedding.")
        || name.starts_with("talker.code_predictor.lm_head."))
        && name.ends_with(".weight")
}

fn main_access_class(name: &str) -> Result<AccessClass, FttsError> {
    if name == "talker.model.text_embedding.weight" {
        Ok(AccessClass::ColdTextEmbedding)
    } else if name.starts_with("speaker_encoder.") {
        Ok(AccessClass::EnrollmentSpeakerEncoder)
    } else if name.starts_with("talker.code_predictor.")
        || name == "talker.model.codec_embedding.weight"
    {
        Ok(AccessClass::HotRecurrentMicrodecoder)
    } else if name.starts_with("talker.model.")
        || name.starts_with("talker.codec_head.")
        || name.starts_with("talker.text_projection.")
    {
        Ok(AccessClass::HotRecurrentTalker)
    } else {
        Err(FttsError::Generic(format!(
            "pinned main tensor {name} has no reviewed access-class assignment"
        )))
    }
}

fn pinned_license_notice() -> String {
    format!(
        "This artifact contains model weights derived from\n\
         Qwen3-TTS-12Hz-0.6B-Base (https://huggingface.co/Qwen/Qwen3-TTS-12Hz-0.6B-Base)\n\
         and code derived from QwenLM/Qwen3-TTS (https://github.com/QwenLM/Qwen3-TTS).\n\n\
         Copyright 2026 Alibaba Cloud\n\n\
         Licensed under the Apache License, Version 2.0.\n\
         http://www.apache.org/licenses/LICENSE-2.0\n\n\
         CHANGES: the original bfloat16 weights were converted to franken_tts's\n\
         quantized .fttsq container. Tensors were requantized according to the\n\
         artifact's quantization manifest; protected tensors remain verbatim.\n\
         The model graph is re-implemented in Rust.\n\n\
         Apache License, Version 2.0:\n\n{APACHE_LICENSE}"
    )
}

/// The SIGINT/SIGTERM bridge for one `say` run (bead frankentts-astz).
///
/// `ctrlc` delivers signals on its own thread, so the registered closure is ordinary
/// code, not an async-signal handler: the first strike records [`CancelState::tripped`]
/// and trips the engine token (the frame loop notices within one 80 ms frame); any
/// later strike exits immediately with the cancelled code — the behavioral equivalent
/// of restoring the default disposition, so a wedged process can still be killed. The
/// OS hook is installed once per process and each run swaps in its own state; a failed
/// install degrades to the default disposition rather than failing the run.
struct CancelState {
    /// Signal strikes seen so far: first vs force-exit.
    signals: std::sync::atomic::AtomicU32,
    /// Set by the first signal; polled where the token cannot reach — the resident
    /// daemon round-trip, whose v1 wire protocol has no cancel operation.
    tripped: std::sync::atomic::AtomicBool,
    /// Tripped by the first signal; aborts the in-process engine loop.
    token: ftts_core::CancellationToken,
}

impl CancelState {
    fn new() -> Self {
        Self {
            signals: std::sync::atomic::AtomicU32::new(0),
            tripped: std::sync::atomic::AtomicBool::new(false),
            token: ftts_core::CancellationToken::new(),
        }
    }

    /// Whether any cancellation request has landed, by either route.
    fn was_tripped(&self) -> bool {
        self.tripped.load(std::sync::atomic::Ordering::Relaxed) || self.token.is_cancelled()
    }
}

/// What one delivered signal means for the run.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum StrikeAction {
    /// First signal: cancel cooperatively.
    Trip,
    /// Any later signal: stop now.
    ForceExit,
}

/// The pure two-strike decision, unit-tested here; real delivery timing belongs to
/// the cancellation e2e battery (`frankentts-9t5v`).
fn next_strike_action(signals_seen: u32) -> StrikeAction {
    if signals_seen <= 1 {
        StrikeAction::Trip
    } else {
        StrikeAction::ForceExit
    }
}

/// The ctrlc hook itself, installed on first force. It reads [`ACTIVE_CANCEL`] on
/// every delivery, so later runs replace the served state without touching the OS
/// handler again.
static SIGNAL_HOOK: std::sync::LazyLock<()> = std::sync::LazyLock::new(|| {
    // Best effort by design: if the hook cannot be installed (exotic platform,
    // sandbox), Ctrl-C keeps its default killing disposition instead.
    let _ = ctrlc::set_handler(|| {
        let Ok(guard) = ACTIVE_CANCEL.lock() else {
            return;
        };
        let Some(state) = guard.as_ref() else {
            drop(guard);
            // No `say` run is served: the strike belongs to a live `ftts talk`
            // session. Strike one cancels cooperatively through the router; any
            // later strike force-exits with the cancelled code.
            let seen = TALK_STRIKES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
            if next_strike_action(seen) == StrikeAction::ForceExit {
                std::process::exit(i32::from(FttsExitCode::Cancelled.as_u8()));
            }
            let talk_inbox = TALK_SIGNAL_INBOX
                .lock()
                .ok()
                .and_then(|armed| armed.clone());
            match talk_inbox {
                Some(inbox) => {
                    let _ = inbox.send(crate::talk::RouterIn::Sigint);
                }
                // The bridge is armed but the router is gone; honour the strike.
                None => std::process::exit(i32::from(FttsExitCode::Cancelled.as_u8())),
            }
            return;
        };
        let seen = state
            .signals
            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
            + 1;
        drop(guard);
        match next_strike_action(seen) {
            StrikeAction::Trip => trip_active_cancel(),
            StrikeAction::ForceExit => {
                std::process::exit(i32::from(FttsExitCode::Cancelled.as_u8()));
            }
        }
    });
});

static ACTIVE_CANCEL: std::sync::Mutex<Option<std::sync::Arc<CancelState>>> =
    std::sync::Mutex::new(None);

/// Armed by a live `ftts talk` session so SIGINT strikes reach its router
/// ([`crate::talk::RouterIn::Sigint`]: cancel the current utterance, settle its
/// receipt, exit 6). Disarmed when the session ends; strikes with no live session
/// force-exit with the cancelled code, matching the two-strike contract.
static TALK_SIGNAL_INBOX: std::sync::Mutex<
    Option<std::sync::mpsc::SyncSender<crate::talk::RouterIn>>,
> = std::sync::Mutex::new(None);

/// SIGINT strikes seen while no `say` run is served (i.e. during `ftts talk`).
static TALK_STRIKES: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);

/// Make `state` the run the signal bridge serves.
fn install_cancel_handler(state: std::sync::Arc<CancelState>) {
    LazyLock::force(&SIGNAL_HOOK);
    *ACTIVE_CANCEL.lock().expect("cancel-state mutex poisoned") = Some(state);
}

/// Arm the process-wide signal hook for a `talk` session.
///
/// Unlike one-shot `say`, talk has no [`CancelState`] to install: its first strike travels through
/// [`TALK_SIGNAL_INBOX`] to the session router. The hook still has to be forced before model load,
/// otherwise the operating system retains its default SIGINT disposition and kills the process
/// before the router can settle `speak_cancelled` and `session_end` receipts.
fn install_talk_signal_handler() {
    TALK_STRIKES.store(0, std::sync::atomic::Ordering::Relaxed);
    LazyLock::force(&SIGNAL_HOOK);
}

/// Record the cancellation and trip whichever engine token is currently serving.
fn trip_active_cancel() {
    let Ok(guard) = ACTIVE_CANCEL.lock() else {
        return;
    };
    if let Some(state) = guard.as_ref() {
        state
            .tripped
            .store(true, std::sync::atomic::Ordering::Relaxed);
        state.token.cancel();
    }
}

/// Finalize what a cancelled run already delivered and word the disposition for the
/// terminal event's message field — the existing `run_error` shape carries it, no new
/// fields anywhere.
///
/// File sinks get their header patched to exactly the samples that landed: a parseable
/// partial artifact beats a torn file. Compressed targets keep that partial WAV at its
/// staging path and skip the system encoder entirely — handing a truncated file to the
/// encoder would produce garbage or nothing, never a valid `.m4a`, and the event says
/// so. Raw streams already ended at a packet boundary; the streamed byte count is the
/// accounting receipt.
fn cancelled_run_disposition(audio: AudioOutput, plan: Option<&OutputPlan>) -> FttsError {
    let streamed_bytes = audio.byte_offset();
    let samples = match audio.finish() {
        Ok(samples) => samples,
        Err(error) => {
            return FttsError::Cancelled(format!(
                "cancelled by signal; the partial WAV could not be finalized: {error}"
            ));
        }
    };
    let message = match plan {
        None => format!("cancelled by signal after streaming {streamed_bytes} raw PCM bytes"),
        Some(plan) if plan.format == OutputFormat::Wav => format!(
            "cancelled after {samples} samples; partial WAV kept at {}",
            plan.final_path.display()
        ),
        Some(plan) => format!(
            "cancelled after {samples} samples; encoding to {} skipped, partial WAV kept at {}",
            plan.final_path.display(),
            plan.wav_path.display()
        ),
    };
    FttsError::Cancelled(message)
}

fn run_say(
    cli: &Cli,
    args: &SayArgs,
    environment: &Environment,
    stdin: &mut dyn Read,
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
    capabilities: IoCapabilities,
) -> Result<(), FttsError> {
    let run = robot::RunContext::generate();
    // `--stream raw` puts PCM on stdout, so events move to stderr. One contract, chosen once here
    // so no later emission can pick the other stream and interleave NDJSON with audio bytes. The
    // two branches also settle the borrows: in raw mode audio owns `stdout` and events own
    // `stderr`; otherwise events own `stdout` and the raw sink is a discard that never runs.
    let outcome = if args.stream == Some(StreamMode::Raw) {
        run_say_events(
            cli,
            args,
            environment,
            stdin,
            &run,
            SayEventOutput {
                raw_audio: stdout,
                human_progress: false,
            },
            &mut |event| write_json_line(stderr, event),
        )
    } else if args.robot || !capabilities.human_output {
        let mut discard = io::sink();
        run_say_events(
            cli,
            args,
            environment,
            stdin,
            &run,
            SayEventOutput {
                raw_audio: &mut discard,
                human_progress: false,
            },
            &mut |event| write_json_line(stdout, event),
        )
    } else {
        // A terminal gets the human view of the same lifecycle. The NDJSON contract is untouched:
        // it is what every pipe, file, CI job and agent still receives, because none of them is a
        // terminal. `--robot` forces it back on for a human debugging the stream itself.
        let mut discard = io::sink();
        let destination = args
            .output
            .as_deref()
            .or(args.output_positional.as_deref())
            .map(|path| path.display().to_string());
        let mut presenter = style::SayPresenter::writing_to(destination);
        run_say_events(
            cli,
            args,
            environment,
            stdin,
            &run,
            SayEventOutput {
                raw_audio: &mut discard,
                human_progress: true,
            },
            &mut |event| {
                presenter
                    .event(event, stdout)
                    .map_err(|error| FttsError::Generic(format!("cannot write progress: {error}")))
            },
        )
    };

    if let Err(error) = &outcome {
        // The error is reported on the machine contract, not only as a human line: run_error is a
        // stderr event by definition (see the catalogue), so it goes to stderr on both stream
        // shapes.
        let mut event = run.event(robot::EventType::RunError);
        event.insert("exit_code".to_owned(), json!(error.exit_code().as_u8()));
        event.insert("kind".to_owned(), json!(error.exit_code().description()));
        event.insert("message".to_owned(), json!(error.to_string()));
        event.insert("remediation".to_owned(), json!(error.remediation()));
        event.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
        write_json_line(stderr, &Value::Object(event))?;
    }

    outcome
}

/// `ftts make-video`: synthesize (or take a WAV) and render the branded
/// share video. Frames, waveform, and text are pure Rust (`ftts-video`);
/// `.mp4` goes through the same first-available-system-encoder contract as
/// `ftts say`'s `.m4a` path, and `.y4m` + `.wav` is the native no-encoder
/// output.
fn run_make_video(
    cli: &Cli,
    args: &MakeVideoArgs,
    environment: &Environment,
    stdin: &mut dyn Read,
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
    capabilities: IoCapabilities,
) -> Result<(), FttsError> {
    let output = args
        .output
        .clone()
        .or_else(|| args.output_positional.clone())
        .ok_or_else(|| {
            FttsError::Usage(
                "`ftts make-video` needs an output path (`ftts make-video \"text\" out.mp4`)"
                    .to_owned(),
            )
        })?;
    let extension = output
        .extension()
        .and_then(|extension| extension.to_str())
        .map(str::to_ascii_lowercase);
    let is_mp4 = match extension.as_deref() {
        Some("mp4") => true,
        Some("y4m") => false,
        other => {
            return Err(FttsError::Usage(format!(
                "unsupported video extension `.{}`; use .mp4 (system encoder) or .y4m (native)",
                other.unwrap_or("<none>")
            )));
        }
    };

    // The voice pill needs a human name: an explicit --label wins, a preset
    // keeps its capitalized name, a custom voice shows its file stem. With
    // no voice given, the label follows the same default chain `say` uses
    // (FTTS_DEFAULT_VOICE, then an enrolled default voice, then built-in matt)
    // rather than claiming "Matt" over someone's enrolled voice.
    let capitalize = |raw: &str| {
        let mut chars = raw.chars();
        chars
            .next()
            .map(|first| first.to_uppercase().collect::<String>() + chars.as_str())
            .unwrap_or_else(|| raw.to_owned())
    };
    let stem_of = |path: &Path| {
        path.file_stem()
            .and_then(|stem| stem.to_str())
            .map(str::to_owned)
    };
    let label = args.label.clone().unwrap_or_else(|| {
        if let Some(voice) = &args.voice {
            return stem_of(voice)
                .map(|stem| capitalize(&stem))
                .unwrap_or_else(|| "Voice".to_owned());
        }
        if let Some(audio) = &args.audio {
            // Rendering someone's own recording: name it after the file.
            return stem_of(audio)
                .map(|stem| capitalize(&stem))
                .unwrap_or_else(|| "Voice".to_owned());
        }
        if let Some(default_voice) = environment.value("FTTS_DEFAULT_VOICE")
            && let Some(stem) = stem_of(Path::new(default_voice))
        {
            return capitalize(&stem);
        }
        let enrolled_default = resolve_model(args.model.as_deref(), environment)
            .ok()
            .and_then(|model| synth::ModelBundle::resolve(Path::new(&model)).ok())
            .is_some_and(|bundle| {
                bundle.root.join("default.ftvoice").is_file()
                    || bundle.root.join("default.spk").is_file()
            });
        if enrolled_default {
            "My voice".to_owned()
        } else {
            "Matt".to_owned()
        }
    });

    // Audio: either supplied, or synthesized through the full `say` pipeline
    // (same events, presenter, and resident engine). An mp4 gets a staging
    // WAV that is consumed by the encoder; a y4m synthesizes straight into
    // its `.wav` sibling, which stays as the video's audio track.
    let staging: Option<PathBuf> = if args.audio.is_none() {
        if is_mp4 {
            let mut path = output.as_os_str().to_owned();
            path.push(".ftts-staging.wav");
            Some(PathBuf::from(path))
        } else {
            Some(output.with_extension("wav"))
        }
    } else {
        None
    };
    if let Some(staging_path) = &staging {
        let say_args = SayArgs {
            text: args.text.clone(),
            output_positional: None,
            file: args.file.clone(),
            model: args.model.clone(),
            voice: args.voice.clone(),
            output: Some(staging_path.clone()),
            stream: None,
            check: false,
            robot: false,
            no_resident: args.no_resident,
        };
        run_say(
            cli,
            &say_args,
            environment,
            stdin,
            stdout,
            stderr,
            capabilities,
        )?;
    }
    let audio_path = args
        .audio
        .clone()
        .or_else(|| staging.clone())
        .unwrap_or_default();

    // The video phase reports on the same machine contract as everything else: its own
    // run (the synthesis phase above already closed a `say` run), with `stage` events
    // around rendering and a `run_complete` carrying the video frame count. A terminal
    // gets the human progress line instead; agents were previously left with silence
    // between the say run ending and the process exiting.
    let interactive = capabilities.human_output;
    let settings = EffectiveSettings::resolve(cli, environment)?;
    let run = robot::RunContext::generate();
    let mut seq = 0_u64;
    let emit = |event: &Value, stdout: &mut dyn Write| -> Result<(), FttsError> {
        if interactive {
            return Ok(());
        }
        write_json_line(stdout, event)
    };
    let mut start = run.event(robot::EventType::RunStart);
    start.insert("command".to_owned(), json!("make-video"));
    start.insert("profile".to_owned(), json!(settings.profile.as_str()));
    start.insert(
        "packet_frames".to_owned(),
        json!(settings.packet_frames.as_str()),
    );
    start.insert("math_mode".to_owned(), json!(settings.math_mode.as_str()));
    start.insert("stateless".to_owned(), json!(true));
    start.insert("seed".to_owned(), json!(cli.seed));
    start.insert("model".to_owned(), json!(args.model.as_deref()));
    start.insert("voice".to_owned(), json!(label));
    emit(&Value::Object(start), stdout)?;

    if interactive {
        writeln!(stdout, "rendering video: {}", output.display())
            .map_err(|error| FttsError::Generic(format!("cannot write progress: {error}")))?;
    }
    let request = ftts_video::VideoRequest {
        audio: &audio_path,
        output: &output,
        voice_label: &label,
    };
    emit_stage(
        &run,
        &mut |e| emit(e, stdout),
        "video_render",
        "begin",
        &mut seq,
    )?;
    let mut last_percent = 0usize;
    let mut video_frames = 0_u64;
    let render_result = ftts_video::render(&request, &mut |progress| {
        video_frames = progress.total_frames as u64;
        if !interactive {
            return;
        }
        let percent = progress.frame * 100 / progress.total_frames;
        if percent >= last_percent + 10 || progress.frame == progress.total_frames {
            last_percent = percent;
            let _ = write!(
                stdout,
                "\r  frame {}/{} ({percent}%)",
                progress.frame, progress.total_frames
            );
            let _ = stdout.flush();
        }
    });
    if interactive {
        let _ = writeln!(stdout);
    }
    match &render_result {
        Ok(()) => {
            emit_stage(
                &run,
                &mut |e| emit(e, stdout),
                "video_render",
                "end",
                &mut seq,
            )?;
        }
        Err(message) => {
            // `run_error` is a stderr event by the catalogue, on both stream shapes.
            let mut event = run.event(robot::EventType::RunError);
            let error = FttsError::Generic(message.clone());
            event.insert("exit_code".to_owned(), json!(error.exit_code().as_u8()));
            event.insert("kind".to_owned(), json!(error.exit_code().description()));
            event.insert("message".to_owned(), json!(message));
            event.insert("remediation".to_owned(), json!(error.remediation()));
            event.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
            if !interactive {
                write_json_line(stderr, &Value::Object(event))?;
            }
        }
    }
    render_result.map_err(FttsError::Generic)?;
    let video_bytes = fs::metadata(&output).map_or(0, |meta| meta.len());
    let mut complete = run.event(robot::EventType::RunComplete);
    complete.insert("exit_code".to_owned(), json!(FttsExitCode::Success.as_u8()));
    complete.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
    complete.insert("frames".to_owned(), json!(video_frames));
    // The say run above already reported the PCM bytes; this run's product is the video.
    complete.insert("audio_bytes".to_owned(), json!(0));
    complete.insert("video_bytes".to_owned(), json!(video_bytes));
    emit(&Value::Object(complete), stdout)?;

    // The staging WAV is consumed into the mp4; remove it exactly as the
    // `.m4a` OutputPlan removes its staging file. The `.y4m` path keeps its
    // audio, renamed to the output's `.wav` sibling by the renderer.
    if is_mp4 && let Some(staging_path) = &staging {
        let _ = fs::remove_file(staging_path);
    }
    if interactive {
        writeln!(stdout, "wrote {}", output.display())
            .map_err(|error| FttsError::Generic(format!("cannot write result: {error}")))?;
    }
    Ok(())
}

/// Emit one `stage` event and advance the run's stage counter.
fn emit_stage(
    run: &robot::RunContext,
    emit: &mut dyn FnMut(&Value) -> Result<(), FttsError>,
    name: &str,
    state: &str,
    seq: &mut u64,
) -> Result<(), FttsError> {
    let mut event = run.event(robot::EventType::Stage);
    event.insert("name".to_owned(), json!(name));
    event.insert("seq".to_owned(), json!(*seq));
    event.insert("state".to_owned(), json!(state));
    event.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
    event.insert("budget_ms".to_owned(), Value::Null);
    *seq += 1;
    emit(&Value::Object(event))
}

/// The `say` pipeline proper, emitting its lifecycle through `emit`.
///
/// Split out so the caller owns stream selection and the single `run_error` emission point: a
/// pipeline that emitted its own errors would have to know which stream it was on at every `?`.
struct SayEventOutput<'a> {
    raw_audio: &'a mut dyn Write,
    human_progress: bool,
}

fn run_say_events(
    cli: &Cli,
    args: &SayArgs,
    environment: &Environment,
    stdin: &mut dyn Read,
    run: &robot::RunContext,
    output: SayEventOutput<'_>,
    emit: &mut dyn FnMut(&Value) -> Result<(), FttsError>,
) -> Result<(), FttsError> {
    let settings = EffectiveSettings::resolve(cli, environment)?;

    let mut start = run.event(robot::EventType::RunStart);
    start.insert("command".to_owned(), json!("say"));
    start.insert("profile".to_owned(), json!(settings.profile.as_str()));
    start.insert(
        "packet_frames".to_owned(),
        json!(settings.packet_frames.as_str()),
    );
    start.insert("math_mode".to_owned(), json!(settings.math_mode.as_str()));
    start.insert("stateless".to_owned(), json!(true));
    start.insert("seed".to_owned(), json!(cli.seed));
    start.insert("model".to_owned(), json!(args.model.as_deref()));
    start.insert(
        "voice".to_owned(),
        json!(args.voice.as_ref().map(|path| path.display().to_string())),
    );
    emit(&Value::Object(start))?;

    let mut seq = 0u64;

    emit_stage(run, emit, "resolve", "begin", &mut seq)?;
    let text = read_text(args, stdin)?;
    let model = resolve_model(args.model.as_deref(), environment)?;
    let voice = resolve_requested_voice(args.voice.as_deref(), environment)?;
    emit_stage(run, emit, "resolve", "end", &mut seq)?;

    let request = SynthesisRequest::new(text)
        .with_normalization_options(settings.normalization_options())
        .with_normalization_trace(cli.trace.is_some());

    // Privacy-safe by construction: shape and rule names only, never the text itself. The CLI
    // promises no persisted synthesis history, and an event stream an agent may log is exactly
    // where that promise would leak if this carried the input.
    let mut prepared = run.event(robot::EventType::TextPrepared);
    prepared.insert("normalize".to_owned(), json!(settings.normalize.as_str()));
    prepared.insert(
        "unicode_version".to_owned(),
        json!(ftts_model_qwen::tokenizer::unicode_version()),
    );
    prepared.insert("char_count".to_owned(), json!(request.text.chars().count()));
    prepared.insert(
        "trace_requested".to_owned(),
        json!(request.trace_normalization),
    );
    emit(&Value::Object(prepared))?;

    // `-o PATH` and the positional OUTPUT are the same request; clap rejects supplying both.
    let requested_output: Option<PathBuf> = args
        .output
        .clone()
        .or_else(|| args.output_positional.clone());
    let output_plan = requested_output
        .as_deref()
        .map(OutputPlan::for_path)
        .transpose()?;

    emit_stage(run, emit, "admission", "begin", &mut seq)?;
    let admission = admission_plan(&request.text, &settings)?;
    emit_stage(run, emit, "admission", "end", &mut seq)?;

    if args.check {
        let event = json!({
            "schema_version": ROBOT_SCHEMA_VERSION,
            "event": "check_complete",
            "run_id": run.run_id(),
            "model": model,
            "voice": voice,
            "profile": settings.profile.as_str(),
            "packet_frames": settings.packet_frames.as_str(),
            "math_mode": settings.math_mode.as_str(),
            "voice_pack": settings.voice_pack.as_str(),
            "normalize": settings.normalize.as_str(),
            "normalization_trace_requested": request.trace_normalization,
            "seed": cli.seed,
            "trace": cli.trace.as_ref().map(|path| path.display().to_string()),
            "output": requested_output.as_ref().map(|path| path.display().to_string()),
            "admission": admission,
        });
        emit(&event)?;
        let mut complete = run.event(robot::EventType::RunComplete);
        complete.insert("exit_code".to_owned(), json!(FttsExitCode::Success.as_u8()));
        complete.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
        complete.insert("frames".to_owned(), json!(0));
        complete.insert("audio_bytes".to_owned(), json!(0));
        emit(&Value::Object(complete))?;
        return Ok(());
    }

    // --- audio destination, decided before any model work ----------------------------------
    // A run that synthesizes for thirty seconds and then discovers it has nowhere to put the
    // result has wasted the user's time; the refusal belongs here, before the weights load.
    let raw_stream = args.stream == Some(StreamMode::Raw);
    let mut audio = match (&output_plan, raw_stream) {
        (Some(plan), false) => AudioOutput::wav(&plan.wav_path)?,
        (None, true) => AudioOutput::raw(),
        (None, false) => {
            return Err(FttsError::Usage(
                "`ftts say` has nowhere to put the audio; add an output path (`ftts say \"text\" \
                 out.wav`, or `-o PATH`) or `--stream raw` for PCM on stdout"
                    .to_owned(),
            ));
        }
        // clap declares every output form and `--stream` mutually exclusive.
        (Some(_), true) => unreachable!("clap enforces the conflict"),
    };

    // --- model load ------------------------------------------------------------------------
    emit_stage(run, emit, "load", "begin", &mut seq)?;
    let bundle = synth::ModelBundle::resolve(Path::new(&model))?;
    let voice_path = match voice.as_deref().map(PathBuf::from).or_else(|| {
        // Packs outrank raw vectors when both exist; a pack is what modern enrollment writes.
        ["default.ftvoice", "default.spk"]
            .iter()
            .map(|name| bundle.root.join(name))
            .find(|candidate| candidate.is_file())
    }) {
        Some(path) => path,
        // Out-of-box: no --voice, no FTTS_DEFAULT_VOICE, no enrollment — speak with the built-in
        // default preset rather than refusing. The presets are real enrolled x-vectors taken from
        // speech, so they sit on the speaker encoder's manifold; any user enrollment or explicit
        // voice always outranks them.
        None => materialize_preset_voice(DEFAULT_PRESET_VOICE)
            .expect("the default preset name is a member of PRESET_VOICES")?,
    };
    // A `--voice` that names an audio file (not a .spk vector) computes an ephemeral
    // enrollment, and gets the same automatic denoise `ftts enroll` applies — otherwise the
    // one-off form of the exact same operation would sound worse than the saved form. The
    // report goes unread here: `say` has no enrollment console, and the .spk/preset paths
    // never enter the cleanup code.
    let mut say_denoise_report = None;
    let denoise_ephemeral = bundle.root.join(synth::DENOISE_ARTIFACT_RELPATH).is_file();
    // Ephemeral audio sources keep the automatic denoise here (same rationale as enroll);
    // pack sources already carry their cleaned-audio identity, so no second cleanup runs.
    let voice_conditioning = synth::say_voice_conditioning(
        &bundle,
        &voice_path,
        (denoise_ephemeral).then_some(&mut say_denoise_report),
    )?;
    // With the resident engine (the default), the model stays loaded in a background
    // process and this invocation skips its own hydration; the daemon's load happens
    // inside the synthesis stage on its first request. Any resident-path unavailability
    // falls back to the classic in-process load below, never to a failure.
    //
    // `--stream raw` BYPASSES the resident: the daemon's frozen v1 wire protocol delivers
    // one whole PCM blob after complete synthesis (resident.rs), so a resident-served run
    // can never stream live — and a warm run silently regressing to buffered delivery
    // while the cold run streams would be worse than either behavior alone. Raw streaming
    // therefore pays the in-process load; the warm+streaming surface is the talk session.
    // ICL conditioning cannot ride the resident wire protocol (v1 carries vectors only);
    // serving it through the daemon would silently strip the transcript+tokens quality
    // path, so those runs pay the in-process load instead.
    let use_resident =
        resident::enabled(args.no_resident) && !raw_stream && voice_conditioning.is_xvector();
    let load_inline = || {
        if output.human_progress && !args.robot && !raw_stream {
            synth::LoadedModel::load_with_human_progress(&bundle)
        } else {
            synth::LoadedModel::load(&bundle)
        }
    };
    let loaded = if use_resident {
        None
    } else {
        Some(load_inline()?)
    };
    emit_stage(run, emit, "load", "end", &mut seq)?;

    // --- synthesis -------------------------------------------------------------------------
    // Canonical greedy consumes no RNG state, so an absent `--seed` changes nothing today;
    // 0 is the documented default rather than a value picked per run, which would make a
    // future switch to the production sampler silently irreproducible.
    let seed = cli.seed.unwrap_or(0);

    // The signal bridge goes up before anything slow: a SIGINT during the resident
    // round-trip must land somewhere even though the v1 wire protocol cannot cancel
    // the daemon. Inline synthesis shares this token, so one handler serves both
    // paths (bead frankentts-astz).
    let cancel = std::sync::Arc::new(CancelState::new());
    install_cancel_handler(cancel.clone());

    emit_stage(run, emit, "synthesis", "begin", &mut seq)?;
    let resident_audio = if use_resident {
        let audio = resident::try_synthesize_interruptible(
            &bundle,
            &resident::WireRequest {
                text: &request.text,
                normalize: settings.normalize.as_str(),
                trace: request.trace_normalization,
                speaker: voice_conditioning.embedding(),
                seed,
            },
            // Strike-one must land while the daemon still renders: the poll slice
            // turns the consumed SIGINT into Cancelled within ~100 ms instead of
            // whenever the whole utterance happens to finish (g4zq).
            &|| cancel.was_tripped(),
        )?;
        // The daemon finished anyway — v1 has no cancel op — but honoring the request
        // means discarding the reply, not shipping audio the user asked us to stop
        // making. Same terminal shape as an inline cancel: run_error, exit 6.
        if audio.is_some() && cancel.was_tripped() {
            return Err(FttsError::Cancelled(
                "cancelled while the resident engine was serving the request; its \
                 completed audio was discarded"
                    .to_owned(),
            ));
        }
        audio
    } else {
        None
    };
    // Robot-mode resident observability (bead frankentts-xw2v): which path served the
    // request, as a stage pair so the begin/end discipline holds. The stage NAME
    // carries the state — `resident-hit` (daemon served it), `resident-miss`
    // (consulted but none served; inline fallback) — because the strict-closed stage
    // schema has no spare field and zero schema churn is the standing rule. Not
    // emitted when the resident was disabled outright: `--no-resident` runs are
    // ordinary inline runs, not resident events.
    if use_resident {
        let state = if resident_audio.is_some() {
            "hit"
        } else {
            "miss"
        };
        emit_stage(run, emit, &format!("resident-{state}"), "begin", &mut seq)?;
        emit_stage(run, emit, &format!("resident-{state}"), "end", &mut seq)?;
    }
    // Whether the in-process live path already wrote PCM and emitted `audio_chunk` events
    // during synthesis. The resident path cannot (its v1 wire reply is one whole blob), so
    // it keeps the post-synthesis packetization below.
    let mut live_output_began = false;
    let audio_result = match resident_audio {
        Some(audio) => (audio, false),
        None => {
            let loaded = match loaded {
                Some(loaded) => loaded,
                // The resident path was requested but no daemon could serve it.
                None => load_inline()?,
            };
            let engine = ftts_core::TtsEngine::from_process_environment()
                .map_err(|error| FttsError::Generic(format!("cannot start the engine: {error}")))?;
            // The engine loop aborts on the SHARED token: one SIGINT trips it through
            // the signal bridge, and `cancel.was_tripped()` is what turns whatever
            // refusal the abort produces into the cancelled disposition below.
            let cancellation = &cancel.token;

            // In-process synthesis streams for real: the engine runs on a scoped thread with
            // a channel-backed PcmPacketSink, and THIS thread — which owns `emit`, the audio
            // sink, and the raw stream — consumes packets as they are decoded, writing PCM
            // and emitting `audio_chunk` (and throttled `frame`) events while generation is
            // still running. Backpressure is the bounded channel: a stalled consumer parks
            // the codec worker, which parks the generator — synthesis slows to the consumer's
            // pace instead of buffering unboundedly. Channel disconnect is the shutdown
            // signal in both directions: the producer dropping its senders ends the consume
            // loop, and the consumer dropping the receiver aborts the producer's next send.
            // One consumer thread serves both pipes, so a stalled EVENT reader also pauses
            // synthesis — bounded and cancel-aware, and the fail-closed consumer contract
            // (drain both streams concurrently) already forbids that consumer shape; the
            // independent-queue design belongs to the talk session, not the one-shot CLI.
            enum Live {
                Packet(Vec<f32>, usize),
                Progress(u64, Option<u64>),
            }
            struct ChannelSink(std::sync::mpsc::SyncSender<Live>);
            impl synth::PcmPacketSink for ChannelSink {
                fn deliver(&mut self, samples: &[f32], frames: usize) -> Result<(), FttsError> {
                    self.0
                        .send(Live::Packet(samples.to_vec(), frames))
                        .map_err(|_| {
                            FttsError::Generic(
                                "the live audio consumer stopped accepting packets".to_owned(),
                            )
                        })
                }
            }
            let (live_tx, live_rx) = std::sync::mpsc::sync_channel::<Live>(64);
            let produced = std::thread::scope(|scope| {
                let handle = scope.spawn(|| {
                    // The observer lives inside this closure so that EVERY sender is owned
                    // by the producer side: when synthesis returns, sink and observer drop,
                    // the channel disconnects, and the consume loop below terminates. An
                    // observer outliving the scope would hold a sender forever and deadlock
                    // the loop. Progress sends are try_send — lossy by design (progress
                    // coalesces under pressure); audio uses blocking send and never drops.
                    let progress = std::sync::Mutex::new((live_tx.clone(), None::<u64>));
                    let observer = move |event: ftts_core::SynthesisEvent| {
                        let Ok(mut guard) = progress.lock() else {
                            return;
                        };
                        match event {
                            ftts_core::SynthesisEvent::ResourceAdmission {
                                admitted: true,
                                predicted_max_frames,
                                ..
                            } => guard.1 = Some(predicted_max_frames),
                            ftts_core::SynthesisEvent::FrameProgress { frame } => {
                                let total = guard.1;
                                let _ = guard.0.try_send(Live::Progress(frame, total));
                            }
                            _ => {}
                        }
                    };
                    let mut sink = ChannelSink(live_tx);
                    synth::synthesize(
                        &loaded,
                        &engine,
                        &request,
                        &voice_conditioning,
                        seed,
                        cancellation,
                        &observer,
                        usize::from(settings.packet_frames.frames_per_packet()),
                        None,
                        Some(&mut sink),
                    )
                });

                let mut consumer_error: Option<FttsError> = None;
                let mut last_frame_event: Option<std::time::Instant> = None;
                while let Ok(message) = live_rx.recv() {
                    let step = match message {
                        Live::Packet(pcm, frames) => (|| -> Result<(), FttsError> {
                            if !live_output_began {
                                emit_stage(run, emit, "output", "begin", &mut seq)?;
                                live_output_began = true;
                            }
                            let event = audio.write_packet(
                                &pcm,
                                output.raw_audio,
                                run.run_id(),
                                u8::try_from(frames).unwrap_or(u8::MAX),
                            )?;
                            emit(&event)?;
                            if raw_stream {
                                // Latency depends on flush discipline, not on the writer's
                                // incidental buffering: one packet, one flush.
                                output.raw_audio.flush().map_err(|error| {
                                    FttsError::Generic(format!("cannot flush raw PCM: {error}"))
                                })?;
                            }
                            Ok(())
                        })(),
                        Live::Progress(frame, total) => (|| -> Result<(), FttsError> {
                            // The frozen catalogue pins `frame` as "throttled, never one
                            // per frame": at most one per second. A frame event MAY
                            // precede stage{output,begin} — frames 1..packet exist before
                            // the first packet decodes, and early progress is the point.
                            let due = last_frame_event
                                .is_none_or(|at| at.elapsed() >= std::time::Duration::from_secs(1));
                            if due {
                                last_frame_event = Some(std::time::Instant::now());
                                let mut event = run.event(robot::EventType::Frame);
                                event.insert("index".to_owned(), json!(frame));
                                event.insert(
                                    "total_estimate".to_owned(),
                                    total.map_or(Value::Null, |estimate| json!(estimate)),
                                );
                                event.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
                                emit(&Value::Object(event))?;
                            }
                            Ok(())
                        })(),
                    };
                    if let Err(error) = step {
                        // Remember the true cause, then hang up: the producer's next sink
                        // send fails, aborting synthesis promptly.
                        consumer_error = Some(error);
                        break;
                    }
                }
                drop(live_rx);
                let produced = match handle.join() {
                    Ok(result) => result,
                    Err(_) => Err(FttsError::Generic(
                        "the synthesis thread panicked".to_owned(),
                    )),
                };
                match consumer_error {
                    // The consumer's failure is the root cause; the producer's error is
                    // the induced channel abort and would bury it.
                    Some(error) => Err(error),
                    None => produced,
                }
            });
            let produced = match produced {
                Ok(produced) => produced,
                Err(error) => {
                    // A signal during synthesis outranks whatever refusal the abort
                    // produced: the run reports cancelled (exit 6) with its partial-
                    // artifact disposition, never an incidental channel error.
                    if cancel.was_tripped() {
                        return Err(cancelled_run_disposition(audio, output_plan.as_ref()));
                    }
                    return Err(error);
                }
            };
            (produced, true)
        }
    };
    let (audio_result, live_streamed) = audio_result;
    emit_stage(run, emit, "synthesis", "end", &mut seq)?;

    // --- the output tail ---------------------------------------------------------------------
    // The live path already wrote every packet and opened the `output` stage at the first
    // one; only the buffered (resident) path packetizes here, post hoc.
    if live_streamed {
        if !live_output_began {
            // Zero-packet live runs are refused before this point today, but stage events
            // come in pairs regardless of how the run evolves.
            emit_stage(run, emit, "output", "begin", &mut seq)?;
        }
    } else {
        let packet_samples = settings.packet_frames.samples_per_packet();
        let packet_frame_count = settings.packet_frames.frames_per_packet();
        emit_stage(run, emit, "output", "begin", &mut seq)?;
        for packet in audio_result.pcm.chunks(packet_samples) {
            let event =
                audio.write_packet(packet, output.raw_audio, run.run_id(), packet_frame_count)?;
            emit(&event)?;
        }
    }
    let streamed_bytes = audio.byte_offset();
    let samples = audio.finish()?;
    // `audio_bytes` must agree with `samples`, and `samples` now reports what the file really
    // holds after tail trimming. Deriving the byte count from it keeps `run_complete` internally
    // consistent instead of pairing a trimmed sample count with an untrimmed byte count. The raw
    // stream is never trimmed, so its running total is already the truth and is used as-is.
    let audio_bytes = if raw_stream {
        streamed_bytes
    } else {
        samples * u64::from(ftts_core::audio::BITS_PER_SAMPLE / 8)
    };
    if let Some(plan) = &output_plan {
        plan.finalize()?;
    }
    emit_stage(run, emit, "output", "end", &mut seq)?;

    let mut complete = run.event(robot::EventType::RunComplete);
    complete.insert("exit_code".to_owned(), json!(FttsExitCode::Success.as_u8()));
    complete.insert("elapsed_ms".to_owned(), json!(run.elapsed_ms()));
    complete.insert("frames".to_owned(), json!(audio_result.frames));
    complete.insert("audio_bytes".to_owned(), json!(audio_bytes));
    complete.insert("samples".to_owned(), json!(samples));
    complete.insert(
        "duration_ms".to_owned(),
        json!(samples * 1000 / u64::from(ftts_core::audio::SAMPLE_RATE_HZ)),
    );
    complete.insert(
        "prepared_token_count".to_owned(),
        json!(audio_result.prepared_token_count),
    );
    // The product TTFA is time-to-first-AUDIBLE-sample (leading silence must not flatter
    // the number); output that never crosses the audibility floor falls back to the raw
    // first-delivery mark rather than claiming nothing was delivered. One field, one
    // definition — the raw-vs-audible delta is test-receipt material, not event schema.
    if let Some(ttfa) = audio_result.ttfa_audible.or(audio_result.ttfa) {
        complete.insert(
            "ttfa_ms".to_owned(),
            json!(u64::try_from(ttfa.as_millis()).unwrap_or(u64::MAX)),
        );
    }
    emit(&Value::Object(complete))?;
    Ok(())
}

/// Where synthesised PCM goes, and the `audio_chunk` events that describe it.
///
/// The two destinations are mutually exclusive by contract (AGENTS.md agent ergonomics): either
/// events own stdout and audio goes to `-o PATH`, or `--stream raw` gives stdout to PCM and every
/// event goes to stderr. Raw bytes and NDJSON are never interleaved on one stream, so this type
/// owns the decision once instead of leaving it to each call site.
///
/// `audio_chunk` reports the bytes written, never the bytes themselves.
pub enum AudioSink {
    /// A WAV file. The header is finalised on [`AudioSink::finish`], so a run cut short still
    /// leaves a playable file describing the samples that landed.
    Wav(Box<ftts_core::audio::WavWriter<fs::File>>),
    /// Raw little-endian 16-bit PCM on a caller-supplied stream (`--stream raw`).
    RawPcm,
    /// `--check` and other non-synthesising paths.
    None,
}

/// Accumulating state for the `audio_chunk` event stream.
pub struct AudioOutput {
    sink: AudioSink,
    byte_offset: u64,
    samples_written: u64,
}

/// Audio container selected by the output path's extension.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OutputFormat {
    /// Written natively by the pure-Rust WAV writer.
    Wav,
    /// AAC in an MPEG-4 container, encoded by `afconvert` (macOS) or `ffmpeg`.
    M4a,
    /// MP3, encoded by `lame` or `ffmpeg`.
    Mp3,
    /// FLAC, encoded by `flac` or `ffmpeg`.
    Flac,
}

/// Where the WAV bytes land and what happens to them after synthesis.
///
/// Synthesis always writes the pure-Rust WAV stream ("self-contained" covers everything up to
/// and including that file). For a compressed extension the WAV goes to a sibling staging file
/// and is then handed to the first available *system* encoder — an optional post-step, never a
/// runtime dependency of synthesis itself. No encoder found is a refusal with the tool list,
/// not a silent format switch.
#[derive(Clone, Debug)]
struct OutputPlan {
    /// The path the user asked for.
    final_path: PathBuf,
    /// Where the WAV sink writes; equals `final_path` for `.wav`.
    wav_path: PathBuf,
    format: OutputFormat,
}

impl OutputPlan {
    fn for_path(path: &Path) -> Result<Self, FttsError> {
        let extension = path
            .extension()
            .and_then(|extension| extension.to_str())
            .map(str::to_ascii_lowercase);
        let format = match extension.as_deref() {
            Some("wav") | None => OutputFormat::Wav,
            Some("m4a" | "aac") => OutputFormat::M4a,
            Some("mp3") => OutputFormat::Mp3,
            Some("flac") => OutputFormat::Flac,
            Some(other) => {
                return Err(FttsError::Usage(format!(
                    "unsupported output extension `.{other}`; use .wav (native), .m4a, .mp3, or \
                     .flac (system encoder)"
                )));
            }
        };
        let wav_path = if format == OutputFormat::Wav {
            path.to_path_buf()
        } else {
            let mut staging = path.as_os_str().to_owned();
            staging.push(".ftts-staging.wav");
            PathBuf::from(staging)
        };
        Ok(Self {
            final_path: path.to_path_buf(),
            wav_path,
            format,
        })
    }

    /// Encodes the staged WAV into the requested container and removes the staging file.
    fn finalize(&self) -> Result<(), FttsError> {
        if self.format == OutputFormat::Wav {
            return Ok(());
        }
        let wav = self.wav_path.as_os_str();
        let target = self.final_path.as_os_str();
        // (encoder, arguments) attempts in preference order; the first tool present decides.
        let attempts: &[(&str, Vec<&std::ffi::OsStr>)] = &match self.format {
            OutputFormat::M4a => [
                (
                    "afconvert",
                    vec![
                        "-f".as_ref(),
                        "m4af".as_ref(),
                        "-d".as_ref(),
                        "aac".as_ref(),
                        wav,
                        target,
                    ],
                ),
                (
                    "ffmpeg",
                    vec![
                        "-y".as_ref(),
                        "-loglevel".as_ref(),
                        "error".as_ref(),
                        "-i".as_ref(),
                        wav,
                        "-c:a".as_ref(),
                        "aac".as_ref(),
                        target,
                    ],
                ),
            ],
            OutputFormat::Mp3 => [
                (
                    "lame",
                    vec!["--quiet".as_ref(), "-V2".as_ref(), wav, target],
                ),
                (
                    "ffmpeg",
                    vec![
                        "-y".as_ref(),
                        "-loglevel".as_ref(),
                        "error".as_ref(),
                        "-i".as_ref(),
                        wav,
                        "-codec:a".as_ref(),
                        "libmp3lame".as_ref(),
                        "-q:a".as_ref(),
                        "2".as_ref(),
                        target,
                    ],
                ),
            ],
            OutputFormat::Flac => [
                (
                    "flac",
                    vec![
                        "--totally-silent".as_ref(),
                        "-f".as_ref(),
                        "-o".as_ref(),
                        target,
                        wav,
                    ],
                ),
                (
                    "ffmpeg",
                    vec![
                        "-y".as_ref(),
                        "-loglevel".as_ref(),
                        "error".as_ref(),
                        "-i".as_ref(),
                        wav,
                        "-c:a".as_ref(),
                        "flac".as_ref(),
                        target,
                    ],
                ),
            ],
            OutputFormat::Wav => unreachable!("handled above"),
        };

        let mut tried = Vec::new();
        for (tool, arguments) in attempts {
            // `tool` is always one of the fixed string literals in `attempts` above — a
            // compile-time allowlist. User-controlled data (the two paths) enters only as argv.
            match std::process::Command::new(tool).args(arguments).status() {
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                    tried.push(*tool);
                }
                Err(error) => {
                    return Err(FttsError::Generic(format!(
                        "audio encoder `{tool}` could not run: {error}; the synthesized WAV is \
                         preserved at {}",
                        self.wav_path.display()
                    )));
                }
                Ok(status) if status.success() => {
                    // The staging WAV is an intermediate this run created; the requested artifact
                    // now exists, so the intermediate is removed.
                    let _ = fs::remove_file(&self.wav_path);
                    return Ok(());
                }
                Ok(status) => {
                    return Err(FttsError::Generic(format!(
                        "audio encoder `{tool}` exited with {status}; the synthesized WAV is \
                         preserved at {}",
                        self.wav_path.display()
                    )));
                }
            }
        }
        Err(FttsError::Generic(format!(
            "no system audio encoder found for {} (tried: {}); install one or use a .wav output. \
             The synthesized WAV is preserved at {}",
            self.final_path.display(),
            tried.join(", "),
            self.wav_path.display()
        )))
    }
}

impl AudioOutput {
    /// Open a WAV file sink.
    ///
    /// # Errors
    ///
    /// If the file cannot be created or the provisional header cannot be written.
    pub fn wav(path: &Path) -> Result<Self, FttsError> {
        let file = fs::File::create(path).map_err(|error| {
            FttsError::Generic(format!(
                "cannot create audio output {}: {error}",
                path.display()
            ))
        })?;
        // File output trims the model's end-of-utterance noise burst (DISC-005). The raw PCM
        // stream deliberately does not: trimming needs the last quarter second held back, and
        // `--stream raw` exists for latency. `FTTS_TRIM_TAIL=0` restores the untrimmed bytes.
        let trim_tail = !matches!(
            std::env::var("FTTS_TRIM_TAIL").ok().as_deref(),
            Some("0") | Some("false")
        );
        let writer = if trim_tail {
            ftts_core::audio::WavWriter::new_trimming_tail(file, ftts_core::audio::SAMPLE_RATE_HZ)
        } else {
            ftts_core::audio::WavWriter::new(file, ftts_core::audio::SAMPLE_RATE_HZ)
        }
        .map_err(|error| {
            FttsError::Generic(format!(
                "cannot write WAV header to {}: {error}",
                path.display()
            ))
        })?;
        Ok(Self {
            sink: AudioSink::Wav(Box::new(writer)),
            byte_offset: 0,
            samples_written: 0,
        })
    }

    /// A raw-PCM sink; the caller supplies the stream on each write.
    #[must_use]
    pub const fn raw() -> Self {
        Self {
            sink: AudioSink::RawPcm,
            byte_offset: 0,
            samples_written: 0,
        }
    }

    /// A sink that discards audio, for paths that synthesise nothing.
    #[must_use]
    pub const fn none() -> Self {
        Self {
            sink: AudioSink::None,
            byte_offset: 0,
            samples_written: 0,
        }
    }

    /// The stable `sink` string reported in `audio_chunk`.
    #[must_use]
    pub const fn sink_name(&self) -> &'static str {
        match self.sink {
            AudioSink::Wav(_) => "file",
            AudioSink::RawPcm => "stdout",
            AudioSink::None => "none",
        }
    }

    /// Bytes of audio emitted so far.
    #[must_use]
    pub const fn byte_offset(&self) -> u64 {
        self.byte_offset
    }

    /// Write one packet and return its `audio_chunk` event.
    ///
    /// `raw` is where PCM goes under `--stream raw`; it is ignored by the other sinks. The event's
    /// `byte_offset` is the offset *before* this packet, so a consumer can seek with it — on the
    /// RAW stream. On a trimmed file sink the chunk events describe samples HANDED to the writer,
    /// up to a quarter second of which the tail trim may withhold, so the final chunk's advertised
    /// range can exceed the file; `run_complete.audio_bytes` is the authoritative file size.
    ///
    /// `duration_ms` is derived from the sample count rather than taken from a caller-supplied
    /// clock: it describes how much *audio* this packet holds, which is a property of the samples,
    /// not of how long the run took to produce them.
    ///
    /// # Errors
    ///
    /// If the sink rejects the write.
    pub fn write_packet(
        &mut self,
        pcm: &[f32],
        raw: &mut dyn Write,
        run_id: &str,
        frame_count: u8,
    ) -> Result<Value, FttsError> {
        let offset_before = self.byte_offset;
        let bytes = (pcm.len() * 2) as u64;

        match &mut self.sink {
            AudioSink::Wav(writer) => writer.write_samples(pcm).map_err(|error| {
                FttsError::Generic(format!("cannot write audio samples: {error}"))
            })?,
            AudioSink::RawPcm => {
                let mut buffer = Vec::with_capacity(pcm.len() * 2);
                for sample in pcm {
                    buffer
                        .extend_from_slice(&ftts_core::audio::sample_to_i16(*sample).to_le_bytes());
                }
                raw.write_all(&buffer).map_err(|error| {
                    FttsError::Generic(format!("cannot write raw PCM: {error}"))
                })?;
            }
            AudioSink::None => {}
        }

        self.byte_offset += bytes;
        self.samples_written += pcm.len() as u64;

        let mut event = robot::EventType::AudioChunk.event();
        event.insert("run_id".to_owned(), json!(run_id));
        event.insert("byte_offset".to_owned(), json!(offset_before));
        event.insert("bytes".to_owned(), json!(bytes));
        event.insert(
            "duration_ms".to_owned(),
            json!((pcm.len() as u64) * 1000 / u64::from(ftts_core::audio::SAMPLE_RATE_HZ.max(1))),
        );
        event.insert("packet_frames".to_owned(), json!(frame_count.to_string()));
        event.insert("sink".to_owned(), json!(self.sink_name()));
        Ok(Value::Object(event))
    }

    /// Finalise the sink, patching the WAV header to the real length.
    ///
    /// # Errors
    ///
    /// If the header cannot be rewritten.
    pub fn finish(self) -> Result<u64, FttsError> {
        let mut samples = self.samples_written;
        if let AudioSink::Wav(writer) = self.sink {
            // Report what the FILE contains, not what was handed to the sink. Tail trimming makes
            // those differ, and `run_complete.samples` claiming audio the file does not hold is a
            // false number in a machine-readable stream: a consumer that trusts it computes the
            // wrong duration. `finish_reporting` exists precisely to close that gap.
            let (_, written) = writer.finish_reporting().map_err(|error| {
                FttsError::Generic(format!("cannot finalize the WAV header: {error}"))
            })?;
            samples = written as u64;
        }
        Ok(samples)
    }
}

fn read_text(args: &SayArgs, stdin: &mut dyn Read) -> Result<String, FttsError> {
    let text = match (&args.text, &args.file) {
        (Some(text), None) if text == "-" => read_utf8(stdin, "stdin")?,
        (Some(text), None) => text.clone(),
        (None, Some(path)) if path == Path::new("-") => read_utf8(stdin, "stdin")?,
        (None, Some(path)) => fs::read_to_string(path).map_err(|error| {
            FttsError::Input(format!(
                "cannot read text file {}: {error}; use `ftts say --file PATH --check --model PATH`",
                path.display()
            ))
        })?,
        (None, None) => {
            return Err(FttsError::Usage(
                "missing text; use `ftts say TEXT`, `ftts say --file PATH`, or `ftts say -`".to_owned(),
            ));
        }
        (Some(_), Some(_)) => unreachable!("clap enforces the conflict"),
    };

    if text.trim().is_empty() {
        return Err(FttsError::Input(
            "text is empty; provide non-whitespace UTF-8 text to `ftts say`".to_owned(),
        ));
    }
    Ok(text)
}

fn read_utf8(reader: &mut dyn Read, source: &str) -> Result<String, FttsError> {
    let mut bytes = Vec::new();
    reader.read_to_end(&mut bytes).map_err(|error| {
        FttsError::Input(format!(
            "cannot read {source}: {error}; retry with readable UTF-8 input"
        ))
    })?;
    String::from_utf8(bytes).map_err(|error| {
        FttsError::Input(format!(
            "{source} is not valid UTF-8: {error}; transcode it before `ftts say`"
        ))
    })
}

fn resolve_model(explicit: Option<&Path>, environment: &Environment) -> Result<String, FttsError> {
    resolve_model_from(
        explicit,
        &model_search_paths(environment),
        default_pull_model_dir(environment).as_deref(),
    )
}

/// The full resolution order — `--model`, then the searched artifact paths (`FTTS_MODEL_DIR`,
/// then the home cache), then the `ftts pull` destination directory, accepted only when it holds
/// a complete bundle. Takes its inputs as data so tests can exercise the order against temp
/// directories without mutating process environment.
fn resolve_model_from(
    explicit: Option<&Path>,
    searched: &[PathBuf],
    pull_dir: Option<&Path>,
) -> Result<String, FttsError> {
    if let Some(path) = explicit {
        // A pinned checkpoint is a *directory* of five files, so `--model DIR` is the natural
        // thing to type and is accepted as such. `.fttsq` is a single file, and both forms reach
        // the same resolver rather than one being a special case documented somewhere else.
        if path.is_dir() {
            return Ok(path.display().to_string());
        }
        return resolve_existing_file(path, "model artifact")
            .map(|path| path.display().to_string());
    }

    if let Some(path) = searched.iter().find(|path| path.is_file()) {
        return Ok(path.display().to_string());
    }
    // A directory named by FTTS_MODEL_DIR may itself BE the model: a pinned checkpoint snapshot
    // (`model.safetensors` + configs) or a directory holding the canonical artifact. `--model DIR`
    // already accepts that shape; the search path accepting it too is what lets a bare
    // `ftts say "text" out.wav` work after one exported variable.
    if let Some(directory) = searched
        .iter()
        .filter_map(|path| path.parent())
        .find(|directory| directory.join("model.safetensors").is_file())
    {
        return Ok(directory.display().to_string());
    }

    // The `ftts pull` destination is a *bundle* directory (checkpoints + tokenizer files), not a
    // single artifact, so it counts only when the whole bundle is present — a half-finished pull
    // resolving here would fail later with a less actionable error than the one below.
    if let Some(directory) = pull_dir
        && directory.is_dir()
        && synth::ModelBundle::resolve(directory).is_ok()
    {
        return Ok(directory.display().to_string());
    }

    let searched = searched
        .iter()
        .map(|path| path.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    Err(FttsError::ModelNotFound(format!(
        "no model artifact was found; searched: [{searched}]; run `ftts pull` to fetch the model \
         (~2.0 GB), or pass --model PATH or set FTTS_MODEL_DIR"
    )))
}

fn resolve_optional_file(path: Option<&Path>, label: &str) -> Result<Option<String>, FttsError> {
    path.map(|path| resolve_existing_file(path, label).map(|path| path.display().to_string()))
        .transpose()
}

fn resolve_requested_voice(
    explicit: Option<&Path>,
    environment: &Environment,
) -> Result<Option<String>, FttsError> {
    if let Some(path) = explicit {
        // A bare preset name selects a built-in voice — but only when no such file exists, so
        // `--voice aria` in a directory containing a file named `aria` still means the file.
        if !path.exists()
            && let Some(name) = path.to_str()
            && let Some(materialized) = materialize_preset_voice(name)
        {
            return materialized.map(|path| Some(path.display().to_string()));
        }
        // A failed bare word was probably a preset-name attempt: name the built-ins in the
        // refusal so the user does not have to hunt the docs for the list.
        let looks_like_name =
            path.extension().is_none() && path.components().count() == 1 && !path.exists();
        return resolve_optional_file(Some(path), "voice source").map_err(|error| {
            if looks_like_name {
                FttsError::Input(format!(
                    "{error}; built-in voice names are: {}",
                    preset_names()
                ))
            } else {
                error
            }
        });
    }
    environment
        .value("FTTS_DEFAULT_VOICE")
        .map(Path::new)
        .map(|path| resolve_existing_file(path, "FTTS_DEFAULT_VOICE"))
        .transpose()
        .map(|path| path.map(|path| path.display().to_string()))
}

fn run_enroll(
    args: &EnrollArgs,
    environment: &Environment,
    stdin: &mut dyn Read,
    stdout: &mut dyn Write,
    capabilities: IoCapabilities,
) -> Result<(), FttsError> {
    let started = std::time::Instant::now();
    let model = resolve_model(args.model.as_deref(), environment)?;
    let bundle = synth::ModelBundle::resolve(Path::new(&model))?;
    let output = match (&args.output, args.default) {
        (Some(path), false) => path.clone(),
        (None, true) => bundle.root.join("default.ftvoice"),
        (None, false) => {
            return Err(FttsError::Usage(
                "`ftts enroll` needs -o PATH or --default; enrollment never overwrites a voice source"
                    .to_owned(),
            ));
        }
        (Some(_), true) => unreachable!("clap enforces the conflict"),
    };

    // Transcript source: inline text or a UTF-8 file. Read BEFORE any heavy work so a typo in
    // the path fails fast rather than after a full decode + embed.
    let transcript: Option<String> = match (&args.transcript_text, &args.transcript_file) {
        (Some(text), _) => Some(text.clone()),
        (None, Some(path)) => Some(std::fs::read_to_string(path).map_err(|error| {
            FttsError::Input(format!(
                "cannot read transcript {}: {error}",
                path.display()
            ))
        })?),
        (None, None) => None,
    };
    let resolved = resolve_enroll_mode(args.mode, transcript.as_deref());

    let mut denoise_report = None;
    let mut dereverb_report = None;
    let denoise = if args.no_denoise {
        false
    } else {
        args.denoise || bundle.root.join(synth::DENOISE_ARTIFACT_RELPATH).is_file()
    };

    // Decode once. Diagnostics state what was measured BEFORE the user hears any defect in
    // their clone; the usability gate refuses structurally unusable input (no speech at all)
    // with exit 8 unless --force says otherwise.
    let raw_pcm = synth::decode_reference_audio_any(Path::new(&args.reference_audio))?;
    let dx = diagnostics::diagnose(&raw_pcm, synth::reverb_time_s(&raw_pcm).map(f64::from));
    for warning in dx.warnings() {
        style::warn(stdout, &warning)
            .map_err(|error| FttsError::Generic(format!("cannot write warning: {error}")))?;
    }
    if let Some(reason) = unusable_reference_reason(&dx, raw_pcm.len()) {
        if args.force {
            style::warn(
                stdout,
                &format!("forcing enrollment of unusable reference: {reason}"),
            )
            .map_err(|error| FttsError::Generic(format!("cannot write warning: {error}")))?;
        } else {
            return Err(FttsError::EnrollmentQualityRefusal(format!(
                "{reason}; pass --force to enroll it anyway"
            )));
        }
    }

    let source_bytes = std::fs::read(&args.reference_audio).map_err(|error| {
        FttsError::Input(format!(
            "cannot read reference {}: {error}",
            args.reference_audio.display()
        ))
    })?;
    let (speaker, cleaned_pcm) = synth::enroll_outputs_from_reference_pcm(
        &bundle,
        raw_pcm,
        synth::ReferenceCleanup {
            denoise: denoise.then_some(&mut denoise_report),
            dereverb: args.dereverb.then_some(&mut dereverb_report),
        },
    )?;
    if let Some(report) = dereverb_report {
        style::ok(
            stdout,
            &format!(
                "dereverberated reference {}",
                style::detail(&format!(
                    "RT60-equivalent {:.2}{:.2} s",
                    report.before_rt60_s, report.after_rt60_s
                )),
            ),
        )
        .map_err(|error| FttsError::Generic(format!("cannot write dereverb report: {error}")))?;
    }
    if let Some(report) = denoise_report {
        let moved = report.before_dbfs - report.after_dbfs;
        style::ok(
            stdout,
            &format!(
                "denoised reference {}",
                style::detail(&format!(
                    "pause floor {:.1}{:.1} dBFS ({moved:.1} dB quieter)",
                    report.before_dbfs, report.after_dbfs
                )),
            ),
        )
        .map_err(|error| FttsError::Generic(format!("cannot write denoise report: {error}")))?;
    }

    // The fallback notice is LOUD on purpose: continuation-style cloners reproduce
    // prompt-recording defects, and a quiet downgrade is how users end up with a worse
    // clone than they thought they enrolled.
    if let ResolvedEnrollMode::Quick { reason } = &resolved {
        style::warn(
            stdout,
            &format!("QUICK mode — x-vector only, no ICL conditioning ({reason})"),
        )
        .map_err(|error| FttsError::Generic(format!("cannot write warning: {error}")))?;
    }

    // Consent: affirmed via flag or interactively; either way the ANSWER is what the pack
    // records. A silent default would make every pack lie by omission.
    let consent_method = if args.consent_attest {
        ftts_artifacts::voice::ConsentMethod::Flag
    } else {
        ftts_artifacts::voice::ConsentMethod::Interactive
    };
    let consent_attested = args.consent_attest
        || style::confirm(
            stdin,
            stdout,
            "Do you have the right to clone this voice? (recorded in the pack)",
            capabilities.can_confirm,
        )
        .map_err(|error| FttsError::Generic(format!("cannot read a reply: {error}")))?
        .unwrap_or_default();
    if !consent_attested {
        style::warn(stdout, "pack will record consent: NOT ATTESTED")
            .map_err(|error| FttsError::Generic(format!("cannot write warning: {error}")))?;
    }

    // QUALITY adds the ICL identity block: codec tokens cut from the SAME cleaned audio the
    // embedding came from, so one pack conditions one voice, not two.
    let (profile, codec_codes, pack_transcript) = match resolved {
        ResolvedEnrollMode::Quality => {
            let encoder = ftts_model_qwen::speech_encoder::SpeechEncoder::load(
                &bundle.root.join("speech_tokenizer/model.safetensors"),
            )
            .map_err(|error| {
                FttsError::Input(format!(
                    "quality-mode enrollment needs the codec encoder \
                     (speech_tokenizer/model.safetensors): {error}"
                ))
            })?;
            let codes = encoder.encode_24khz_pcm(&cleaned_pcm).map_err(|error| {
                FttsError::Input(format!("cannot encode reference to codec tokens: {error}"))
            })?;
            (
                ftts_artifacts::voice::VoiceProfile::Portable,
                Some(codes),
                transcript,
            )
        }
        ResolvedEnrollMode::Quick { .. } => {
            (ftts_artifacts::voice::VoiceProfile::Private, None, None)
        }
    };

    let speech_regions = crate::diagnostics::voice_activity_regions(&cleaned_pcm)
        .into_iter()
        .map(|(start, end)| (start as u64, end as u64))
        .collect();
    let pack = assemble_enrollment_pack(AssemblePackInput {
        profile,
        consent: ftts_artifacts::voice::ConsentAttestation {
            attested: consent_attested,
            method: consent_method,
        },
        transcript: pack_transcript,
        speech_regions,
        diagnostics: mirror_diagnostics(&dx),
        preprocessing: ftts_artifacts::voice::PreprocessingRecipe {
            target_sample_rate_hz: 24_000,
            resampler: "lanczos6".to_owned(),
            denoise: denoise_report.map(|report| ftts_artifacts::voice::CleanupRecord {
                engine: if bundle.root.join(synth::DENOISE_ARTIFACT_RELPATH).is_file()
                    && !args.no_denoise
                {
                    "fastenhancer-s".to_owned()
                } else {
                    "omlsa".to_owned()
                },
                before: f64::from(report.before_dbfs),
                after: f64::from(report.after_dbfs),
            }),
            dereverb: dereverb_report.map(|report| ftts_artifacts::voice::CleanupRecord {
                engine: "spectral-dereverb".to_owned(),
                before: f64::from(report.before_rt60_s),
                after: f64::from(report.after_rt60_s),
            }),
        },
        provenance: ftts_artifacts::voice::Provenance {
            engine: format!("ftts {}", env!("CARGO_PKG_VERSION")),
            source_audio_sha256: Some(ftts_artifacts::sha256::hex_digest(
                &ftts_artifacts::sha256::digest(&source_bytes),
            )),
            source_frames: None,
        },
        embedding: speaker,
        codec_codes,
    });
    let bytes = ftts_artifacts::voice::serialize_voice_pack(&pack)
        .map_err(|error| FttsError::ArtifactFormat(error.to_string()))?;

    // Occupied destination asks rather than refuses — but only when somebody is there to ask
    // (same contract as the raw-vector writer always had).
    let backup = if output.exists() {
        let consented = if args.overwrite {
            true
        } else {
            style::warn(
                stdout,
                &format!(
                    "{} already holds an enrolled voice",
                    style::emphasis(&output.display().to_string())
                ),
            )
            .map_err(|error| {
                FttsError::Generic(format!("cannot write overwrite notice: {error}"))
            })?;
            match style::confirm(stdin, stdout, "Replace it?", capabilities.can_confirm)
                .map_err(|error| FttsError::Generic(format!("cannot read a reply: {error}")))?
            {
                Some(reply) => reply,
                None => {
                    return Err(FttsError::Input(format!(
                        "{} already exists; pass --overwrite to replace it (the displaced voice is \
                         kept as {}.bak)",
                        output.display(),
                        output.display()
                    )));
                }
            }
        };
        if !consented {
            style::info(stdout, "left the existing voice in place")
                .map_err(|error| FttsError::Generic(format!("cannot write result: {error}")))?;
            return Ok(());
        }
        Some(replace_voice_pack(&output, &bytes)?)
    } else {
        write_voice_pack_new(&output, &bytes)?;
        None
    };

    let elapsed_ms = started.elapsed().as_millis();
    let detail = match &pack.codec_codes {
        Some(codes) => format!(
            "{} · {} · quality · {} codec frames · consent {} · {elapsed_ms} ms",
            pack.profile.as_str(),
            style::detail("ICL"),
            codes.len(),
            if pack.consent.attested {
                "attested"
            } else {
                "NOT ATTESTED"
            },
        ),
        None => format!(
            "{} · quick · x-vector only · consent {} · {elapsed_ms} ms",
            pack.profile.as_str(),
            if pack.consent.attested {
                "attested"
            } else {
                "NOT ATTESTED"
            },
        ),
    };
    style::ok(
        stdout,
        &format!(
            "enrolled {}{} {}",
            style::emphasis(&args.reference_audio.display().to_string()),
            style::emphasis(&output.display().to_string()),
            style::detail(&detail),
        ),
    )
    .map_err(|error| FttsError::Generic(format!("cannot write enrollment result: {error}")))?;
    if let Some(backup) = backup {
        style::info(
            stdout,
            &format!(
                "previous voice kept at {}",
                style::emphasis(&backup.display().to_string())
            ),
        )
        .map_err(|error| FttsError::Generic(format!("cannot write backup notice: {error}")))?;
    }
    if args.default {
        style::info(
            stdout,
            &format!(
                "{} will use it when --voice is absent",
                style::emphasis("ftts say")
            ),
        )
        .map_err(|error| FttsError::Generic(format!("cannot write result: {error}")))?;
    }
    Ok(())
}

/// Structurally unusable references get exit 8, not a warning: there is no voice in this
/// recording to enroll, and everything downstream of a silent pack is noise. Threshold-based
/// quality refusals stay reserved until owner-validated listening thresholds exist.
fn unusable_reference_reason(
    dx: &crate::diagnostics::AudioDiagnostics,
    pcm_len: usize,
) -> Option<String> {
    if pcm_len == 0 {
        return Some("reference decoded to zero samples".to_owned());
    }
    if dx.voice_activity_ratio <= 0.0 {
        return Some("no speech detected anywhere in the reference".to_owned());
    }
    None
}

fn mirror_diagnostics(
    dx: &crate::diagnostics::AudioDiagnostics,
) -> ftts_artifacts::voice::EnrollmentDiagnostics {
    ftts_artifacts::voice::EnrollmentDiagnostics {
        clipping_fraction: dx.clipping_fraction,
        longest_clip_run: dx.longest_clip_run,
        intersample_overshoot_db: dx.intersample_overshoot_db,
        snr_estimate_db: dx.snr_estimate_db,
        pause_floor_dbfs: dx.pause_floor_dbfs,
        reverb_time_s: dx.reverb_time_s,
        music_bed_likelihood: dx.music_bed_likelihood,
        stationarity_drift: dx.stationarity_drift,
        loudness_rms_dbfs: dx.loudness_rms_dbfs,
        voice_activity_ratio: dx.voice_activity_ratio,
    }
}

/// Everything `run_enroll` hands to pack construction; a named struct keeps the constructor
/// callable from tests without audio fixtures or a model bundle.
struct AssemblePackInput {
    profile: ftts_artifacts::voice::VoiceProfile,
    consent: ftts_artifacts::voice::ConsentAttestation,
    transcript: Option<String>,
    speech_regions: Vec<(u64, u64)>,
    diagnostics: ftts_artifacts::voice::EnrollmentDiagnostics,
    preprocessing: ftts_artifacts::voice::PreprocessingRecipe,
    provenance: ftts_artifacts::voice::Provenance,
    embedding: Vec<f32>,
    codec_codes: Option<Vec<u32>>,
}

fn assemble_enrollment_pack(input: AssemblePackInput) -> ftts_artifacts::voice::VoicePack {
    ftts_artifacts::voice::VoicePack {
        profile: input.profile,
        consent: input.consent,
        language: None,
        transcript: input.transcript,
        speech_regions: input.speech_regions,
        diagnostics: Some(input.diagnostics),
        preprocessing: Some(input.preprocessing),
        provenance: input.provenance,
        embedding: input.embedding,
        codec_codes: input.codec_codes,
        reference_audio: None,
        section_digests: Default::default(),
    }
}

/// Writes a `.ftvoice` pack without replacing an existing file (staged temp + rename, so a
/// crash cannot leave a half-written voice).
fn write_voice_pack_new(path: &Path, bytes: &[u8]) -> Result<(), FttsError> {
    let staged = path.with_extension("ftvoice.partial");
    std::fs::write(&staged, bytes).map_err(|error| {
        FttsError::Input(format!(
            "cannot stage enrolled voice {}: {error}",
            staged.display()
        ))
    })?;
    std::fs::rename(&staged, path).map_err(|error| {
        FttsError::Input(format!(
            "cannot finalize enrolled voice {}: {error}",
            path.display()
        ))
    })
}

/// Replaces an existing `.ftvoice`, keeping the displaced pack alongside it as `<path>.bak`.
fn replace_voice_pack(path: &Path, bytes: &[u8]) -> Result<PathBuf, FttsError> {
    let mut backup_name = path.as_os_str().to_owned();
    backup_name.push(".bak");
    let backup = PathBuf::from(backup_name);
    std::fs::copy(path, &backup).map_err(|error| {
        FttsError::Input(format!(
            "cannot back up displaced voice {}: {error}",
            path.display()
        ))
    })?;
    write_voice_pack_new(path, bytes)?;
    Ok(backup)
}

/// One downloadable model file from the embedded manifest.
#[derive(Clone, Debug)]
struct ModelManifestFile {
    /// The bare release-asset name on the GitHub release.
    asset: String,
    /// Relative path under the model directory the asset lands at.
    dest: String,
    /// Pinned lowercase-hex SHA-256 the downloaded bytes must carry.
    sha256: String,
    /// Pinned exact size, checked before the (much more expensive) digest.
    bytes: u64,
}

/// The embedded `ftts pull` download contract: release coordinates plus per-file pins.
#[derive(Clone, Debug)]
struct ModelManifest {
    model_id: String,
    release_tag: String,
    repo: String,
    files: Vec<ModelManifestFile>,
}

impl ModelManifest {
    /// The compiled-in manifest. Parsing it can only fail if the checked-in copy is malformed,
    /// which the unit tests catch before a binary ships.
    fn embedded() -> Result<Self, FttsError> {
        Self::parse(PINNED_MODEL_MANIFEST)
    }

    /// Parses and validates manifest text; every refusal names the offending field, because a
    /// manifest bug otherwise surfaces as a mystery mid-download.
    fn parse(text: &str) -> Result<Self, FttsError> {
        let value: Value = serde_json::from_str(text).map_err(|error| {
            FttsError::ArtifactFormat(format!("model manifest is not valid JSON: {error}"))
        })?;
        if value["schema_version"].as_u64() != Some(1) {
            return Err(FttsError::ArtifactFormat(format!(
                "model manifest schema_version {} is not the supported 1",
                value["schema_version"]
            )));
        }
        let model_id = manifest_string(&value, "model_id")?;
        let release_tag = manifest_string(&value, "release_tag")?;
        let repo = manifest_string(&value, "repo")?;
        let files = value["files"]
            .as_array()
            .filter(|files| !files.is_empty())
            .ok_or_else(|| {
                FttsError::ArtifactFormat("model manifest needs a non-empty files array".to_owned())
            })?
            .iter()
            .map(parse_manifest_file)
            .collect::<Result<Vec<_>, _>>()?;
        Ok(Self {
            model_id,
            release_tag,
            repo,
            files,
        })
    }

    /// The ordered mirror URLs for one file; the only endpoints `ftts pull` ever contacts.
    ///
    /// Hugging Face first: the GitHub release-asset limiter 503'd real users' pulls under
    /// chunked load (2026-08-12) while the same bytes served fine from the HF model repo, and
    /// every asset there carries the release-asset name byte for byte. GitHub stays as the
    /// fallback so either host failing degrades to a slower pull instead of a dead one; the
    /// digest verification after download is what actually decides acceptance, either way.
    fn download_urls(&self, file: &ModelManifestFile) -> [String; 2] {
        [
            format!(
                "https://huggingface.co/Dicklesworthstone/franken-tts-qwen3-tts-12hz-0.6b-base/resolve/main/{}",
                file.asset
            ),
            format!(
                "https://github.com/{}/releases/download/{}/{}",
                self.repo, self.release_tag, file.asset
            ),
        ]
    }

    fn total_bytes(&self) -> u64 {
        self.files
            .iter()
            .fold(0, |sum, file| sum.saturating_add(file.bytes))
    }
}

fn manifest_string(value: &Value, field: &str) -> Result<String, FttsError> {
    value[field]
        .as_str()
        .filter(|text| !text.is_empty())
        .map(str::to_owned)
        .ok_or_else(|| {
            FttsError::ArtifactFormat(format!(
                "model manifest field {field} must be a non-empty string"
            ))
        })
}

fn parse_manifest_file(value: &Value) -> Result<ModelManifestFile, FttsError> {
    let asset = manifest_string(value, "asset")?;
    if asset.contains('/') || asset.contains('\\') {
        return Err(FttsError::ArtifactFormat(format!(
            "manifest asset {asset:?} must be a bare release-asset name"
        )));
    }
    let dest = manifest_string(value, "dest")?;
    validate_manifest_dest(&dest)?;
    let sha256 = manifest_string(value, "sha256")?;
    if !is_sha256_hex(&sha256) {
        return Err(FttsError::ArtifactFormat(format!(
            "manifest sha256 for {asset} must be 64 lowercase hex characters"
        )));
    }
    let bytes = value["bytes"]
        .as_u64()
        .filter(|bytes| *bytes > 0)
        .ok_or_else(|| {
            FttsError::ArtifactFormat(format!(
                "manifest bytes for {asset} must be a positive integer"
            ))
        })?;
    Ok(ModelManifestFile {
        asset,
        dest,
        sha256,
        bytes,
    })
}

/// A manifest `dest` is joined under the model directory, so it must not be able to escape it:
/// no absolute paths, no `..`, no `.`, no backslash separators.
fn validate_manifest_dest(dest: &str) -> Result<(), FttsError> {
    let path = Path::new(dest);
    let traversal_free = path
        .components()
        .all(|component| matches!(component, std::path::Component::Normal(_)));
    if path.is_absolute() || dest.contains('\\') || !traversal_free {
        return Err(FttsError::ArtifactFormat(format!(
            "manifest dest {dest:?} must be a relative path with no traversal; it is joined under the model directory"
        )));
    }
    Ok(())
}

fn is_sha256_hex(text: &str) -> bool {
    text.len() == 64
        && text
            .bytes()
            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
}

/// The directory `ftts pull` fills when `--model` is absent, and the last resort model resolution
/// falls back to: the first `FTTS_MODEL_DIR` entry when set, else `$HOME/.cache/franken_tts/model`.
fn default_pull_model_dir(environment: &Environment) -> Option<PathBuf> {
    if let Some(first) = environment
        .value("FTTS_MODEL_DIR")
        .and_then(|dirs| std::env::split_paths(dirs).next())
        .filter(|path| !path.as_os_str().is_empty())
    {
        return Some(first);
    }
    std::env::var_os("HOME").map(|home| PathBuf::from(home).join(DEFAULT_MODEL_CACHE_SUBDIR))
}

/// Skip-versus-download for one manifest file, factored out so it is testable without a network.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum PullDecision {
    /// The destination already carries the pinned size AND the pinned digest.
    Skip,
    /// Absent, wrong-sized, wrong-hashed, or `--force`.
    Download,
}

/// `Skip` requires both pins to hold: size alone accepts a same-length corruption, and hashing
/// alone would digest gigabytes a length check could reject for free (which is why the cheap check
/// runs first). Any mismatch re-downloads rather than erroring — repairing a bad file is exactly
/// what `pull` is for.
fn pull_decision(dest: &Path, file: &ModelManifestFile, force: bool) -> PullDecision {
    if force {
        return PullDecision::Download;
    }
    let Ok(metadata) = fs::metadata(dest) else {
        return PullDecision::Download;
    };
    if !metadata.is_file() || metadata.len() != file.bytes {
        return PullDecision::Download;
    }
    match ftts_artifacts::sha256::hex_digest_file(dest) {
        Ok(digest) if digest == file.sha256 => PullDecision::Skip,
        _ => PullDecision::Download,
    }
}

/// Downloads `url` to `staging` with the system `curl`.
///
/// Shelling out is deliberate: inference never touches the network, so the binary links no HTTP
/// stack. Only `pull` needs one, and `curl` is the same system-tool seam the audio encoders and
/// decoders already use.
fn download_with_curl(url: &str, staging: &Path, pinned_bytes: u64) -> Result<(), FttsError> {
    // Hardening beyond the happy path: HTTPS only through every redirect (a release URL should
    // never bounce through http), a connect timeout and a stall detector instead of hanging a
    // silent `-sS` transfer forever, and the pinned size as a hard transfer cap so a
    // misbehaving endpoint cannot fill the disk before the post-download size check runs.
    let outcome = std::process::Command::new("curl")
        .args([
            "-L",
            "--fail",
            "--retry",
            "3",
            "-sS",
            "--proto",
            "=https",
            "--proto-redir",
            "=https",
            "--connect-timeout",
            "30",
            "--speed-limit",
            "1024",
            "--speed-time",
            "60",
            "--max-filesize",
        ])
        .arg(pinned_bytes.to_string())
        .arg("-o")
        .arg(staging)
        .arg(url)
        .status();
    match outcome {
        Err(error) if error.kind() == io::ErrorKind::NotFound => Err(FttsError::Generic(
            "`ftts pull` downloads with the system `curl`, which was not found on PATH; \
             install curl and retry, or download the release assets by hand"
                .to_owned(),
        )),
        Err(error) => Err(FttsError::Generic(format!("cannot run curl: {error}"))),
        Ok(status) if status.success() => Ok(()),
        Ok(status) => Err(FttsError::Generic(format!(
            "curl failed downloading {url} ({status}); check network access and retry `ftts pull`"
        ))),
    }
}

/// Size first, digest second, both against the embedded pins.
fn verify_pulled_file(path: &Path, file: &ModelManifestFile) -> Result<(), FttsError> {
    let metadata = fs::metadata(path).map_err(|error| {
        FttsError::Generic(format!(
            "cannot stat downloaded {}: {error}",
            path.display()
        ))
    })?;
    if metadata.len() != file.bytes {
        return Err(FttsError::ArtifactFormat(format!(
            "downloaded {} is {} bytes, expected {}; the incomplete download was discarded, retry `ftts pull`",
            file.asset,
            metadata.len(),
            file.bytes
        )));
    }
    let digest = ftts_artifacts::sha256::hex_digest_file(path).map_err(|error| {
        FttsError::Generic(format!(
            "cannot hash downloaded {}: {error}",
            path.display()
        ))
    })?;
    if digest != file.sha256 {
        return Err(FttsError::ArtifactFormat(format!(
            "downloaded {} carries sha256 {digest}, expected {}; the corrupt download was discarded, retry `ftts pull`",
            file.asset, file.sha256
        )));
    }
    Ok(())
}

/// `<dest>.part`, in the destination directory so the final rename never crosses a filesystem.
fn pull_staging_path(dest: &Path) -> PathBuf {
    let mut name = dest.file_name().map(OsString::from).unwrap_or_default();
    name.push(".part");
    dest.with_file_name(name)
}

/// Downloads one asset to `<dest>.part`, verifies it against the pins, and atomically publishes.
///
/// A staging file that fails verification is removed. This is the opposite of `convert`'s
/// retained staging, on purpose: a failed local conversion is diagnosable evidence, while a
/// corrupt download says nothing beyond "the network truncated it", and a multi-gigabyte corpse
/// in the cache directory helps no one.
fn pull_one_file(
    manifest: &ModelManifest,
    file: &ModelManifestFile,
    dest: &Path,
) -> Result<(), FttsError> {
    if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent).map_err(|error| {
            FttsError::Generic(format!(
                "cannot create model directory {}: {error}",
                parent.display()
            ))
        })?;
    }
    let staging = pull_staging_path(dest);
    // The staging name is predictable, and `curl -o` opens it with a plain create-or-truncate
    // that follows symlinks. A pre-planted entry (stale crash debris, or a symlink in a shared
    // model directory) must be cleared first, checked via symlink_metadata so a link is seen as
    // itself rather than its target.
    match fs::symlink_metadata(&staging) {
        Ok(_) => fs::remove_file(&staging).map_err(|error| {
            FttsError::Generic(format!(
                "cannot clear stale staging file {}: {error}",
                staging.display()
            ))
        })?,
        Err(error) if error.kind() == io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(FttsError::Generic(format!(
                "cannot stat staging path {}: {error}",
                staging.display()
            )));
        }
    }
    // Try each mirror in order; a failure (transport, HTTP, or digest) clears the staging
    // debris and moves on, and only the LAST mirror's error surfaces — by then it is the
    // honest answer to "why did the pull fail everywhere".
    let urls = manifest.download_urls(file);
    let mut last_error = None;
    let mut verified = false;
    for url in &urls {
        match download_with_curl(url, &staging, file.bytes)
            .and_then(|()| verify_pulled_file(&staging, file))
        {
            Ok(()) => {
                verified = true;
                break;
            }
            Err(error) => {
                let _ = fs::remove_file(&staging);
                last_error = Some(error);
            }
        }
    }
    if !verified {
        return Err(last_error.expect("at least one mirror was attempted"));
    }
    // Durability before publish: rename orders the directory entry, not the data. Without the
    // fsync a crash can leave a truncated file at the verified name — and the tokenizer/codec
    // sidecars, unlike the .fttsq, carry no load-time digest to catch that. Same contract as
    // FttsqWriter::write_to_path. The handle must be writable: Windows refuses to flush a
    // read-only handle (ERROR_ACCESS_DENIED), while Unix fsync accepts one.
    fs::OpenOptions::new()
        .write(true)
        .open(&staging)
        .and_then(|file| file.sync_all())
        .map_err(|error| {
            FttsError::Generic(format!(
                "cannot fsync downloaded {}: {error}",
                staging.display()
            ))
        })?;
    fs::rename(&staging, dest).map_err(|error| {
        FttsError::Generic(format!(
            "downloaded {} verified but could not be published to {}: {error}",
            file.asset,
            dest.display()
        ))
    })
}

fn run_pull(
    args: &PullArgs,
    environment: &Environment,
    stdout: &mut dyn Write,
) -> Result<(), FttsError> {
    let manifest = ModelManifest::embedded()?;
    let destination = match &args.model {
        Some(path) => path.clone(),
        None => default_pull_model_dir(environment).ok_or_else(|| {
            FttsError::Usage(
                "cannot choose a model directory: pass --model PATH, or set FTTS_MODEL_DIR or HOME"
                    .to_owned(),
            )
        })?,
    };
    writeln!(
        stdout,
        "pulling {} ({} files, {} bytes) into {}",
        manifest.model_id,
        manifest.files.len(),
        manifest.total_bytes(),
        destination.display()
    )
    .map_err(output_error)?;
    for file in &manifest.files {
        let dest = destination.join(&file.dest);
        match pull_decision(&dest, file, args.force) {
            PullDecision::Skip => writeln!(
                stdout,
                "{} ({} bytes): already present, verified",
                file.dest, file.bytes
            )
            .map_err(output_error)?,
            PullDecision::Download => {
                writeln!(stdout, "{} ({} bytes): downloading", file.dest, file.bytes)
                    .map_err(output_error)?;
                pull_one_file(&manifest, file, &dest)?;
                writeln!(stdout, "{} ({} bytes): verified", file.dest, file.bytes)
                    .map_err(output_error)?;
            }
        }
    }
    writeln!(stdout, "model ready at {}", destination.display()).map_err(output_error)
}

fn resolve_existing_file<'a>(path: &'a Path, label: &str) -> Result<&'a Path, FttsError> {
    if path.is_file() {
        Ok(path)
    } else {
        Err(FttsError::ModelNotFound(format!(
            "{label} {} does not exist or is not a file; use an existing PATH",
            path.display()
        )))
    }
}

/// Preflight admission for `say --check`, computed by the **engine**, not by the CLI.
///
/// This used to be a CLI-local heuristic whose own text said "model-specific KV and memory
/// admission is pending the V_REL engine". That engine now exists, so the preflight calls
/// [`ftts_core::admission`] directly. The point is not code reuse: it is that `--check` and the
/// synthesis that follows it must reach the *same* verdict for the same request. A preflight that
/// says yes and an engine that then says no is worse than no preflight, because the caller
/// budgeted on the first answer.
///
/// Prompt length is not knowable before tokenization, so `--check` reports the admission decision
/// for an *estimated* prompt length and labels it as such. The binding decision remains the
/// engine's, taken after real tokenization.
fn admission_plan(text: &str, settings: &EffectiveSettings) -> Result<Value, FttsError> {
    if text.len() > SCAFFOLD_ADMISSION_TEXT_LIMIT_BYTES {
        return Err(FttsError::BudgetTimeout(format!(
            "text is {} bytes, above the Phase-0 admission bound of {} bytes; split the document before retrying",
            text.len(),
            SCAFFOLD_ADMISSION_TEXT_LIMIT_BYTES
        )));
    }

    let characters = text.chars().count();
    // A deliberately conservative stand-in until the tokenizer is on this path: over-estimating
    // the prompt can only make the preflight refuse something the engine would admit, which is the
    // safe direction. Under-estimating would promise capacity that is not there.
    let estimated_prompt_tokens = u64::try_from(characters).unwrap_or(u64::MAX);
    // The engine's own env-resolved policy (FTTS_MEMORY_BUDGET_MB / FTTS_MAX_FRAMES), not a copy
    // of it — a second parse of the same variables is a second thing to drift.
    let policy = ftts_core::process_engine_config().admission;

    match policy.admit(estimated_prompt_tokens) {
        Ok(plan) => Ok(json!({
            "status": "accepted",
            "scope": "preflight on an ESTIMATED prompt length; the binding decision is the \
                      engine's, taken after tokenization",
            "text_bytes": text.len(),
            "text_characters": characters,
            "estimated_prompt_tokens": estimated_prompt_tokens,
            "predicted_max_frames": plan.predicted_max_frames,
            "predicted_peak_bytes": plan.predicted_peak_bytes,
            "budget_bytes": plan.budget_bytes,
            "binding_constraint": plan.binding_constraint.as_str(),
            "packet_frames": settings.packet_frames.as_str(),
            "profile": settings.profile.as_str(),
        })),
        // AdmissionRejection's Display already carries the shortfall, the binding constraint and
        // what to do about it, so it is passed through rather than re-summarised into something
        // less specific.
        Err(rejection) => Err(FttsError::BudgetTimeout(rejection.to_string())),
    }
}

#[derive(Debug, clap::Args)]
struct CardArgs {
    #[command(subcommand)]
    command: CardCommand,
}

#[derive(Debug, Subcommand)]
enum CardCommand {
    /// Render a voice as a shareable card PNG (mosaic + lossless chunk).
    Export {
        /// Voice source: a .spk vector file or a built-in voice name
        /// (matt, james, leo, robert, judy, aria, ember, liam, anthony, russell, steve, daniel, meryl, laurence, jack, michael, jodie, denzel).
        #[arg(value_name = "PATH|NAME")]
        voice: String,
        /// Name written INTO the card (shown on phones at import).
        /// Default: the preset name or the .spk file stem.
        #[arg(long, value_name = "NAME")]
        name: Option<String>,
        /// Output PNG path. Default: <name>-voice-card.png beside the source.
        #[arg(short, long, value_name = "PATH")]
        output: Option<PathBuf>,
    },
    /// Read a voice card image (PNG or JPEG) back into a .spk vector.
    Import {
        /// The card image: an original PNG, a screenshot, or a re-compressed JPEG.
        #[arg(value_name = "IMAGE")]
        image: PathBuf,
        /// Output .spk path. Default: <embedded name>.spk beside the image.
        #[arg(short, long, value_name = "PATH")]
        output: Option<PathBuf>,
    },
}

fn run_card(args: &CardArgs, stdout: &mut dyn Write) -> Result<(), FttsError> {
    match &args.command {
        CardCommand::Export {
            voice,
            name,
            output,
        } => {
            let (vector, default_name, base_dir) = if let Some((preset_name, _, bytes)) =
                PRESET_VOICES.iter().find(|(n, _, _)| n == voice)
            {
                let vector: Vec<f32> = bytes
                    .as_chunks::<4>()
                    .0
                    .iter()
                    .map(|chunk| f32::from_le_bytes(*chunk))
                    .collect();
                ((vector), (*preset_name).to_owned(), PathBuf::from("."))
            } else {
                let path = PathBuf::from(voice);
                // A bare word that is not a preset and not a file is almost always a
                // typo'd preset name; a raw file-not-found error would hide that.
                if !path.exists()
                    && !voice.contains('.')
                    && !voice.contains('/')
                    && !voice.contains('\\')
                {
                    let names: Vec<&str> = PRESET_VOICES.iter().map(|(name, _, _)| *name).collect();
                    return Err(FttsError::Input(format!(
                        "`{voice}` is not a built-in voice (those are: {}) and no such file exists",
                        names.join(", ")
                    )));
                }
                let vector = card::read_spk(&path)?;
                let stem = path
                    .file_stem()
                    .map_or_else(|| "voice".to_owned(), |s| s.to_string_lossy().into_owned());
                let dir = path
                    .parent()
                    .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
                (vector, stem, dir)
            };
            let card_name = name.clone().unwrap_or(default_name);
            let png = card::render_card_png(&card_name, &vector)?;
            let destination = output.clone().unwrap_or_else(|| {
                base_dir.join(format!(
                    "{}-voice-card.png",
                    card::safe_file_stem(&card_name)
                ))
            });
            std::fs::write(&destination, &png).map_err(|error| {
                FttsError::Generic(format!("cannot write {}: {error}", destination.display()))
            })?;
            writeln!(
                stdout,
                "wrote {} ({} KB) — the mosaic is the voice; phones import it from Photos",
                destination.display(),
                png.len() / 1024
            )
            .map_err(|error| FttsError::Generic(error.to_string()))?;
            Ok(())
        }
        CardCommand::Import { image, output } => {
            let bytes = std::fs::read(image).map_err(|error| {
                FttsError::Input(format!("cannot read {}: {error}", image.display()))
            })?;
            let (voice_name, vector) = card::decode_card(&bytes)?;
            let destination = output
                .clone()
                .unwrap_or_else(|| card::default_import_path(image, &voice_name));
            card::write_spk(&destination, &vector)?;
            writeln!(
                stdout,
                "imported \"{voice_name}\" -> {} — use it with: ftts say --voice {}",
                destination.display(),
                destination.display()
            )
            .map_err(|error| FttsError::Generic(error.to_string()))?;
            Ok(())
        }
    }
}

fn run_voice_inspect(path: &Path, stdout: &mut dyn Write) -> Result<(), FttsError> {
    let path = resolve_existing_file(path, "voice pack")?;
    let bytes = std::fs::read(path)
        .map_err(|error| FttsError::Input(format!("cannot read {}: {error}", path.display())))?;
    if bytes.starts_with(ftts_artifacts::voice::VOICE_MAGIC) {
        let pack = ftts_artifacts::voice::parse_voice_pack(&bytes).map_err(|error| {
            FttsError::Input(format!(
                "{} is not a valid voice pack: {error}",
                path.display()
            ))
        })?;
        style::ok(
            stdout,
            &format!(
                "{}{} voice pack",
                style::emphasis(&path.display().to_string()),
                pack.profile.as_str(),
            ),
        )
        .map_err(|error| FttsError::Generic(error.to_string()))?;
        let consent = if pack.consent.attested {
            format!("attested ({})", pack.consent.method.as_str())
        } else {
            "NOT ATTESTED".to_owned()
        };
        style::info(
            stdout,
            &format!(
                "consent {consent} · embedding {} f32 · transcript {} · codec tokens {} · audio {}",
                pack.embedding.len(),
                if pack.transcript.is_some() {
                    "yes"
                } else {
                    "no"
                },
                match pack.codec_codes.as_deref() {
                    Some(codes) => format!("{} frames", codes.len()),
                    None => "none".to_owned(),
                },
                if pack.reference_audio.is_some() {
                    "embedded"
                } else {
                    "absent"
                },
            ),
        )
        .map_err(|error| FttsError::Generic(error.to_string()))?;
        if let Some(dx) = &pack.diagnostics {
            for warning in dx_warnings(dx) {
                style::warn(stdout, &warning)
                    .map_err(|error| FttsError::Generic(error.to_string()))?;
            }
        }
        write_json_line(
            stdout,
            &json!({
                "schema_version": ROBOT_SCHEMA_VERSION,
                "event": "voice_inspect",
                "path": path.display().to_string(),
                "status": "ok",
                "profile": pack.profile.as_str(),
                "consent_attested": pack.consent.attested,
                "consent_method": pack.consent.method.as_str(),
                "language": pack.language,
                "transcript_present": pack.transcript.is_some(),
                "codec_codes_present": pack.codec_codes.is_some(),
                "reference_audio_present": pack.reference_audio.is_some(),
                "diagnostics": pack.diagnostics
                    .as_ref()
                    .map(|dx| json!({
                        "clipping_fraction": dx.clipping_fraction,
                        "longest_clip_run": dx.longest_clip_run,
                        "intersample_overshoot_db": dx.intersample_overshoot_db,
                        "snr_estimate_db": dx.snr_estimate_db,
                        "pause_floor_dbfs": dx.pause_floor_dbfs,
                        "reverb_time_s": dx.reverb_time_s,
                        "music_bed_likelihood": dx.music_bed_likelihood,
                        "stationarity_drift": dx.stationarity_drift,
                        "loudness_rms_dbfs": dx.loudness_rms_dbfs,
                        "voice_activity_ratio": dx.voice_activity_ratio,
                    })),
                "recipe_hash": pack.recipe_hash().ok(),
                "embedding_sha256": ftts_artifacts::sha256::hex_digest(
                    &ftts_artifacts::sha256::digest(&{
                        let mut b = Vec::with_capacity(pack.embedding.len() * 4);
                        for v in &pack.embedding { b.extend_from_slice(&v.to_le_bytes()); }
                        b
                    })),
                "provenance_engine": pack.provenance.engine,
            }),
        )
    } else if bytes.len() == synth::SPEAKER_VECTOR_BYTES {
        write_json_line(
            stdout,
            &json!({
                "schema_version": ROBOT_SCHEMA_VERSION,
                "event": "voice_inspect",
                "path": path.display().to_string(),
                "status": "legacy_speaker_vector",
            }),
        )
    } else {
        Err(FttsError::Input(format!(
            "{} is neither a .ftvoice pack nor a raw .spk vector; re-enroll to produce a pack",
            path.display()
        )))
    }
}

/// Re-renders a stored diagnostics record through the live advisory thresholds, so an old pack
/// speaks with the same voice the enrollment console used.
fn dx_warnings(dx: &ftts_artifacts::voice::EnrollmentDiagnostics) -> Vec<String> {
    let audio = crate::diagnostics::AudioDiagnostics {
        clipping_fraction: dx.clipping_fraction,
        longest_clip_run: dx.longest_clip_run,
        intersample_overshoot_db: dx.intersample_overshoot_db,
        snr_estimate_db: dx.snr_estimate_db,
        pause_floor_dbfs: dx.pause_floor_dbfs,
        reverb_time_s: dx.reverb_time_s,
        music_bed_likelihood: dx.music_bed_likelihood,
        stationarity_drift: dx.stationarity_drift,
        loudness_rms_dbfs: dx.loudness_rms_dbfs,
        voice_activity_ratio: dx.voice_activity_ratio,
    };
    audio.warnings()
}

fn run_robot(
    command: RobotCommand,
    environment: &Environment,
    stdout: &mut dyn Write,
) -> Result<(), FttsError> {
    // Every object below is built from `robot::EventType`, so the discriminator and
    // schema_version cannot be forgotten, and the frozen contract test in ftts-conformance
    // fails if any of these stops matching the catalogue.
    let event = match command {
        RobotCommand::Schema { contract } => match contract {
            SchemaContract::Run => robot::schema_document(robot::DOCUMENTED_ENVIRONMENT),
            SchemaContract::Session => {
                session_protocol::session_schema_document(robot::DOCUMENTED_ENVIRONMENT)
            }
        },
        RobotCommand::Health => {
            let searched = model_search_paths(environment);
            let found = searched.iter().find(|path| looks_like_model_artifact(path));
            let mut object = robot::EventType::Health.event();
            object.insert("status".to_owned(), json!("phase0_skeleton"));
            object.insert("model_loaded".to_owned(), json!(false));
            // Presence is a magic-bytes header sniff, never a tensor load: `robot health` must
            // stay cheap enough for an agent to call it on every invocation.
            object.insert("model_present".to_owned(), json!(found.is_some()));
            object.insert(
                "model_path".to_owned(),
                json!(found.map(|path| path.display().to_string())),
            );
            object.insert(
                "model_dir".to_owned(),
                json!(environment.value("FTTS_MODEL_DIR")),
            );
            // Every directory consulted, so a resolution failure is actionable rather than a
            // bare "not found".
            object.insert(
                "searched".to_owned(),
                json!(
                    searched
                        .iter()
                        .map(|path| path.display().to_string())
                        .collect::<Vec<_>>()
                ),
            );
            object.insert("stateless_default".to_owned(), json!(true));
            object.insert(
                "threads".to_owned(),
                json!(
                    environment
                        .value("FTTS_THREADS")
                        .and_then(|value| value.parse::<u64>().ok())
                ),
            );
            object.insert(
                "recommended_command".to_owned(),
                json!("ftts say --check --model PATH TEXT"),
            );
            Value::Object(object)
        }
        RobotCommand::Backends => {
            let mut object = robot::EventType::Backends.event();
            // Capability vs executed-route split: `available` is every tier this build can
            // certify on this CPU; `dispatched` is the one the int8 route would actually run.
            object.insert(
                "available".to_owned(),
                json!(
                    ftts_kernels::int8::Int8Tier::available()
                        .iter()
                        .map(|tier| tier.as_str())
                        .collect::<Vec<_>>()
                ),
            );
            object.insert(
                "dispatched".to_owned(),
                json!(ftts_kernels::int8::Int8Tier::dispatch().as_str()),
            );
            object.insert("isa_features".to_owned(), json!(detected_isa_features()));
            let plan = ftts_kernels::int8::autotuned_plan();
            object.insert(
                "kernel_plan".to_owned(),
                json!({
                    "version": 0,
                    "decode_gemv": plan.decode_gemv.as_str(),
                    "batch_gemm": plan.batch_gemm.as_str(),
                    "persisted": matches!(
                        ftts_kernels::int8::plan_source(),
                        ftts_kernels::int8::PlanSource::PersistedCache
                    ),
                }),
            );
            object.insert("pool_sizing".to_owned(), Value::Null);
            object.insert(
                "force_arch".to_owned(),
                json!(environment.value("FTTS_FORCE_ARCH")),
            );
            Value::Object(object)
        }
        RobotCommand::Selftest => {
            // The permanent integer-kernel law, executed on the end user's silicon: every census
            // binding row through the real dot kernels on every dispatchable tier. The event's
            // top-level fields are pinned by the frozen v1 schema fixture (status/reason/checks);
            // per-row detail lives inside `checks`.
            let report = ftts_kernels::selftest::run_selftest();
            let checks: Vec<Value> = report
                .checks
                .iter()
                .map(|check| {
                    json!({
                        "row": check.row.id,
                        "scope": check.row.scope.as_str(),
                        "census_tensor": check.row.census_tensor,
                        "reduction_k": check.row.reduction_k,
                        "tier": check.tier.as_str(),
                        "contract": check.contract.as_str(),
                        "dispatched": check.tier == report.dispatched,
                        "accumulator_i32": check.accumulator_i32,
                        "reference_i64": check.reference_i64,
                        "passed": check.passed,
                    })
                })
                .collect();
            let mut object = robot::EventType::Selftest.event();
            object.insert(
                "status".to_owned(),
                json!(if report.passed() { "passed" } else { "failed" }),
            );
            object.insert("reason".to_owned(), Value::Null);
            object.insert("checks".to_owned(), json!(checks));
            Value::Object(object)
        }
    };
    write_json_line(stdout, &event)
}

/// Every path the model resolver consults, in order.
///
/// Shared by `robot health` and the resolution error so the two can never disagree about what
/// was searched — a "not found" that lists different directories than `health` reports is worse
/// than no list at all.
fn model_search_paths(environment: &Environment) -> Vec<PathBuf> {
    let mut searched = environment
        .value("FTTS_MODEL_DIR")
        .map(std::env::split_paths)
        .map(|paths| {
            paths
                .map(|path| path.join(MODEL_BASENAME))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if let Some(home) = std::env::var_os("HOME") {
        let home = PathBuf::from(home);
        searched.push(home.join(".cache/franken_tts/models").join(MODEL_BASENAME));
        // The `ftts pull` destination, listed after the legacy plural directory so existing
        // installs keep winning; it is also the bundle-directory fallback in `resolve_model_from`,
        // which is what lets a bare `ftts pull` then `ftts say` work with no env var at all.
        searched.push(home.join(DEFAULT_MODEL_CACHE_SUBDIR).join(MODEL_BASENAME));
    }
    searched
}

/// A cheap header sniff: is there a plausible `.fttsq` artifact at this path?
///
/// Reads the magic bytes only. Deliberately never opens the tensor data — `robot health` is
/// meant to be callable on every agent invocation, and a multi-gigabyte read would make it a
/// thing agents avoid calling, which defeats the point.
fn looks_like_model_artifact(path: &Path) -> bool {
    use std::io::Read as _;

    let Ok(mut file) = fs::File::open(path) else {
        return false;
    };
    let mut magic = [0u8; 5];
    file.read_exact(&mut magic).is_ok() && &magic == b"FTTSQ"
}

/// ISA features detected at runtime, for `robot backends`.
///
/// Reported as a plain list so an agent can see what the dispatcher had available; the kernel
/// tiers themselves land with the Phase-3 engines.
fn detected_isa_features() -> Vec<&'static str> {
    let mut features = Vec::new();
    #[cfg(target_arch = "aarch64")]
    {
        if std::arch::is_aarch64_feature_detected!("neon") {
            features.push("neon");
        }
        if std::arch::is_aarch64_feature_detected!("dotprod") {
            features.push("dotprod");
        }
        if std::arch::is_aarch64_feature_detected!("i8mm") {
            features.push("i8mm");
        }
    }
    #[cfg(target_arch = "x86_64")]
    {
        if std::arch::is_x86_feature_detected!("avx2") {
            features.push("avx2");
        }
        if std::arch::is_x86_feature_detected!("avxvnni") {
            features.push("avx-vnni");
        }
        if std::arch::is_x86_feature_detected!("avx512vnni") {
            features.push("avx512-vnni");
        }
    }
    features
}

fn run_doctor(
    args: &DoctorArgs,
    environment: &Environment,
    stdout: &mut dyn Write,
) -> Result<(), FttsError> {
    let model_present = model_search_paths(environment)
        .iter()
        .find(|path| looks_like_model_artifact(path))
        .map(|path| path.display().to_string());
    let report = json!({
        "schema_version": ROBOT_SCHEMA_VERSION,
        "status": if model_present.is_some() { "ready" } else { "model_missing" },
        "stateless_default": true,
        "persistent_history": false,
        "model_present": model_present,
        "environment": environment.documented_values(),
        "recommended_command": if model_present.is_some() {
            "ftts say \"hello\" -o hello.wav"
        } else {
            "ftts pull"
        },
    });
    if args.json {
        write_json_line(stdout, &report)
    } else {
        let human = format!(
            "FrankenTTS ftts — local readiness\nstateless default: yes\nmodel: {}\nnext: {}\n",
            model_present.as_deref().map_or_else(
                || "missing — run `ftts pull`".to_owned(),
                |p| format!("present ({p})")
            ),
            report["recommended_command"]
                .as_str()
                .unwrap_or("ftts robot schema"),
        );
        write!(stdout, "{human}").map_err(output_error)
    }
}

fn write_json_line(writer: &mut dyn Write, value: &Value) -> Result<(), FttsError> {
    serde_json::to_writer(&mut *writer, value)
        .map_err(|error| FttsError::Generic(format!("cannot serialize CLI JSON: {error}")))?;
    writer.write_all(b"\n").map_err(output_error)
}

fn output_error(error: io::Error) -> FttsError {
    FttsError::Generic(format!("cannot write CLI output: {error}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn preset_voices_are_valid_speaker_vectors() {
        assert!(
            PRESET_VOICES
                .iter()
                .any(|(name, _, _)| *name == DEFAULT_PRESET_VOICE),
            "the default preset must exist in the table"
        );
        for (name, character, bytes) in PRESET_VOICES {
            assert_eq!(
                bytes.len(),
                synth::SPEAKER_VECTOR_BYTES,
                "preset {name} must be exactly one 1,024-float x-vector"
            );
            assert!(
                !character.is_empty(),
                "preset {name} needs a character line"
            );
        }
    }

    #[test]
    fn preset_names_resolve_and_unknown_names_do_not() {
        let environment = Environment {
            values: BTreeMap::new(),
            stage_budget_values: BTreeMap::new(),
        };
        let resolved = resolve_requested_voice(Some(Path::new("aria")), &environment)
            .expect("preset name resolves")
            .expect("preset yields a path");
        let bytes = fs::read(&resolved).expect("materialized preset readable");
        assert_eq!(bytes.len(), synth::SPEAKER_VECTOR_BYTES);

        let error = resolve_requested_voice(Some(Path::new("no-such-voice")), &environment)
            .expect_err("unknown names are refused");
        assert!(
            error.to_string().contains("aria"),
            "the refusal must list the built-in names, got: {error}"
        );
    }

    // Re-baselined for the `talk` subcommand (bead frankentts-edz0), which landed without
    // updating this snapshot. The snapshot exists to make CLI-surface changes deliberate rather
    // than accidental, so it is re-baselined only alongside a real, intended command — never
    // widened to stop failing.
    const CLAP_SURFACE_SNAPSHOT: &str = "commands=say,make-video,enroll,voice,card,convert,pull,talk,robot,doctor,resident-daemon\nrobot=schema,health,backends,selftest\nsay=file,model,voice,output,stream,check,robot,no-resident\npull=model,force\nglobal=profile,packet-frames,math-mode,voice-pack,normalize,trace,seed\n";

    #[test]
    fn clap_surface_matches_snapshot() {
        let command = Cli::command();
        let commands = command
            .get_subcommands()
            .map(|command| command.get_name())
            .collect::<Vec<_>>()
            .join(",");
        let robot = command
            .get_subcommands()
            .find(|command| command.get_name() == "robot")
            .expect("robot subcommand")
            .get_subcommands()
            .map(|command| command.get_name())
            .collect::<Vec<_>>()
            .join(",");
        let say = command
            .get_subcommands()
            .find(|command| command.get_name() == "say")
            .expect("say subcommand")
            .get_arguments()
            .filter_map(|argument| argument.get_long())
            .collect::<Vec<_>>()
            .join(",");
        let pull = command
            .get_subcommands()
            .find(|command| command.get_name() == "pull")
            .expect("pull subcommand")
            .get_arguments()
            .filter_map(|argument| argument.get_long())
            .collect::<Vec<_>>()
            .join(",");
        let global = command
            .get_arguments()
            .filter_map(|argument| argument.get_long())
            .filter(|argument| *argument != "help")
            .collect::<Vec<_>>()
            .join(",");
        let actual = format!(
            "commands={commands}\nrobot={robot}\nsay={say}\npull={pull}\nglobal={global}\n"
        );
        assert_eq!(actual, CLAP_SURFACE_SNAPSHOT);
    }

    #[test]
    fn argument_file_and_stdin_text_are_identical() {
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../README.md");
        let expected = fs::read_to_string(&root).expect("checked-in README");
        let from_argument = read_text(
            &SayArgs {
                output_positional: None,
                text: Some(expected.clone()),
                file: None,
                model: None,
                voice: None,
                output: None,
                stream: None,
                check: true,
                robot: false,
                no_resident: true,
            },
            &mut Cursor::new(Vec::<u8>::new()),
        )
        .expect("argument text");
        let from_file = read_text(
            &SayArgs {
                output_positional: None,
                text: None,
                file: Some(root),
                model: None,
                voice: None,
                output: None,
                stream: None,
                check: true,
                robot: false,
                no_resident: true,
            },
            &mut Cursor::new(Vec::<u8>::new()),
        )
        .expect("file text");
        let from_stdin = read_text(
            &SayArgs {
                output_positional: None,
                text: Some("-".to_owned()),
                file: None,
                model: None,
                voice: None,
                output: None,
                stream: None,
                check: true,
                robot: false,
                no_resident: true,
            },
            &mut Cursor::new(expected.as_bytes()),
        )
        .expect("stdin text");

        assert_eq!(from_argument, from_file);
        assert_eq!(from_argument, from_stdin);
    }

    #[test]
    fn check_plan_is_deterministic_and_marks_its_scope() {
        let settings = EffectiveSettings {
            profile: ExecutionProfile::Strict,
            packet_frames: PacketFrames::Four,
            math_mode: MathMode::Strict,
            voice_pack: VoicePackProfile::Portable,
            normalize: NormalizeMode::Conservative,
        };
        let first = admission_plan("hello", &settings).expect("admission plan");
        let second = admission_plan("hello", &settings).expect("admission plan");
        assert_eq!(first, second);
        assert_eq!(first["status"], "accepted");
        // The preflight is explicit that it estimates the prompt and that the engine decides.
        assert!(
            first["scope"]
                .as_str()
                .unwrap_or_default()
                .contains("ESTIMATED")
        );
    }

    #[test]
    fn the_cli_preflight_and_the_engine_agree_on_the_same_request() {
        // The property that matters: `--check` saying yes and the engine then saying no is worse
        // than no preflight, because the caller budgeted on the first answer. Both must be the
        // same computation, not two implementations of the same rule.
        let settings = EffectiveSettings {
            profile: ExecutionProfile::Balanced,
            packet_frames: PacketFrames::Four,
            math_mode: MathMode::Strict,
            voice_pack: VoicePackProfile::Portable,
            normalize: NormalizeMode::Verbatim,
        };
        let text = "a moderately sized utterance for admission";
        let plan = admission_plan(text, &settings).expect("preflight admits");

        let policy = ftts_core::process_engine_config().admission;
        let engine = policy
            .admit(text.chars().count() as u64)
            .expect("engine admits the same request");

        assert_eq!(plan["predicted_peak_bytes"], engine.predicted_peak_bytes);
        assert_eq!(plan["predicted_max_frames"], engine.predicted_max_frames);
        assert_eq!(plan["budget_bytes"], engine.budget_bytes);
        assert_eq!(
            plan["binding_constraint"],
            engine.binding_constraint.as_str()
        );
    }

    #[test]
    fn a_wav_sink_writes_a_playable_file_and_conforming_audio_chunk_events() {
        let dir = std::env::temp_dir().join(format!("ftts-wav-sink-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let path = dir.join("out.wav");

        let frame: Vec<f32> = (0..1_920)
            .map(|i| (i as f32 / 1_920.0 * std::f32::consts::TAU).sin() * 0.5)
            .collect();
        let mut sink = AudioOutput::wav(&path).expect("wav sink");
        let mut discard = Vec::new();

        let first = sink
            .write_packet(&frame, &mut discard, "run-1", 1)
            .expect("packet 1");
        let second = sink
            .write_packet(&frame, &mut discard, "run-1", 1)
            .expect("packet 2");

        // Every emitted object must satisfy the frozen robot contract, not merely look plausible.
        assert!(robot::validate_event(&first).is_empty(), "{first:?}");
        assert!(robot::validate_event(&second).is_empty(), "{second:?}");
        assert_eq!(first["sink"], "file");
        assert_eq!(first["byte_offset"], 0);
        assert_eq!(first["bytes"], 1_920 * 2);
        assert_eq!(first["duration_ms"], 80, "1,920 samples at 24 kHz is 80 ms");
        // The offset is cumulative, so a consumer can seek with it.
        assert_eq!(second["byte_offset"], 1_920 * 2);

        let samples = sink.finish().expect("finish");
        assert_eq!(samples, 1_920 * 2);

        // The file on disk must describe exactly what it holds.
        let bytes = std::fs::read(&path).expect("read wav");
        assert_eq!(&bytes[0..4], b"RIFF");
        assert_eq!(&bytes[8..12], b"WAVE");
        let declared = u32::from_le_bytes(bytes[40..44].try_into().expect("data size"));
        assert_eq!(declared as usize, 1_920 * 2 * 2);
        assert_eq!(bytes.len(), 44 + 1_920 * 2 * 2);
        assert!(
            discard.is_empty(),
            "a file sink must not also emit raw PCM to the stream"
        );
    }

    #[test]
    fn a_raw_sink_writes_pcm_to_the_stream_and_never_mixes_it_with_events() {
        // The stream contract: under --stream raw, stdout carries PCM only. An event object landing
        // in the same buffer would corrupt both — the audio and the NDJSON.
        let mut sink = AudioOutput::raw();
        let mut raw = Vec::new();
        let pcm = vec![0.5f32; 4];
        let event = sink
            .write_packet(&pcm, &mut raw, "run-1", 1)
            .expect("packet");

        assert!(robot::validate_event(&event).is_empty(), "{event:?}");
        assert_eq!(event["sink"], "stdout");
        assert_eq!(raw.len(), 8, "four 16-bit samples");
        let first = i16::from_le_bytes([raw[0], raw[1]]);
        assert_eq!(first, ftts_core::audio::sample_to_i16(0.5));
        // The PCM buffer must contain no JSON.
        assert!(
            !raw.windows(2).any(|w| w == b"{\""),
            "raw PCM stream must never contain an event object"
        );
    }

    #[test]
    fn a_none_sink_still_reports_conforming_events() {
        let mut sink = AudioOutput::none();
        let mut discard = Vec::new();
        let event = sink
            .write_packet(&[0.0f32; 960], &mut discard, "run-1", 2)
            .expect("packet");
        assert!(robot::validate_event(&event).is_empty(), "{event:?}");
        assert_eq!(event["sink"], "none");
        assert_eq!(event["packet_frames"], "2");
        assert!(discard.is_empty());
        assert_eq!(sink.finish().expect("finish"), 960);
    }

    #[test]
    fn a_health_violation_renders_as_a_contract_conforming_robot_event() {
        // The engine-to-wire seam: the violation's class, remedy and invalidates_output must
        // survive the crossing, and the result must satisfy the frozen robot contract.
        let silent =
            ftts_core::HealthEvent::Violation(ftts_core::health::HealthViolation::OutputSilent {
                silent_millis: 1_500,
            });
        let event = robot::health_violation_event("run-1", silent, 42);
        assert!(
            robot::validate_event(&event).is_empty(),
            "{:?}",
            robot::validate_event(&event)
        );
        assert_eq!(event["event"], "health_violation");
        assert_eq!(event["violation"], "output_silent");
        assert_eq!(event["invalidates_output"], true);
        assert!(event["detail"].as_str().expect("detail").contains("1500"));
        assert!(event["remedy"].as_str().expect("remedy").len() > 40);

        // A kernel demotion is informational: the run stayed correct, just slower. If this were
        // reported as invalidating, an agent would discard good audio.
        let demoted =
            ftts_core::HealthEvent::Violation(ftts_core::health::HealthViolation::KernelDemoted {
                from: ftts_core::health::KernelTier::Optimized("i8mm"),
                to: ftts_core::health::KernelTier::Scalar,
            });
        let event = robot::health_violation_event("run-1", demoted, 43);
        assert!(robot::validate_event(&event).is_empty());
        assert_eq!(event["invalidates_output"], false);

        // Budget and cancellation are health signals too, and both truncate the audio.
        for event in [
            ftts_core::HealthEvent::BudgetExceeded,
            ftts_core::HealthEvent::Cancelled,
        ] {
            let rendered = robot::health_violation_event("run-1", event, 44);
            assert!(robot::validate_event(&rendered).is_empty());
            assert_eq!(rendered["invalidates_output"], true);
        }
    }

    #[test]
    fn normalization_defaults_to_verbatim_conformance_mode() {
        let cli = Cli {
            profile: None,
            packet_frames: None,
            math_mode: None,
            voice_pack: None,
            normalize: None,
            trace: None,
            seed: None,
            command: Command::Robot(RobotArgs {
                command: RobotCommand::Health,
            }),
        };
        assert_eq!(
            EffectiveSettings::resolve(&cli, &Environment::default())
                .expect("default settings")
                .normalize,
            NormalizeMode::Verbatim
        );
        assert_eq!(
            EffectiveSettings::resolve(&cli, &Environment::default())
                .expect("default settings")
                .normalization_options(),
            NormalizationOptions::default(),
            "CLI defaults must use the same verbatim options as the library"
        );
    }

    #[test]
    fn cli_normalization_modes_map_to_shared_engine_options() {
        for (cli_mode, engine_mode) in [
            (NormalizeMode::Verbatim, NormalizationMode::Verbatim),
            (NormalizeMode::Conservative, NormalizationMode::Conservative),
            (NormalizeMode::LocaleAware, NormalizationMode::LocaleAware),
        ] {
            let settings = EffectiveSettings {
                profile: ExecutionProfile::Balanced,
                packet_frames: PacketFrames::Four,
                math_mode: MathMode::Strict,
                voice_pack: VoicePackProfile::Portable,
                normalize: cli_mode,
            };
            assert_eq!(settings.normalization_options().mode, engine_mode);
        }
    }

    #[test]
    fn embed_q8_flag_flips_exactly_the_text_embedding_and_says_so_in_the_manifest() {
        let default_specs = pinned_main_tensor_specs(false, false).expect("inventory parses");
        let armed_specs = pinned_main_tensor_specs(true, false).expect("inventory parses");
        assert_eq!(default_specs.len(), armed_specs.len());
        for (default, armed) in default_specs.iter().zip(&armed_specs) {
            assert_eq!(default.name, armed.name);
            if default.name == "talker.model.text_embedding.weight" {
                assert_eq!(default.storage, TensorStoragePolicy::Verbatim);
                assert_eq!(armed.storage, TensorStoragePolicy::Q8PerGroup64);
            } else {
                assert_eq!(
                    default.storage, armed.storage,
                    "--embed-q8 must touch no tensor but the text embedding ({})",
                    default.name
                );
            }
        }
    }

    #[test]
    fn micro_q8_flag_flips_exactly_the_microdecoder_tables_and_says_so_in_the_manifest() {
        let default_specs = pinned_main_tensor_specs(false, false).expect("inventory parses");
        let armed_specs = pinned_main_tensor_specs(false, true).expect("inventory parses");
        assert_eq!(default_specs.len(), armed_specs.len());
        let mut flipped = 0;
        for (default, armed) in default_specs.iter().zip(&armed_specs) {
            assert_eq!(default.name, armed.name);
            if is_micro_table(&default.name) {
                assert_eq!(default.storage, TensorStoragePolicy::Verbatim);
                assert_eq!(
                    armed.storage,
                    TensorStoragePolicy::Q8PerOutputChannel,
                    "--micro-q8 must quantize every microdecoder table ({})",
                    armed.name
                );
                flipped += 1;
            } else {
                assert_eq!(
                    default.storage, armed.storage,
                    "--micro-q8 must touch no tensor outside the microdecoder tables ({})",
                    default.name
                );
            }
        }
        assert_eq!(
            flipped, 30,
            "15 residual embedding tables plus 15 scoring heads"
        );
    }

    #[test]
    fn pinned_main_conversion_plan_preserves_the_reviewed_q8_boundary() {
        let specs =
            pinned_main_tensor_specs(false, false).expect("checked-in main inventory parses");
        let (_manifest, _plan) = pinned_main_conversion_plan(false, false)
            .expect("checked-in main conversion plan builds");
        assert_eq!(specs.len(), PINNED_MAIN_TENSOR_COUNT);
        assert_eq!(
            specs
                .iter()
                .filter(|spec| spec.storage == TensorStoragePolicy::Q8PerOutputChannel)
                .count(),
            231,
            "28 talker + 5 microdecoder layers times seven attention/MLP projections"
        );

        let text_embedding = specs
            .iter()
            .find(|spec| spec.name == "talker.model.text_embedding.weight");
        assert!(
            text_embedding.is_some(),
            "pinned inventory must contain the text embedding"
        );
        if let Some(text_embedding) = text_embedding {
            assert_eq!(text_embedding.storage, TensorStoragePolicy::Verbatim);
            assert_eq!(text_embedding.access_class, AccessClass::ColdTextEmbedding);
        }

        let talker_projection = specs
            .iter()
            .find(|spec| spec.name == "talker.model.layers.0.mlp.down_proj.weight");
        assert!(
            talker_projection.is_some(),
            "pinned inventory must contain the talker projection"
        );
        if let Some(talker_projection) = talker_projection {
            assert_eq!(
                talker_projection.storage,
                TensorStoragePolicy::Q8PerOutputChannel
            );
            assert_eq!(
                talker_projection.access_class,
                AccessClass::HotRecurrentTalker
            );
        }

        let micro_projection = specs
            .iter()
            .find(|spec| spec.name == "talker.code_predictor.model.layers.0.mlp.down_proj.weight");
        assert!(
            micro_projection.is_some(),
            "pinned inventory must contain the microdecoder projection"
        );
        if let Some(micro_projection) = micro_projection {
            assert_eq!(
                micro_projection.storage,
                TensorStoragePolicy::Q8PerOutputChannel
            );
            assert_eq!(
                micro_projection.access_class,
                AccessClass::HotRecurrentMicrodecoder
            );
        }

        let primary_embedding = specs
            .iter()
            .find(|spec| spec.name == "talker.model.codec_embedding.weight");
        assert!(
            primary_embedding.is_some(),
            "pinned inventory must contain the primary-code embedding"
        );
        if let Some(primary_embedding) = primary_embedding {
            assert_eq!(
                primary_embedding.access_class,
                AccessClass::HotRecurrentMicrodecoder,
                "the primary-code embedding feeds residual depth one every frame"
            );
        }

        let primary_head = specs
            .iter()
            .find(|spec| spec.name == "talker.codec_head.weight");
        assert!(
            primary_head.is_some(),
            "pinned inventory must contain the primary-code head"
        );
        if let Some(primary_head) = primary_head {
            assert_eq!(primary_head.storage, TensorStoragePolicy::Verbatim);
            assert_eq!(primary_head.access_class, AccessClass::HotRecurrentTalker);
        }

        let text_projection = specs
            .iter()
            .find(|spec| spec.name == "talker.text_projection.linear_fc1.weight");
        assert!(
            text_projection.is_some(),
            "pinned inventory must contain the text-projection MLP"
        );
        if let Some(text_projection) = text_projection {
            assert_eq!(text_projection.storage, TensorStoragePolicy::Verbatim);
            assert_eq!(
                text_projection.access_class,
                AccessClass::HotRecurrentTalker
            );
        }

        let head = specs
            .iter()
            .find(|spec| spec.name == "talker.code_predictor.lm_head.0.weight");
        assert!(
            head.is_some(),
            "pinned inventory must contain the residual-code head"
        );
        if let Some(head) = head {
            assert_eq!(head.storage, TensorStoragePolicy::Verbatim);
            assert_eq!(head.access_class, AccessClass::HotRecurrentMicrodecoder);
        }

        let speaker = specs
            .iter()
            .find(|spec| spec.name == "speaker_encoder.fc.weight");
        assert!(
            speaker.is_some(),
            "pinned inventory must contain the speaker encoder"
        );
        if let Some(speaker) = speaker {
            assert_eq!(speaker.storage, TensorStoragePolicy::Verbatim);
            assert_eq!(speaker.access_class, AccessClass::EnrollmentSpeakerEncoder);
        }
    }

    #[test]
    fn conversion_notice_carries_changes_and_the_full_license() {
        let notice = pinned_license_notice();
        assert!(notice.contains("Copyright 2026 Alibaba Cloud"));
        assert!(notice.contains("CHANGES: the original bfloat16 weights were converted"));
        assert!(notice.contains("Apache License"));
        assert!(notice.contains("TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION"));
    }

    #[test]
    fn convert_refusal_still_emits_a_versioned_robot_lifecycle() {
        let cli = Cli {
            profile: None,
            packet_frames: None,
            math_mode: None,
            voice_pack: None,
            normalize: None,
            trace: None,
            seed: None,
            command: Command::Robot(RobotArgs {
                command: RobotCommand::Health,
            }),
        };
        let args = ConvertArgs {
            // A readable file with the wrong name reaches the explicit pinned-source refusal
            // before any destination is created.
            source: PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml"),
            output: PathBuf::from("never-created.fttsq"),
            embed_q8: false,
            micro_q8: false,
        };
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();
        let error = run_convert(
            &cli,
            &args,
            &Environment::default(),
            &mut stdout,
            &mut stderr,
        )
        .expect_err("the non-pinned source must be refused");
        assert_eq!(error.exit_code(), FttsExitCode::Input);

        let stdout = String::from_utf8(stdout).expect("NDJSON stdout");
        let stderr = String::from_utf8(stderr).expect("NDJSON stderr");
        assert!(robot::validate_ndjson(&stdout).is_empty());
        assert!(robot::validate_ndjson(&stderr).is_empty());
        let stdout_events = stdout
            .lines()
            .map(|line| serde_json::from_str::<Value>(line).expect("JSON event"))
            .collect::<Vec<_>>();
        assert_eq!(stdout_events[0]["event"], "run_start");
        assert_eq!(stdout_events[1]["event"], "stage");
        assert_eq!(
            serde_json::from_str::<Value>(stderr.trim()).expect("run error")["event"],
            "run_error"
        );
    }

    #[test]
    fn say_check_emits_a_versioned_admission_outcome() {
        let model = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("Cargo.toml");
        let cli = Cli {
            profile: Some(ExecutionProfile::Balanced),
            packet_frames: Some(PacketFrames::Four),
            math_mode: Some(MathMode::Strict),
            voice_pack: Some(VoicePackProfile::Portable),
            normalize: Some(NormalizeMode::Conservative),
            trace: None,
            seed: Some(7),
            command: Command::Robot(RobotArgs {
                command: RobotCommand::Health,
            }),
        };
        let args = SayArgs {
            text: Some("checked text".to_owned()),
            output_positional: None,
            file: None,
            model: Some(model),
            voice: None,
            output: None,
            stream: None,
            check: true,
            robot: false,
            no_resident: true,
        };
        let mut stdin = Cursor::new(Vec::<u8>::new());
        let mut stdout = Vec::new();
        let mut stderr = Vec::new();

        run_say(
            &cli,
            &args,
            &Environment::default(),
            &mut stdin,
            &mut stdout,
            &mut stderr,
            IoCapabilities::default(),
        )
        .expect("check path");

        assert!(stderr.is_empty());
        let text = String::from_utf8(stdout).expect("utf-8 events");

        // The whole emitted stream must conform, not just the event this test cares about.
        assert!(
            robot::validate_ndjson(&text).is_empty(),
            "emitted stream violates the contract: {:?}",
            robot::validate_ndjson(&text)
        );

        let events: Vec<Value> = text
            .lines()
            .map(|line| serde_json::from_str(line).expect("one JSON object per line"))
            .collect();
        let names: Vec<&str> = events
            .iter()
            .map(|event| event["event"].as_str().expect("event name"))
            .collect();
        assert_eq!(
            names,
            vec![
                "run_start",
                "stage",
                "stage",
                "text_prepared",
                "stage",
                "stage",
                "check_complete",
                "run_complete",
            ],
            "the skeleton lifecycle must flow end-to-end on the empty pipeline"
        );

        // Every event in a run repeats the same run_id, which is what lets an agent stitch a run
        // together across the two streams.
        let run_id = events[0]["run_id"]
            .as_str()
            .expect("run_start carries run_id");
        assert!(!run_id.is_empty());
        assert!(events.iter().all(|event| event["run_id"] == run_id));
        assert!(
            events
                .iter()
                .all(|event| event["schema_version"] == ROBOT_SCHEMA_VERSION)
        );

        // Stage sequence numbers are dense and ordered, so a consumer can detect a dropped event.
        let seqs: Vec<u64> = events
            .iter()
            .filter(|event| event["event"] == "stage")
            .map(|event| event["seq"].as_u64().expect("seq"))
            .collect();
        assert_eq!(seqs, vec![0, 1, 2, 3]);

        let check = &events[6];
        // "accepted", not "scaffold_accepted": the preflight is now the engine's own
        // ftts_core::admission computation rather than a CLI-local heuristic, so `--check` and the
        // synthesis that follows it cannot reach different verdicts for the same request.
        assert_eq!(check["admission"]["status"], "accepted");
        assert!(
            check["admission"]["predicted_peak_bytes"].is_u64(),
            "the engine-backed plan reports a real predicted peak"
        );
        assert_eq!(check["normalization_trace_requested"], false);

        // text_prepared reports shape and provenance only; the input text must never appear.
        let prepared = &events[3];
        assert_eq!(prepared["char_count"], "checked text".chars().count());
        assert!(prepared["unicode_version"].is_string());
        assert!(
            !text.contains("checked text"),
            "the event stream must not carry the user's text"
        );

        assert_eq!(events[7]["exit_code"], 0);
    }

    #[test]
    fn a_newline_inside_a_field_cannot_break_ndjson_framing() {
        // The entire contract rests on one JSON object per line. serde_json escapes control
        // characters, so a message containing a newline stays one line and the newline survives as
        // data -- but nothing pinned that until now, and a hand-rolled serializer or a raw write
        // path would silently break every downstream parser.
        let run = robot::RunContext::with_id("r-test");
        let error = FttsError::Generic("first\nsecond".to_owned());
        let mut event = run.event(robot::EventType::RunError);
        event.insert("exit_code".to_owned(), json!(error.exit_code().as_u8()));
        event.insert("kind".to_owned(), json!(error.exit_code().description()));
        event.insert("message".to_owned(), json!(error.to_string()));
        event.insert("remediation".to_owned(), json!(error.remediation()));
        event.insert("elapsed_ms".to_owned(), json!(0));
        let value = Value::Object(event);

        let mut buffer = Vec::new();
        write_json_line(&mut buffer, &value).expect("serializes");
        let text = String::from_utf8(buffer).expect("utf-8");

        assert_eq!(
            text.lines().count(),
            1,
            "framing broken by an embedded newline"
        );
        assert!(robot::validate_ndjson(&text).is_empty());
        let parsed: Value = serde_json::from_str(text.trim_end()).expect("still one object");
        assert!(
            parsed["message"].as_str().expect("message").contains('\n'),
            "the newline must survive as data, not be stripped"
        );
    }

    #[test]
    fn pinned_copies_match_the_truth_pack_canonicals() {
        //  `pinned/` exists because `cargo package` cannot ship the truth pack. The truth pack
        //  stays canonical; a drifted copy would embed a stale pin assertion or attribution in
        //  the shipped binary, so byte-identity is asserted whenever the repo checkout is present.
        let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        for (canonical, embedded, name) in [
            (
                "docs/truth-pack/TENSOR_INVENTORY.json",
                PINNED_TENSOR_INVENTORY,
                "TENSOR_INVENTORY.json",
            ),
            (
                "docs/truth-pack/snapshots/hf/config.json",
                PINNED_MODEL_CONFIG,
                "model_config.json",
            ),
            (
                "docs/truth-pack/snapshots/gh/LICENSE",
                APACHE_LICENSE,
                "QWEN_APACHE_LICENSE",
            ),
        ] {
            match std::fs::read_to_string(root.join(canonical)) {
                Ok(bytes) => assert_eq!(
                    bytes, embedded,
                    "pinned/{name} drifted from {canonical}; re-copy it"
                ),
                Err(_) => eprintln!(
                    "SKIP pinned-copy check for {name}: {canonical} absent (no repo checkout)"
                ),
            }
        }
    }

    #[test]
    fn embedded_model_manifest_is_wellformed_and_agrees_with_the_converter_pin() {
        let manifest = ModelManifest::embedded().expect("embedded manifest parses");
        assert_eq!(manifest.model_id, "qwen3-tts-12hz-0.6b-base");
        assert_eq!(manifest.release_tag, "model-qwen3-tts-v1");
        assert_eq!(manifest.repo, "Dicklesworthstone/franken_tts");
        assert_eq!(manifest.files.len(), 8);

        for file in &manifest.files {
            assert!(
                is_sha256_hex(&file.sha256),
                "{} carries a malformed digest",
                file.asset
            );
            assert!(file.bytes > 0, "{} has no pinned size", file.asset);
            let dest = Path::new(&file.dest);
            assert!(!dest.is_absolute(), "{} dest is absolute", file.asset);
            assert!(
                dest.components()
                    .all(|component| matches!(component, std::path::Component::Normal(_))),
                "{} dest can traverse out of the model directory",
                file.asset
            );
        }

        // Since frankentts-zm5 the pull ships the canonical quantized artifact, not the raw main
        // checkpoint: enrollment and synthesis both hydrate from the .fttsq, so pulling the raw
        // 1.7 GB main would be pure waste. The artifact lands at the exact basename every model
        // search path probes for.
        let main = manifest
            .files
            .iter()
            .find(|file| file.dest == MODEL_BASENAME)
            .expect("manifest carries the canonical artifact");
        assert_eq!(
            manifest.download_urls(main),
            [
                "https://huggingface.co/Dicklesworthstone/franken-tts-qwen3-tts-12hz-0.6b-base/resolve/main/qwen3-tts-12hz-0.6b-base.fttsq",
                "https://github.com/Dicklesworthstone/franken_tts/releases/download/model-qwen3-tts-v1/qwen3-tts-12hz-0.6b-base.fttsq",
            ]
        );
        assert!(
            !manifest
                .files
                .iter()
                .any(|file| file.dest == PINNED_MAIN_WEIGHTS_FILENAME),
            "pull must not fetch the raw main checkpoint alongside the canonical artifact"
        );

        // Together the files are exactly what ModelBundle::resolve requires plus the two config
        // sidecars, so a completed pull always resolves.
        let dests: Vec<&str> = manifest
            .files
            .iter()
            .map(|file| file.dest.as_str())
            .collect();
        for required in [
            MODEL_BASENAME,
            "speech_tokenizer/model.safetensors",
            "vocab.json",
            "merges.txt",
            "tokenizer_config.json",
        ] {
            assert!(dests.contains(&required), "manifest is missing {required}");
        }
    }

    #[test]
    fn malformed_model_manifests_are_refused_with_the_field_named() {
        fn manifest_with(
            schema_version: u64,
            asset: &str,
            dest: &str,
            sha256: &str,
            bytes: u64,
        ) -> String {
            json!({
                "schema_version": schema_version,
                "model_id": "m",
                "release_tag": "t",
                "repo": "owner/repo",
                "files": [{"asset": asset, "dest": dest, "sha256": sha256, "bytes": bytes}],
            })
            .to_string()
        }
        let good_sha = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

        // The happy shape parses, so every refusal below is attributable to its one bad field.
        ModelManifest::parse(&manifest_with(1, "a.bin", "a.bin", good_sha, 1))
            .expect("well-formed manifest parses");

        for (label, text) in [
            (
                "unsupported schema_version",
                manifest_with(2, "a.bin", "a.bin", good_sha, 1),
            ),
            (
                "short sha256",
                manifest_with(1, "a.bin", "a.bin", "abc123", 1),
            ),
            (
                "uppercase sha256",
                manifest_with(1, "a.bin", "a.bin", &good_sha.to_uppercase(), 1),
            ),
            (
                "zero bytes",
                manifest_with(1, "a.bin", "a.bin", good_sha, 0),
            ),
            (
                "absolute dest",
                manifest_with(1, "a.bin", "/etc/passwd", good_sha, 1),
            ),
            (
                "traversal dest",
                manifest_with(1, "a.bin", "../escape.bin", good_sha, 1),
            ),
            (
                "asset with a path separator",
                manifest_with(1, "dir/a.bin", "a.bin", good_sha, 1),
            ),
            (
                "empty files array",
                json!({
                    "schema_version": 1,
                    "model_id": "m",
                    "release_tag": "t",
                    "repo": "owner/repo",
                    "files": [],
                })
                .to_string(),
            ),
        ] {
            let error = ModelManifest::parse(&text)
                .expect_err(&format!("a manifest with {label} must be refused"));
            assert_eq!(error.exit_code(), FttsExitCode::ArtifactFormat, "{label}");
        }
    }

    #[test]
    fn pull_skips_only_a_file_matching_both_pinned_size_and_digest() {
        let dir = std::env::temp_dir().join(format!("ftts-pull-decision-{}", std::process::id()));
        fs::create_dir_all(&dir).expect("temp dir");
        let payload = b"pinned payload";
        let file = ModelManifestFile {
            asset: "a.bin".to_owned(),
            dest: "a.bin".to_owned(),
            sha256: ftts_artifacts::sha256::hex_digest(payload),
            bytes: payload.len() as u64,
        };
        let dest = dir.join("a.bin");

        let _ = fs::remove_file(&dest);
        assert_eq!(
            pull_decision(&dest, &file, false),
            PullDecision::Download,
            "absent file must download"
        );

        fs::write(&dest, payload).expect("write verified payload");
        assert_eq!(
            pull_decision(&dest, &file, false),
            PullDecision::Skip,
            "matching size and digest must skip"
        );
        assert_eq!(
            pull_decision(&dest, &file, true),
            PullDecision::Download,
            "--force must re-download even a verified file"
        );

        fs::write(&dest, b"pinned_payload").expect("write same-length corruption");
        assert_eq!(
            pull_decision(&dest, &file, false),
            PullDecision::Download,
            "a same-length corruption must be caught by the digest"
        );

        fs::write(&dest, b"short").expect("write truncation");
        assert_eq!(
            pull_decision(&dest, &file, false),
            PullDecision::Download,
            "a truncated file must be caught by the size check"
        );
    }

    #[test]
    fn model_resolution_prefers_explicit_then_searched_then_the_pull_directory() {
        let root = std::env::temp_dir().join(format!("ftts-resolve-order-{}", std::process::id()));

        // A complete bundle directory: ModelBundle::resolve only asks `is_file`, so empty files
        // are a sufficient fake (and would fail loudly if the resolver ever started reading).
        let bundle = root.join("bundle");
        for relative in [
            "model.safetensors",
            "speech_tokenizer/model.safetensors",
            "vocab.json",
            "merges.txt",
            "tokenizer_config.json",
        ] {
            let path = bundle.join(relative);
            fs::create_dir_all(path.parent().expect("bundle parent")).expect("bundle dirs");
            fs::write(&path, b"").expect("bundle file");
        }
        assert!(
            synth::ModelBundle::resolve(&bundle).is_ok(),
            "five empty files must satisfy the resolver's is_file checks"
        );

        let searched_artifact = root.join("searched").join(MODEL_BASENAME);
        fs::create_dir_all(searched_artifact.parent().expect("searched parent"))
            .expect("searched dir");
        fs::write(&searched_artifact, b"").expect("searched artifact");
        let searched = vec![searched_artifact.clone()];
        let absent = vec![root.join("absent").join(MODEL_BASENAME)];

        // 1. `--model` outranks everything.
        assert_eq!(
            resolve_model_from(Some(&bundle), &searched, Some(&bundle)).expect("explicit"),
            bundle.display().to_string()
        );

        // 2. A searched artifact outranks the pull directory.
        assert_eq!(
            resolve_model_from(None, &searched, Some(&bundle)).expect("searched"),
            searched_artifact.display().to_string()
        );

        // 3. The pull directory resolves when nothing searched exists.
        assert_eq!(
            resolve_model_from(None, &absent, Some(&bundle)).expect("pull fallback"),
            bundle.display().to_string()
        );

        // 4. An incomplete pull directory does not resolve, and the error teaches `ftts pull`.
        let incomplete = root.join("incomplete");
        fs::create_dir_all(&incomplete).expect("incomplete dir");
        let error = resolve_model_from(None, &absent, Some(&incomplete))
            .expect_err("an empty pull directory must not resolve");
        assert_eq!(error.exit_code(), FttsExitCode::ModelNotFound);
        assert!(error.to_string().contains("ftts pull"), "{error}");
        assert!(error.to_string().contains("2.0 GB"), "{error}");
        assert!(error.to_string().contains("FTTS_MODEL_DIR"), "{error}");
    }

    #[test]
    fn the_pull_directory_default_prefers_the_env_override() {
        let mut environment = Environment::default();
        environment
            .values
            .insert("FTTS_MODEL_DIR", Some(OsString::from("/tmp/env-model-dir")));
        assert_eq!(
            default_pull_model_dir(&environment),
            Some(PathBuf::from("/tmp/env-model-dir"))
        );

        // Without the override the default lives under $HOME; the exact suffix is the contract
        // `ftts pull` and model resolution share.
        if std::env::var_os("HOME").is_some() {
            let fallback = default_pull_model_dir(&Environment::default())
                .expect("HOME is set, so a default exists");
            assert!(
                fallback.ends_with(DEFAULT_MODEL_CACHE_SUBDIR),
                "{fallback:?}"
            );
        }
    }

    /// Two-strike semantics: the first signal cancels cooperatively, every later one
    /// is a force-exit — the state machine the ctrlc hook runs.
    #[test]
    fn first_signal_trips_and_later_signals_force_exit() {
        assert_eq!(next_strike_action(0), StrikeAction::Trip);
        assert_eq!(next_strike_action(1), StrikeAction::Trip);
        assert_eq!(next_strike_action(2), StrikeAction::ForceExit);
        assert_eq!(next_strike_action(9), StrikeAction::ForceExit);
    }

    /// The handler-trip path without an OS signal: tripping the shared token through
    /// the same routine the hook calls must flip both the flag and the engine token,
    /// which is what `was_tripped` reports to the run's error paths.
    #[test]
    fn trip_active_cancel_marks_the_state_and_token() {
        let cancel = std::sync::Arc::new(CancelState::new());
        assert!(!cancel.was_tripped(), "fresh state starts untripped");

        // Install as the served run, then trip exactly as the signal hook would.
        *ACTIVE_CANCEL.lock().expect("lock") = Some(cancel.clone());
        cancel.token.cancel();
        trip_active_cancel();

        assert!(cancel.tripped.load(std::sync::atomic::Ordering::Relaxed));
        assert!(cancel.was_tripped(), "both routes must report tripped");
        // Restore so other tests never observe this state.
        *ACTIVE_CANCEL.lock().expect("lock") = None;
    }

    /// The disposition wording per sink kind: file sinks name the kept artifact,
    /// compressed targets state the skipped encoding and staging path, raw streams
    /// report streamed bytes. These messages ride the EXISTING run_error.message
    /// field — no new event vocabulary anywhere.
    #[test]
    fn cancelled_dispositions_name_what_happened_to_the_audio() {
        let scratch = std::env::temp_dir().join(format!(
            "ftts-cancel-disposition-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_nanos())
        ));
        std::fs::create_dir_all(&scratch).expect("scratch dir");

        // WAV: partial file finalized at the requested path.
        let wav_plan = OutputPlan::for_path(&scratch.join("out.wav")).expect("wav plan");
        let audio = AudioOutput::wav(&wav_plan.wav_path).expect("wav sink");
        let error = cancelled_run_disposition(audio, Some(&wav_plan));
        assert_eq!(error.exit_code(), FttsExitCode::Cancelled);
        assert!(error.to_string().contains("partial WAV kept at"), "{error}");
        assert!(error.to_string().contains("out.wav"), "{error}");

        // Compressed: encoding skipped, staging WAV named.
        let m4a_plan = OutputPlan::for_path(&scratch.join("out.m4a")).expect("m4a plan");
        assert_eq!(
            m4a_plan.format,
            OutputFormat::M4a,
            "extension selects the compressed arm"
        );
        assert!(
            m4a_plan
                .wav_path
                .to_string_lossy()
                .ends_with(".ftts-staging.wav")
        );
        let audio = AudioOutput::wav(&m4a_plan.wav_path).expect("staging sink");
        let error = cancelled_run_disposition(audio, Some(&m4a_plan));
        assert!(error.to_string().contains("encoding to"), "{error}");
        assert!(error.to_string().contains("skipped"), "{error}");
        assert!(error.to_string().contains(".ftts-staging.wav"), "{error}");

        // Raw: no artifact exists; the byte count is the receipt.
        let audio = AudioOutput::raw();
        let error = cancelled_run_disposition(audio, None);
        assert!(
            error.to_string().contains("streaming 0 raw PCM bytes"),
            "{error}"
        );

        // A zero-packet WAV run still leaves a parseable (header-only) file behind.
        let empty_plan = OutputPlan::for_path(&scratch.join("empty.wav")).expect("plan");
        let audio = AudioOutput::wav(&empty_plan.wav_path).expect("sink");
        let _ = cancelled_run_disposition(audio, Some(&empty_plan));
        let header = std::fs::read(&empty_plan.final_path).expect("finalized wav");
        assert!(header.len() >= 44, "RIFF header present: {}", header.len());
        assert_eq!(&header[..4], b"RIFF", "must be a parseable RIFF file");
    }

    #[test]
    fn voice_inspect_renders_a_real_pack_through_dispatch() {
        let dir = std::env::temp_dir().join(format!(
            "ftts-inspect-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("clock")
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let embedding: Vec<f32> = (0..1024).map(|i| i as f32 * 0.001).collect();
        let pack = ftts_artifacts::voice::VoicePack {
            profile: ftts_artifacts::voice::VoiceProfile::Portable,
            consent: ftts_artifacts::voice::ConsentAttestation {
                attested: true,
                method: ftts_artifacts::voice::ConsentMethod::Flag,
            },
            language: Some("en".to_owned()),
            transcript: Some("Please call Stella.".to_owned()),
            speech_regions: vec![(0, 24_000)],
            diagnostics: None,
            preprocessing: None,
            provenance: Default::default(),
            embedding,
            codec_codes: Some(vec![7, 9]),
            reference_audio: None,
            section_digests: Default::default(),
        };
        let bytes = ftts_artifacts::voice::serialize_voice_pack(&pack).expect("serialize pack");
        let path = dir.join("inspect.ftvoice");
        std::fs::write(&path, &bytes).expect("write pack");

        let cli = Cli::parse_from([
            "ftts",
            "voice",
            "inspect",
            path.to_str().expect("utf-8 path"),
        ]);
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut stdin: &[u8] = &[];
        dispatch(
            cli,
            environment(),
            &mut stdin,
            &mut stdout,
            &mut stderr,
            IoCapabilities::default(),
        )
        .expect("inspect succeeds");
        let text = String::from_utf8(stdout).expect("utf-8 output");
        let event_line = text.lines().last().expect("at least one output line");
        let event: serde_json::Value = serde_json::from_str(event_line).expect("json event");
        assert_eq!(event["event"], "voice_inspect");
        assert_eq!(event["status"], "ok");
        assert_eq!(event["profile"], "portable");
        assert_eq!(event["consent_attested"], true);
        assert_eq!(event["consent_method"], "flag");
        assert_eq!(event["transcript_present"], true);
        assert_eq!(event["codec_codes_present"], true);
        assert_eq!(event["reference_audio_present"], false);
        assert!(
            event["recipe_hash"].as_str().is_some_and(|h| h.len() == 64),
            "recipe hash must be a sha256 hex digest"
        );
    }

    #[test]
    fn voice_inspect_reports_legacy_speaker_vectors() {
        let dir = std::env::temp_dir().join(format!("ftts-inspect-spk-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("temp dir");
        let path = dir.join("legacy.spk");
        let vector: Vec<u8> = (0..synth::SPEAKER_VECTOR_BYTES)
            .map(|i| (i % 251) as u8)
            .collect();
        // A finite f32 vector, not arbitrary noise: encode like the enrollment writer.
        let mut bytes = Vec::with_capacity(synth::SPEAKER_VECTOR_BYTES);
        for i in 0..1024usize {
            bytes.extend_from_slice(&(i as f32 * 0.001).to_le_bytes());
        }
        drop(vector);
        std::fs::write(&path, &bytes).expect("write vector");

        let cli = Cli::parse_from([
            "ftts",
            "voice",
            "inspect",
            path.to_str().expect("utf-8 path"),
        ]);
        let mut stdout: Vec<u8> = Vec::new();
        let mut stderr: Vec<u8> = Vec::new();
        let mut stdin: &[u8] = &[];
        dispatch(
            cli,
            environment(),
            &mut stdin,
            &mut stdout,
            &mut stderr,
            IoCapabilities::default(),
        )
        .expect("inspect of a legacy vector still succeeds");
        let text = String::from_utf8(stdout).expect("utf-8 output");
        let event: serde_json::Value =
            serde_json::from_str(text.lines().last().expect("line")).expect("json");
        assert_eq!(event["status"], "legacy_speaker_vector");
    }

    #[test]
    fn enroll_mode_resolution_follows_the_documented_policy() {
        use EnrollMode::*;
        // QUALITY demands a transcript; without one it refuses to pretend.
        assert_eq!(
            resolve_enroll_mode(Quality, Some("Please call Stella.")),
            ResolvedEnrollMode::Quality
        );
        let missing = resolve_enroll_mode(Quality, None);
        assert!(matches!(missing, ResolvedEnrollMode::Quick { .. }));
        // Blank transcripts are not transcripts.
        assert!(matches!(
            resolve_enroll_mode(Auto, Some("   ")),
            ResolvedEnrollMode::Quick { .. }
        ));
        // AUTO degrades loudly; explicit QUICK never upgrades silently.
        assert!(matches!(
            resolve_enroll_mode(Auto, None),
            ResolvedEnrollMode::Quick { .. }
        ));
        assert!(matches!(
            resolve_enroll_mode(Quick, Some("words")),
            ResolvedEnrollMode::Quick { .. }
        ));
        assert_eq!(
            resolve_enroll_mode(Quality, Some("Please call Stella.")),
            ResolvedEnrollMode::Quality
        );
    }

    #[test]
    fn unusable_references_name_their_reason() {
        let silent = crate::diagnostics::AudioDiagnostics {
            clipping_fraction: 0.0,
            longest_clip_run: 0,
            intersample_overshoot_db: 0.0,
            snr_estimate_db: None,
            pause_floor_dbfs: -120.0,
            reverb_time_s: None,
            music_bed_likelihood: 0.0,
            stationarity_drift: 0.0,
            loudness_rms_dbfs: -120.0,
            voice_activity_ratio: 0.0,
        };
        let reason = unusable_reference_reason(&silent, 48_000).expect("silent is unusable");
        assert!(reason.contains("no speech"), "{reason}");
        assert!(unusable_reference_reason(&silent, 0).is_some());
        let healthy = crate::diagnostics::AudioDiagnostics {
            voice_activity_ratio: 0.8,
            ..silent
        };
        assert!(unusable_reference_reason(&healthy, 48_000).is_none());
    }

    #[test]
    fn quick_pack_roundtrips_and_quality_pack_carries_identity() {
        let embedding: Vec<f32> = (0..1024).map(|i| i as f32 * 0.001).collect();
        let dx = ftts_artifacts::voice::EnrollmentDiagnostics {
            clipping_fraction: 0.0,
            longest_clip_run: 0,
            intersample_overshoot_db: 0.2,
            snr_estimate_db: Some(30.0),
            pause_floor_dbfs: -55.0,
            reverb_time_s: Some(0.3),
            music_bed_likelihood: 0.01,
            stationarity_drift: 0.1,
            loudness_rms_dbfs: -20.0,
            voice_activity_ratio: 0.9,
        };
        let quick = assemble_enrollment_pack(AssemblePackInput {
            profile: ftts_artifacts::voice::VoiceProfile::Private,
            consent: ftts_artifacts::voice::ConsentAttestation {
                attested: true,
                method: ftts_artifacts::voice::ConsentMethod::Flag,
            },
            transcript: None,
            speech_regions: vec![(0, 24_000)],
            diagnostics: dx.clone(),
            preprocessing: ftts_artifacts::voice::PreprocessingRecipe {
                target_sample_rate_hz: 24_000,
                resampler: "lanczos6".to_owned(),
                denoise: None,
                dereverb: None,
            },
            provenance: Default::default(),
            embedding: embedding.clone(),
            codec_codes: None,
        });
        assert_eq!(quick.profile.as_str(), "private");
        let parsed = parse_pack_ok(&quick);
        assert!(parsed.transcript.is_none());

        let quality = assemble_enrollment_pack(AssemblePackInput {
            profile: ftts_artifacts::voice::VoiceProfile::Portable,
            transcript: Some("Please call Stella.".to_owned()),
            codec_codes: Some(vec![3, 1, 4]),
            ..AssemblePackInput {
                profile: quick.profile,
                consent: quick.consent,
                transcript: None,
                speech_regions: quick.speech_regions.clone(),
                diagnostics: dx,
                preprocessing: quick.preprocessing.clone().unwrap(),
                provenance: Default::default(),
                embedding,
                codec_codes: None,
            }
        });
        let parsed_q = parse_pack_ok(&quality);
        assert_eq!(parsed_q.transcript.as_deref(), Some("Please call Stella."));
        assert_eq!(parsed_q.codec_codes.as_deref(), Some(&[3u32, 1, 4][..]));
        assert_eq!(parsed_q.profile.as_str(), "portable");
    }

    fn parse_pack_ok(pack: &ftts_artifacts::voice::VoicePack) -> ftts_artifacts::voice::VoicePack {
        let bytes = ftts_artifacts::voice::serialize_voice_pack(pack)
            .map_err(|e| e.to_string())
            .expect("serialize");
        ftts_artifacts::voice::parse_voice_pack(&bytes)
            .map_err(|e| e.to_string())
            .expect("parse")
    }

    #[test]
    fn pack_writers_stage_and_back_up_without_replacing_the_extension() {
        let dir = std::env::temp_dir().join(format!("enroll-writer-{}", std::process::id()));
        std::fs::create_dir_all(&dir).expect("dir");
        let path = dir.join("w.ftvoice");
        write_voice_pack_new(&path, b"first").expect("first write");
        let backup = replace_voice_pack(&path, b"second").expect("replace");
        assert_eq!(backup, dir.join("w.ftvoice.bak"));
        assert_eq!(std::fs::read(&backup).unwrap(), b"first");
        assert_eq!(std::fs::read(&path).unwrap(), b"second");
        // No partial staging files left behind.
        assert!(!dir.join("w.ftvoice.partial").exists());
    }

    #[test]
    fn doctor_reports_expected_json_and_human_format() {
        let environment = Environment {
            values: BTreeMap::new(),
            stage_budget_values: BTreeMap::new(),
        };

        // JSON mode
        let mut json_out = Vec::new();
        let args_json = DoctorArgs { json: true };
        run_doctor(&args_json, &environment, &mut json_out).expect("run_doctor json");
        let report: Value = serde_json::from_slice(&json_out).expect("valid json");
        assert_eq!(report["schema_version"], ROBOT_SCHEMA_VERSION);
        assert_eq!(report["stateless_default"], true);
        assert_eq!(report["persistent_history"], false);

        // Human mode
        let mut text_out = Vec::new();
        let args_text = DoctorArgs { json: false };
        run_doctor(&args_text, &environment, &mut text_out).expect("run_doctor text");
        let text_str = String::from_utf8(text_out).expect("valid utf8");
        assert!(text_str.contains("FrankenTTS ftts — local readiness"));
        assert!(text_str.contains("stateless default: yes"));
    }
}