newt-tui 0.8.0

Newt-Agent TUI surfaces (ratatui): code mode + pilot mode
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
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
//! Newt-Agent TUI — a lean chat + agentic-coding TUI in the spirit of Codex /
//! Claude Code, deliberately scoped to *chat and agentic coding* (not as
//! feature-rich). Splash + chat REPL + slash commands + ocap-gated tool use.
//! NOT a settings UI: configuration is plain `~/.newt/config.toml`
//! (see `newt config`). Additional features and the multi-agent matrix live in
//! the downstream `gilamonster-agent`, which inherits these crates.
//!
//! Model: GPT-5 | Harness: Codex | Operator: Shawn Hartsock | Time: 16:53 EDT | Date: 2026-08-12

mod auth_command;
mod brand;
mod chat;
mod codex_env;
mod color;
mod context_window;
mod crew_form;
mod help;
#[cfg(feature = "rich-tui")]
mod inference_panel;
mod migration_notices;
mod navigator_cmds;
mod session_capability;
mod workspace_launch;
mod workspace_settings;
pub use workspace_launch::{
    resolve_code_workspace, workspace_protection_for_diagnostics, CodeWorkspace,
};
// `chat.rs` establishes and reapplies the session capability, and
// lib_tests/caveat_policy_tests.rs covers it beside `policy_for`, which stays
// here — so this is a named re-export rather than a moved test module.
pub(crate) use session_capability::SessionCapability;
// `newt auth`'s driver. Re-exported, not moved out of the public API:
// newt-cli calls `newt_tui::run_auth`, so the path must not change.
pub use auth_command::run_auth;
// Only `lib.rs` itself calls these (`resolve_backend_choice`); nothing else in
// the crate does, so this is a private import rather than a re-export.
use codex_env::{codex_env_allowed, codex_env_backend};
mod turn_input;
// `with_live_spill_watch` (both cfg arms) and `with_interrupt_watch` are the
// only two the rest of the crate calls from non-test code: chat.rs,
// commands/model.rs and interrupt_ack_pty_test.rs. Both exist in EVERY config,
// so this needs no cfg. Named, not a glob.
pub(crate) use turn_input::{with_interrupt_watch, with_live_spill_watch};
mod roadmap_cmds;
// Crate-internal consumers of the roadmap family: `chat.rs`'s `/roadmap` arm.
// The test-only names are imported by `lib_tests/skills_integration.rs`
// directly, so no re-export here is dead in a non-test build. Named, not a glob.
pub(crate) use roadmap_cmds::{
    autocapture_commit_after_turn, git_head_short, handle_roadmap_command, roadmap_subcommand_reads,
};
mod persona_route;
mod preference_pins;
// Seven items, all with production consumers outside this file:
// tab_switch.rs, tabs.rs and chat.rs. lib_tests/resumed_preference_tests.rs
// stays declared here — it is 804 lines and covers refresh_backend, Persona
// and resolve_backend_choice too, so it is not this family's alone.
pub(crate) use preference_pins::{
    apply_startup_preference_pin, restore_preference_pin, ConversationPreferenceSwitch,
    PinDegraded, PinRestore, PreferenceBaseline, StartupConversation,
};
// `chat.rs` applies a persona's backend route. `persona_backend_route` left
// this re-export with #2161-era preference_pins: its one caller,
// `restore_preference_pin`, now names the module directly.
pub(crate) use persona_route::apply_persona_backend;
// Danger-tiering for permission grants (facade P1b, §7-F3/F4): pure-data
// classification of a `(capability, target)` grant into a `DangerTier`, read by
// the permission prompt to show a system-computed blast-radius line and refuse a
// plain `[s]ession allow` for high-danger targets.
mod commands;
#[cfg(feature = "live-spill")]
mod completed_spill;
mod danger;
pub mod dgx_probe;
/// #2085 PR-E2: where a non-setting state mutator's journal event is named,
/// and the registry gate that decides whether it may be written at all.
mod event_receipt;
pub mod herdr;
/// #1950: the ONE inline-viewport constructor, and the one answer to "where is
/// the cursor?" when the terminal will not say.
#[cfg(feature = "rich-tui")]
mod inline_viewport;
// C2 (#1876): the RichTUI renderer for one interaction. Rich-only — the pure
// view model it draws lives in `newt_core::interaction_view`, where ratatui is
// not a dependency, so "no renderer in the model" is a compile error.
#[cfg(feature = "rich-tui")]
mod interaction_view;
// #2524 item 7: the RichTUI free-text modal for a pending clarification
// batch — a small purpose-built reader beside `interaction_view`'s
// choice-list modal, for the reason its own module doc gives.
#[cfg(feature = "rich-tui")]
mod clarification_modal;
/// C2 (#1876) — the PTY acceptance proof that the inline INTERACTION frame
/// hands the terminal back on every exit path: clean close, panic, and error
/// return. Same tier and same reasoning as the pager's, and it additionally
/// pins that this surface never enters the alternate screen, which the
/// plain-scroller carve-out does not permit during a turn.
#[cfg(all(test, unix, feature = "rich-tui"))]
mod interaction_view_pty_test;
#[cfg(feature = "live-spill")]
mod live_spill;
/// #1889 — the PTY acceptance proof that the operator PANELS hand the
/// terminal back (cooked mode) on every exit path, panic included. Same tier
/// and same reasoning as `interaction_view_pty_test`, which it is modelled on:
/// a Drop-on-unwind restoration cannot be observed from inside the process
/// doing the unwinding.
#[cfg(all(test, unix, feature = "rich-tui"))]
mod panel_raw_mode_pty_test;
mod permissions;
mod prompt;
/// §6.5 — the PTY regression proof that a permission prompt stays VISIBLE when
/// the harness blocks on a human. Its own file because it needs crate-private
/// access to the production gate + prompt reader, and its own tier because it
/// needs a real terminal to observe a terminal property. See the module docs.
#[cfg(all(test, unix))]
mod prompt_visibility_test;
// #2010: press-time acknowledgement on a real terminal — every Ctrl-C (1st,
// 2nd, Nth) changes the rendered grid WHILE the turn is still blocked. Same
// self-re-exec tier as `prompt_visibility_test`; not `#[ignore]`d, because the
// assertion is structural ("on screen while still running"), not a stopwatch.
#[cfg(all(test, unix))]
mod interrupt_ack_pty_test;
#[cfg(any(feature = "rich-tui", feature = "live-spill"))]
mod scrollbar;
/// #1981: the ONE list of top-level slash commands. Three lists knew this
/// before and none agreed; see the module doc.
/// #1981: `/settings` — the typed form the knob verbs are absorbed into.
mod settings_form;
/// #2002 — the PTY acceptance that WORKS the `/settings` form end to end:
/// menu rendered on the grid, a field picked by number, a value applied, and
/// the receipt read back off disk. Same tier and same reasoning as its
/// siblings above; it grounds the mocked `settings_form` unit tests.
#[cfg(all(test, unix, feature = "rich-tui"))]
mod settings_form_pty_test;
#[cfg(feature = "rich-tui")]
mod shell;
mod slash_registry;
#[cfg(feature = "live-spill")]
mod spill_view;
mod status_topics;
/// #1669 PR-A — the staged tab switch and the one tab-action handler, against
/// live session state. Separate from the pure model so the staging discipline
/// (Stage-0 read, deactivate, hydrate, reset⊕overlay, owner handoff) reads in
/// one place instead of inside `run_chat`.
mod tab_switch;
/// #1669 PR-A — the pure session-tab model. TTY-free and unit-tested on its
/// own; `chat.rs` performs the staged switch and the lifecycle owner handoff
/// this module only reports.
mod tabs;
/// #1677 — the PTY acceptance proof that the transcript pager hands the
/// terminal back (cooked mode + primary screen) on every exit path, including
/// a panic. Same tier and same reasoning as `prompt_visibility_test`: a
/// terminal property can only be observed on a terminal. Rich-only, because
/// the surface it proves exists only there.
#[cfg(all(test, unix, feature = "rich-tui"))]
mod transcript_pager_pty_test;
// #1670: the transcript view. The module splits along the charter boundary —
// the PURE row model (stored turns → styled rows) is always compiled and
// always tested, while the terminal half (alt-screen + raw mode + ratatui
// draw loop) is COMPILE-gated to `rich-tui` inside the module. That gate is
// mechanical, not merely runtime: `ratatui`/`crossterm` are non-optional deps
// of this crate, so without it a lean binary would carry an alt-screen
// surface it can never legitimately enter — the boundary erosion
// `plain_scroller_tui.md` forbids. Dependency direction, deliberately:
// durable conversation model → transcript view model → RichTUI pager.
//
// On LEAN the view model has no consumer (lean answers `/transcript` with the
// existing plain `conversation_show_message` spine), so it is dead code there
// — deliberately. It stays compiled so its pure row/fold/scroll tests run in
// the DEFAULT `cargo test`, the configuration the lean CI lane and most
// contributors actually execute; gating the whole module would silently drop
// that correctness suite from the default gate. The allowance is scoped to the
// lean config alone, so genuinely-unused code in a rich build still fails the
// zero-warnings policy.
#[cfg_attr(not(feature = "rich-tui"), allow(dead_code))]
mod transcript_pager;
mod type_ahead;
// OSC 8 terminal hyperlinks — clickable URLs in modern terminals (issue #771).
mod mcp;
#[cfg(feature = "rich-tui")]
mod mcp_manager;
#[cfg(feature = "rich-tui")]
mod mcp_panel;
mod mcp_token;
pub mod probe;
pub mod terminal_hyperlink;
mod window_discovery;
mod workspace_state;
// The TTY rich inline input surface (issue #416). Feature-gated so the default
// and headless/wyvern builds never compile it in — newt stays amphibious.
#[cfg(feature = "rich-tui")]
mod rich_input;
/// #1898 — the PTY acceptance proof that a rich TURN hands back BOTH raw mode
/// and bracketed paste on every exit path, panic included. #1411 had recorded
/// this site as safe; it was safe against the error path only.
#[cfg(all(test, unix, feature = "rich-tui"))]
mod rich_input_pty_test;
// The harness config panel (#14) — a severable, TTY-only overlay for the psyche
// operator dials. Gated with the other rich TTY surfaces so wyvern/lean strip it.
#[cfg(feature = "rich-tui")]
mod config_panel;
// The slash-command palette (#1674): pure state + a thin render fn, drawn by
// the rich input surface. Gated with the other rich TTY surfaces so the lean /
// piped / wyvern paths never compile it in.
#[cfg(feature = "rich-tui")]
mod lines_panel;
#[cfg(feature = "rich-tui")]
mod palette;
// One table of named roles, so a colour is chosen once and named everywhere —
// the answer to a census of thirty-odd literals across nine files, including
// `DarkGray` twenty times beside `DarkGrey` thirteen.
#[cfg(feature = "rich-tui")]
mod theme;
// The ONE inline-panel driver — raw mode, viewport, repaint cadence — shared by
// every panel, so a third panel cannot inherit a third copy of the event loop
// `/psyche` and `/backends` were each carrying.
#[cfg(feature = "rich-tui")]
mod modal_size;
#[cfg(feature = "rich-tui")]
mod panel;
#[cfg(feature = "rich-tui")]
mod panel_controls;
#[cfg(feature = "rich-tui")]
mod prefix;
// `/settings` as a chooser (slash_registry's `Disposition::Panel`), over the
// same driver and the same chrome as /psyche and /backends. The typed form
// stays for every surface that has no region to draw in.
#[cfg(feature = "rich-tui")]
mod permissions_panel;
#[cfg(feature = "rich-tui")]
mod settings_panel;
#[cfg(feature = "rich-tui")]
mod theme_panel;
// The backend chooser/editor panel (#1667) — same grammar, same gating; its
// persistence rides the setup wizard's crash-safe lock + plan machinery.
#[cfg(feature = "rich-tui")]
mod backend_panel;
// Assembling the backend chooser — its options and its two filesystem writers
// — in ONE place, now that `/backends` is not its only caller.
#[cfg(feature = "rich-tui")]
mod backend_chooser;
#[cfg(feature = "rich-tui")]
mod vi;
// #2005: the Esc / Ctrl-C precedence table (`assets/esc_ladder.toml`) plus the
// key→trigger-name mapping the `precedence-ladder` crate deliberately does not
// own. Gated with the surfaces whose claimants it ranks — palette, vi, cockpit
// presenter — so the lean / piped / wyvern paths never compile it in.
//
// `unix` as well, because the only NON-TEST consumer is the cockpit
// presenter's key loop and `cockpit`'s live half is unix-gated
// (`cockpit/mod.rs:39` — fd capture via `dup2`/`openpty`). Without it the
// Windows build compiles the table and every claim accessor with no caller,
// and `-D warnings` turns four dead-code lints into a failed build. Matching
// the gate to the callers keeps the boundary a compile error when it drifts,
// rather than an `allow` that hides the drift.
#[cfg(all(unix, feature = "rich-tui"))]
mod esc_ladder;
// #2005: the real-PTY acceptance for the rung above — Esc during a running
// turn interrupts from vi NORMAL, and does NOT from vi INSERT or from a
// half-typed operator. NOT `#[ignore]`d: it is the primary per-PR guard, and a
// guard that runs in no lane is decoration.
#[cfg(all(test, unix, feature = "rich-tui"))]
mod esc_ladder_pty_test;
// #1669: the cockpit — the terminal owned by the UI thread for the whole
// session, editor mounted while a turn runs, session output relayed through a
// pty. The live presenter is unix (fd capture via `dup2`/`openpty`); the module
// itself compiles on Windows too so the platform-agnostic scanner (`ansi`) and
// the #1746 ConPTY feasibility probe can live beside it — see
// `docs/decisions/windows_cockpit_conpty.md`.
#[cfg(feature = "rich-tui")]
mod cockpit;
// The opt-in mouse-capture RAII guard + panic-hook release (#1303). Compiled
// only when an interactive surface is on — the wyvern/lean build never links it.
// unix-only: the mouse tier's sole construction site (`with_live_spill_watch`)
// and the raw-byte decoder are `#[cfg(unix)]`, so on Windows the guard would be
// dead code (`-D warnings`). The whole tier rides the unix gate.
#[cfg(all(unix, any(feature = "rich-tui", feature = "live-spill")))]
mod mouse;
#[cfg(all(unix, any(feature = "rich-tui", feature = "live-spill")))]
pub use mouse::install_panic_release_hook;
/// The chrome every modal wears — one themed border for every dialog.
#[cfg(feature = "rich-tui")]
mod modal;
// The lean input surface (issue #527): a dead-simple word-wrapped text box, the
// flight/wyvern morphology. Always built — it is the footer-off / lean tier.
mod lean_input;
/// Cursor + window arithmetic for a list longer than its panel.
#[cfg(feature = "rich-tui")]
mod list_cursor;
/// The model picker: a windowed, arrow-navigated list.
#[cfg(feature = "rich-tui")]
mod models_panel;
// #1669: the channel seam that lets a session's turn stop owning the keyboard.
mod session_worker;
// #1669 PR-B: the tab projection that crosses the surface protocol.
mod setup;
mod setup_tui;
mod tab_bar;
mod wizard;

use anyhow::Context as _;
use mcp::Mcp;
// Step 9.7: the agentic loop (ChatCtx / chat_complete / execute_tool and their
// dependency closure) lives in `newt_core::agentic` now — the TUI is a thin
// wrapper that resolves config + caveats per turn and threads them in.
pub(crate) use brand::{
    brand_active, brand_logo, brand_name, brand_plugins, brand_tagline, logo_for_size, LOGO_20,
    LOGO_PLAIN, NEWT_ORANGE, VERSION,
};
#[cfg(feature = "rich-tui")]
pub(crate) use chat::footer_continues;
use chat::run_chat;
pub(crate) use chat::{InputSurface, ReadOutcome};
pub use color::color_supported;
use color::{color_enabled_for, resolve_color_mode};
#[cfg(any(feature = "rich-tui", test))]
pub(crate) use help::help_lines;
pub use help::render_help;
#[cfg(test)]
use help::{canonical_help_topic, command_help_page};
use help::{print_command_help, render_help_for_tui};
#[cfg(test)]
use newt_core::agentic::newt_line;
use newt_core::agentic::{print_harness_notice, print_newt, ChatCtx, NEWT_ORANGE_CT};
use newt_core::recover_context_window_400;
#[cfg(test)]
use prompt::expand_prompt_tokens;
#[cfg(feature = "rich-tui")]
use prompt::resolve_gutter_setting;
#[cfg(feature = "rich-tui")]
use prompt::rich_surface_selected;
use prompt::{
    current_prompt_and_preview, debug_mode, footer_mode, footer_rich_enabled, prompt_str,
    prompt_token_help, resolve_edit_mode, strip_one_quote_pair, trace_mode, verbose_mode,
};
pub use prompt::{DEFAULT_LEAN_PROMPT, DEFAULT_RICH_PROMPT, PROMPT_TOKENS};
use workspace_state::workspace_state_block;
#[cfg(test)]
use workspace_state::{
    format_workspace_state_block, parse_git_porcelain_dirty_files, WorkspaceStateSnapshot,
};

/// Run the (non-interactive) setup wizard unconditionally — used by `newt init`.
/// Probes Ollama and (re)writes `~/.newt/config.toml`; edit that file for
/// anything else.
mod splash;

pub fn run_init(color: bool) -> anyhow::Result<()> {
    wizard::run_init(color)
}

/// Run the interactive setup wizard — used by `newt setup`. Asks where the
/// model runs (local Ollama or a remote DGX endpoint), probes for installed
/// models, and writes `~/.newt/config.toml` after a preview + confirmation.
pub fn run_setup(color: bool) -> anyhow::Result<()> {
    setup::run(color)
}

pub async fn run_setup_target_with_model(
    target: &str,
    token_env: Option<&str>,
    token_file: Option<&std::path::Path>,
    model: Option<&str>,
    yes: bool,
    config_path: Option<&std::path::Path>,
) -> anyhow::Result<()> {
    setup::run_target(target, token_env, token_file, model, yes, config_path).await
}

/// Run the interactive crew-settings form — used by `newt crew --edit [name]`
/// and the in-session `/crew edit`. Prompts field-by-field (planner/navigator/
/// triage loadouts, control loop, test command, budgets), previews, and writes
/// `~/.newt/crews/<name>.toml`. A cooked-terminal prompt/response form (NOT a
/// ratatui surface — `docs/decisions/plain_scroller_tui.md`).
pub fn run_crew_edit(name: Option<&str>, color: bool) -> anyhow::Result<()> {
    crew_form::run_edit(name, color)
}

/// [`run_crew_edit`], asking through the session's surface seam (#1862 C1)
/// rather than this thread's terminal. `/crew edit` uses this; the `newt crew
/// edit` CLI, which owns the terminal, uses [`run_crew_edit`].
///
/// # Errors
///
/// Propagates a crew write failure.
pub(crate) fn run_crew_edit_with_ask(
    name: Option<&str>,
    color: bool,
    ask: SlashAsk<'_>,
) -> anyhow::Result<()> {
    crew_form::run_edit_with_ask(name, color, ask)
}

/// Open the harness config panel (#14) for the psyche operator dials and return
/// its [`config_panel::PanelOutcome`], or — when stdout is not a TTY (piped /
/// headless) — print a short note pointing at the text `/psyche` view and return
/// `Cancelled`. The panel applies (only the changed) dials through the same
/// setters the flags / slash commands use; `persist` (the caller's closure, which
/// owns the `PersonaStore`) is the only filesystem I/O the panel's TRANSACTION
/// depends on, so a failed save keeps the panel open without mutating the
/// runtime (review-3 §1). Not the only I/O it performs any more: applying a dial
/// now appends a settings receipt (#1965), which is best-effort by construction
/// — `settings_receipt::record` swallows its own failures, because failing to
/// observe a change must never undo it. The caller acts on the
/// returned outcome — applying the persona action, rerouting, and reporting from
/// fresh runtime state. **Rich-tui only** — the lean build has no ratatui surface,
/// so the `/psyche edit` handler prints the fallback directly. See
/// `harness_config_panel.md`.
#[cfg(feature = "rich-tui")]
pub(crate) fn run_psyche_panel(
    seed: config_panel::PanelSeed,
    persist: impl FnMut(&str, &str, bool) -> config_panel::SaveResult,
    window: Option<session_worker::PanelWindow>,
    color: bool,
    verbose: bool,
) -> config_panel::PanelOutcome {
    if std::io::IsTerminal::is_terminal(&std::io::stdout()) {
        match config_panel::run(seed, persist, window) {
            Ok(outcome) => outcome,
            Err(e) => {
                print_newt(&format!("psyche panel error: {e}"), color, verbose);
                config_panel::PanelOutcome::Cancelled
            }
        }
    } else {
        // rich-tui compiled but stdout is not a TTY (piped / headless): no overlay.
        print_newt(
            "the psyche panel needs an interactive rich terminal — use /psyche status \
             for the text view, or /psyche cognition / tenacity / initiative <level> \
             to change the dials.",
            color,
            verbose,
        );
        config_panel::PanelOutcome::Cancelled
    }
}

use std::io::{self, IsTerminal, Write as _};
use std::path::{Path, PathBuf};

use crossterm::{
    cursor::{Hide, MoveTo, Show},
    execute,
    style::{Color as CtColor, Print, ResetColor, SetForegroundColor},
    terminal::{Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
};
use newt_core::tty::raw_mode::RawModeGuard;

/// The PRODUCTION half of a source file, for the structural guards that assert
/// "no other path exists" (#1889, #1898).
///
/// Those tests live IN the file they read, so `include_str!` pulls in their own
/// needles; cutting at the test module is both the fix and the right scope.
///
/// Two things this gets right that the first copy did not, both found by
/// `rich_input.rs`:
///
/// * It cuts at the test MODULE, not at the first `#[cfg(test)]` anywhere.
///   `rich_input.rs` has an inline `#[cfg(test)]` item at :360, ~700 lines
///   above the code under test, so a first-occurrence split returned a prefix
///   that contained none of it.
/// * It accepts BOTH shapes of test module — the inline `mod tests {` and a
///   relocated `#[cfg(test)] #[path = "…"] mod …;` sibling — and cuts at
///   whichever appears first. A file whose tests moved out is still a file
///   whose production half ends where the test declaration begins.
/// * It PANICS when the marker is missing instead of returning "". An empty
///   string satisfies every `count() == 0` assertion, so the failure mode of
///   the convenient version is a guard that passes because it read nothing.
///
/// Gated with its callers, not merely with `test`: both structural guards live
/// in `rich-tui` modules, so under the LEAN configuration this function has no
/// caller and `-D warnings` refuses it. Caught by the lean clippy gate added in
/// #1890 — the configuration that had no gate at all a day ago.
#[cfg(all(test, feature = "rich-tui"))]
pub(crate) fn production_source(src: &str) -> &str {
    // TWO marker shapes, because a file's test module is either inline or
    // relocated to a sibling file under `#[path]`. Widened here rather than
    // forked at the call sites: this is the single owner of "where does
    // production end", and a second copy is what the reuse discipline exists
    // to prevent.
    //
    // The EARLIEST valid cut wins, not the first marker in this list. A file
    // carrying both shapes must yield the prefix before whichever comes first,
    // or production would be over-reported by everything between them.
    ["\n#[cfg(test)]\nmod tests {", "\n#[cfg(test)]\n#[path = "]
        .iter()
        .filter_map(|marker| src.split(marker).next())
        .filter(|prefix| prefix.len() < src.len())
        .min_by_key(|prefix| prefix.len())
        .expect(
            "the file must end in an unindented `#[cfg(test)] mod tests {` or \
             `#[cfg(test)] #[path = …]` — without one of those markers this \
             helper would hand back an empty string, and every count-based \
             assertion would pass having read nothing",
        )
}

/// Runs `restore` on every exit path of the scope holding it — normal return,
/// `?`, or panic. Split out from [`SplashScreenGuard`] so the "it always runs"
/// property is unit-testable without owning a real terminal: the guard proper
/// closes over crossterm calls, this closes over anything.
struct RestoreOnDrop<F: FnMut()> {
    restore: F,
}

impl<F: FnMut()> Drop for RestoreOnDrop<F> {
    fn drop(&mut self) {
        (self.restore)();
    }
}

/// RAII owner of the splash's terminal state: raw mode, the alternate screen,
/// and cursor visibility.
///
/// **#1411.** The splash used to enable raw mode and restore it ~30 lines
/// later, with *three* fallible `?` operators in between: the `execute!` that
/// enters the alternate screen and `show_splash`. Any I/O
/// error in that window returned early past the restore and left the operator
/// in the alternate screen, in raw mode, with the cursor hidden — a terminal
/// that echoes nothing and shows no cursor, recoverable only via `reset`. A
/// panic did the same. Of the three crossterm raw-mode pairs in this crate this
/// was the only one with no guard at all (`lean_input::RawGuard` has one;
/// `rich_input::read_turn` avoids `?` around its event loop).
///
/// **CORRECTION (#1898).** That last clearance was wrong, and it stood for
/// long enough to matter. "Avoids `?` around its event loop" is true and
/// covers the ERROR path only — a PANIC inside `event_loop` unwound past both
/// `DisableBracketedPaste` and `disable_raw_mode()`. `read_turn` now owns
/// `rich_input::RawPasteGuard`, which restores both from `Drop`.
///
/// The lesson is about this comment, not that function: a site recorded as
/// SAFE is worse than one nobody has looked at, because nobody looks twice.
/// The audit that found it (#1897) re-read every raw-mode pair in the
/// workspace rather than trusting this list. As of #1898 every pair is
/// Drop-guarded: `SplashScreenGuard`, `lean_input::RawGuard`,
/// `newt_core::tty::modal::RawGuard`,
/// `transcript_pager::AltScreenGuard`, `interaction_view::InlineGuard`,
/// `config_panel::PanelRawGuard` (both panels, #1889),
/// `rich_input::RawPasteGuard`, and `cockpit/presenter` via `RestoreOnDrop`.
///
/// Per the repo's "make the bug unrepresentable" rule, the fix is ownership
/// rather than another restore call: the terminal cannot be taken without
/// binding something that gives it back.
///
/// **This deliberately adds a fourth mode guard** to a crate whose #1408 story
/// C1 is *consolidating* mode ownership into one nesting-aware owner. That is
/// intentional sequencing, not an oversight: C1 needs the lean firewall
/// (#1409) under it first, and leaving a reachable terminal-corrupting bug
/// parked until then is the worse trade. This type is written to be absorbed —
/// enter/restore is exactly the shape C1 needs.
struct SplashScreenGuard {
    /// **Composed onto the one nesting-aware owner (#1905).** The splash owns
    /// the alternate screen and cursor visibility; raw mode is
    /// [`RawModeGuard`]'s. Its own doc predicted this: *"This type is written
    /// to be absorbed — enter/restore is exactly the shape C1 needs."*
    ///
    /// DECLARATION ORDER IS THE CONTRACT. Rust drops fields in declaration
    /// order, after the struct's own `Drop::drop` — and this type has none, so
    /// `_restore` runs first and `_raw` second. Screen and cursor come back
    /// before line discipline does, which is the order this guard already had
    /// when both lived in one closure. Swapping these two lines would invert
    /// it silently.
    _restore: RestoreOnDrop<fn()>,
    /// **The whole screen, held (#1980).** Declared AFTER `_restore` on
    /// purpose: this type has no `Drop::drop`, so fields are the only ordering
    /// there is, and the rows must come back only once the alternate screen has
    /// been left. Declared BEFORE `_raw` for the reason the comment above
    /// gives — screen state before line discipline.
    ///
    /// `SuspendHolder`: entering the alternate screen genuinely suspends what
    /// is beneath it, the terminal preserves and restores the primary screen,
    /// and the policy therefore never refuses. No new failure path here; what
    /// changes is that a surface minting `Refuse` or `Shift` can now see that
    /// the screen is taken.
    _region: newt_core::tty::RegionLease,
    _raw: RawModeGuard,
}

impl SplashScreenGuard {
    /// Take the terminal: raw mode, then the alternate screen on a cleared
    /// frame with the cursor hidden.
    ///
    /// The guard is bound *before* the fallible `execute!`, so a failure
    /// entering the alternate screen still gives raw mode back — that path was
    /// itself one of the three leaks.
    fn enter() -> io::Result<Self> {
        let raw = RawModeGuard::enter()?;
        let region = newt_core::tty::Terminal::lease_region(
            newt_core::tty::Region::WholeScreen,
            newt_core::tty::OnCollision::SuspendHolder,
        )
        .ok_or_else(|| io::Error::other("the screen could not be leased"))?;
        let guard = Self {
            // Raw mode is NOT in this closure any more — `_raw` owns it. What
            // remains is exactly the splash's own state.
            _restore: RestoreOnDrop {
                restore: || {
                    let _ = execute!(io::stdout(), Show, LeaveAlternateScreen);
                },
            },
            _region: region,
            _raw: raw,
        };
        // Flush the tty input queue on taking the terminal. This stays HERE and
        // must never move into `RawModeGuard` (#1905): it is not part of raw
        // mode, and every frame silently eating pending input would be a new
        // bug wearing a refactor's clothes. A slow pre-splash step
        // — notably the first-run summarizer model pull (#661 group C), which runs
        // for seconds in cooked mode — lets impatient keystrokes or echoed bytes
        // queue up; entering raw mode does NOT discard them, so the splash's first
        // input poll would consume one (a lone Esc / q / Ctrl-C reads as quit) and
        // newt would exit before the splash is ever seen. TCIFLUSH drops the
        // pending input atomically — no poll/read drain race.
        #[cfg(unix)]
        // SAFETY: tcflush on the stdin tty fd passes no pointers and touches no
        // memory; the worst case on a non-tty fd is a harmless ENOTTY.
        unsafe {
            libc::tcflush(libc::STDIN_FILENO, libc::TCIFLUSH);
        }
        execute!(
            io::stdout(),
            EnterAlternateScreen,
            Hide,
            Clear(ClearType::All),
            MoveTo(0, 0)
        )?;
        Ok(guard)
    }
}

/// #1411 regression cover for the splash's terminal-restore contract.
///
/// These drive [`RestoreOnDrop`] rather than a real terminal, deliberately:
/// the defect was never "the restore call is wrong", it was "the restore call
/// is *skipped* on some exit paths". That is a control-flow property, and
/// control flow is exactly what a fully-mocked unit test can prove. The
/// end-to-end proof that the restored terminal actually echoes again is a
/// real-PTY concern and lands with the shared harness in #1410.
///
/// Each test below mirrors one of the three `?` operators that used to sit
/// between `enable_raw_mode()` and `disable_raw_mode()`; the pre-#1411 shape —
/// a bare `disable_raw_mode()` call at the bottom of the block — fails all of
/// them, because on those paths control never reaches the bottom.
#[cfg(test)]
#[path = "lib_tests/splash_guard_tests.rs"]
mod splash_guard_tests;

#[cfg(test)]
#[path = "lib_tests/slash_ask_seam_tests.rs"]
mod slash_ask_seam_tests;

// ---------------------------------------------------------------------------
// Public entry points
// ---------------------------------------------------------------------------

pub fn run_code(
    path: Option<&std::path::Path>,
    no_splash: bool,
    persona: Option<&str>,
    // FR-5 (#999): the session operating altitude from `--altitude` (doer vs
    // coach). `None` ⇒ each persona's own altitude applies (doer when unset).
    // When set it overrides a loaded persona's altitude, or — with no `--persona`
    // — synthesizes a minimal altitude-only persona. It rides on `active_persona`
    // so no session-management helper needs new plumbing.
    altitude: Option<newt_core::Altitude>,
    // #479 part 2: the crew/team runner, BUILT BY THE BINARY (newt-cli owns
    // newt-scheduler + the worktree) and injected down — newt-tui stays
    // scheduler-free. `None` ⇒ the `/team` tools are never advertised.
    crew_runner: Option<&dyn newt_core::agentic::CrewRunner>,
    // First-run provisioning (#985): when the binary needs to fetch the on-host
    // summarizer model, the splash covers that work with a spinner. `None` ⇒ no
    // setup step. The download runs on a background thread; see `SetupHandle`.
    setup: Option<SetupHandle>,
) -> anyhow::Result<()> {
    // Color: NEWT_COLOR (--color/--mono) > NO_COLOR/TERM=dumb > [tui] color > auto
    // (issue #527). Config is folded in here, where a session reads it; the
    // `color_supported_with` shim (used pre-config, e.g. the wizard) stays Auto.
    let mut migration_notices = crate::migration_notices::Pending::default();
    let cfg_color = newt_core::Config::resolve(&mut |notice| migration_notices.report(notice))
        .ok()
        .and_then(|c| c.tui)
        .map(|t| t.color)
        .unwrap_or_default();
    let color = color_enabled_for(
        resolve_color_mode(&|k| std::env::var(k).ok(), cfg_color),
        io::stdout().is_terminal(),
    );

    if let Some(p) = path {
        newt_core::settings::set_workspace(p);
    }
    let workspace = resolve_workspace(path);

    // `no_splash` is already resolved by the caller (CLI flags + config).
    let inline = no_splash;

    if !inline {
        // SPLASH FIRST — it covers the initialization work, and the first-run
        // wizard's menus roll underneath (normal scrollback) after it drops.
        // #1411: the guard owns raw mode + the alternate screen + the cursor for
        // this whole block, so the `?`s below cannot strand the terminal.
        let screen = SplashScreenGuard::enter()?;
        let mut stdout = io::stdout();
        // Background work starts AT splash entry: a configured box pre-warms
        // its backend probe while the logo shows; run_chat consumes the result
        // when (and only when) the resolved choice still matches.
        let prewarm = spawn_backend_prewarm(&mut |notice| migration_notices.report(notice));
        // The unboxed state names the splash context ("initial setup") —
        // computed before `setup` is consumed below.
        let unconfigured =
            newt_core::Config::resolve(&mut |notice| migration_notices.report(notice))
                .map(|c| c.is_unconfigured())
                .unwrap_or(true);
        let context = if unconfigured || setup.is_some() {
            "initial setup"
        } else {
            "starting"
        };
        // ONE splash covers everything (field note: two consecutive splash
        // screens read as a bug): a first-run provision (#985) renders as an
        // extra spinner line on this same screen — input blocked except a
        // triple abort while it runs — and the splash's own spinner keeps a
        // launch from ever looking hung.
        let status = if prewarm.is_some() {
            "warming up backend…"
        } else {
            "initializing…"
        };
        let cont = splash::show_splash(&mut stdout, &workspace, color, status, context, setup)?;
        // Give the terminal back before anything else prints: chat must not run
        // inside the alternate screen. Explicit rather than implicit at the end
        // of the block so the ordering stays visible to a reader.
        drop(screen);
        migration_notices.flush();
        if !cont {
            if let Some(pw) = prewarm {
                pw.handle.abort();
            }
            return Ok(());
        }
        // The branded crawl header opens the post-splash scrollback (the seam
        // inheriting agents override — see brand::crawl_header), then the
        // first-run wizard's menus roll underneath it when unconfigured.
        if unconfigured {
            print!("{}", brand::crawl_header(Some("initial setup")));
        }
        wizard::maybe_run(color)?;
        print_inline_header(&workspace, color);
        return run_chat(&workspace, color, persona, altitude, crew_runner, prewarm);
    }

    // No splash owns the terminal on this branch. Deliver before the wizard
    // or either run_chat path, including inline setup's early return.
    migration_notices.flush();
    // No-splash paths keep the pre-splash order exactly (wizard first): CI,
    // piped, and --no-splash launches see no behavior change.
    wizard::maybe_run(color)?;
    if let Some(setup) = setup {
        // No-splash (#985): the header still shows, then an inline setup spinner
        // covers the provisioning before chat starts.
        print_inline_header(&workspace, color);
        run_setup_inline(&setup);
        return run_chat(&workspace, color, persona, altitude, crew_runner, None);
    }

    print_inline_header(&workspace, color);
    run_chat(&workspace, color, persona, altitude, crew_runner, None)
}

/// A backend probe started at splash entry so a configured box's session
/// start finds the answer already in flight (or done) instead of probing
/// cold after the splash.
pub(crate) struct Prewarm {
    /// The URL the probe ran against — consumption is gated on it still
    /// matching the resolved choice (a first-run wizard may have changed
    /// everything in between).
    pub(crate) url: String,
    pub(crate) handle:
        tokio::task::JoinHandle<Option<newt_core::backend_probe::EndpointProbeResult>>,
}

/// True when a pre-warmed probe is for the same endpoint the session
/// resolved — trailing-slash-insensitive. Pure.
pub(crate) fn prewarm_applies(choice_url: &str, prewarm_url: &str) -> bool {
    choice_url.trim_end_matches('/') == prewarm_url.trim_end_matches('/')
}

/// Whole-request bound for the session's endpoint probes. LAN boxes answer in
/// well under a second; a hosted HTTPS gateway needs DNS + TLS + auth and
/// real-world jitter — field testing showed api.openai.com blowing a 3 s
/// bound while being perfectly healthy, so the remote beat is a patient 10 s.
pub(crate) fn probe_timeout_secs(url: &str) -> u64 {
    if url.starts_with("https://") {
        10
    } else {
        1
    }
}

/// Start the pre-warm probe for the resolved backend choice, if this box is
/// configured (an unconfigured box has nothing real to probe — the wizard is
/// about to change everything) and a tokio runtime is available.
fn spawn_backend_prewarm(
    report: &mut dyn FnMut(newt_core::tty::Notice<'static>),
) -> Option<Prewarm> {
    let runtime = tokio::runtime::Handle::try_current().ok()?;
    let cfg = newt_core::Config::resolve_runtime_unpublished(report).ok()?;
    if cfg.is_unconfigured() {
        return None;
    }
    let choice = resolve_backend_choice(&cfg).ok()?;
    let url = choice.url.clone();
    let api_key = choice.api_key.clone();
    let needs_probe = choice.kind_needs_probe;
    let kind = choice.kind;
    let secs = probe_timeout_secs(&url);
    let task_url = url.clone();
    let handle = runtime.spawn(async move {
        let client = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(secs))
            .build()
            .ok()?;
        if needs_probe {
            newt_core::backend_probe::detect_endpoint(&client, &task_url, api_key.as_deref())
                .await
                .ok()
        } else {
            // Same shape adopt_backend_choice's known-kind path fetches cold.
            let api = newt_core::backend_probe::api_for(kind);
            let models = api
                .list_models(&client, &task_url, api_key.as_deref())
                .await
                .ok()?;
            let warm = api
                .warm_models(&client, &task_url, api_key.as_deref())
                .await
                .unwrap_or_default();
            Some(newt_core::backend_probe::EndpointProbeResult {
                endpoint: task_url.trim_end_matches('/').to_string(),
                serving: api.serving(models.len()),
                kind,
                models,
                warm,
                engine: None,
            })
        }
    });
    Some(Prewarm { url, handle })
}

/// Compact inline header — the session preamble.
/// Prints LOGO_20 with text to the right using ANSI column-move escapes,
/// then scrolls naturally into history. No alt screen, no raw mode.
/// Printed in BOTH splash and no-splash modes (see `run_code`).
fn print_inline_header(workspace: &str, color: bool) {
    print!("{}", render_inline_header(workspace, color));
}

/// Render the inline header to a string. Pure — unit-testable.
fn render_inline_header(workspace: &str, color: bool) -> String {
    use std::fmt::Write as _;

    if !color {
        let plugins = brand_plugins()
            .map(|p| format!("  ·  {p}"))
            .unwrap_or_default();
        return format!("{} v{VERSION}  ·  {workspace}{plugins}\n\n", brand_name());
    }

    // Place text at column 23 (just past the 20-col logo).
    let text_col = 23u16;
    let logo = brand_logo(LOGO_20, "ansi-20");
    let logo_lines: Vec<&str> = logo.lines().collect();
    let n = logo_lines.len();

    // Text lines aligned to the middle-right of the logo.
    let mid = n / 2;
    let header = brand_tagline();
    let plugins = brand_plugins();
    let version = format!("v{VERSION}");
    let text: &[(&str, bool)] = &[
        (header.as_str(), false),
        (version.as_str(), true),                 // dim
        (plugins.as_deref().unwrap_or(""), true), // dim; empty row hides itself
        (
            "ready — type a task, /help for commands, /exit to quit",
            true,
        ),
        ("keybindings — /vi (default) · /emacs · /nano", true),
    ];
    let text_start = mid.saturating_sub(1);

    let mut out = String::new();
    for (i, logo_line) in logo_lines.iter().enumerate() {
        // Logo line already contains ANSI color codes.
        out.push_str(logo_line);
        // Move cursor to column text_col on this row, print text if scheduled.
        let ti = i.wrapping_sub(text_start);
        if let Some((msg, dim)) = text.get(ti) {
            if !msg.is_empty() {
                // \x1b[{col}G moves cursor to absolute column (1-indexed).
                let style_on = if *dim { "\x1b[38;2;100;100;100m" } else { "" };
                let style_off = if *dim { "\x1b[0m" } else { "" };
                let _ = write!(out, "\x1b[{text_col}G{style_on}{msg}{style_off}");
            }
        }
        out.push('\n');
    }
    out.push('\n');
    out
}

pub fn run_pilot(_flight_id: &str) -> anyhow::Result<()> {
    anyhow::bail!("newt-tui::run_pilot not yet implemented")
}

// The binary (newt-cli) provisions the on-host summarizer model on a background
// The first-run setup / provisioning screen (`SetupEvent`, `SetupHandle`,
// the spinner render loop) lives in `setup_tui.rs` — the UI of the setup step.
// (`setup.rs` is the config wizard logic; `wizard.rs` is the silent prober.)
pub use crate::permissions::ocap_high_danger_predicate;
#[cfg(unix)]
use crate::permissions::try_watch_stdin;
use crate::permissions::{
    permission_prompting_configured, production_danger_table, prompt_permission_choice,
    should_prompt_permissions, PermissionPromptState, PromptChoice, PromptPermissionGate,
};
use crate::setup_tui::run_setup_inline;
pub use crate::setup_tui::{SetupEvent, SetupHandle};

// ---------------------------------------------------------------------------
// Chat — plain terminal REPL
//
// No alternate screen, no custom scroll. The terminal's own scrollback
// buffer handles history. Works identically over SSH and inside tmux.
//
// This is a standing design decision, not a stopgap — newt is amphibious
// (human CLI + headless swarm) and the chat surface stays a plain scroller.
// Advanced TUI belongs in gilamonster-agent / monitor repos. Before adding
// any screen control here, read docs/decisions/plain_scroller_tui.md.
//
// NEWT_CHAT_STYLE=verbose  — show "newt" / "you" labels before the caret
// (default is compact: just the colored caret / symbol)
// ---------------------------------------------------------------------------

/// Return today's date as `YYYY-MM-DD` using the system clock.
pub(crate) fn today_date() -> String {
    // Using std::time for a lightweight date without a chrono dep.
    // We only need YYYY-MM-DD so we derive it from epoch seconds manually.
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    // Days since Unix epoch.
    let days = secs / 86400;
    // Algorithm from http://howardhinnant.github.io/date_algorithms.html
    let z = days as i64 + 719468;
    let era = z.div_euclid(146097);
    let doe = z.rem_euclid(146097) as u32;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!("{y:04}-{m:02}-{d:02}")
}

// ---------------------------------------------------------------------------
// File-descriptor hygiene — prevent EMFILE from killing the input surface
// ---------------------------------------------------------------------------

/// Mark every open fd above stderr (`fd > 2`) as `O_CLOEXEC` so that
/// subprocesses spawned by `run_command` (via agent-bridle / brush) do NOT
/// inherit the parent's terminal fd, history file handle, or socket fds.
///
/// Call this **after** the input surface and history are initialised so that
/// their fds are also marked. Safe to call multiple times — already-CLOEXEC fds
/// are skipped.
///
/// macOS returns `LONG_MAX` for `sysconf(_SC_OPEN_MAX)`; we cap the sweep
/// at 4096 which covers any realistic fd table.
#[cfg(unix)]
fn mark_fds_cloexec() {
    let max = unsafe { libc::sysconf(libc::_SC_OPEN_MAX) };
    let max_fd = if max > 0 {
        max.min(4096) as libc::c_int
    } else {
        256
    };
    for fd in 3..max_fd {
        unsafe {
            let flags = libc::fcntl(fd, libc::F_GETFD);
            if flags >= 0 && (flags & libc::FD_CLOEXEC == 0) {
                libc::fcntl(fd, libc::F_SETFD, flags | libc::FD_CLOEXEC);
            }
        }
    }
}

/// Probe whether the fd table has at least one free slot by attempting to
/// open the platform null device. Returns `false` when the process is at EMFILE — i.e.,
/// the next `open("/dev/tty")` by the input surface would fail and panic.
///
/// Uses only `std::fs` (no libc dep) so it compiles on all platforms.
fn terminal_fd_available() -> bool {
    terminal_fd_available_from_probe(|| std::fs::File::open(null_device_path()).map(drop))
}

fn terminal_fd_available_from_probe(probe: impl FnOnce() -> std::io::Result<()>) -> bool {
    probe().is_ok()
}

#[cfg(windows)]
fn null_device_path() -> &'static str {
    "NUL"
}

#[cfg(not(windows))]
fn null_device_path() -> &'static str {
    "/dev/null"
}

/// Collect the absolute paths of executables in the CLI-granted directories
/// (`--venv` and `--exec-path`). Used to widen the exec caveat at session start
/// so the agent can run tools from those directories without needing them in
/// `[tui.permissions] extra_exec` in the config file.
#[cfg(unix)]
fn scan_cli_exec_grants() -> Vec<String> {
    use std::os::unix::fs::PermissionsExt;
    let mut dirs: Vec<String> = Vec::new();
    if let Ok(venv) = std::env::var("NEWT_VENV") {
        dirs.push(format!("{venv}/bin"));
    }
    if let Ok(paths) = std::env::var("NEWT_EXEC_PATHS") {
        for p in paths.split(':') {
            if !p.is_empty() {
                dirs.push(p.to_string());
            }
        }
    }
    dirs.iter()
        .flat_map(|dir| std::fs::read_dir(dir).ok().into_iter().flatten())
        .flatten()
        .filter_map(|e| {
            let path = e.path();
            if !path.is_file() {
                return None;
            }
            let mode = path.metadata().ok()?.permissions().mode();
            if mode & 0o111 == 0 {
                return None;
            }
            // Retain the executable spelling, including venv symlinks. The
            // sandbox canonicalizes it for kernel projection; a basename would
            // instead select only trusted system binaries with that name.
            std::path::absolute(path).ok()?.to_str().map(str::to_string)
        })
        .collect()
}

#[cfg(not(unix))]
fn scan_cli_exec_grants() -> Vec<String> {
    Vec::new()
}

/// The session's runtime authority, as far as `disposition` lets this request
/// use it (#2332). The run_command guidance renders only when the dispatch
/// predicate admits run_command, so the text never tells a model to call a
/// tool dispatch will refuse.
fn runtime_authority_note(disposition: newt_core::agentic::PromptDisposition) -> Option<String> {
    let switches = (
        newt_core::agentic::ocap_disabled(),
        newt_core::agentic::full_access_requested(),
    );
    let active = match switches {
        (true, true) => "--disable-ocap/--yolo AND --full-access are",
        (true, false) => "--disable-ocap/--yolo is",
        (false, true) => "--full-access is",
        (false, false) => return None,
    };
    if !newt_core::agentic::tool_allowed(disposition, "run_command") {
        return Some(format!(
            "Runtime authority: {active} active for this session, but this request is \
             limited to the tools in your catalog. Use those or answer directly; do not \
             call a tool that is not listed."
        ));
    }
    let note = match switches {
        (true, true) =>
            "Runtime authority: --disable-ocap/--yolo AND --full-access are active. \
             run_command is available with unrestricted exec authority and uses the \
             unconfined host shell; the configured [tui.permissions] preset and its \
             exec floor are lifted. A posture, persona, or operating mode may still \
             attenuate that session baseline. \
             Do not claim a capability wall without first calling run_command and \
             grounding the claim in its returned tool result. Native fs tools are \
             unrestricted; web_fetch has unrestricted configured net authority.",
        (true, false) =>
            "Runtime authority: --disable-ocap/--yolo is active. run_command uses the \
             unconfined host shell when the active exec floor permits it, not the \
             brush/agent-bridle confined shell. Do not claim run_command is unavailable \
             due to brush in this mode. Native fs tools remain workspace-fenced; \
             web_fetch remains net-leashed.",
        _ =>
            "Runtime authority: --full-access is active. run_command is available with \
             unrestricted exec authority; the configured permission preset and exec \
             floor are lifted for this invocation, though a posture, persona, or \
             operating mode may still attenuate that session baseline. Do not claim a capability wall \
             without first calling run_command and grounding the claim in its returned \
             tool result. Native fs tools and configured net authority are unrestricted.",
    };
    Some(note.to_string())
}

fn filesystem_authority_note() -> &'static str {
    if newt_core::agentic::full_access_requested() {
        "# Filesystem authority\n\
         The full-access session baseline permits reads and writes outside the \
         workspace. A posture, persona, or operating mode may still attenuate it. \
         Treat an actual fs_read/fs_write tool denial as authoritative; do not \
         infer confinement without a returned tool result.\n"
    } else {
        "# Filesystem confinement\n\
         You are confined to the workspace (the current directory) plus any paths \
         the operator explicitly opened. A read or write outside that returns \
         `capability denied: fs_read/fs_write does not permit '<path>'`. Do NOT \
         retry a denied path or try to work around it — instead tell the operator \
         it's outside your workspace and that they can relaunch with \
         `--read <path>` (read-only) or `--write <path>` (read+write) to grant it.\n"
    }
}

/// The ambient "environment" the agent can see — its own model name, the
/// harness + version, the backend it's talking to, and the current date/time.
/// Prepended to the system prompt each turn so these are *current* (the system
/// prompt itself is frozen at conversation start). Without it the model has no
/// way to know its identity and confabulates one (e.g. inventing a name for
/// commit attribution). Kept short — it rides in every request.
fn runtime_context_block(
    model: &str,
    endpoint: &str,
    kind: newt_core::BackendKind,
    identity: &newt_core::AgentIdentity,
    disposition: newt_core::agentic::PromptDisposition,
) -> String {
    let now = chrono::Local::now()
        .format("%Y-%m-%d %H:%M:%S %Z")
        .to_string();
    let backend = match kind {
        newt_core::BackendKind::Openai => "openai-compatible",
        newt_core::BackendKind::Anthropic => "anthropic",
        _ => "ollama",
    };
    let author_email = identity.email.as_str();
    let author_name = identity.name.as_str();
    let runtime_authority = runtime_authority_note(disposition)
        .map(|note| format!("# Runtime authority\n{note}\n"))
        .unwrap_or_default();
    let filesystem_authority = filesystem_authority_note();
    format!(
        "# Environment (refreshed every turn)\n\
         Harness: newt-agent v{VERSION}\n\
         Model: {model}\n\
         Backend: {backend} @ {endpoint}\n\
         Current date/time: {now}\n\
         You are the model named above, running under the newt-agent harness. \
         When asked who or what you are — and when attributing work (commit \
         trailers, git notes, PR text) — use this real model name and harness; \
         never invent or guess an identity.\n\
         {runtime_authority}\
         # Git commit identity\n\
         Configured Git identity: `{author_name} <{author_email}>`. \
         Use ordinary Git commands for repository work. Harness-managed commits \
         record every contributing model/harness pair from the attribution ledger. \
         Never invent an author identity or claim a commit or signature without \
         a successful tool result.\n\
         {filesystem_authority}"
    )
}

/// Read-only enforcement caveats (read anything; no write/exec/net) — the safe
/// default when nothing is configured or identity setup fails.
fn read_only_caveats(workspace: &str) -> newt_core::caveats::Caveats {
    newt_core::ToolPermissions {
        preset: newt_core::PermissionPreset::ReadOnly,
        extra_exec: Vec::new(),
        net: Vec::new(),
        prompt: false,
        ..Default::default()
    }
    .to_caveats(workspace)
}

/// Lower the configured TUI permission policy to a `Caveats` value. With no
/// `[tui]` config the policy is **read-only** — never `Caveats::top()`. Pure in
/// its inputs, so the safe-default behavior is unit-testable.
///
/// CLI exec grants (`--venv`, `--exec-path`) are injected here: they widen the
/// exec scope at session-start so the agent can run tools in those directories
/// without requiring per-binary `extra_exec` entries in the config file. Only
/// `Scope::Only` is widened; `Scope::All` (FullAccess) is already unrestricted.
///
/// The agent's reads are **locked to the workspace by default**: newt's presets
/// ship `fs_read = All` (read anything anywhere), but the operator wants the
/// agent confined to the CWD unless a path is explicitly opened. So `policy_for`
/// fences `fs_read` to `workspace + the granted paths` for every preset EXCEPT
/// `full_access` (which is `fs_write = All` — an explicit "no fence" choice).
/// `--read <path>` adds a read path; `--write <path>` adds a read+write path
/// (write implies read) and is also widened into the already-fenced `fs_write`.
fn policy_for(tui: Option<newt_core::TuiConfig>, workspace: &str) -> newt_core::caveats::Caveats {
    policy_for_launch(tui, workspace, newt_core::launch_authority::current())
}

fn policy_for_launch(
    tui: Option<newt_core::TuiConfig>,
    workspace: &str,
    authority: newt_core::launch_authority::LaunchAuthority,
) -> newt_core::caveats::Caveats {
    use newt_core::caveats::Scope;
    // --full-access / NEWT_FULL_ACCESS=1: per-invocation preset override —
    // build the policy from `full_access` (`Caveats::top()`, the exact value
    // `ToolPermissions::to_caveats` yields for that preset) regardless of the
    // configured preset. This also empties the #774 exec floor (`Scope::All`
    // + no mode ⇒ `exec_floor_from` → None), so combined with --yolo the
    // host-shell bypass covers every command. Surfaced loudly at session
    // start by `full_access_banner`.
    let mut caveats = if authority.full_access() {
        newt_core::caveats::Caveats::top()
    } else if authority.workspace_access() {
        let mut permissions = tui.map(|t| t.permissions).unwrap_or_default();
        permissions.preset = newt_core::PermissionPreset::WorkspaceFullAccess;
        permissions.to_caveats(workspace)
    } else {
        tui.map(|t| t.permissions.to_caveats(workspace))
            .unwrap_or_else(|| read_only_caveats(workspace))
    };
    let extra = scan_cli_exec_grants();
    if !extra.is_empty() {
        if let Scope::Only(ref mut set) = caveats.exec {
            set.extend(extra);
        }
    }
    // Opt out of the read-fence ONLY for a preset whose reads AND writes are
    // BOTH deliberately unbounded — i.e. `full_access` (`fs_read == All &&
    // fs_write == All`). Keying on both axes (not `fs_write` alone) makes the
    // read-axis intent explicit: `read_only` is `fs_read == All, fs_write ==
    // none`, and its broad read scope is fenced ON PURPOSE here, not as an
    // accident of the discriminator. That is deliberate — `read_only` is the
    // DEFAULT preset for an unconfigured session, and confining the default is
    // the entire point of the lock (an unconfigured agent must not read outside
    // the CWD). `read_only` still reads broadly *within* the workspace and any
    // `--read`/`--write` grants. Every other preset is locked to the workspace +
    // the grants by the shared newt-core helper (the headless crew/worker paths
    // call the same helper).
    let reads_deliberately_unbounded =
        matches!(caveats.fs_read, Scope::All) && matches!(caveats.fs_write, Scope::All);
    if !reads_deliberately_unbounded {
        newt_core::caveats::apply_cli_fs_grants(&mut caveats, workspace);
    }
    caveats
}

/// Resolve the configured `[tui]` block, if any.
fn resolve_tui(cfg: &newt_core::Config) -> Option<newt_core::TuiConfig> {
    cfg.tui.clone()
}

/// Mint a signed operating key for `policy`, rooted in the per-user key at
/// `key_path` (generated on first use). Its caveats are provably `⊑` the user's
/// full authority, and it can only ever delegate *narrower* children.
pub(crate) fn mint_operating_key(
    key_path: &std::path::Path,
    policy: &newt_core::caveats::Caveats,
) -> Result<newt_identity::AgentKey, newt_identity::IdentityError> {
    let user = newt_identity::load_or_generate(key_path)?;
    let root = newt_identity::session_root(&user);
    newt_identity::attenuate(&root, policy)
}

// ---------------------------------------------------------------------------
// Prompted ocap grants — issue #263 (`--prompt-for-permissions`)
// Interactive permission prompting (`--prompt-for-permissions`, #263) — the
// OCAP grant UI + `PromptPermissionGate`/`PermissionPromptState` state machine
// — lives in `permissions.rs`. The `/posture` named-preset clamp (#307) stays
// below.

// ---------------------------------------------------------------------------
// Operating modes (`/mode`) — working style, never authority.
//
// The TYPE lives in `newt_core::operating_mode` since #2009 PR4b (shared
// vocabulary belongs in the minimal layer, and `settings_form::apply` has
// to reach it). This alias keeps every `OperatingMode` reference in this
// crate reading the same as it did.
// ---------------------------------------------------------------------------

pub(crate) use newt_core::operating_mode::OperatingMode;

/// Session-local model selection behind `/mode auto`.
///
/// The selected style is bound to the conversation that requested it and is
/// consumed by its next action-shaped turn. Conversation-boundary handlers
/// clear it eagerly, so `/new`, restore, and persona-driven rotation cannot
/// resurrect a stale model choice.
#[derive(Debug, Default)]
struct AutoModeState {
    selected: std::sync::Mutex<Option<(String, OperatingMode)>>,
}

impl AutoModeState {
    fn take_for(&self, conversation_id: &str) -> Option<OperatingMode> {
        let Ok(mut selected) = self.selected.lock() else {
            return None;
        };
        match selected.take() {
            Some((bound_id, mode)) if bound_id == conversation_id => Some(mode),
            Some(_) | None => None,
        }
    }

    #[cfg(test)]
    fn pending_for(&self, conversation_id: &str) -> Option<OperatingMode> {
        self.selected
            .lock()
            .ok()
            .and_then(|selected| match selected.as_ref() {
                Some((bound_id, mode)) if bound_id == conversation_id => Some(*mode),
                _ => None,
            })
    }

    fn clear(&self) {
        if let Ok(mut selected) = self.selected.lock() {
            *selected = None;
        }
    }

    fn bind<'a>(&'a self, conversation_id: &'a str) -> TurnAutoModeControl<'a> {
        TurnAutoModeControl {
            state: self,
            conversation_id,
        }
    }
}

/// Per-TUI-session state for the model-entered Plan phase. This is deliberately
/// not process-global: multiple embedded or test sessions must never clamp one
/// another's tool calls.
#[derive(Debug, Default)]
struct PlanModeState {
    active: std::sync::atomic::AtomicBool,
    /// #2424: set by `exit_plan_mode`, cleared by the turn-end approval hook
    /// taking it. Separate from `active` so the clamp itself is untouched
    /// until approval — the whole point of the request/approve split.
    exit_requested: std::sync::atomic::AtomicBool,
    /// Plan-before-act: the current turn is the implementing turn an
    /// approval seeded, so the executor must not ask about that plan again.
    /// Set at prompt comprehension from the input's origin, every turn.
    implementing_approved: std::sync::atomic::AtomicBool,
}

impl PlanModeState {
    fn is_active(&self) -> bool {
        self.active.load(std::sync::atomic::Ordering::Acquire)
    }

    fn set_implementing_approved(&self, seeded_by_approval: bool) {
        self.implementing_approved
            .store(seeded_by_approval, std::sync::atomic::Ordering::Release);
    }

    fn clear(&self) {
        self.active
            .store(false, std::sync::atomic::Ordering::Release);
        self.exit_requested
            .store(false, std::sync::atomic::Ordering::Release);
        self.implementing_approved
            .store(false, std::sync::atomic::Ordering::Release);
    }
}

impl newt_core::agentic::PlanModeControl for PlanModeState {
    fn is_plan_mode(&self) -> bool {
        self.is_active()
    }

    fn set_plan_mode(&self, active: bool) -> Result<(), String> {
        self.active
            .store(active, std::sync::atomic::Ordering::Release);
        Ok(())
    }

    fn request_exit(&self) -> Result<(), String> {
        self.exit_requested
            .store(true, std::sync::atomic::Ordering::Release);
        Ok(())
    }

    fn take_exit_requested(&self) -> bool {
        self.exit_requested
            .swap(false, std::sync::atomic::Ordering::AcqRel)
    }

    fn exit_requested(&self) -> bool {
        self.exit_requested
            .load(std::sync::atomic::Ordering::Acquire)
    }

    fn implementing_approved_plan(&self) -> bool {
        self.implementing_approved
            .load(std::sync::atomic::Ordering::Acquire)
    }
}

/// Per-conversation state for the Plan phase's one draft slot (design:
/// `docs/design/plan-mode-draft-present-approve.md`, #2424). Persists the
/// latest revision to `session_plan_path` on every save — the one filesystem
/// write this seam performs; the model's own clamp never touches the
/// filesystem directly. Cleared alongside `PlanModeState` on `/new`, restore,
/// or persona rotation, so a fresh conversation never inherits a stale draft.
///
/// Every entry is bound to the OBJECTIVE it was drafted under — the root
/// prompt id of the operator lineage (`TurnPromptContext::active()
/// .root_prompt_id()`), which a discussion continuation shares and a fresh
/// operator prompt does not. A draft from objective A is invisible to
/// objective B: it is neither presented nor seeded there, so an approval
/// under B can never execute A's plan.
#[derive(Debug, Default)]
struct PlanDraftState {
    latest: std::sync::Mutex<Option<ObjectiveDraft>>,
    /// The exact snapshot last shown to the operator, so a turn that saved no
    /// NEW revision (or none at all) presents nothing — the "present exactly
    /// once" half of the design — and so approval seeds implementation from
    /// what was shown, never from the mutable slot. Consumed by approval.
    presented: std::sync::Mutex<Option<ObjectivePresented>>,
}

#[derive(Debug, Clone)]
struct ObjectiveDraft {
    objective: newt_core::PromptId,
    draft: newt_core::agentic::PlanDraft,
}

#[derive(Debug, Clone)]
struct ObjectivePresented {
    objective: newt_core::PromptId,
    plan: newt_core::agentic::PresentedPlan,
}

/// The one filesystem write the draft seam performs. Injected into
/// [`TurnPlanDraftSink`] so the unit tier records writes in memory and the
/// real-resource tier grounds this exact function.
type PlanDraftPersist<'a> = &'a (dyn Fn(&std::path::Path, &str) -> std::io::Result<()> + Sync);

fn persist_plan_to_disk(path: &std::path::Path, markdown: &str) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, markdown)
}

impl PlanDraftState {
    fn clear(&self) {
        if let Ok(mut latest) = self.latest.lock() {
            *latest = None;
        }
        if let Ok(mut presented) = self.presented.lock() {
            *presented = None;
        }
    }

    fn bind<'a>(
        &'a self,
        conversation_id: &'a str,
        objective: Option<newt_core::PromptId>,
        persist: PlanDraftPersist<'a>,
    ) -> TurnPlanDraftSink<'a> {
        TurnPlanDraftSink {
            state: self,
            conversation_id,
            objective,
            persist,
        }
    }

    /// The latest draft for `objective`, if it has not already been
    /// presented. Records the presented snapshot as a side effect — call
    /// this exactly once, at the end of a turn, never mid-turn to steer
    /// model-facing behavior.
    fn take_for_presentation(
        &self,
        objective: newt_core::PromptId,
    ) -> Option<newt_core::agentic::PresentedPlan> {
        let held = self.latest.lock().ok()?.clone()?;
        if held.objective != objective {
            return None;
        }
        let mut presented = self.presented.lock().ok()?;
        if presented.as_ref().is_some_and(|p| {
            p.objective == objective && p.plan.draft.revision == held.draft.revision
        }) {
            return None;
        }
        let plan = newt_core::agentic::PresentedPlan::new(held.draft);
        *presented = Some(ObjectivePresented {
            objective,
            plan: plan.clone(),
        });
        Some(plan)
    }

    /// Consume the presented snapshot for `objective` on approval. `None`
    /// when nothing was presented under this objective — including when the
    /// only presented plan belongs to another objective — or when an earlier
    /// approval already consumed it, so one "yes" seeds at most one turn.
    fn take_approved(
        &self,
        objective: newt_core::PromptId,
    ) -> Option<newt_core::agentic::PresentedPlan> {
        let mut presented = self.presented.lock().ok()?;
        if presented.as_ref()?.objective != objective {
            return None;
        }
        presented.take().map(|p| p.plan)
    }
}

/// Turn-bound adapter that persists to one conversation's `plan.md`.
struct TurnPlanDraftSink<'a> {
    state: &'a PlanDraftState,
    conversation_id: &'a str,
    /// The objective this turn runs under; `None` (no receipt for the turn)
    /// refuses to save rather than bind a draft to nothing.
    objective: Option<newt_core::PromptId>,
    persist: PlanDraftPersist<'a>,
}

/// Pure: the next revision after `current`, starting at 1 — and restarting
/// at 1 when the objective changes, since the slot is per objective.
fn next_plan_draft_revision(
    current: Option<&ObjectiveDraft>,
    objective: newt_core::PromptId,
) -> u32 {
    match current {
        Some(held) if held.objective == objective => held.draft.revision + 1,
        _ => 1,
    }
}

impl newt_core::agentic::PlanDraftSink for TurnPlanDraftSink<'_> {
    fn save_draft(&self, markdown: String) -> Result<u32, String> {
        let objective = self
            .objective
            .ok_or_else(|| "plan draft: no active objective to bind to".to_string())?;
        let mut latest = self
            .state
            .latest
            .lock()
            .map_err(|_| "plan draft lock poisoned".to_string())?;
        let revision = next_plan_draft_revision(latest.as_ref(), objective);
        let path = newt_core::session_plan_path(self.conversation_id);
        (self.persist)(&path, &markdown).map_err(|error| format!("plan draft write: {error}"))?;
        *latest = Some(ObjectiveDraft {
            objective,
            draft: newt_core::agentic::PlanDraft { revision, markdown },
        });
        Ok(revision)
    }

    fn latest_draft(&self) -> Option<newt_core::agentic::PlanDraft> {
        let held = self.state.latest.lock().ok()?.clone()?;
        (Some(held.objective) == self.objective).then_some(held.draft)
    }
}

/// Conversation-scoped operating state with one boundary-clear operation.
///
/// Keeping these together makes it impossible for `/new`, persona rotation,
/// or restore to clear one model-selected mode while accidentally retaining
/// the other.
#[derive(Debug, Default)]
struct ConversationModeStates {
    auto: AutoModeState,
    plan: PlanModeState,
    plan_draft: PlanDraftState,
}

impl ConversationModeStates {
    fn clear(&self) {
        self.auto.clear();
        self.plan.clear();
        self.plan_draft.clear();
    }
}

/// Turn-bound adapter lent to the core loop only while the human-selected
/// session mode is Auto.
struct TurnAutoModeControl<'a> {
    state: &'a AutoModeState,
    conversation_id: &'a str,
}

impl newt_core::agentic::OperatingModeControl for TurnAutoModeControl<'_> {
    fn select_operating_mode(&self, requested: &str) -> Result<String, String> {
        let Some(mode) = OperatingMode::from_keyword(requested) else {
            return Err(
                "choose one of: chat, dev, admin, plan, diagnose (full-auto is human-only)"
                    .to_string(),
            );
        };
        if matches!(mode, OperatingMode::Auto | OperatingMode::FullAuto) {
            return Err(format!(
                "{} cannot be model-selected; choose chat, dev, admin, plan, or diagnose",
                mode.as_str()
            ));
        }
        let mut selected = self
            .state
            .selected
            .lock()
            .map_err(|_| "session mode state is unavailable".to_string())?;
        *selected = Some((self.conversation_id.to_string(), mode));
        Ok(format!(
            "selected {} for the next action-shaped turn in this conversation. \
             The current turn's operating mode, disposition, caveats, and permissions are unchanged.",
            mode.as_str()
        ))
    }
}

/// Apply a human `/mode` command to session state and return printable lines.
/// Invalid input is fail-closed: the active mode is left untouched.
fn operating_mode_command_lines(
    arg: &str,
    active: &mut OperatingMode,
) -> Result<Vec<String>, String> {
    let arg = arg.trim().to_ascii_lowercase();
    if arg.is_empty() || arg == "list" {
        let mut lines = vec![format!(
            "active operating mode: {} — {}",
            active.as_str(),
            active.description()
        )];
        lines.push("available operating modes:".to_string());
        lines.extend(
            OperatingMode::all()
                .iter()
                .map(|mode| format!("  {:<9} {}", mode.as_str(), mode.description())),
        );
        return Ok(lines);
    }
    if matches!(arg.as_str(), "show" | "status") {
        return Ok(vec![format!(
            "active operating mode: {} — {}",
            active.as_str(),
            active.description()
        )]);
    }
    if matches!(arg.as_str(), "off" | "clear" | "reset" | "default") {
        *active = OperatingMode::Chat;
        return Ok(vec![
            "operating mode reset to chat (the default)".to_string()
        ]);
    }
    let Some(mode) = OperatingMode::from_keyword(&arg) else {
        let names = OperatingMode::all()
            .iter()
            .map(|mode| mode.as_str())
            .collect::<Vec<_>>()
            .join(" | ");
        return Err(format!("unknown /mode '{arg}' — usage: /mode <{names}>"));
    };
    *active = mode;
    Ok(vec![format!(
        "operating mode set to {} — {}",
        mode.as_str(),
        mode.description()
    )])
}

/// Resolve the working style for this turn. An explicit human mode is stable;
/// `auto` first honors a conversation-local model selection on action-shaped
/// work, then falls back to a deterministic, inspectable choice from accepted
/// prompt intake. Protected non-action intake always wins. A legacy
/// model-entered plan phase is represented as `plan` so the prompt card and
/// executor cannot disagree.
fn effective_operating_mode(
    configured: OperatingMode,
    intake: &newt_core::agentic::PromptIntake,
    model_plan_phase: bool,
    auto_selected: Option<OperatingMode>,
) -> OperatingMode {
    use newt_core::agentic::PromptDisposition;
    if model_plan_phase {
        return OperatingMode::Plan;
    }
    if configured != OperatingMode::Auto {
        return match (configured, intake.disposition()) {
            // These two modes carry implementation imperatives. On protected
            // non-action intake, render disposition-compatible instructions
            // instead so small models are not told both to edit and not edit.
            (
                OperatingMode::Dev | OperatingMode::Admin | OperatingMode::FullAuto,
                PromptDisposition::Research,
            ) => OperatingMode::Diagnose,
            (
                OperatingMode::Dev | OperatingMode::Admin | OperatingMode::FullAuto,
                PromptDisposition::Plan,
            ) => OperatingMode::Plan,
            (
                OperatingMode::Dev | OperatingMode::Admin | OperatingMode::FullAuto,
                PromptDisposition::Ask | PromptDisposition::Explain,
            ) => OperatingMode::Chat,
            _ => configured,
        };
    }

    let prompt = intake
        .atomic_asks()
        .iter()
        .map(newt_core::agentic::AtomicAsk::text)
        .collect::<Vec<_>>()
        .join("\n")
        .to_ascii_lowercase();
    match intake.disposition() {
        PromptDisposition::Act => {
            if let Some(selected) = auto_selected
                .filter(|mode| !matches!(mode, OperatingMode::Auto | OperatingMode::FullAuto))
            {
                return selected;
            }
            // Action keywords win prompt intake. Only an explicit leading
            // orchestration intent overrides the normal developer style, so
            // "fix the diagnose mode" and "implement plan mode" remain dev.
            let mut objective = prompt.trim_start();
            for prefix in ["please ", "can you ", "could you ", "would you "] {
                if let Some(rest) = objective.strip_prefix(prefix) {
                    objective = rest.trim_start();
                    break;
                }
            }
            let starts_any =
                |needles: &[&str]| needles.iter().any(|needle| objective.starts_with(needle));
            if starts_any(&[
                "diagnose ",
                "investigate ",
                "troubleshoot ",
                "find the root cause",
            ]) {
                OperatingMode::Diagnose
            } else if starts_any(&["plan ", "write a plan", "make a plan", "formulate a plan"]) {
                OperatingMode::Plan
            } else if starts_any(&[
                "use admin mode",
                "work in admin mode",
                "act as a sysadmin",
                "perform system administration",
            ]) {
                OperatingMode::Admin
            } else {
                OperatingMode::Dev
            }
        }
        PromptDisposition::Research => OperatingMode::Diagnose,
        PromptDisposition::Ask | PromptDisposition::Explain => OperatingMode::Chat,
        PromptDisposition::Plan => OperatingMode::Plan,
    }
}

/// A mode can preserve or narrow prompt intake, never widen it. Plan and
/// diagnose force action-shaped prompts through the same `PromptIntake` object
/// later used by the model card, artifact recorder, catalog, and dispatcher.
fn apply_operating_mode_to_intake(
    mode: OperatingMode,
    intake: &mut newt_core::agentic::PromptIntake,
) {
    match mode {
        OperatingMode::Plan => {
            intake.enforce_read_only(newt_core::agentic::PromptDisposition::Plan);
        }
        OperatingMode::Diagnose => {
            intake.enforce_read_only(newt_core::agentic::PromptDisposition::Research);
        }
        _ => {}
    }
}

/// Only an operator-selected mode or an active model Plan phase may clamp
/// authority. Inferred working styles guide the response; they cannot remove
/// existing grants. Every clamp is a meet, so it cannot add authority either.
fn operating_mode_caveats(
    configured: OperatingMode,
    model_plan_phase: bool,
    caveats: newt_core::Caveats,
) -> newt_core::Caveats {
    let mode = if model_plan_phase {
        OperatingMode::Plan
    } else {
        configured
    };
    match mode {
        OperatingMode::Plan => caveats.meet(&newt_core::agentic::plan_phase_clamp()),
        OperatingMode::Diagnose => caveats.meet(&diagnose_mode_clamp()),
        _ => caveats,
    }
}

/// The ceiling re-applied by the permission gate after recalled or new grants.
fn operating_mode_permission_clamp(
    configured: OperatingMode,
    model_plan_phase: bool,
    posture_clamp: Option<newt_core::Caveats>,
) -> Option<newt_core::Caveats> {
    let has_posture_clamp = posture_clamp.is_some();
    let ceiling = operating_mode_caveats(
        configured,
        model_plan_phase,
        posture_clamp.unwrap_or_else(newt_core::Caveats::top),
    );
    (has_posture_clamp || ceiling != newt_core::Caveats::top()).then_some(ceiling)
}

/// Diagnose may gather remote read-only evidence, while still denying every
/// workspace mutation and executable spawn. Plan is stricter and remains
/// fully offline through [`newt_core::agentic::plan_phase_clamp`].
fn diagnose_mode_clamp() -> newt_core::Caveats {
    use newt_core::{CountBound, Scope};
    newt_core::Caveats {
        fs_read: Scope::All,
        fs_write: Scope::none(),
        exec: Scope::none(),
        net: Scope::All,
        max_calls: CountBound::Unlimited,
        valid_for_generation: Scope::All,
    }
}

fn operating_mode_prompt(configured: OperatingMode, effective: OperatingMode) -> String {
    let (description, instructions) = match (configured != effective, effective) {
        (true, OperatingMode::Diagnose) => (
            "Gather evidence and identify the cause.",
            "Gather evidence using the tools needed for the assignment under the session grants. \
             Report supported findings and continue any already requested follow-through. Ask \
             when a consequential decision or required permission remains unresolved.",
        ),
        (true, OperatingMode::Plan) => (
            "Organize the requested work into a concrete, sequenced plan.",
            "Build a concrete plan using necessary evidence and tools under the session grants. \
             Follow the requested scope and any active Plan-phase restrictions. Ask about \
             unresolved decisions or required permissions.",
        ),
        _ => (effective.description(), effective.instructions()),
    };
    let identity = if configured == effective {
        format!("Operating mode: {} — {}", effective.as_str(), description)
    } else {
        format!(
            "Configured session mode: {}. Effective working style for this turn: {} — {}.",
            configured.as_str(),
            effective.as_str(),
            description,
        )
    };
    let auto_control = if configured == OperatingMode::Auto {
        "\nAuto-mode control: use select_operating_mode when the next action-shaped turn \
         should use chat, dev, admin, plan, or diagnose. A selection takes effect only \
         on a later turn and grants no authority. Never attempt to select full-auto."
    } else {
        ""
    };
    let configured_invariants = if configured == OperatingMode::Admin {
        "\nConfigured admin invariants remain in force: Do no harm. Make minimal changes. \
         Respect privacy. With great power comes great responsibility."
    } else {
        ""
    };
    format!(
        "<operating_mode configured=\"{}\" effective=\"{}\">\n{}\n\
         Effective instructions:\n{}{}{}\n\
         Inferred styles guide the response; they do not change session grants or \
         bypass permission gates. Explicit operator Plan or Diagnose modes and an \
         active model Plan phase retain their permission ceilings. Stay within the \
         requested task.\n</operating_mode>",
        configured.as_str(),
        effective.as_str(),
        identity,
        instructions,
        auto_control,
        configured_invariants,
    )
}

// ---------------------------------------------------------------------------
// Named permission presets + the `/posture` command (issue #307).
// ---------------------------------------------------------------------------

// `ActivePosture` and `build_posture` live in `newt_core::posture` since #2009
// PR10c — §5.1's ledger named the posture as what blocked the Permissions
// section's write half, and a pure `settings_form::apply` cannot read a
// `run_chat` local. These aliases keep every reference in this crate reading
// as it did.
pub(crate) use newt_core::posture::{build_posture, ActivePosture};

/// Compose posture guidance from current session state on every turn. It is
/// deliberately not appended to the frozen base prompt: switching or clearing
/// a posture therefore cannot leave stale instructions behind, and `/new`
/// cannot accidentally drop an active posture.
fn posture_prompt(posture: &ActivePosture) -> String {
    let authority_line = if posture.permission_clamp().is_none() {
        format!(
            "Active permission posture: {} (no permission clamp)",
            posture.name
        )
    } else {
        format!(
            "Active permission posture: {} — {}",
            posture.name, posture.clamp_summary
        )
    };
    let mut lines = vec![
        format!(
            "<permission_posture name=\"{}\">",
            posture.name.replace('"', "&quot;")
        ),
        authority_line,
    ];
    if posture.permission_clamp().is_none() {
        lines.push(
            "This posture has no configured permission floor. Its skill and framing \
             do not grant authority; the session's existing boundaries remain in force."
                .to_string(),
        );
    } else {
        lines.push(
            "This posture's permission preset is an authority floor. It can only \
             narrow permissions and cannot be overridden by the operating mode or \
             a session grant."
                .to_string(),
        );
    }
    if let Some(framing) = &posture.framing {
        lines.push(format!("Posture framing: {framing}"));
    }
    if let Some(skill) = &posture.skill_body {
        lines.push(format!("Preloaded posture skill guidance:\n{skill}"));
    }
    lines.push("</permission_posture>".to_string());
    lines.join("\n")
}

fn session_control_prompt(
    configured_mode: OperatingMode,
    effective_mode: OperatingMode,
    posture: Option<&ActivePosture>,
) -> String {
    let mut prompt = operating_mode_prompt(configured_mode, effective_mode);
    if let Some(posture) = posture {
        prompt.push_str("\n\n");
        prompt.push_str(&posture_prompt(posture));
    }
    prompt
}

/// The session's EFFECTIVE authority for this turn: the session base
/// (`SessionCapability::caveats`) intersected with the active posture's
/// optional preset clamp. This is the single intersection point the
/// enforcement path consults — `meet` is the greatest lower bound, so the
/// result can never exceed EITHER the base or a configured preset. With no
/// active posture, or a posture with no preset, it is the base unchanged.
fn effective_caveats(
    base: &newt_core::Caveats,
    posture: Option<&ActivePosture>,
) -> newt_core::Caveats {
    match posture.and_then(ActivePosture::permission_clamp) {
        Some(clamp) => base.meet(clamp),
        None => base.clone(),
    }
}

/// Persona selection cannot change the operator's permission policy. Profile
/// caveats remain inspectable guidance; explicit postures and OCAP grants own
/// authority. Keep this turn boundary pure for both restrictive and broad roles.
fn meet_persona_caveats(
    base: newt_core::Caveats,
    _persona: Option<&Persona>,
) -> newt_core::Caveats {
    base
}

/// #774 (P0): the always-on exec FLOOR threaded to `execute_tool` as
/// `exec_floor`. The operator's `[tui.permissions]` exec clamp is a
/// NON-OPTIONAL floor — enforced even with NO active `/posture`.
///
/// `effective_exec` is the base `[tui.permissions]` exec scope already met with
/// any configured `/posture` clamp (i.e.
/// `effective_caveats(base, posture).exec`), so the floor is meet-only: a
/// posture preset can only TIGHTEN it, never widen it past either the base or
/// the preset.
///
/// Returns `Some(effective_exec)` whenever the operator configured a restrictive
/// exec clamp (`Scope::Only`) OR a `/posture` permission floor is active, so an
/// out-of-floor command can never take the `--disable-ocap` / `--yolo`
/// unconfined bypass — it falls through to the confined shell, which enforces
/// the (already-clamped) caveats and denies it. Returns `None` ONLY when exec is
/// unrestricted (`Scope::All`) AND no posture permission floor is active,
/// leaving the unrestricted `--disable-ocap` bypass exactly as it was pre-#307.
///
/// Before #774 the floor was sourced from the active `/posture` ALONE
/// (`active_posture.map(|p| p.clamp.exec.clone())`), so a configured
/// `[tui.permissions]` clamp imposed NO floor without a posture — the
/// design-review F1 finding: the operator's exec clamp was not enforced by
/// default on the bypass path.
fn exec_floor_from(
    effective_exec: &newt_core::caveats::Scope<String>,
    posture_floor_active: bool,
) -> Option<newt_core::caveats::Scope<String>> {
    use newt_core::caveats::Scope;
    match effective_exec {
        // Unrestricted base, no posture preset ⇒ no floor (pre-#307 bypass).
        Scope::All if !posture_floor_active => None,
        // A configured restriction or posture preset is an always-on floor.
        scope => Some(scope.clone()),
    }
}

/// Render the `/permissions` listing: this session's prompted decisions (in
/// prompt order), retained authority, and the explicit promotion entrypoints.
///
/// `active_posture` (issue #307) reflects an applied `/posture` preset as an
/// authority floor at the top of the listing, even when prompting is off.
pub(crate) fn permissions_command_lines(
    state: &PermissionPromptState,
    enabled: bool,
    log_path: Option<&std::path::Path>,
    active_posture: Option<&ActivePosture>,
) -> Vec<String> {
    let mut lines = Vec::new();
    if let Some(posture) = active_posture {
        if posture.permission_clamp().is_none() {
            lines.push(format!(
                "active permission posture: {} (no permission clamp)",
                posture.name
            ));
        } else {
            lines.push(format!(
                "active permission posture: {} — preset '{}' clamps authority (floor): {}",
                posture.name, posture.preset_name, posture.clamp_summary
            ));
            lines.push(
                "this clamp WINS over --disable-ocap/--yolo and over session grants (#307)"
                    .to_string(),
            );
        }
    }
    if !enabled {
        lines.push(
            "permission prompting is OFF (start with --prompt-for-permissions or set \
             [tui.permissions] prompt = true)"
                .to_string(),
        );
    }
    lines.push(format!(
        "session allows: {} · encrypted permanent allows: {} · terminal default: {}",
        state.session_allow_count(),
        state.durable_grants.len(),
        state.terminal_default().as_str()
    ));
    if state.decisions.is_empty() {
        lines.push("no prompted permission decisions this session".to_string());
    } else {
        lines.push("prompted permission decisions this session:".to_string());
        for d in &state.decisions {
            lines.push(format!(
                "  {:<5} {:<7}  {}:{}  via {}",
                d.decision, d.scope, d.kind, d.target, d.tool
            ));
        }
    }
    if let Some(path) = log_path {
        lines.push(format!("log: {}", path.display()));
        lines.push(
            "make session allows permanent in /settings → Permissions (OCAP), or /permissions save. \
             The reviewed snapshot is signed and encrypted; the log is never authority. \
             The hostname prompt's [A] choice still saves net hosts to TOML config."
                .to_string(),
        );
    }
    lines
}

#[cfg(feature = "rich-tui")]
pub(crate) fn permission_panel_lines(
    state: &PermissionPromptState,
    enabled: bool,
    log: Option<&std::path::Path>,
    posture: Option<&ActivePosture>,
) -> Vec<String> {
    let mut rows = permissions_command_lines(state, enabled, log, posture);
    if let Some(path) = log {
        rows.push(String::new());
        rows.extend(permission_audit_lines(path, 50));
    }
    rows
}

/// Parse the flat, pre-chain `PermissionRecord` lines out of a JSONL body
/// (one JSON object per line, no [`newt_core::event_journal::JournalLine`]
/// envelope). Unparseable lines are dropped — they are not part of a chain
/// to report a break against, since this body predates the chain entirely.
fn flat_permission_records(body: &str) -> Vec<newt_core::PermissionRecord> {
    body.lines()
        .filter(|l| !l.trim().is_empty())
        .filter_map(|l| serde_json::from_str(l).ok())
        .collect()
}

/// One `/permissions audit` row; chained and unchained history share it.
fn audit_row(rec: &newt_core::PermissionRecord) -> String {
    format!(
        "  {:<7} {:<9} {:<8} {} via {}",
        rec.decision, rec.scope, rec.kind, rec.target, rec.tool
    )
}

/// `/ocap propose` — fold this session's flight-recorder capture into a
/// reviewable `approve.toml` proposal (issue #2679). The capture is GLOBAL
/// across sessions, so it is narrowed to this session via the `session:`
/// argument thread through [`newt_core::ocap_propose::propose_for`]: only the
/// caveats recorded under the current session id survive (session-less
/// caveats from before scoping existed are excluded), so a shared capture file never
/// mixes one session's observed authority with another's. The proposer itself
/// is shared with the CLI, so the panel cannot drift from the headless
/// command. `save` records the low-danger candidates UNSIGNED (they are
/// no-ops until `newt doctor --sign-ocap`).
///
/// Returns the rendered lines, or an error line.
fn ocap_propose_command_lines(
    capture_override: Option<PathBuf>,
    config: Option<&Path>,
    save: bool,
    session: Option<&str>,
) -> anyhow::Result<Vec<String>> {
    // The capture is global across sessions. With no owning session there is
    // nothing that is provably THIS session's evidence, so propose nothing
    // rather than fall back to an all-session read (that is the CLI's job).
    let Some(session) = session else {
        return Ok(vec![
            "No active session, so there is no session-scoped evidence to propose from. \
`newt ocap propose` (CLI) reviews the whole capture."
                .to_string(),
        ]);
    };
    let config_path = config
        .map(Path::to_path_buf)
        .or_else(newt_core::Config::user_config_path)
        .ok_or_else(|| anyhow::anyhow!("cannot resolve the newt config directory"))?;

    // No capture file means there is no observed authority to propose from —
    // arm the recorder first. Never fabricate a proposal.
    let capture_path = resolve_ocap_capture_path(capture_override, &config_path);
    let capture_text = match std::fs::read_to_string(&capture_path) {
        Ok(t) => t,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Ok(vec![
                format!("No flight-recorder capture at {}.", capture_path.display()),
                "Arm the recorder by running a task under `--full-access` (or set \
`$NEWT_FLIGHT_RECORDER`); then `/ocap propose` turns that observed authority into a \
reviewable proposal."
                    .to_string(),
            ]);
        }
        Err(e) => return Err(anyhow::anyhow!("read {}: {e}", capture_path.display())),
    };

    // Read the four store files RAW (unverified) so already-written-but-unsigned
    // candidates count as accounted-for and re-runs converge — same as the CLI.
    let store_dir = config_path.with_file_name("ocap");
    let store_files: Vec<(newt_core::ocap_store::Verdict, Option<String>)> =
        newt_core::ocap_store::VERDICTS
            .iter()
            .map(|&v| {
                (
                    v,
                    std::fs::read_to_string(store_dir.join(v.filename())).ok(),
                )
            })
            .collect();
    // The existing approve file is merged into, never replaced: every entry
    // and signature in it survives a save. An unreadable file refuses the save
    // rather than overwrite what could not be read.
    let approve_path = store_dir.join(newt_core::ocap_store::Verdict::Approve.filename());
    let existing = match std::fs::read_to_string(&approve_path) {
        Ok(t) => Some(t),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
        Err(e) => return Err(anyhow::anyhow!("read {}: {e}", approve_path.display())),
    };

    let now = crate::probe::today_local_date();
    let (merged, proposal) = newt_core::ocap_propose::propose_for(
        &capture_text,
        &store_files,
        existing.as_deref(),
        crate::ocap_high_danger_predicate(),
        &now,
        Some(session),
    )
    .map_err(|e| anyhow::anyhow!("propose: {e}"))?;

    if proposal.is_empty() {
        return Ok(vec![
            "This session's capture is fully accounted for by the current policy — nothing to propose."
                .to_string(),
        ]);
    }

    // `save` records the low-danger candidates UNSIGNED — they are no-ops until
    // `newt doctor --sign-ocap`. Never write past the danger gate.
    let wrote = save && proposal.additions_len() > 0;
    if wrote {
        let merged_toml = merged
            .to_toml()
            .map_err(|e| anyhow::anyhow!("serialize approve.toml: {e}"))?;
        std::fs::create_dir_all(&store_dir)
            .map_err(|e| anyhow::anyhow!("create {}: {e}", store_dir.display()))?;
        std::fs::write(&approve_path, &merged_toml)
            .map_err(|e| anyhow::anyhow!("write {}: {e}", approve_path.display()))?;
    }
    Ok(render_ocap_proposal(&proposal, wrote))
}

/// Usage line for a malformed `/ocap` command.
pub(crate) const OCAP_USAGE: &str = "usage: /ocap propose        show this session's grant candidates\n       /ocap propose save   also write them, unsigned, to approve.toml";

/// Parse `/ocap propose [save]` (the slash body, without the leading `/`).
/// `Some(save)` for the two accepted forms; `None` for anything else.
pub(crate) fn parse_ocap_command(slash_body: &str) -> Option<bool> {
    let words: Vec<&str> = slash_body.split_whitespace().collect();
    match words.as_slice() {
        ["ocap", "propose"] => Some(false),
        ["ocap", "propose", "save"] => Some(true),
        _ => None,
    }
}

/// The human note on a proposed entry, or `"observed"` when none is present —
/// mirrors the CLI's `note_of` (`newt-cli/src/ocap_cmd.rs`) so the panel and
/// the headless command label entries the same way.
fn note_of(note: &Option<String>) -> &str {
    note.as_deref().unwrap_or("observed")
}

/// Pure render of a `/ocap propose` proposal — the low-danger additions, the
/// deferred high-danger observations with reasons, and the next step. Mirrors
/// `newt ocap propose`'s `render` (`newt-cli/src/ocap_cmd.rs`) so the panel and
/// the headless command print the same shape.
fn render_ocap_proposal(proposal: &newt_core::ocap_propose::Proposal, wrote: bool) -> Vec<String> {
    let mut out = Vec::new();
    out.push(format!(
        "Proposed {} durable candidate(s) from this session's capture:",
        proposal.additions_len()
    ));
    for e in &proposal.additions.exec {
        out.push(format!("  exec  {}   [{}]", e.target, note_of(&e.note)));
    }
    for e in &proposal.additions.fs {
        let mode = if e.write { "rw" } else { "ro" };
        out.push(format!(
            "  fs    {} ({mode})   [{}]",
            e.path,
            note_of(&e.note)
        ));
    }
    for e in &proposal.additions.net {
        out.push(format!("  net   {}   [{}]", e.host, note_of(&e.note)));
    }
    out.push(String::new());
    for d in &proposal.deferred {
        out.push(format!("  deferred (review, high danger): {}", d.class));
        out.push(format!(
            "    {} — {}",
            d.command,
            d.reason.trim_start_matches("observed: ").trim()
        ));
    }
    out.push(String::new());
    if wrote {
        out.push(String::from(
            "Wrote the low-danger candidates to the approve store (UNSIGNED — \
             these grants are no-ops until you `newt doctor --sign-ocap`).",
        ));
    } else {
        out.push(String::from(
            "This is a reviewable proposal only. To record the low-danger candidates \
             UNSIGNED, run `/ocap propose save`, then `newt doctor --sign-ocap` to bless them.",
        ));
    }
    out
}

/// Capture-path selection for `/ocap propose`, shared shape with the CLI's
/// `resolve_capture_path`: an explicit `--capture`/file override wins, then a
/// non-opt-out `$NEWT_FLIGHT_RECORDER`, then the default beside the config.
fn resolve_ocap_capture_path(capture: Option<PathBuf>, config_path: &Path) -> PathBuf {
    if let Some(p) = capture {
        return p;
    }
    if let Some(v) = std::env::var_os(newt_core::flight_recorder::CAPTURE_PATH_ENV) {
        let s = v.to_string_lossy();
        if !(s.eq_ignore_ascii_case("off") || s == "0") {
            return PathBuf::from(v);
        }
    }
    config_path
        .with_file_name("flight-recorder")
        .join("unconfined.jsonl")
}

/// Render up to `limit` flat records as unchained-history rows, newest last
/// (append order) — matches the labelling the chained rows below it use.
fn push_unchained(out: &mut Vec<String>, records: &[newt_core::PermissionRecord], limit: usize) {
    let show = if limit == 0 { records.len() } else { limit };
    for rec in records.iter().take(show) {
        out.push(format!("{} (unchained)", audit_row(rec)));
    }
}

/// Report what the chain proves before anything it contains is presented as
/// evidence — one header row per [`newt_core::permission_journal::ChainBreak`],
/// mirroring `newt ocap denials`' `render_integrity`
/// (`newt-cli/src/ocap_cmd.rs`).
fn push_chain_breaks(
    out: &mut Vec<String>,
    breaks: &[newt_core::permission_journal::ChainBreak],
    anchored: bool,
) {
    use newt_core::permission_journal::ChainBreak;
    if breaks.is_empty() {
        return;
    }
    let anchor = if anchored {
        "anchored to the stored head"
    } else {
        "no stored head ref, so removal from the END was NOT checked"
    };
    out.push(format!(
        "!! CHAIN BROKEN — this permission log does not verify ({} problem(s); {anchor}).",
        breaks.len()
    ));
    for br in breaks {
        out.push(match br {
            ChainBreak::Edited { index } => {
                format!("!!   record {index}: edited — its bytes no longer match its own address")
            }
            ChainBreak::Unreadable { index } => {
                format!("!!   record {index}: its address does not parse")
            }
            ChainBreak::BrokenLink { index } => format!(
                "!!   record {index}: broken link — a record before it was deleted or reordered"
            ),
            ChainBreak::NotAChain { index } => {
                format!("!!   record {index}: not a single-parent chain link")
            }
            ChainBreak::Truncated { expected_head } => format!(
                "!!   truncated — the chain no longer reaches the stored head {expected_head}"
            ),
        });
    }
}

/// Parse the permission log into human-readable audit rows (newest-first).
///
/// #2529 round 2 (items 1–4): a tampered chain never renders like genuine
/// history, and a pre-chain body — whether rotated aside to `.pre-chain` or
/// still sitting unrotated in the log itself — is shown as unchained history
/// rather than silently vanishing.
pub(crate) fn permission_audit_lines(log_path: &std::path::Path, limit: usize) -> Vec<String> {
    let body = match std::fs::read_to_string(log_path) {
        Ok(body) => body,
        Err(e) => {
            return vec![format!(
                "unable to read permission log {}: {e}",
                log_path.display()
            )];
        }
    };

    let mut out = Vec::new();
    let chained = newt_core::permission_journal::read_jsonl(&body);

    // Item 4: not yet rotated — the whole file is still a flat pre-chain
    // body. Detected on read, not by a write-time flag.
    if chained.is_empty() && !body.trim().is_empty() {
        let unchained = flat_permission_records(&body);
        if !unchained.is_empty() {
            out.push(
                "pre-chain migration: this log has not been rotated onto the chain yet — \
                 the lines below carry no integrity guarantee"
                    .to_string(),
            );
            push_unchained(&mut out, &unchained, limit);
            return out;
        }
    }

    // Item 3: an unparseable line is a chain break, not a silent skip.
    let raw_lines = body.lines().filter(|l| !l.trim().is_empty()).count();
    let unparseable = raw_lines.saturating_sub(chained.len());
    let head = newt_core::permission_journal::read_head(log_path);
    let mut breaks = newt_core::permission_journal::verify_chain(&chained, head.as_deref());
    breaks.extend((0..unparseable).map(|_| {
        newt_core::permission_journal::ChainBreak::Unreadable {
            index: chained.len(),
        }
    }));
    // Item 2: a header row per break, before any record renders.
    push_chain_breaks(&mut out, &breaks, head.is_some());

    // Item 1: a rotated pre-chain sibling exists — say so, and render its
    // lines (within `limit`) as unchained history.
    let pre_chain_path = newt_core::permission_journal::pre_chain_path(log_path);
    if let Ok(pre_body) = std::fs::read_to_string(&pre_chain_path) {
        let unchained = flat_permission_records(&pre_body);
        if !unchained.is_empty() {
            out.push(format!(
                "pre-chain migration: {} holds the earlier lines",
                pre_chain_path.display()
            ));
            push_unchained(&mut out, &unchained, limit);
        }
    }

    let records = newt_core::permission_journal::records(&chained);
    if records.is_empty() {
        if out.is_empty() {
            out.push("no permission log entries yet".to_string());
        }
        return out;
    }

    let show = if limit == 0 { records.len() } else { limit };
    let shown = records.len().min(show);
    out.push(format!(
        "permission audit: {shown} of {} (newest first)",
        records.len()
    ));
    for rec in records.iter().rev().take(show) {
        out.push(audit_row(rec));
    }
    out
}

// ---------------------------------------------------------------------------
// INTERIM (#297): --disable-ocap / --yolo session surfacing. Removed with the
// bypass when brush upstreams CommandInterceptor (agent-bridle#20).
// ---------------------------------------------------------------------------

/// INTERIM (#297): the unmissable session-start banner shown when the ocap
/// exec bypass is asserted (`--disable-ocap` / `--yolo` /
/// `NEWT_DISABLE_OCAP=1`). The bypass itself lives at the `run_command`
/// dispatch in newt-core; this is the loud surfacing half of the contract.
fn ocap_disabled_banner() -> String {
    "⚠ ocap DISABLED (--disable-ocap): permitted commands may run unconfined on the \
     host shell; active exec floors can force confinement or denial — fs tools keep \
     the workspace fence; drop the flag to restore default confinement (#297)"
        .to_string()
}

/// INTERIM (#297): the ONE `ocap-disabled` line written to the #263
/// permission log at session start, so the audit trail shows this session
/// requested the unconfined exec bypass. `decision: "ocap-disabled"`, `scope:
/// "session"` per the issue; the `*` target means the bypass is enabled for the
/// session, while effective exec floors still decide each command. A record,
/// not authority: nothing reads it back.
fn ocap_disabled_record(conversation_id: &str) -> newt_core::PermissionRecord {
    newt_core::PermissionRecord::new(
        conversation_id,
        "run_command",
        newt_core::DenialKind::Exec,
        "*",
        "ocap-disabled",
        "session",
    )
}

/// The unmissable session-start banner shown when the `--full-access` preset
/// override is asserted (`NEWT_FULL_ACCESS=1`). The override itself lives in
/// `policy_for`; this is the loud surfacing half of the contract, mirroring
/// `ocap_disabled_banner`.
fn full_access_banner() -> String {
    // #926: frame this as *ambient authority* + OCAP attenuation, not merely
    // "unrestricted" — the point of the harness is to attenuate the user's full
    // ambient authority into structural grants; --full-access temporarily hands
    // that ambient authority back. It also switches run_command to the `host`
    // shell engine (a real /bin/sh in the platform kernel jail).
    "⚠ FULL ACCESS (--full-access): the agent is granted your full AMBIENT authority \
     for this run — the Object-Capability attenuations (fs fence, net leash, exec \
     allowlist) are lifted and run_command uses the `host` shell engine (a real \
     /bin/sh inside the platform kernel jail). Writes are still prompted. Drop the \
     flag to restore Object-Capability authority restrictions. Private HTTP destinations \
     still require exact MCP net grants in [tui.permissions] net."
        .to_string()
}

/// The ONE `full-access` line written to the #263 permission log at session
/// start, so the audit trail shows this session ran with the unrestricted
/// preset override. The override widens every capability axis; the log schema
/// records one line keyed on the exec axis (the sharpest one), `target: "*"`,
/// `scope: "session"` — the override is per-session, never per-command. A
/// record, not authority: nothing reads it back.
fn full_access_record(conversation_id: &str) -> newt_core::PermissionRecord {
    newt_core::PermissionRecord::new(
        conversation_id,
        "session",
        newt_core::DenialKind::Exec,
        "*",
        "full-access",
        "session",
    )
}

/// Contract honesty (#2532 review, item 3): the ONE `ocap-store-folded` line
/// written to the #263 permission log at session start when
/// `fold_ocap_approvals` actually widened something — so `/permissions` (and
/// the audit trail) can show provenance for a caveat the operator did not
/// grant THIS session, matching headless's contract-record receipt for the
/// same fold. `target` carries the count rather than a single axis/target,
/// since the fold is many grants folded in one step; `scope: "durable-store"`
/// distinguishes it from a `session`/`durable` (`/permissions`-promoted)
/// grant. Only called when `folded_count > 0` — a log line for zero folds is
/// noise, not audit.
fn ocap_store_folded_record(
    conversation_id: &str,
    folded_count: usize,
) -> newt_core::PermissionRecord {
    newt_core::PermissionRecord::new(
        conversation_id,
        "session",
        newt_core::DenialKind::Exec,
        &format!("{folded_count} durable grant(s)"),
        "allow",
        "durable-store",
    )
}

/// Process-environment synchronization for tests.
///
/// `cargo test` runs tests of this binary concurrently while the environment
/// is process-global. Tests that mutate env vars (e.g. `NEWT_EXEC_PATHS`,
/// `NEWT_VENV`) or that read resolution which depends on them take a guard,
/// so a mutation can never land mid-test.
///
/// **All four functions return the SAME lock** — `newt_core::process_env`'s
/// (#1850). This module used to own a private `RwLock` while
/// `newt_core::test_guard::GlobalSettingsGuard` owned an independent `Mutex`
/// over the same variables; two locks over one environment serialize nothing,
/// and the resulting race took down `tab_switch::state_machine_tests` and
/// `helper_fn_tests` wholesale in ~30% of `--all-features` runs. The
/// read/write and sync/async names are kept because they still document a
/// call site's INTENT, but the lock underneath is one exclusive, reentrant
/// lock that the production writers take as well.
#[cfg(test)]
pub(crate) mod test_env_guard {
    use newt_core::process_env::{lock, EnvGuard};

    /// Guard for synchronous tests that READ env-dependent resolution.
    pub(crate) fn env_read_guard() -> EnvGuard {
        lock()
    }

    /// Reader guard for `#[tokio::test]` tests. Kept as its own `async fn`
    /// so call sites keep their `.await`; the lock itself is sync and needs
    /// no runtime, which is why the old `blocking_read`-panics-in-a-runtime
    /// hazard is gone.
    pub(crate) async fn env_read_guard_async() -> EnvGuard {
        lock()
    }

    /// Guard for tests that MUTATE the process environment.
    pub(crate) fn env_write_guard() -> EnvGuard {
        lock()
    }

    /// Writer guard for `#[tokio::test]` tests. Gated like the rest of the
    /// #297 disable-ocap tests it serves, so Windows does not trip
    /// `-D warnings` on dead code.
    #[cfg(unix)]
    pub(crate) async fn env_write_guard_async() -> EnvGuard {
        lock()
    }
}

/// **#1850 regression — one lock over the process environment.**
///
/// The flake this pins was never a wrong assertion. It was TWO locks:
/// `newt_core::test_guard::GlobalSettingsGuard` (a `Mutex`) and this crate's
/// `test_env_guard` (an `RwLock`), each claiming `NEWT_PROVIDER` /
/// `NEWT_DGX_MODEL`, neither excluding the other — plus production writers
/// holding neither under `// SAFETY: single-threaded REPL`, a claim that is
/// true of the REPL and false under `cargo test`.
///
/// The cost was ~30% of `cargo test -p newt-tui --lib --all-features` runs,
/// with whole modules going down together: 30 `tab_switch::state_machine_tests`
/// panicking inside a backend re-resolve, and
/// `helper_fn_tests::resolver_default_backend_beats_the_openai_heuristic`
/// asserting against a literal `"bound-model"` that exists nowhere but
/// `lib_tests::env_resolution`'s fixture.
#[cfg(test)]
#[path = "lib_tests/process_env_isolation_tests.rs"]
mod process_env_isolation_tests;

#[cfg(test)]
#[path = "lib_tests/caveat_policy_tests.rs"]
mod caveat_policy_tests;

/// `NoteSink` over the session `MemoryManager` (Step 19.3, #248): the model's
/// `save_note` tool and the human's `/remember` command route through the
/// SAME `MemoryManager` → `NoteStore` write path — one store, one write-time
/// security scan, one char budget. Borrows the manager only for the duration
/// of a single `chat_complete` call.
struct ManagerNoteSink<'m> {
    memory: &'m mut newt_core::MemoryManager,
}

impl newt_core::NoteSink for ManagerNoteSink<'_> {
    fn add(&mut self, fact: &str) -> anyhow::Result<()> {
        self.memory.add_note(fact)
    }
    fn replace(&mut self, old_substring: &str, new_text: &str) -> anyhow::Result<()> {
        self.memory.replace_note(old_substring, new_text)
    }
    fn remove(&mut self, substring: &str) -> anyhow::Result<()> {
        self.memory.remove_note(substring)
    }
    fn usage_line(&self) -> String {
        self.memory
            .usage()
            .iter()
            .find(|(label, _, _)| label == "notes")
            .map(|(_, cur, max)| {
                let pct = if *max > 0 { cur * 100 / max } else { 0 };
                format!("notes: {cur}/{max} chars ({pct}%)")
            })
            .unwrap_or_else(|| "notes: usage unavailable".to_string())
    }
}

/// Build the agentic loop's compression summarizer (Step 18.4, #247): one
/// tools-disabled completion against the active backend, mirroring the
/// `Summarizing` provider's `with_summarizer` wiring below — but async,
/// because the loop invokes it mid-turn from inside its own async context.
/// A non-2xx status or empty content is an error so the loop falls back to
/// the static compaction marker instead of injecting garbage.
///
/// `num_ctx` is the same effective context cap the main loop sends
/// (`options.num_ctx` on Ollama): the summary request is typically the
/// largest single message of the session, and without the cap Ollama
/// silently truncates it at the model's default window (F5).
/// OpenAI-compatible endpoints configure context server-side — ignored.
/// Summarizer knobs (Step 24.2, #559). Consolidated into one struct so new knobs
/// (24.3's fallback model, …) add a field rather than another positional param
/// at every `make_loop_summarizer` call site. `Default` lets a call site set
/// only what it cares about (`..Default::default()`).
#[derive(Clone)]
struct SummarizerOpts {
    /// Effective `num_ctx` cap sent to Ollama (F5); `None` = model default.
    num_ctx: Option<u32>,
    /// Ollama `keep_alive` for the warm + summary requests (Step 24.1).
    keep_alive: String,
    /// Per-request timeout in seconds (Step 24.2; `summarizer.toml` `timeout_secs`).
    timeout_secs: u64,
    /// Retry attempts before falling back to the static marker (Step 24.2).
    retries: u32,
    /// Optional fallback model (Step 24.3; `summarizer.toml` `fallback_model`).
    /// When the primary model's attempts all fail, the summary is retried once
    /// on this model — a rung above the static marker. `None` = no fallback.
    fallback_model: Option<String>,
    /// Styling ONLY: may the live retry/fallback notices carry ANSI color?
    /// Never a capability signal — `color` used to gate whether these notices
    /// were emitted *at all*, which is exactly the styling-into-I/O-ownership
    /// overload `LineCaps` exists to end (see `newt_core::tty::caps`).
    color: bool,
    /// Whether this process may narrate onto the terminal at all (Step 24.7's
    /// real question). `None` — the default — emits zero bytes, so a headless
    /// or captured stream stays clean even under `NEWT_COLOR=always`.
    caps: newt_core::tty::LineCaps,
    /// #2313 b3: the session's shared run allowance, when one is configured.
    /// A summary request is a real inference call against the same run as
    /// the primary loop, so it draws from the SAME budget the primary loop's
    /// `ChatCtx.run_allowance` reserves against — this is the session's own
    /// `Arc` clone, not a second counter. `None` (the default) is unbudgeted,
    /// unchanged behavior.
    run_allowance: Option<std::sync::Arc<newt_core::agentic::run_allowance::RunAllowance>>,
}

impl Default for SummarizerOpts {
    fn default() -> Self {
        Self {
            num_ctx: None,
            keep_alive: "5m".to_string(),
            timeout_secs: 60,
            retries: 2,
            fallback_model: None,
            color: false,
            caps: newt_core::tty::LineCaps::None,
            run_allowance: None,
        }
    }
}

/// Live summarizer-progress notices (Step 24.7, #559). The summarizer runs
/// under the `summarizing context…` spinner, so each notice has to scroll into
/// history *without* destroying the row the spinner is redrawing.
///
/// These are the pure text builders; [`summarizer_notice`] wraps one in a
/// `Notice` and the arbiter does the cooperating. Until this migration the
/// wrapping was a local `summarizer_progress` that wrote `\r\x1b[K` straight to
/// stdout with no lease — the race documented on
/// `newt_core::tty::Terminal::emit_line`.
fn retry_progress_msg(attempt: u32, total: u32) -> String {
    format!("↻ summarizer retrying (attempt {attempt}/{total})…")
}
fn fallback_progress_msg(model: &str) -> String {
    format!("⚠ summarizer falling back to {model}…")
}
fn failure_progress_msg(err: &anyhow::Error) -> String {
    format!("⚠ summarizer failed ({err}); using static compression marker…")
}

/// One summarizer notice, as a `Notice` value. The text already leads with its
/// own sigil, so the glyph is empty and `line()` is the message verbatim —
/// which is what keeps the builders above (and their tests) untouched.
fn summarizer_notice(msg: String) -> newt_core::tty::Notice<'static> {
    newt_core::tty::Notice::new(newt_core::tty::Level::Warn, "", msg)
}

/// One summary attempt: send, check status, parse the content.
async fn summarize_attempt(
    client: &reqwest::Client,
    chat_url: &str,
    body: &serde_json::Value,
    api_key: &Option<String>,
    openai: bool,
) -> anyhow::Result<(String, Option<newt_core::TokenUsage>)> {
    let mut req = client.post(chat_url).json(body);
    if let Some(key) = api_key {
        req = req.bearer_auth(key);
    }
    let resp = req.send().await?;
    if !resp.status().is_success() {
        anyhow::bail!("summarizer endpoint {}", resp.status());
    }
    let json: serde_json::Value = resp.json().await?;
    extract_summary(&json, openai)
}

/// Extract the summary text from a chat response, robust to THINKING models.
/// A thinking model asked to summarize may wrap the summary in inline
/// `<think>…</think>` (stripped here via `split_reasoning`) or — on Ollama — put
/// its reasoning in a separate `thinking` field and leave `content` EMPTY. The
/// request sends `think: false` to prevent the empty-content case for
/// cooperative models; this is the response-side belt-and-suspenders. A
/// still-empty result is a genuine empty summary (the caller degrades it to the
/// static marker) rather than a `<think>`-polluted string masquerading as one.
fn extract_summary(
    json: &serde_json::Value,
    openai: bool,
) -> anyhow::Result<(String, Option<newt_core::TokenUsage>)> {
    let raw = if openai {
        json["choices"][0]["message"]["content"].as_str()
    } else {
        json["message"]["content"].as_str()
    }
    .unwrap_or("");
    let (clean, _reasoning) = newt_core::split_reasoning(raw);
    if clean.trim().is_empty() {
        anyhow::bail!("summarizer returned empty content (thinking-only reply?)");
    }
    let usage = if openai {
        newt_core::agentic::openai_usage(&json["usage"])
    } else {
        newt_core::agentic::ollama_usage(json)
    };
    Ok((clean, usage))
}

#[cfg(test)]
#[path = "lib_tests/summarizer_extract_tests.rs"]
mod summarizer_extract_tests;

/// Warm (Ollama), build the body, and run the retry loop for ONE model. Used
/// for the primary model and, on total failure, the optional fallback (24.3).
async fn summarize_one_model(
    url: &str,
    model: &str,
    openai: bool,
    prompt: &str,
    opts: &SummarizerOpts,
    api_key: &Option<String>,
) -> anyhow::Result<(String, Option<newt_core::TokenUsage>)> {
    let chat_url = if openai {
        format!("{}/v1/chat/completions", url.trim_end_matches('/'))
    } else {
        format!("{}/api/chat", url.trim_end_matches('/'))
    };
    // Step 24.1 (#559): for Ollama, warm the model under a generous timeout
    // BEFORE the short-timeout summary request, so a cold reload is absorbed
    // here instead of blowing the summary timeout. Best-effort: warm errors are
    // ignored (the real request surfaces a hard failure).
    if !openai {
        let warm_url = format!("{}/api/generate", url.trim_end_matches('/'));
        let warm_body = serde_json::json!({
            "model": model,
            "keep_alive": opts.keep_alive,
            "stream": false,
        });
        if let Ok(warm_client) = reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(600))
            .build()
        {
            let mut wreq = warm_client.post(&warm_url).json(&warm_body);
            if let Some(key) = api_key {
                wreq = wreq.bearer_auth(key);
            }
            let _ = wreq.send().await;
        }
    }
    // No `tools` key => the model cannot emit tool calls. Ollama also gets
    // `keep_alive` (mirroring the main loop) so the summary request doesn't
    // reset the model's residency to Ollama's default.
    let body = if openai {
        serde_json::json!({
            "model": model,
            "messages": [{"role": "user", "content": prompt}],
            "stream": false,
        })
    } else {
        // `think: false` — a summary is a direct extraction task, not a
        // reasoning one. A thinking model (emits_thinking) otherwise returns a
        // thinking-only reply with EMPTY content that degrades to the static
        // marker (silent context loss). Non-thinking models / older Ollama
        // ignore the field.
        let mut b = serde_json::json!({
            "model": model,
            "messages": [{"role": "user", "content": prompt}],
            "stream": false,
            "think": false,
            "keep_alive": opts.keep_alive,
        });
        if let Some(ctx_size) = opts.num_ctx {
            b["options"] = serde_json::json!({ "num_ctx": ctx_size });
        }
        b
    };
    // Step 24.2 (#559): retry with backoff before giving up. The per-request
    // timeout is configurable (`summarizer.toml` `timeout_secs`).
    let client = reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(opts.timeout_secs))
        .build()?;
    let mut last_err: Option<anyhow::Error> = None;
    for attempt in 0..=opts.retries {
        if attempt > 0 {
            // Step 24.7 (#559): surface the retry live (scrolls above the
            // `summarizing context…` spinner) so the recovery is honest.
            summarizer_notice(retry_progress_msg(attempt + 1, opts.retries + 1)).emit(
                opts.caps,
                newt_core::tty::Sink::Stdout,
                opts.color,
            );
            // Exponential backoff capped at ~4s: 250ms, 500ms, 1s, …
            let backoff = std::time::Duration::from_millis(250u64 << (attempt - 1).min(4));
            tokio::time::sleep(backoff).await;
        }
        // #2313 b3: reserve one call against the session's shared run
        // allowance before each dispatch, including retries -- a summary
        // request is a real inference call against the same run as the
        // primary loop, and each attempt (not just the first) is one call.
        // Refused here, before any wire bytes go out, exactly like the
        // primary loop's own `attempt_capture::send`.
        if let Some(allowance) = &opts.run_allowance {
            allowance.try_reserve()?;
        }
        match summarize_attempt(&client, &chat_url, &body, api_key, openai).await {
            Ok(s) => return Ok(s),
            Err(e) => last_err = Some(e),
        }
    }
    Err(last_err.unwrap_or_else(|| anyhow::anyhow!("summarizer failed")))
}

fn make_loop_summarizer(
    url: String,
    model: String,
    kind: newt_core::BackendKind,
    api_key: Option<String>,
    model_path: Option<String>,
    opts: SummarizerOpts,
) -> newt_core::Summarizer {
    // #661 group C: an embedded summarizer runs the in-process candle engine
    // (#659) instead of an HTTP backend — zero contention with the primary model.
    if kind == newt_core::BackendKind::Embedded {
        return make_embedded_summarizer(model, model_path, opts.timeout_secs);
    }
    Box::new(move |prompt: String| {
        let url = url.clone();
        let model = model.clone();
        let api_key = api_key.clone();
        let opts = opts.clone();
        let openai = kind == newt_core::BackendKind::Openai;
        Box::pin(async move {
            match summarize_one_model(&url, &model, openai, &prompt, &opts, &api_key).await {
                Ok(s) => Ok(s),
                // Step 24.3 (#559): the primary model's attempts all failed — try
                // an explicitly configured fallback model once (a rung above the
                // static marker). Without explicit configuration, surface the
                // primary error so the compressor degrades immediately.
                Err(primary_err) => {
                    match opts.fallback_model.clone() {
                        Some(fb) if fb != model => {
                            // Step 24.7 (#559): announce the fallback live.
                            summarizer_notice(fallback_progress_msg(&fb)).emit(
                                opts.caps,
                                newt_core::tty::Sink::Stdout,
                                opts.color,
                            );
                            summarize_one_model(&url, &fb, openai, &prompt, &opts, &api_key)
                                .await
                                .map_err(|fallback_err| {
                                    anyhow::anyhow!(
                                        "primary summarizer failed: {primary_err}; fallback summarizer '{fb}' failed: {fallback_err}"
                                    )
                                })
                        }
                        _ => {
                            summarizer_notice(failure_progress_msg(&primary_err)).emit(
                                opts.caps,
                                newt_core::tty::Sink::Stdout,
                                opts.color,
                            );
                            Err(primary_err)
                        }
                    }
                }
            }
        })
    })
}

/// A summarizer that always fails with `msg`. The compressor degrades to the
/// deterministic static marker (group D guarantees a fit), and the failure is
/// surfaced — used when an embedded summarizer is requested but cannot be built.
fn failing_summarizer(msg: String) -> newt_core::Summarizer {
    Box::new(move |_prompt: String| {
        let msg = msg.clone();
        Box::pin(async move { Err(anyhow::anyhow!(msg)) })
    })
}

/// Build the in-process candle summarizer (#661 group C). Backend metadata is
/// shared across calls; each call loads its GGUF on a bounded blocking worker.
/// The configured per-request timeout covers loading and generation, with
/// cooperative cancellation between synchronous steps. Falls back to a failing
/// summarizer (→ static marker) when the model file is missing or the build lacks
/// the `embedded` feature.
#[cfg_attr(not(feature = "embedded"), allow(unused_variables))]
fn make_embedded_summarizer(
    model: String,
    model_path: Option<String>,
    timeout_secs: u64,
) -> newt_core::Summarizer {
    #[cfg(feature = "embedded")]
    {
        let Some(path) = model_path else {
            return failing_summarizer(
                "summarizer kind=embedded needs `summarizer.model_path` (the local GGUF)"
                    .to_string(),
            );
        };
        match newt_inference::embedded::EmbeddedBackend::new(&model, &path) {
            Ok(backend) => {
                let backend = std::sync::Arc::new(backend);
                Box::new(move |prompt: String| {
                    let backend = backend.clone();
                    Box::pin(async move {
                        let req = newt_inference::ChatRequest {
                            messages: vec![newt_inference::backend::Message::user(prompt)],
                            max_tokens: Some(1024),
                        };
                        backend
                            .complete_with_timeout(
                                req,
                                std::time::Duration::from_secs(timeout_secs),
                            )
                            .await
                            .map(|reply| (reply.content, reply.usage))
                    })
                })
            }
            Err(e) => failing_summarizer(format!("embedded summarizer init failed: {e}")),
        }
    }
    #[cfg(not(feature = "embedded"))]
    {
        failing_summarizer(
            "summarizer kind=embedded, but this build lacks the `embedded` feature — \
             rebuild with --features embedded"
                .to_string(),
        )
    }
}

// ---------------------------------------------------------------------------
// Semantic embedder construction (#720)
// ---------------------------------------------------------------------------

/// An [`Embedder`](newt_core::Embedder) that always fails with `msg`. Used when an
/// embedded embedder is requested but cannot be built (no `embedding_model_path`,
/// the model dir is absent, or the build lacks the `embedded` feature) — semantic
/// indexing then degrades to a no-op with one actionable message, mirroring the
/// summarizer's [`failing_summarizer`].
struct FailingEmbedder {
    msg: String,
}

#[async_trait::async_trait]
impl newt_core::Embedder for FailingEmbedder {
    async fn embed(&self, _text: &str) -> anyhow::Result<Vec<f32>> {
        Err(anyhow::anyhow!(self.msg.clone()))
    }
}

/// Whether the semantic feature should embed on the **in-process** backend
/// rather than over HTTP. Embedded is the default when the semantic config does
/// not name an HTTP endpoint/protocol; Ollama/OpenAI embeddings are an explicit
/// performance-tuning choice. Pure for testing.
fn embeddings_backend_is_embedded(cfg: &newt_core::SemanticConfig) -> bool {
    cfg.embeddings_api == Some(newt_core::BackendKind::Embedded)
        || (cfg.embeddings_api.is_none() && cfg.embeddings_endpoint.is_none())
}

/// #1279 precedence for the embedded model dir: an explicit
/// `[context.semantic].embedding_model_path` wins; otherwise the pulled default
/// model dir (`newt models pull-embed`) when it is present. Pure — the caller
/// supplies `default_present` from the fs check
/// (`newt_inference::palette::embed_model_dir_if_present`), so this stays
/// unit-testable. `None` ⇒ no model available anywhere (the caller coaches the
/// pull command).
fn effective_embedding_model_path(
    explicit: Option<String>,
    default_present: Option<std::path::PathBuf>,
) -> Option<String> {
    explicit.or_else(|| default_present.map(|d| d.to_string_lossy().into_owned()))
}

/// Build the semantic embedder (#720). By default, or when
/// `embeddings_api = "embedded"`, the in-process candle embedder runs on the
/// laptop so retrieval never touches the DGX chat model's VRAM. HTTP
/// [`EmbeddingsClient`](newt_core::EmbeddingsClient) embeddings are selected
/// only by explicit Ollama/OpenAI semantic config. Always returns a usable
/// `Box<dyn Embedder>` — a mis-configured embedded path yields a failing embedder
/// (→ indexing no-op) rather than panicking. Pure for testing.
fn build_semantic_embedder(
    semantic_cfg: &newt_core::SemanticConfig,
    inf_url: &str,
    inf_kind: newt_core::BackendKind,
    inf_key: Option<&str>,
) -> Box<dyn newt_core::Embedder> {
    if embeddings_backend_is_embedded(semantic_cfg) {
        return make_embedded_embedder(
            semantic_cfg.embedding_model.clone(),
            semantic_cfg.embedding_model_path.clone(),
        );
    }
    let (emb_url, emb_kind, emb_key) =
        resolve_embeddings_target(semantic_cfg, inf_url, inf_kind, inf_key);
    Box::new(newt_core::EmbeddingsClient::new(
        emb_url,
        semantic_cfg.embedding_model.clone(),
        emb_kind,
        emb_key,
        60,
        2,
    ))
}

/// Preflight semantic embedder availability before walking the workspace. This
/// keeps default-on semantic context cheap in binaries that were not built with
/// the embedded feature, or where the local model path is not configured yet.
fn semantic_embedder_unavailable_reason(cfg: &newt_core::SemanticConfig) -> Option<String> {
    if !embeddings_backend_is_embedded(cfg) {
        return None;
    }
    #[cfg(not(feature = "embedded"))]
    {
        Some(
            "embedded semantic retrieval is selected, but this binary lacks the `embedded` \
             feature; rebuild with --features embedded or configure an explicit \
             [context.semantic].embeddings_endpoint"
                .to_string(),
        )
    }
    #[cfg(feature = "embedded")]
    {
        let Some(path) = cfg.embedding_model_path.as_deref() else {
            return Some(
                "embedded semantic retrieval has no model — run `newt models pull-embed` to \
                 fetch the default on-host model (bge-small), or set \
                 [context.semantic].embedding_model_path to a local candle-clean standard-BERT dir"
                    .to_string(),
            );
        };
        let dir = std::path::Path::new(path);
        if !dir.is_dir() {
            return Some(format!(
                "embedded semantic retrieval model dir not found: {}",
                dir.display()
            ));
        }
        for required in ["config.json", "tokenizer.json", "model.safetensors"] {
            let file = dir.join(required);
            if !file.exists() {
                return Some(format!(
                    "embedded semantic retrieval model file not found: {}",
                    file.display()
                ));
            }
        }
        None
    }
}

/// Build the in-process candle embedder (#720). The `CandleEmbedder` loads a
/// candle-clean standard-BERT model from `model_path` (a local dir) once and
/// embeds on a non-contending device (CPU by default). Falls back to a failing
/// embedder (→ indexing no-op) when `model_path` is unset, the model dir is
/// absent, or the build lacks the `embedded` feature.
#[cfg_attr(not(feature = "embedded"), allow(unused_variables))]
fn make_embedded_embedder(
    model: String,
    model_path: Option<String>,
) -> Box<dyn newt_core::Embedder> {
    #[cfg(feature = "embedded")]
    {
        let Some(path) = model_path else {
            return Box::new(FailingEmbedder {
                msg: "embedded semantic retrieval has no model — run `newt models pull-embed` \
                      (fetches bge-small), or set `[context.semantic].embedding_model_path` to a \
                      local candle-clean standard-BERT model dir"
                    .to_string(),
            });
        };
        match newt_inference::embed::CandleEmbedder::new(&model, &path) {
            Ok(e) => Box::new(e),
            Err(err) => Box::new(FailingEmbedder {
                msg: format!("embedded embedder init failed: {err}"),
            }),
        }
    }
    #[cfg(not(feature = "embedded"))]
    {
        Box::new(FailingEmbedder {
            msg: "embeddings_api=embedded, but this build lacks the `embedded` feature — \
                  rebuild with --features embedded"
                .to_string(),
        })
    }
}

fn semantic_zero_index_hint(cfg: &newt_core::SemanticConfig) -> String {
    if embeddings_backend_is_embedded(cfg) {
        return "semantic: indexed 0 chunks — no embedding model; run `newt models pull-embed` \
                to fetch the default on-host model (bge-small), or set \
                [context.semantic].embedding_model_path to a local candle-clean standard-BERT \
                model dir (retrieval is a no-op until embeddings work)"
            .to_string();
    }
    let target = cfg
        .embeddings_endpoint
        .as_deref()
        .unwrap_or("the active chat backend");
    format!(
        "semantic: indexed 0 chunks — embeddings from {target} produced no vectors for '{}'; \
         configure [context.semantic].embeddings_endpoint/embeddings_api for an Ollama/OpenAI \
         embeddings service, or set embedding_model_path to use embedded embeddings \
         (retrieval is a no-op until embeddings work)",
        cfg.embedding_model
    )
}

// ---------------------------------------------------------------------------
// End-of-conversation note extraction (Step 19.4, #248)
// ---------------------------------------------------------------------------

/// Marker prefixed to every note the close-time extraction writes, so a
/// reader of NOTES.md (or the `/memory` listing) can tell auto-extracted
/// facts from ones a human (`/remember`) or the model mid-session
/// (`save_note`) chose to keep. Plain entry text — the note schema carries
/// no per-entry metadata and is deliberately not extended here.
const EXTRACTED_NOTE_PREFIX: &str = "(auto-extracted) ";

/// Per-message character cap for the rendered extraction transcript. The
/// message COUNT is bounded by [`newt_core::trim_for_summary`]; this bounds
/// the other axis so one giant paste can't make the request unbounded.
const EXTRACTION_MSG_CHAR_CAP: usize = 2_000;

/// The extraction prompt: at most 3 durable, conversation-transcending
/// facts as `- ` bullets, or the literal `NONE`. Kept tight on purpose —
/// the transcript carries the bulk of the tokens.
fn build_extraction_prompt(transcript: &str) -> String {
    format!(
        "This coding-agent conversation is closing. From the transcript below, \
         extract at most 3 durable facts worth remembering in future \
         conversations — decisions made, constraints discovered, preferences \
         stated. Reply with one short bullet per fact, each line starting with \
         \"- \". Do NOT record task progress or anything only meaningful to \
         this session. If nothing qualifies, reply with exactly NONE.\
         \n\nTranscript:\n{transcript}"
    )
}

/// Render the session history into a bounded transcript for the extraction
/// prompt. The message count is bounded by [`newt_core::trim_for_summary`]
/// — the SAME head+tail helper the cap-exit summary request uses for its
/// input — and each message is clipped to [`EXTRACTION_MSG_CHAR_CAP`] chars,
/// so the request never ships the whole history unbounded. Returns `None`
/// when there is no conversational content to extract from (the system
/// prompt and the empty current-task slot don't count).
fn render_extraction_transcript(messages: &[newt_core::MemMessage]) -> Option<String> {
    let json_msgs: Vec<serde_json::Value> = messages
        .iter()
        .filter(|m| m.role != newt_core::Role::System && !m.content.trim().is_empty())
        .map(|m| serde_json::json!({"role": m.role.as_str(), "content": m.content}))
        .collect();
    if json_msgs.is_empty() {
        return None;
    }
    let rendered = newt_core::trim_for_summary(&json_msgs, 2, 6)
        .iter()
        .map(|m| {
            let role = m["role"].as_str().unwrap_or("user");
            let content = m["content"].as_str().unwrap_or_default();
            let clipped: String = content.chars().take(EXTRACTION_MSG_CHAR_CAP).collect();
            let marker = if content.chars().count() > EXTRACTION_MSG_CHAR_CAP {
                " [clipped]"
            } else {
                ""
            };
            format!("{role}: {clipped}{marker}")
        })
        .collect::<Vec<_>>()
        .join("\n");
    Some(rendered)
}

/// Parse the extraction reply into at most 3 bullets. The literal `NONE`
/// reply and any reply without bullet lines both yield an empty list —
/// deliberately silent: "nothing worth keeping" is the common close and
/// must not print a notice every time (documented UX choice).
fn parse_extraction_bullets(reply: &str) -> Vec<String> {
    if reply.trim().eq_ignore_ascii_case("none") {
        return Vec::new();
    }
    reply
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            ["- ", "* ", "• "].iter().find_map(|p| line.strip_prefix(p))
        })
        .map(str::trim)
        .filter(|s| !s.is_empty() && !s.eq_ignore_ascii_case("none"))
        .take(3)
        .map(String::from)
        .collect()
}

/// The 19.4 gate, pure for testing: extraction runs only when the config key
/// (`[memory] extract_notes_on_close`, default off) is set, the session
/// persists (an `--ephemeral` session must leave no trace, and NOTES.md IS a
/// trace), and the conversation completed at least one turn in THIS session
/// (a resumed-then-immediately-closed conversation adds nothing new).
fn should_extract_on_close(enabled: bool, ephemeral: bool, turns: usize) -> bool {
    enabled && !ephemeral && turns > 0
}

/// Whether the current process is an ephemeral session (`--ephemeral` /
/// `NEWT_EPHEMERAL`). Such sessions must leave no trace on disk, so the sticky
/// `/backends`/`/model` writers ([`newt_core::settings`]) are skipped — the
/// same "no trace" invariant that gates [`should_extract_on_close`].
pub(crate) fn is_ephemeral_session() -> bool {
    std::env::var_os("NEWT_EPHEMERAL").is_some()
}

/// One honest line about what the close-time extraction wrote. Scan- or
/// budget-rejected bullets are dropped (never retried) and disclosed here;
/// the cause goes to `tracing::warn`, so the visible line stays
/// cause-neutral and true for every rejection kind.
fn close_extraction_notice(saved: usize, rejected: usize) -> String {
    let noun = if saved == 1 { "note" } else { "notes" };
    if rejected > 0 {
        format!("extracted {saved} {noun} on close ({rejected} rejected)")
    } else {
        format!("extracted {saved} {noun} on close")
    }
}

/// Step 19.4 (#248): ONE synchronous tools-disabled completion at
/// conversation close (`/new` and clean exit — never the EMFILE/panic crash
/// paths), distilling at most 3 durable facts into NOTES.md. No background
/// fork (design doc § Do-Not-Copy #3): this runs inline, once, bounded by
/// the request's own timeout.
///
/// `complete` is built by [`make_loop_summarizer`] — the same request the
/// cap-exit summary uses, which sends **no `tools` key**, so the model
/// structurally cannot emit tool calls. Every accepted bullet goes through
/// `MemoryManager::add_note` → `NoteStore::add` → the 19.2 write-time scan —
/// the SAME path `save_note` and `/remember` use; there is no raw file
/// write. Mid-session note writes don't reach the frozen system prompt
/// anyway, so writing during close loses nothing — the notes load next
/// session.
///
/// Returns the notice line when bullets were processed, `None` when the gate
/// skipped, nothing qualified (silent NONE), or the backend failed — a
/// failure logs a warning and must NEVER block `/new` or exit.
async fn run_close_extraction(
    enabled: bool,
    ephemeral: bool,
    turns: usize,
    memory: &mut newt_core::MemoryManager,
    complete: &newt_core::Summarizer,
) -> Option<String> {
    if !should_extract_on_close(enabled, ephemeral, turns) {
        return None;
    }
    let transcript = render_extraction_transcript(&memory.build_messages("", ""))?;
    // TODO(#2313): record the extraction usage in the per-attempt ledger (PR2).
    let reply = match complete(build_extraction_prompt(&transcript)).await {
        Ok((r, _usage)) => r,
        Err(e) => {
            tracing::warn!(error = %e, "close-time note extraction failed — moving on");
            return None;
        }
    };
    let bullets = parse_extraction_bullets(&reply);
    if bullets.is_empty() {
        return None;
    }
    let (mut saved, mut rejected) = (0usize, 0usize);
    for bullet in &bullets {
        match memory.add_note(&format!("{EXTRACTED_NOTE_PREFIX}{bullet}")) {
            Ok(()) => saved += 1,
            Err(e) => {
                rejected += 1;
                tracing::warn!(error = %e, "extracted note rejected — dropped");
            }
        }
    }
    Some(close_extraction_notice(saved, rejected))
}

/// One-line banner naming the active profile and the techniques it composes —
/// printed once at session start so the operator sees what the profile turned on.
fn announce_profile(
    name: &str,
    profile: &newt_core::config::ProfileConfig,
    via: &newt_core::config::PickVia,
    color: bool,
) {
    let techs = if profile.techniques.is_empty() {
        "no techniques".to_string()
    } else {
        profile.techniques.join(", ")
    };
    let source = match via {
        newt_core::config::PickVia::Profile => String::new(),
        newt_core::config::PickVia::Bundle(b) => format!(" (via bundle '{b}')"),
        newt_core::config::PickVia::InferredBundle(b) => format!(" (via bundle '{b}', inferred)"),
    };
    if color {
        let _ = execute!(
            io::stdout(),
            SetForegroundColor(CtColor::DarkGrey),
            Print(format!("▸ profile '{name}' — {techs}{source}\n")),
            ResetColor,
        );
    } else {
        println!("▸ profile '{name}' — {techs}{source}");
    }
}

/// The session's resolved loadout state, rendered for `/loadout show` — the
/// audit companion to `/config`. Separates what a named loadout *declares* (its
/// `[loadouts.<name>]` axes) from what actually *resolved* this session
/// (backend endpoint + model, the active profile and its provenance, the
/// persona), so an operator can see at a glance whether an axis was overridden
/// by an explicit flag. Pure (no I/O) so it can be unit-tested.
struct LoadoutView<'a> {
    /// Active loadout name (`NEWT_LOADOUT`), if one was selected.
    name: Option<&'a str>,
    /// The named loadout's declared composition, if it resolves in config.
    loadout: Option<&'a newt_core::Loadout>,
    /// Resolved backend endpoint + model in effect this session.
    inf_url: &'a str,
    inf_model: &'a str,
    /// The active profile pick (name + provenance), if any.
    profile_pick: Option<&'a newt_core::config::ProfilePick>,
    /// The active persona/role name, if any.
    persona: Option<&'a str>,
}

impl LoadoutView<'_> {
    fn render(&self) -> String {
        let mut lines: Vec<String> = Vec::new();
        match self.name {
            Some(n) => lines.push(format!("Active loadout: {n}")),
            None => lines.push("No loadout active.".to_string()),
        }
        // What the named loadout declared (dispatcher inputs).
        if let Some(l) = self.loadout {
            lines.push("  declared:".to_string());
            for (label, val) in [
                ("provider", l.provider.as_deref()),
                ("model", l.model.as_deref()),
                ("kit", l.kit.as_deref()),
                ("profile", l.profile.as_deref()),
                ("role", l.role.as_deref()),
            ] {
                if let Some(v) = val {
                    lines.push(format!("    {label:<9}{v}"));
                }
            }
            if let Some(s) = &l.settings {
                if let Some(n) = s.num_ctx {
                    lines.push(format!("    {:<9}{n}", "num_ctx"));
                }
                if let Some(f) = &s.framing {
                    lines.push(format!("    {:<9}{f}", "framing"));
                }
            }
        } else if let Some(n) = self.name {
            lines.push(format!("  (no [loadouts.{n}] in config)"));
        }
        // What actually resolved this session (the effect each axis had).
        lines.push("  resolved:".to_string());
        lines.push(format!(
            "    {:<9}{} @ {}",
            "backend", self.inf_model, self.inf_url
        ));
        let profile_line = match self.profile_pick {
            Some(p) => {
                let via = match &p.via {
                    newt_core::config::PickVia::Profile => String::new(),
                    newt_core::config::PickVia::Bundle(b) => format!(" (via bundle '{b}')"),
                    newt_core::config::PickVia::InferredBundle(b) => {
                        format!(" (via bundle '{b}', inferred)")
                    }
                };
                format!("{}{}", p.name, via)
            }
            None => "(none)".to_string(),
        };
        lines.push(format!("    {:<9}{profile_line}", "profile"));
        lines.push(format!(
            "    {:<9}{}",
            "persona",
            self.persona.unwrap_or("(none)")
        ));
        lines.join("\n")
    }
}

/// The `verify_gate` technique (R2), post-turn: resolve the produced Python files'
/// imports against the workspace's FFI surface and return a one-block warning of
/// any that import modules absent from it — `None` when clean, or when the
/// workspace has no PyO3 surface to check against. **Non-destructive** (it
/// surfaces fabrications; revert/retry is a later increment). The `surface_match`
/// strictness comes from the profile knob.
///
/// Scope: resolves against the project's PyO3 surface + the Python stdlib — apt
/// for the binding-examples workflow it was built for; a broader Python project
/// may see informational false positives (hence warn-only, opt-in per profile).
fn verify_gate_summary(
    workspace: &str,
    mode: newt_core::verify_gate::SurfaceMatch,
) -> Option<String> {
    let ws = std::path::Path::new(workspace);
    let manifest = newt_core::ffi_manifest::FfiManifest::from_workspace(ws).ok()?;
    if manifest.is_empty() {
        return None; // no authoritative surface to check against
    }
    let report =
        newt_core::verify_gate::gate_python_workspace_with(ws, &manifest.known_modules(), mode)
            .ok()?;
    if report.accept() {
        return None;
    }
    let mut s = format!(
        "verify_gate: {} file(s) import modules not in the workspace surface (the real paths \
         are in the system prompt):",
        report.revert_set().len()
    );
    for f in &report.files {
        if f.is_clean() {
            continue;
        }
        let mods: Vec<&str> = f.fabrications.iter().map(|x| x.module.as_str()).collect();
        s.push_str(&format!(
            "\n    {}  [{}]",
            f.path.display(),
            mods.join(", ")
        ));
    }
    Some(s)
}

/// The result of the `retry` technique's post-turn pass: what was reverted (for the
/// `↩` banner) and the grounded corrective re-prompt to feed the model if the
/// re-prompt budget allows (increment 2b).
struct RevertAction {
    banner: String,
    corrective: String,
    /// Workspace-relative paths actually restored by the governed write
    /// ledger. Used to append compensating prompt artifacts without claiming
    /// access to the restored bytes.
    reverted: Vec<std::path::PathBuf>,
}

/// What the loop should do after a revert, given the remaining re-prompt budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum RetryStep {
    /// Re-prompt the model (the loop queues the corrective turn); budget decremented.
    Reprompt,
    /// The cap is spent — leave the files reverted and report honestly.
    GiveUp,
}

/// Pure decision: with `budget` re-prompts left after a revert, do we re-prompt or
/// give up? Split out so the cap/give-up logic is unit-tested independently of the
/// interactive loop (the headless equivalent is [`apply_revert_retry`]'s own loop).
fn retry_step(budget: u32) -> RetryStep {
    if budget > 0 {
        RetryStep::Reprompt
    } else {
        RetryStep::GiveUp
    }
}

/// The `retry` technique's post-turn pass: gate the produced `.py` files, **revert**
/// the flagged set to its pre-turn state via the per-turn write `ledger`, and return
/// the banner + the grounded corrective re-prompt (`None` when clean / no surface /
/// nothing newt wrote was flagged).
///
/// The ledger records only newt's own `write_file`/`edit_file` writes this turn, so
/// [`revert_only`](newt_core::verify_gate::revert_only) restores edited files and
/// removes created ones **without ever touching a file newt did not write** (build
/// output, pre-existing fabrications, anything reached via a symlink). The caller
/// decides whether to act on `corrective` based on the re-prompt budget
/// ([`retry_step`]).
async fn retry_revert(
    workspace: &str,
    mode: newt_core::verify_gate::SurfaceMatch,
    ledger: &std::cell::RefCell<newt_core::verify_gate::WriteLedger>,
) -> Option<RevertAction> {
    use newt_core::verify_gate::{
        corrective_prompt, gate_python_workspace_with, revert_only, RetrySurface,
    };
    let ws = std::path::Path::new(workspace);
    let manifest = newt_core::ffi_manifest::FfiManifest::from_workspace(ws).ok()?;
    if manifest.is_empty() {
        return None; // no authoritative surface to gate against
    }
    let modules = manifest.known_modules();
    let report = gate_python_workspace_with(ws, &modules, mode).ok()?;
    if report.accept() {
        return None;
    }
    // Per-file fabricated modules for the banner, captured before the report moves.
    let mods_by_path: std::collections::BTreeMap<std::path::PathBuf, String> = report
        .files
        .iter()
        .filter(|f| !f.is_clean())
        .map(|f| {
            let mods: Vec<&str> = f.fabrications.iter().map(|x| x.module.as_str()).collect();
            (f.path.clone(), mods.join(", "))
        })
        .collect();
    let block = manifest.render_block();
    // The grounded re-prompt, built before the report is consumed by revert_only.
    let corrective = corrective_prompt(&report, &block);
    let surface = RetrySurface {
        modules: &modules,
        mode,
        block: &block,
    };
    let outcome = revert_only(ws, &surface, ledger, report).await.ok()?;
    if outcome.reverted.is_empty() {
        return None; // every flagged file was something newt did not write — left as-is
    }
    let mut detail = String::new();
    for p in &outcome.reverted {
        let mods = mods_by_path.get(p).map(String::as_str).unwrap_or("");
        detail.push_str(&format!("\n    {}  [{}]", p.display(), mods));
    }
    let banner = format!(
        "retry: reverted {} file(s) newt wrote this turn to pre-turn state:{detail}",
        outcome.reverted.len()
    );
    Some(RevertAction {
        banner,
        corrective,
        reverted: outcome.reverted,
    })
}

/// The inference backend the TUI session should talk to — a flat split of
/// immutable INTENT (what config + operator asked for, captured at resolve
/// time and never touched by probes) and mutable ROUTE (what probing and
/// adoption established since). Adoption evidence survives refreshes via
/// [`merge_refresh`], and overlays never destroy the declaration they
/// overlaid.
#[derive(Debug)]
pub(crate) struct BackendChoice {
    /// The configured backend's name ("" for env-synthesized/legacy choices) —
    /// feeds cap_key (instance keying) and honest status lines.
    pub(crate) name: String,
    pub(crate) url: String,
    // ── immutable intent ─────────────────────────────────────────────
    /// The backend's declared model, if any.
    pub(crate) declared_model: Option<String>,
    /// The operator's explicit per-session request (`NEWT_DGX_MODEL`),
    /// kept apart from the declaration so adoption can fall back to the
    /// declared model when the request is unavailable.
    pub(crate) requested_model: Option<String>,
    /// The DECLARED serving axis (declaration layer + the core's
    /// destination normalization: a model_path route is Instance even when
    /// the declaration omitted the axis).
    pub(crate) declared_serving: Option<newt_core::Serving>,
    /// The explicit `--backend-serving` REQUEST for this invocation, if
    /// any — operator intent, outranking every cached observation.
    pub(crate) requested_serving: Option<newt_core::Serving>,
    /// The config-declared wire protocol (`None` = probe at connect).
    pub(crate) configured_kind: Option<newt_core::BackendKind>,
    /// The config-declared OpenAI surface (`None` = probe at connect).
    pub(crate) configured_api: Option<newt_core::OpenAiApi>,
    /// Managed mode — lets adoption prefer a warm model on a Shared box.
    pub(crate) managed: Option<newt_core::ManagedMode>,
    pub(crate) api_key: Option<String>,
    /// The embedded artifact path, when this backend routes to a local
    /// model file instead of an endpoint — the other destination axis.
    pub(crate) model_path: Option<String>,
    // ── mutable route ────────────────────────────────────────────────
    /// The model the session is actually driving: request > declaration at
    /// resolve time; adoption replaces it with served reality — INCLUDING
    /// clearing it when a live multiplexer establishes no pick (`None` is
    /// truthful; display falls back through [`Self::display_model`]).
    pub(crate) active_model: Option<String>,
    /// The serving axis a CACHED probe observation attests (the receipt's
    /// observation layer) — provenance kept separate from live adoption,
    /// so a fresh resolution's cache always lands and the two can never
    /// overwrite each other.
    pub(crate) observed_serving: Option<newt_core::Serving>,
    /// The serving axis LIVE adoption/probing established THIS session —
    /// written only by the adopt path, the strongest route evidence.
    pub(crate) adopted_serving: Option<newt_core::Serving>,
    pub(crate) kind: newt_core::BackendKind,
    /// True when the config omitted `kind` — adopt must run `detect_endpoint`
    /// instead of trusting a placeholder wire protocol.
    pub(crate) kind_needs_probe: bool,
    /// For an OpenAI backend: which HTTP surface (chat/completions vs the newer
    /// /v1/responses). Surfaced to the agent loop via `NEWT_OPENAI_API`.
    pub(crate) api: newt_core::OpenAiApi,
    /// True when the config omitted `api` — adopt must run `detect_openai_api`
    /// for OpenAI backends instead of trusting the chat_completions placeholder.
    pub(crate) api_needs_probe: bool,
    /// The server-declared context window (#1199), probed FRESH at session-start
    /// adopt — not read from the persisted cache (which could hold a stale
    /// None). `None` when the API can't be asked; the budget then falls back to
    /// config / the learned cache.
    pub(crate) context_window: Option<u32>,
    // ── capability layers + display history ──────────────────────────
    /// The immutable capability layers (card binding + inline), constructed
    /// once per resolution by `ResolvedCapabilities::resolve` from the
    /// config's pre-overlay binding seed.
    pub(crate) capabilities: newt_core::model_card::ResolvedCapabilities,
    /// A card-resolution error minted by THIS resolution (unknown/invalid
    /// card) — held for identity-compared display, never destroyed.
    pub(crate) card_resolution_error: Option<String>,
    /// What the card display owner last SHOWED — survives refreshes so an
    /// unchanged state stays quiet.
    pub(crate) notices: CardNotices,
}

impl BackendChoice {
    /// A choice with no config-backed intent — the env-synthesized/legacy
    /// arms and tests. Route starts at `active_model` with nothing adopted;
    /// callers set the request/declaration facts they actually have.
    pub(crate) fn synthesized(
        name: &str,
        url: String,
        kind: newt_core::BackendKind,
        active_model: Option<String>,
    ) -> Self {
        Self {
            name: name.to_string(),
            url,
            declared_model: None,
            requested_model: None,
            declared_serving: None,
            requested_serving: None,
            observed_serving: None,
            configured_kind: None,
            configured_api: None,
            managed: None,
            api_key: None,
            model_path: None,
            active_model: active_model.filter(|m| !m.trim().is_empty()),
            adopted_serving: None,
            kind,
            kind_needs_probe: false,
            api: newt_core::OpenAiApi::default(),
            api_needs_probe: false,
            context_window: None,
            capabilities: newt_core::model_card::ResolvedCapabilities::none(),
            card_resolution_error: None,
            notices: CardNotices::default(),
        }
    }

    /// The serving axis the session currently operates under, by
    /// PROVENANCE strength: live adoption > explicit request > cached
    /// observation > declaration (destination-normalized).
    pub(crate) fn route_serving(&self) -> Option<newt_core::Serving> {
        self.adopted_serving
            .or(self.requested_serving)
            .or(self.observed_serving)
            .or(self.declared_serving)
    }

    /// The route's typed destination — where the session's bytes go: the
    /// endpoint, or the embedded artifact path. Feeds the destination-first
    /// capability decision ([`newt_core::model_card::ResolvedCapabilities::for_route`]).
    pub(crate) fn route_destination(&self) -> newt_core::BackendDestination {
        newt_core::BackendDestination::new(Some(self.url.clone()), self.model_path.clone())
    }

    /// The label for status lines: the live route model, else the declared
    /// intent, else "(server decides)". DISPLAY ONLY — never an identity.
    pub(crate) fn display_model(&self) -> &str {
        self.active_model
            .as_deref()
            .or(self.declared_model.as_deref())
            .unwrap_or("(server decides)")
    }

    /// The serving principal this choice currently represents, for the
    /// capability decision.
    ///
    /// * An established/declared **Instance** (or a config-declared embedded
    ///   engine) is a single artifact.
    /// * A **Multiplexer** with a live model is that model; with none yet,
    ///   Unknown (a half-initialized choice must not report a retarget it
    ///   cannot know about).
    /// * **No axis at all**: an operator-SELECTED identity (request, else
    ///   declaration) justifies exact association — an adopted guess never
    ///   does, so `active_model` is deliberately not consulted here.
    pub(crate) fn principal(&self) -> newt_core::model_card::ServingPrincipal<'_> {
        use newt_core::model_card::ServingPrincipal as P;
        match self.route_serving() {
            Some(newt_core::Serving::Instance) => P::Instance,
            Some(newt_core::Serving::Multiplexer) => {
                match self
                    .active_model
                    .as_deref()
                    .filter(|m| !m.trim().is_empty())
                {
                    Some(m) => P::MultiplexerModel(m),
                    // A live multiplexer with no established pick: Unknown —
                    // a stale declared/requested label must not become the
                    // principal a card activates against.
                    None => P::Unknown,
                }
            }
            // An embedded route (a model_path destination) serves ONE
            // artifact — derived from the TYPED destination, never from a
            // possibly-stale declared kind beside an endpoint.
            None if self.url.is_empty()
                && self.model_path.as_deref().is_some_and(|p| !p.is_empty()) =>
            {
                P::Instance
            }
            None => match self
                .requested_model
                .as_deref()
                .or(self.declared_model.as_deref())
                .filter(|m| !m.trim().is_empty())
            {
                Some(m) => P::SelectedModel(m),
                None => P::Unknown,
            },
        }
    }

    /// The capability decision for the CURRENT principal — computed at use
    /// time, never cached across a serving/model change, so a rebuilt or
    /// refreshed choice cannot re-enable a card the current model does not
    /// match.
    pub(crate) fn capability_decision(&self) -> newt_core::model_card::CapabilityDecision {
        self.capabilities
            .for_route(&self.route_destination(), self.principal())
    }

    /// Observe + render card-layer state at a printing seam — THE display
    /// owner. Compares typed applicability identity and the resolution
    /// error against what was last shown, records the new history, and
    /// returns only the lines worth printing (nothing on a no-op).
    pub(crate) fn card_notice_lines(&mut self) -> Vec<String> {
        let now = self.capability_decision().applicability().clone();
        let (next, lines) =
            notice_transition(&self.notices, self.card_resolution_error.as_deref(), &now);
        self.notices = next;
        lines
    }
}

/// The display history for card-layer notices — what has been SHOWN, so
/// every seam (startup, adoption, refresh) dedupes by TYPED identity
/// instead of prose comparison or destructive `take()`.
#[derive(Debug, Clone, Default, PartialEq)]
pub(crate) struct CardNotices {
    last_error: Option<String>,
    last_applicability: Option<newt_core::model_card::CardApplicability>,
}

/// Pure transition function: compare what is now true against what was last
/// shown; return the updated history and the lines worth printing.
/// Identity rules: an identical `Inactive(A,B)` stays quiet;
/// `Inactive(…,B) → Inactive(…,C)` is a new transition; `Inactive → Active`
/// announces the card re-applying; a resolution error prints once per
/// distinct message.
fn notice_transition(
    prev: &CardNotices,
    error: Option<&str>,
    now: &newt_core::model_card::CardApplicability,
) -> (CardNotices, Vec<String>) {
    use newt_core::model_card::CardApplicability as A;
    let mut lines = Vec::new();
    if let Some(e) = error {
        if prev.last_error.as_deref() != Some(e) {
            lines.push(e.to_string());
        }
    } else if prev.last_error.is_some() {
        // Error RECOVERY is a transition too: a fixed card must not just
        // silently start applying after sessions of error lines.
        lines.push("card resolution recovered — the configured card resolves again".to_string());
    }
    // Applicability transitions render EXHAUSTIVELY over typed identity —
    // any change in which card (or whether one) governs card-derived
    // behavior is visible: replacement, removal, activation, deactivation,
    // and every inactive shape. Only two states stay deliberately quiet:
    // an unchanged identity (dedupe), and the very first observation when
    // the card simply applies (startup Active needs no banner).
    if prev.last_applicability.as_ref() != Some(now) {
        match (prev.last_applicability.as_ref(), now) {
            // Card replaced: A → B, both applying.
            (Some(A::Active { card: before }), A::Active { card: after }) if before != after => {
                lines.push(format!(
                    "card switched: `{before}` → `{after}` — card-derived behavior now \
                     follows `{after}`"
                ));
            }
            // Re-activation after any non-applying shape.
            (
                Some(A::InactiveModel { .. } | A::InactiveDestination { .. } | A::Undecided { .. }),
                A::Active { card },
            ) => {
                lines.push(format!(
                    "card `{card}` applies again — the session is serving its bound model"
                ));
            }
            // Activation from an explicitly card-less state (mid-session:
            // a card was configured/bound where none governed before).
            (Some(A::None), A::Active { card }) => {
                lines.push(format!(
                    "card `{card}` now applies — card-derived behavior follows it"
                ));
            }
            // First observation: a card that simply applies at startup
            // stays quiet; anything else renders its prose below.
            (None, A::Active { .. }) => {}
            // Card removed / binding gone: card-derived behavior is off.
            (Some(prev_state), A::None) if !matches!(prev_state, A::None) => {
                lines.push(
                    "card removed — no card governs this backend; card-derived behavior \
                     is off (inline backend settings kept)"
                        .to_string(),
                );
            }
            // Every non-applying shape has prose of its own.
            _ => {
                if let Some(line) = applicability_prose(now) {
                    lines.push(line);
                }
            }
        }
    }
    (
        CardNotices {
            last_error: error.map(str::to_string),
            last_applicability: Some(now.clone()),
        },
        lines,
    )
}

/// The operator-facing prose for a non-applying card state; `None` for the
/// quiet states. THE one prose owner — core keeps every outcome typed
/// (renderer-neutrality, #1803), and every display seam renders through
/// here, never its own copy. Public: headless `solve` (newt-cli) renders
/// its stderr line through this same owner.
pub fn applicability_prose(a: &newt_core::model_card::CardApplicability) -> Option<String> {
    use newt_core::model_card::CardApplicability as A;
    match a {
        A::None | A::Active { .. } => None,
        A::InactiveModel {
            card,
            bound_model,
            active_model,
        } => Some(format!(
            "card `{card}` is bound to {} — the session is serving {active_model}, so \
             card-derived behavior (capabilities and family policy) is off (inline \
             backend settings kept); rebind the card or switch back",
            bound_model.as_deref().unwrap_or("(no declared model)"),
        )),
        A::InactiveDestination {
            card,
            bound_destination,
            active_destination,
        } => Some(format!(
            "card `{card}` is bound at {} — the session is routed to {}, so \
             card-derived behavior (capabilities and family policy) is off (inline \
             backend settings kept)",
            describe_destination(bound_destination),
            describe_destination(active_destination),
        )),
        A::Undecided { card } => Some(format!(
            "card `{card}` is configured but the serving principal is not established — \
             card-derived behavior (capabilities and family policy) stays off until \
             adoption decides"
        )),
        // Core's applicability enum is non-exhaustive-shaped by policy: an
        // unrecognized future state renders conservatively rather than
        // silently.
        #[allow(unreachable_patterns)]
        other => Some(format!("card state changed: {other:?}")),
    }
}

/// One destination, for prose: the endpoint or the artifact path.
fn describe_destination(d: &newt_core::BackendDestination) -> String {
    d.endpoint
        .clone()
        .or_else(|| d.model_path.clone())
        .unwrap_or_else(|| "(no destination)".into())
}

#[cfg(test)]
#[path = "lib_tests/notice_transition_tests.rs"]
mod notice_transition_tests;

/// The complete INTENT key: two resolutions with equal intent describe the
/// same operator ask, so the established route may carry across a refresh.
fn same_intent(a: &BackendChoice, b: &BackendChoice) -> bool {
    a.name == b.name
        && a.url == b.url
        && a.declared_model == b.declared_model
        && a.requested_model == b.requested_model
        && a.declared_serving == b.declared_serving
        && a.requested_serving == b.requested_serving
        && a.configured_kind == b.configured_kind
        && a.configured_api == b.configured_api
        && a.managed == b.managed
        && a.api_key == b.api_key
}

/// Fold a fresh resolution over the previous choice. On a same-intent no-op
/// ONLY the established route/probe results carry over; the freshly
/// resolved capabilities and resolution error always stand (a config edit
/// must be able to fix a card without a restart); display history always
/// survives. Returns whether adoption needs to (re)run.
fn merge_refresh(prev: &BackendChoice, next: &mut BackendChoice) -> bool {
    next.notices = prev.notices.clone();
    if !same_intent(prev, next) {
        return true;
    }
    next.kind = prev.kind;
    next.kind_needs_probe = prev.kind_needs_probe;
    next.api = prev.api;
    next.api_needs_probe = prev.api_needs_probe;
    // ONLY the live-adopted evidence carries; the fresh resolution's CACHED
    // observation (observed_serving) always stands — a prior offline
    // session's None must never erase a newly written probe cache.
    next.adopted_serving = prev.adopted_serving;
    next.active_model = prev.active_model.clone();
    next.context_window = prev.context_window;
    false
}

/// Adoption inputs from the choice's IMMUTABLE intent: the synthesized view
/// carries the DECLARED model / configured serving / managed mode — never
/// the session override — while the override rides separately as the
/// REQUEST. `adopt()` then owns the policy: an unavailable request falls
/// back to the declaration, and a Managed Shared backend may prefer a warm
/// model.
fn adoption_inputs(choice: &BackendChoice) -> (newt_core::BackendConfig, Option<String>) {
    (
        newt_core::BackendConfig {
            name: choice.name.clone(),
            endpoint: choice.url.clone(),
            model: choice.declared_model.clone(),
            kind: Some(choice.kind),
            serving: choice
                .requested_serving
                .or(choice.observed_serving)
                .or(choice.declared_serving),
            managed: choice.managed,
            ..Default::default()
        },
        choice.requested_model.clone(),
    )
}

/// Adoption mutates ONLY the route: the established serving axis and the
/// active model. Intent fields are never written.
fn apply_adoption(choice: &mut BackendChoice, adoption: &newt_core::backend_probe::Adoption) {
    choice.adopted_serving = Some(adoption.serving);
    // Unconditional: a multiplexer that established NO pick clears the
    // route model — a stale declared/requested label must not survive as
    // the principal a card could activate against.
    choice.active_model = adoption.model.clone().filter(|m| !m.trim().is_empty());
}

/// The session-start ready preamble. Includes the backend wire protocol
/// (`ollama`/`openai`) so it's unambiguous which engine the endpoint speaks —
/// e.g. an Ollama `:11434` vs an OpenAI-compatible (vLLM) endpoint. Pure for
/// testing.
fn ready_line(version: &str, model: &str, url: &str, kind: newt_core::BackendKind) -> String {
    format!(
        "v{version} ready — {model} @ {url} ({}){}  (Ctrl-D or /exit to quit)",
        kind.label(),
        tenacity_indicator(newt_core::tenacity::effective_tenacity())
    )
}

/// The preamble tenacity indicator (#12): shown only when tenacity is raised
/// above `Normal`, so an operator sees at a glance that the round limit is
/// lifted (`· tenacity: relentless`). Empty at `Normal` to keep the default
/// line clean. Pure — unit-tested directly.
fn tenacity_indicator(t: newt_core::Tenacity) -> String {
    if t == newt_core::Tenacity::Normal {
        String::new()
    } else {
        format!(" · tenacity: {}", t.label())
    }
}

fn should_probe_openai_surface(
    kind: newt_core::BackendKind,
    api_needs_probe: bool,
    model: &str,
    url: &str,
    serving: Option<newt_core::Serving>,
) -> bool {
    kind == newt_core::BackendKind::Openai
        && api_needs_probe
        && !model.is_empty()
        && (url.starts_with("https://") || serving == Some(newt_core::Serving::Instance))
}

/// Resolve where the semantic embedder sends requests: `(url, protocol, key)`.
/// An explicit `embeddings_endpoint` (with its protocol; no inherited key)
/// decouples embeddings from chat — point it at a real embeddings host while
/// chat runs on a vLLM coder. Unset → fall back to the active backend
/// (back-compat), now protocol-aware so an OpenAI backend uses `/v1/embeddings`.
/// Pure for testing.
fn resolve_embeddings_target(
    cfg: &newt_core::SemanticConfig,
    inf_url: &str,
    inf_kind: newt_core::BackendKind,
    inf_key: Option<&str>,
) -> (String, newt_core::BackendKind, Option<String>) {
    match cfg.embeddings_endpoint.clone() {
        Some(url) => (
            url,
            cfg.embeddings_api.unwrap_or(newt_core::BackendKind::Ollama),
            None,
        ),
        None => (
            inf_url.to_string(),
            cfg.embeddings_api.unwrap_or(inf_kind),
            inf_key.map(str::to_string),
        ),
    }
}

/// Resolve the backend for the TUI. Precedence (unifies the loadout provider
/// axis with the `/backend` live toggle):
///
/// 1. **`NEWT_PROVIDER`** names a `[backends]` entry — the loadout's `provider`
///    axis (Slice 2). The named backend supplies endpoint/kind/auth; `NEWT_DGX_MODEL`
///    (the loadout's `model`) overrides the backend's default model when set.
/// 2. Legacy env shim: `NEWT_DGX_OLLAMA_URL`/`NEWT_DGX_HOST` synthesize an
///    ollama endpoint (one release, #1126).
/// 3. **`default_backend`** (#1130) names the configured start backend.
/// 4. **`NEWT_BACKEND`** (set by `/backend`) forces the openai-vs-ollama *kind*.
/// 5. A sole backend; then the legacy `[dgx]` node shim; then prefer-openai
///    among several; then the localhost fallback.
///
/// `NEWT_PROVIDER` is the most specific (a named entry); `NEWT_BACKEND` is the
/// coarse kind toggle `/backend` uses. A loadout-sourced provider is hard-error-
/// validated upstream ([`newt_core::Loadout::validate`]); a directly-set
/// `NEWT_PROVIDER` naming no backend falls through to (2).
/// The name of the backend the session currently resolves to, for the `◀ active`
/// marker in `/backends`. Prefers an explicit `NEWT_PROVIDER` pin (the exact name
/// `/backends <name>` sets); otherwise matches the resolved endpoint+kind back to
/// a configured `[[backends]]` entry. `None` when nothing matches (e.g. the
/// historical DGX fallback that isn't itself a named backend).
pub(crate) fn active_backend_name(resolved: &newt_core::ResolvedConfig) -> Option<String> {
    if let Some(name) = std::env::var("NEWT_PROVIDER")
        .ok()
        .filter(|s| !s.is_empty())
    {
        if resolved.backends.iter().any(|b| b.name == name) {
            return Some(name);
        }
    }
    let choice = resolve_backend_choice(resolved).ok()?;
    resolved
        .backends
        .iter()
        .find(|b| b.endpoint == choice.url && (b.kind.is_none() || b.kind == Some(choice.kind)))
        .map(|b| b.name.clone())
}

/// Session-start / backend-switch adoption (#1139 C1b, epic #1126): ask the
/// chosen backend what it ACTUALLY serves (bounded ~1s) and adopt served
/// reality via [`newt_core::backend_probe::adopt`]. Returns status lines to
/// print. Offline/timeout → keep the file-hint model and say so — NEVER a
/// silent failover to another backend. Embedded backends are not probed.
///
/// When the config omitted `kind` (`kind_needs_probe`), race `/api/tags` vs
/// `/v1/models` via [`newt_core::backend_probe::detect_endpoint`] first so a
/// minimal `name`+`endpoint` backend still connects.
fn adopt_backend_choice(choice: &mut BackendChoice, prewarm: Option<Prewarm>) -> Vec<String> {
    use newt_core::backend_probe;
    if choice.kind == newt_core::BackendKind::Embedded && !choice.kind_needs_probe {
        return Vec::new();
    }
    let lines = Vec::new();
    // Splash-first pre-warm: a probe started at splash entry for THIS
    // endpoint means the answer is already in flight (or done) — await it
    // instead of probing cold. Gated on the URL still matching (a first-run
    // wizard may have rewritten the config since the probe was spawned) and
    // fail-soft: a failed/mismatched pre-warm falls through to the cold path.
    let prewarmed = prewarm
        .filter(|pw| prewarm_applies(&choice.url, &pw.url))
        .and_then(|pw| {
            tokio::task::block_in_place(|| tokio::runtime::Handle::current().block_on(pw.handle))
                .ok()
                .flatten()
        });
    if let Some(probe) = prewarmed {
        let detected = if choice.kind_needs_probe {
            choice.kind = probe.kind;
            choice.kind_needs_probe = false;
            if choice.route_serving().is_none() {
                choice.adopted_serving = Some(probe.serving);
            }
            Some(probe.kind)
        } else {
            None
        };
        return finish_adoption(choice, lines, probe.models, probe.warm, detected);
    }
    let secs = probe_timeout_secs(&choice.url);
    let client = match reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(secs))
        .build()
    {
        Ok(c) => c,
        Err(_) => return Vec::new(),
    };
    // run_chat is sync inside the tokio runtime — bridge like wizard.rs does.
    let fetched = tokio::task::block_in_place(|| {
        tokio::runtime::Handle::current().block_on(async {
            if choice.kind_needs_probe {
                match backend_probe::detect_endpoint(
                    &client,
                    &choice.url,
                    choice.api_key.as_deref(),
                )
                .await
                {
                    Ok(probe) => {
                        choice.kind = probe.kind;
                        choice.kind_needs_probe = false;
                        if choice.route_serving().is_none() {
                            choice.adopted_serving = Some(probe.serving);
                        }
                        Ok((probe.models, probe.warm, Some(probe.kind)))
                    }
                    Err(e) => Err(e),
                }
            } else {
                let api = backend_probe::api_for(choice.kind);
                match api
                    .list_models(&client, &choice.url, choice.api_key.as_deref())
                    .await
                {
                    Ok(models) => {
                        // Warmth refines the no-preference fallback in adopt():
                        // a model already resident answers immediately, install
                        // order says nothing. Fail-soft (None → empty).
                        let warm = api
                            .warm_models(&client, &choice.url, choice.api_key.as_deref())
                            .await
                            .unwrap_or_default();
                        Ok((models, warm, None))
                    }
                    Err(e) => Err(e),
                }
            }
        })
    });
    match fetched {
        Ok((models, warm, detected_kind)) => {
            finish_adoption(choice, lines, models, warm, detected_kind)
        }
        Err(e) => offline_adoption(choice, lines, e),
    }
}

/// PR #2626 review residual finding 3: the model-picker's result is explicit
/// operator intent, honored against the roster displayed by the picker in
/// the selection iteration — never a snapshot taken before the picker
/// opened (roster can change while the picker is open: refresh, load/unload,
/// or simply time passing). `None` (cancel, or a picked model that isn't in
/// that fresh roster) is the only case that falls through to refusal. Pure
/// so the decision is unit-testable without driving a real terminal or probe.
fn resolve_modal_choice(picked: Option<(String, Vec<String>)>) -> Option<String> {
    picked.and_then(|(m, served)| served.contains(&m).then_some(m))
}

/// PR #2626 review round 4 ("smallest repair"): the ambiguous-default picker,
/// as a seam `finish_adoption` calls rather than inlines. Production passes
/// this real, terminal-driving implementation; tests pass a scripted
/// stand-in so the picker-then-resolve decision inside `finish_adoption` runs
/// for real without a PTY, a terminal, or a live probe.
#[cfg_attr(not(feature = "rich-tui"), allow(unused_variables))]
fn pick_ambiguous_default(choice: &BackendChoice) -> Option<(String, Vec<String>)> {
    #[cfg(feature = "rich-tui")]
    {
        std::io::IsTerminal::is_terminal(&std::io::stdout())
            .then(|| models_panel::choose(choice, None).ok().flatten())
            .flatten()
    }
    #[cfg(not(feature = "rich-tui"))]
    {
        None
    }
}

/// The shared adopt tail: probe results (live or pre-warmed) → the choice's
/// model/serving/window/api, with the honest status lines.
fn finish_adoption(
    choice: &mut BackendChoice,
    lines: Vec<String>,
    models: Vec<String>,
    warm: Vec<String>,
    detected_kind: Option<newt_core::BackendKind>,
) -> Vec<String> {
    finish_adoption_with_picker(
        choice,
        lines,
        models,
        warm,
        detected_kind,
        pick_ambiguous_default,
    )
}

/// Test seam: same as [`finish_adoption`] with the picker injectable. Kept
/// as a thin wrapper rather than duplicating the tail so production and
/// tests run the identical decision logic.
fn finish_adoption_with_picker(
    choice: &mut BackendChoice,
    mut lines: Vec<String>,
    models: Vec<String>,
    warm: Vec<String>,
    detected_kind: Option<newt_core::BackendKind>,
    picker: impl FnOnce(&BackendChoice) -> Option<(String, Vec<String>)>,
) -> Vec<String> {
    use newt_core::backend_probe::{self, Served};
    let secs = probe_timeout_secs(&choice.url);
    let client = match reqwest::Client::builder()
        .timeout(std::time::Duration::from_secs(secs))
        .build()
    {
        Ok(c) => c,
        Err(_) => return lines,
    };
    {
        {
            if let Some(kind) = detected_kind {
                lines.push(format!(
                    "detected {} at {} — {} model(s)",
                    kind.label(),
                    choice.url,
                    models.len()
                ));
            }
            // Adoption inputs from the choice's IMMUTABLE intent: the
            // declared model rides in the synthesized view, the operator's
            // per-session request rides separately — `adopt()` owns the
            // fallback policy (an unavailable request falls back to the
            // declaration; Managed Shared may prefer a warm model).
            let (synth, requested) = adoption_inputs(choice);
            let warm_at_probe = warm.clone();
            let declared_name = synth.effective_model().map(str::to_string);
            let mut adoption =
                backend_probe::adopt(&synth, &Served { models, warm }, requested.as_deref());
            if adoption.requested_unavailable {
                // #1122 fail-soft: a restored/typo'd model must not brick the
                // session — say what happened and what we used instead.
                lines.push(match adoption.model.as_deref() {
                    Some(m) => format!(
                        "requested model isn't on {} — falling back to {}; was it a typo, \
                         or removed from the endpoint? /models to list",
                        choice.url, m
                    ),
                    None => format!(
                        "requested model isn't on {} — falling back (was it a typo, or \
                         removed from the endpoint?); /models to list",
                        choice.url
                    ),
                });
            }
            // SEMANTICS (2026-09-28): a blank/missing declared model and a
            // STALE one (the server no longer serves that name) both mean
            // "backend default" — adopt whatever the backend has loaded —
            // and are reported the same non-alarming way, distinct from an
            // explicit operator request (handled above). A stale name gets
            // one extra short note; blank gets none.
            let backend_default =
                requested.is_none() && (declared_name.is_none() || adoption.declared_unavailable);
            // PR #2626 review P2-4: ambiguity must be resolved or explicitly
            // refused whenever adopt() returns it — including when the
            // ORIGINAL request named a model that turned out unavailable
            // (`requested.is_some()`, so `backend_default` is false). Gating
            // this on `backend_default` left that case with only the generic
            // #1122 typo warning above and no fallback model, candidate list,
            // or modal at all.
            if !adoption.ambiguous_warm.is_empty() {
                // #2622: several models loaded, no pin resolved — list order
                // is arbitrary. Tiebreak on the ONE backend-keyed fact newt
                // already has: the model this operator last ran on this
                // endpoint (usage.jsonl). Falls through to asking only when
                // that history doesn't cover any of the loaded candidates.
                // #2626 review: the history rule is the most recent row
                // naming an ELIGIBLE candidate, not merely the most recent
                // row for this endpoint — a later row for a model that's
                // since been unloaded must not shadow an earlier eligible
                // one, so the candidate check runs INSIDE the log scan.
                let last_used = newt_core::Config::user_config_path()
                    .map(|p| p.with_file_name("usage.jsonl"))
                    .and_then(|log| {
                        newt_core::metrics::last_eligible_model_for_endpoint(
                            &log,
                            &choice.url,
                            &adoption.ambiguous_warm,
                        )
                    });
                match last_used {
                    Some(m) => {
                        lines.push(format!(
                            "backend default → {m} (last used on this backend; also loaded: \
                             {})",
                            adoption
                                .ambiguous_warm
                                .iter()
                                .filter(|w| *w != &m)
                                .cloned()
                                .collect::<Vec<_>>()
                                .join(", ")
                        ));
                        adoption.model = Some(m);
                        adoption.ambiguous_warm.clear();
                    }
                    None => {
                        // #2622 TIEBREAK DECIDED: no history covers any of the
                        // loaded candidates — a default must still be chosen
                        // DELIBERATELY, not by list order. On a rich, real
                        // terminal, raise the existing model picker (same
                        // surface `/models` opens) rather than a bare notice;
                        // its choice — or a cancel — decides. Anywhere else
                        // (lean build, piped/non-tty) fall through to the
                        // refusal-with-list below. `picker` is
                        // `pick_ambiguous_default` in production and a
                        // scripted stand-in under test (round 4 seam).
                        let picked = picker(choice);
                        // PR #2626 review residual finding 3: the picker
                        // offers every served model (including ones not warm
                        // at probe time, and its own load/refresh controls),
                        // and the roster can change again while the picker
                        // is open. Validate against the roster displayed by
                        // the picker in the selection iteration — not
                        // `models_at_probe`, which is the OUTER probe from
                        // before the picker ever opened and can no longer
                        // speak for what the backend serves now.
                        match resolve_modal_choice(picked) {
                            Some(m) => {
                                lines.push(format!("backend default → {m} (picked)"));
                                adoption.model = Some(m);
                                adoption.ambiguous_warm.clear();
                            }
                            None => lines.push(format!(
                                "{} has {} models loaded ({}) and none is configured — \
                                 pick one with /model <name>; /models to list",
                                choice.url,
                                adoption.ambiguous_warm.len(),
                                adoption.ambiguous_warm.join(", ")
                            )),
                        }
                    }
                }
            } else if backend_default {
                if let Some(m) = adoption.model.as_deref() {
                    let loaded = warm_at_probe.iter().any(|w| w == m);
                    lines.push(format!(
                        "backend default → {m}{}",
                        if loaded { " (loaded)" } else { "" }
                    ));
                }
                if adoption.declared_unavailable {
                    if let Some(stale) = &declared_name {
                        lines.push(format!(
                            "configured model \"{stale}\" isn't served by {} (renamed or \
                             removed?)",
                            choice.url
                        ));
                    }
                }
            }
            if adoption.model.is_none() && adoption.ambiguous_warm.is_empty() {
                lines.push(format!(
                    "{} listed no models — pull one (or start the server with a model), \
                     then /models",
                    choice.url
                ));
            } else if adoption.requested_ignored {
                lines.push(format!(
                    "model is fixed by this {} instance: {} — restart the server \
                     with another model, or /backends to switch endpoints",
                    choice.kind.label(),
                    adoption.model.as_deref().unwrap_or_default()
                ));
            }
            // Adoption mutates ONLY the route — including CLEARING the
            // active model when a live multiplexer established no pick.
            apply_adoption(choice, &adoption);
            // #1199: auto-detect the context window from the SERVER, fresh —
            // vLLM's max_model_len / Ollama's /api/show. Held on the choice and
            // fed to the budget; never read from the persisted cache (which
            // could pin a stale None and starve a 256k model).
            let window_model = choice.active_model.clone().unwrap_or_default();
            choice.context_window = tokio::task::block_in_place(|| {
                tokio::runtime::Handle::current().block_on(async {
                    backend_probe::api_for(choice.kind)
                        .context_window(
                            &client,
                            &choice.url,
                            &window_model,
                            choice.api_key.as_deref(),
                        )
                        .await
                })
            });
            // OpenAI surface probe: absent `api` → try chat/completions, adopt
            // `responses` when the server says the model is responses-only.
            let mut api_was_probed = false;
            // Avoid forcing a model load on plain-HTTP multiplexers. An HTTPS
            // provider or a fixed-model instance can be capability-probed
            // without reviving the old llama-swap startup timeout.
            if should_probe_openai_surface(
                choice.kind,
                choice.api_needs_probe,
                &window_model,
                &choice.url,
                choice.route_serving(),
            ) {
                match tokio::task::block_in_place(|| {
                    tokio::runtime::Handle::current().block_on(async {
                        backend_probe::detect_openai_api(
                            &client,
                            &choice.url,
                            &window_model,
                            choice.api_key.as_deref(),
                        )
                        .await
                    })
                }) {
                    Ok(api) => {
                        choice.api = api;
                        choice.api_needs_probe = false;
                        api_was_probed = true;
                        lines.push(format!(
                            "detected api={} for {} @ {}",
                            api.label(),
                            choice.display_model(),
                            choice.url
                        ));
                    }
                    Err(e) => lines.push(format!(
                        "api probe failed ({e:#}) — using chat_completions until it answers"
                    )),
                }
            }
            // Persist what the probe OBSERVED through the typed machine
            // channel — probe_v1 files only; an operator-owned same-name
            // drop-in is skipped byte-for-byte and the skip is VISIBLE.
            if !choice.name.is_empty() && (detected_kind.is_some() || api_was_probed) {
                let serving = match choice.route_serving() {
                    // Only an Instance's model is backend truth; a
                    // multiplexer's pick is per-session and has no field to
                    // persist through.
                    Some(newt_core::Serving::Instance) => newt_core::ProbedServing::Instance {
                        model: choice.active_model.clone(),
                    },
                    Some(newt_core::Serving::Multiplexer) => newt_core::ProbedServing::Multiplexer,
                    None => newt_core::ProbedServing::Unknown,
                };
                let observation = newt_core::ProbeObservation {
                    name: choice.name.clone(),
                    endpoint: choice.url.clone(),
                    kind: Some(choice.kind),
                    api: (choice.kind == newt_core::BackendKind::Openai).then_some(choice.api),
                    serving,
                };
                match newt_core::persist_probe_observation(&observation) {
                    Ok(newt_core::ProbeWriteback::Written(path)) => lines.push(format!(
                        "wrote probed backend → {} (delete to reset)",
                        path.display()
                    )),
                    Ok(newt_core::ProbeWriteback::SkippedOperatorOwned(path)) => {
                        lines.push(format!(
                            "probe results not persisted — {} is operator-owned \
                             (delete it, or claim/edit it, to let probes write)",
                            path.display()
                        ));
                    }
                    Ok(newt_core::ProbeWriteback::NotWritten) => {}
                    Err(e) => lines.push(format!("could not write backend drop-in: {e}")),
                }
            }
            // Card-layer transitions surface HERE — the adoption seam —
            // through the ONE display owner, deduped by typed identity.
            lines.extend(choice.card_notice_lines());
        }
    }
    lines
}

/// The offline tail: the endpoint is unreachable — keep the file-hint model
/// with an honest line; never fail the session.
fn offline_adoption(
    choice: &mut BackendChoice,
    mut lines: Vec<String>,
    e: anyhow::Error,
) -> Vec<String> {
    match choice.active_model.as_deref() {
        None => lines.push(format!(
            "{} is unreachable ({e:#}) and no model is configured — check the \
             endpoint, then /backends",
            choice.url
        )),
        Some(model) => lines.push(format!(
            "{} is unreachable ({e:#}) — using configured model {model} until it answers",
            choice.url
        )),
    }
    lines
}

/// One item per configured backend for `/backends`: the `name · kind · model @
/// endpoint` label plus whether it's the active one. Pure (the active name is
/// passed in) so it unit-tests without touching the environment; the caller
/// renders each via [`newt_core::agentic::print_list_item`] (the default list
/// style — red `▸`/`◀` sigils + green `active` on the live row).
pub(crate) fn backends_list_items(
    cfg: &newt_core::Config,
    active: Option<&str>,
) -> Vec<(String, bool)> {
    cfg.backends
        .iter()
        .map(|b| {
            let label = format!(
                "{} · {} · {} @ {}",
                b.name,
                b.kind_label(),
                b.effective_model().unwrap_or("(server decides)"),
                b.endpoint
            );
            (label, active == Some(b.name.as_str()))
        })
        .collect()
}

pub(crate) fn resolve_backend_choice(
    resolved: &newt_core::ResolvedConfig,
) -> Result<BackendChoice, String> {
    let session_model = || {
        std::env::var("NEWT_DGX_MODEL")
            .ok()
            .filter(|s| !s.is_empty())
    };
    let from_backend = |rb: newt_core::ResolvedBackend<'_>| -> Result<BackendChoice, String> {
        let b = rb.backend;
        let receipt = rb.receipt;
        // The chat driver is HTTP-only: an embedded (model_path) backend —
        // judged on the FLATTENED, core-normalized view, never a stale
        // declared kind — is a typed refusal, exactly as in solve. No
        // silent fallback to another backend, no empty-URL HTTP session.
        if b.endpoint.is_empty() || b.kind == Some(newt_core::BackendKind::Embedded) {
            return Err(format!(
                "backend `{}` is an embedded (model_path) backend — chat drives HTTP \
                 backends only; select an HTTP backend (/backends), or serve the \
                 artifact behind an HTTP endpoint",
                b.name
            ));
        }
        // ONE sidecar construction per choice, from the receipt's BINDING
        // evidence (pre-overlay: a CLI/session model override retargets the
        // session, never the card). An unknown named card is a real config
        // error but choice resolution is infallible by contract (a broken
        // backend list must not crash the TUI) — so the error becomes a
        // VISIBLE notice at the next printing seam and the capabilities
        // fall to the conservative inline-only floor.
        let seed = receipt.binding.clone();
        let pinned = newt_core::Config::pinned_config_path();
        let (caps, card_error) =
            match newt_core::model_card::ResolvedCapabilities::resolve(b, &seed, pinned.as_deref())
            {
                Ok(caps) => (caps, None),
                Err(e) => (
                    newt_core::model_card::ResolvedCapabilities::resolve(
                        b,
                        &newt_core::model_card::CardBindingSeed {
                            card: None,
                            ..seed.clone()
                        },
                        None,
                    )
                    .expect("card-less resolution is infallible"),
                    Some(e),
                ),
            };
        // The probe-cached route, straight from the receipt's typed
        // observation — never re-derived from the flattened backend.
        let (observed_serving, _observed_model) = receipt
            .observation
            .as_ref()
            .map(|o| o.serving_axis())
            .unwrap_or((None, None));
        let request = receipt.request.as_ref();
        // The DECLARED axis carries the core's destination normalization: a
        // model_path route IS Instance even when the declaration omitted
        // the axis.
        let declared_serving = receipt.declaration.serving.or_else(|| {
            receipt
                .declaration
                .destination
                .model_path
                .as_deref()
                .is_some_and(|p| !p.is_empty())
                .then_some(newt_core::Serving::Instance)
        });
        Ok(BackendChoice {
            name: b.name.clone(),
            url: b.endpoint.clone(),
            // Immutable intent, from the receipt's DECLARATION layer.
            declared_model: receipt.declaration.model.clone(),
            // The session override (env) is the most-specific request; the
            // CLI --backend-model rides in the receipt's request layer.
            requested_model: session_model()
                .or_else(|| receipt.request.as_ref().and_then(|r| r.model.clone())),
            declared_serving,
            requested_serving: request.and_then(|r| r.serving),
            configured_kind: request.and_then(|r| r.kind).or(receipt.declaration.kind),
            configured_api: request.and_then(|r| r.api).or(receipt.declaration.api),
            managed: receipt.declaration.managed,
            api_key: b.resolve_api_key(),
            model_path: b.model_path.clone(),
            // The route starts at the EFFECTIVE view (session override >
            // flattened model, which already carries the probe-cached
            // Instance model and any CLI request); adoption replaces it
            // with served reality.
            active_model: session_model().or_else(|| b.effective_model().map(str::to_string)),
            // The cached observation keeps its own PROVENANCE slot — the
            // precedence (live > request > cache > declaration) lives in
            // route_serving, not in field blending.
            observed_serving,
            adopted_serving: None,
            kind: b.kind.unwrap_or(newt_core::BackendKind::Ollama),
            kind_needs_probe: b.needs_kind_probe(),
            api: b.api.unwrap_or_default(),
            api_needs_probe: b.api.is_none(),
            context_window: None,
            capabilities: caps,
            card_resolution_error: card_error,
            notices: CardNotices::default(),
        })
    };
    // 1. Explicit selection ($NEWT_PROVIDER / default_backend) through the
    //    SHARED typed contract: unknown, unroutable, and provider outcomes
    //    are HARD errors — never a silent fallback to some other backend
    //    (the pre-#1819 fall-through was exactly the failure mode the typed
    //    selection exists to kill).
    let explicit_selector = std::env::var("NEWT_PROVIDER")
        .ok()
        .filter(|s| !s.is_empty())
        .is_some()
        || resolved
            .default_backend
            .as_deref()
            .is_some_and(|n| !n.is_empty());
    if explicit_selector {
        use newt_core::config::{SelectedBackend, SelectionOutcome};
        match resolved.select_backend() {
            SelectionOutcome::Selected(SelectedBackend::Configured(_)) => {
                let rb = resolved
                    .selected_backend()
                    .expect("the shared index selector just picked a configured backend");
                return from_backend(rb);
            }
            SelectionOutcome::Selected(SelectedBackend::Provider(p)) => {
                return Err(format!(
                    "the backend selection resolves to provider `{}` — chat drives \
                     [[backends]] only; point $NEWT_PROVIDER/default_backend at a \
                     backend (or unset them)",
                    p.name
                ));
            }
            SelectionOutcome::UnknownNamed(name) => {
                return Err(format!(
                    "$NEWT_PROVIDER/default_backend names `{name}`, which matches \
                     nothing configured — fix the selector (chat will not silently \
                     run another backend)"
                ));
            }
            SelectionOutcome::UnroutableNamed(name) => {
                return Err(format!(
                    "$NEWT_PROVIDER/default_backend names `{name}`, which has neither \
                     an endpoint nor a model_path — give it a destination (chat will \
                     not silently run another backend)"
                ));
            }
            // No explicit selector fired inside the contract (e.g. the env
            // var empty) — fall through to the env shims + preference.
            SelectionOutcome::Unset => {}
        }
    }
    // 1.5 Codex-compatible environment (bug/steering-regressions #9): honor
    //     OPENAI_BASE_URL / OPENAI_API_KEY / OPENAI_MODEL the way Codex does,
    //     so `OPENAI_API_KEY=… newt` just works with zero config and
    //     `OPENAI_BASE_URL` can redirect a session at any local-compatible
    //     server. Local-first guard: a bare key only fires when NO backends
    //     are configured — a stray OPENAI_API_KEY in the shell must never
    //     silently reroute a configured setup (and its cost) to OpenAI; an
    //     explicit OPENAI_BASE_URL is a deliberate redirect and always wins.
    {
        let base = std::env::var("OPENAI_BASE_URL").ok();
        let key = std::env::var("OPENAI_API_KEY").ok();
        let model = std::env::var("OPENAI_MODEL").ok();
        if let Some(choice) = codex_env_backend(
            base.as_deref(),
            key.as_deref(),
            model.as_deref(),
            session_model(),
            !resolved.backends.is_empty(),
        ) {
            let detected = [
                base.as_ref().map(|_| "OPENAI_BASE_URL"),
                key.as_ref().map(|_| "OPENAI_API_KEY"),
                model.as_ref().map(|_| "OPENAI_MODEL"),
            ]
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()
            .join(", ");
            if codex_env_allowed(&detected) {
                return Ok(choice);
            }
        }
    }
    // 2. Legacy env shim (one release, #1126): explicit NEWT_DGX_OLLAMA_URL /
    //    NEWT_DGX_HOST synthesize an ollama endpoint, exactly as before.
    let env_url = std::env::var("NEWT_DGX_OLLAMA_URL").ok().or_else(|| {
        std::env::var("NEWT_DGX_HOST").ok().map(|h| {
            let scheme = std::env::var("NEWT_DGX_SCHEME").unwrap_or_else(|_| "http".into());
            let port = std::env::var("NEWT_DGX_OLLAMA_PORT").unwrap_or_else(|_| "11434".into());
            format!("{scheme}://{h}:{port}")
        })
    });
    if let Some(url) = env_url {
        let requested = session_model();
        return Ok(BackendChoice {
            requested_model: requested.clone(),
            ..BackendChoice::synthesized(
                "",
                url,
                newt_core::BackendKind::Ollama,
                requested.or_else(|| Some("llama3.1:8b".into())),
            )
        });
    }
    // 3. NEWT_BACKEND forces the wire kind (`/backend openai|ollama`).
    if let Some(force) = std::env::var("NEWT_BACKEND").ok().filter(|s| !s.is_empty()) {
        let want = if force.eq_ignore_ascii_case("openai") {
            newt_core::BackendKind::Openai
        } else {
            newt_core::BackendKind::Ollama
        };
        if let Some(rb) = resolved.backends().find(|rb| rb.backend.kind == Some(want)) {
            return from_backend(rb);
        }
    }
    // 4. Everything configured — sole / prefer-OpenAI / first ROUTABLE /
    //    provider — delegates to the SHARED typed selection contract, so
    //    chat's fallback can never diverge from solve/worker: a
    //    destination-less first entry is skipped for a later routable one
    //    (the core preference filters by routability), and a provider-only
    //    config is a TYPED refusal, never a silent localhost.
    {
        use newt_core::config::{SelectedBackend, SelectionOutcome};
        match resolved.select_backend() {
            SelectionOutcome::Selected(SelectedBackend::Configured(_)) => {
                let rb = resolved
                    .selected_backend()
                    .expect("the shared index selector just picked a configured backend");
                return from_backend(rb);
            }
            SelectionOutcome::Selected(SelectedBackend::Provider(p)) => {
                return Err(format!(
                    "the backend selection resolves to provider `{}` — chat drives \
                     [[backends]] only; configure a backend (or run the worker)",
                    p.name
                ));
            }
            // Explicit-selector errors were handled in rung 1; if the env
            // changed between the two reads, surface the same typed refusal
            // rather than falling through.
            SelectionOutcome::UnknownNamed(name) => {
                return Err(format!(
                    "$NEWT_PROVIDER/default_backend names `{name}`, which matches \
                     nothing configured — fix the selector"
                ));
            }
            SelectionOutcome::UnroutableNamed(name) => {
                return Err(format!(
                    "$NEWT_PROVIDER/default_backend names `{name}`, which has neither \
                     an endpoint nor a model_path — give it a destination"
                ));
            }
            // Nothing configured qualifies: the chat-only legacy shims below.
            SelectionOutcome::Unset => {}
        }
    }
    // 5. Legacy [dgx] node (one-release shim): configs written by the old
    //    wizard resolve their dgx endpoint + active_model as before.
    if let Some((url, model)) = resolved.dgx.as_ref().and_then(|d| {
        d.nodes.first().and_then(|n| n.ollama.clone()).map(|url| {
            let model = session_model()
                .or_else(|| d.active_model.clone())
                .unwrap_or_else(|| "llama3.1:8b".into());
            (url, model)
        })
    }) {
        let requested = session_model();
        return Ok(BackendChoice {
            requested_model: requested,
            ..BackendChoice::synthesized("", url, newt_core::BackendKind::Ollama, Some(model))
        });
    }
    // 6. Bare fallback: localhost ollama (Config::resolve normally restores
    //    this backend already; this is the belt-and-braces path).
    let requested = session_model();
    Ok(BackendChoice {
        requested_model: requested.clone(),
        ..BackendChoice::synthesized(
            "",
            "http://localhost:11434".into(),
            newt_core::BackendKind::Ollama,
            requested.or_else(|| Some("llama3.1:8b".into())),
        )
    })
}

/// The TUI's config resolution, receipts kept and NOTHING published:
/// process-global settings land only at an accepted-session boundary
/// (startup after the typed backend choice validates; a refresh after it
/// accepts) — a refused session must not publish globals from a route it
/// never accepted. A resolution failure is warned (typed, not silent) and
/// falls back to the AS-IS default config so command surfaces still
/// render; the chat startup path prints its own visible line.
pub(crate) fn resolve_runtime_or_default() -> newt_core::ResolvedConfig {
    crate::migration_notices::read(|report| newt_core::Config::resolve_runtime_unpublished(report))
        .unwrap_or_else(|e| {
            tracing::warn!(error = %e, "config resolution failed — running on built-in defaults");
            newt_core::ResolvedConfig::unrequested(newt_core::Config::default())
        })
}

/// Surface the resolved OpenAI API surface to the agent loop via
/// `NEWT_OPENAI_API` (read by the agent loop to route to the Responses path).
/// Called whenever the session (re)resolves its backend, so a `/backends`
/// switch to a `responses` backend takes effect on the next message.
///
/// Public so the headless surfaces (`newt solve` / worker) that reuse the same
/// loop surface `api = "responses"` too — otherwise a responses-only model
/// (gpt-5.6-sol, gpt-5-codex) is driven over `/v1/chat/completions` and 400s on
/// function tools.
pub fn apply_openai_api_env(api: newt_core::OpenAiApi) {
    // Published under the process-env lock (#1850). "Single-threaded session
    // setup" was true of the REPL and false under `cargo test`, which drives
    // this from parallel test threads.
    newt_core::process_env::set_or_remove(
        "NEWT_OPENAI_API",
        match api {
            newt_core::OpenAiApi::Responses => Some("responses"),
            newt_core::OpenAiApi::ChatCompletions => None,
        },
    );
}

/// Re-resolve the active backend from `cfg` + env into the session's live wire
/// locals — adopting served reality when the endpoint or model changed, and
/// republishing the OpenAI api surface. The single owner of "repoint the session
/// to the current backend choice": shared by the post-slash-command refresh and
/// by persona backend routing. Returns whether the endpoint URL changed, so the
/// caller re-probes DGX telemetry only when it matters.
#[allow(clippy::too_many_arguments)]
pub(crate) fn refresh_backend(
    resolved: &newt_core::ResolvedConfig,
    choice: &mut BackendChoice,
    inf_url: &mut String,
    inf_model: &mut String,
    inf_kind: &mut newt_core::BackendKind,
    inf_key: &mut Option<String>,
    inf_context_window: &mut Option<u32>,
    color: bool,
    verbose: bool,
) -> bool {
    let prev_url = inf_url.clone();
    // The typed selection contract can REFUSE (unknown/unroutable/provider
    // explicit selector): print the refusal and keep the current choice — a
    // live session never silently reroutes, and never crashes mid-flight.
    let mut next = match resolve_backend_choice(resolved) {
        Ok(next) => next,
        Err(refusal) => {
            // Typed refusal: keep the current choice AND the current
            // process-globals — a refused route publishes nothing.
            print_newt(&refusal, color, verbose);
            return false;
        }
    };
    // The route validated — THIS is the accepted-session boundary where the
    // re-resolved configuration's process-global settings publish.
    resolved.publish_runtime_settings();
    // Fold the fresh resolution over the previous choice: on a same-intent
    // no-op the established route/probe results carry; fresh capabilities
    // and resolution errors always stand; display history always survives.
    let _intent_changed = merge_refresh(choice, &mut next);
    *choice = next;
    // Adopt served reality only when the ROUTE actually moved (endpoint or
    // model) — the historical trigger: a plain slash command must not
    // re-probe every time, and two same-endpoint backends can swap without
    // a network round-trip (the pin/tab tiers depend on that). A
    // same-intent refresh carried the established route above, so it
    // compares equal here and stays quiet.
    if choice.url != prev_url || choice.active_model.clone().unwrap_or_default() != *inf_model {
        for line in adopt_backend_choice(choice, None) {
            print_newt(&line, color, verbose);
        }
    }
    // Card-layer notices surface HERE — the seam every mid-session
    // backend/model change flows through — via the ONE display owner,
    // deduped by typed identity (an unchanged state stays quiet, every
    // transition is visible, nothing is destructively taken).
    for line in choice.card_notice_lines() {
        print_newt(&line, color, verbose);
    }
    *inf_url = choice.url.clone();
    *inf_model = choice.active_model.clone().unwrap_or_default();
    *inf_kind = choice.kind;
    *inf_key = choice.api_key.clone();
    *inf_context_window = choice.context_window;
    apply_openai_api_env(choice.api);
    // #1139: this is the ONE seam every mid-session model change flows through —
    // `/backends`, `/model`, and persona routing (`apply_persona_backend`) all land
    // here — so attribute the model's FAMILY in one place. TYPED: the family is
    // the resolved card's declared metadata, under the same association gates as
    // the capability decision — never inferred from the model name (the
    // anti-substring law). No associated card family ⇒ no family (the
    // per-family initiative default simply does not engage).
    newt_core::initiative::set_active_model_family(
        choice
            .capabilities
            .family_for_route(&choice.route_destination(), choice.principal())
            .map(str::to_string),
    );
    *inf_url != prev_url
}

/// #1668: fold the operator posture ACTIONS marked since the last drain into
/// the session's operator baseline and the active conversation's stored pin.
/// The chat loop calls this ONCE per iteration — the single persistence site
/// for the pin, and the single owner of `base_provider` / `base_model` updates.
///
/// Actions accumulate in a process global because the commands that produce
/// them (`commands::model`, `commands::settings`, the psyche panel) cannot
/// reach session state; marking happens where SUCCESS is known, so a listing,
/// a refused pick, or a persona route contributes nothing.
///
/// A conversation whose durable row does not exist yet (the normal state of a
/// fresh session until its first saved turn) keeps its actions PENDING rather
/// than losing them — the write lands on the iteration after the row appears.
/// An ephemeral session has no store, so nothing is ever written: it leaves no
/// trace, exactly as `/backends`' #545 persistence rule already promises.
///
/// `Err` carries a one-line warning for the caller to print; the session is
/// never blocked by a posture write.
/// A tab's display label: the conversation's title, else `#<short-id>`.
///
/// #1669 PR-A, factored from the #1671 footer rule (`chat.rs:1997-2007`) so the
/// bar, the `/tab` list, and the footer cannot disagree. **Labels are never
/// stored** — computed fresh at every read — so `/rename` honesty is free and a
/// title can never go stale in a list.
pub(crate) fn tab_label(store: &newt_core::ConversationStore, conversation_id: &str) -> String {
    store
        .title(conversation_id)
        .ok()
        .flatten()
        .filter(|title| !title.trim().is_empty())
        .unwrap_or_else(|| format!("#{}", short_conversation_id(conversation_id)))
}

/// Retitle `conversation_id`, creating its row if it has none yet.
///
/// #1669 PR-A, extracted from the `/rename` arm so it can target a tab that is
/// NOT the active conversation — the `/tab rename [n] <title>` case.
///
/// **The #1030 guard is preserved verbatim and is the reason this matches on
/// `exists()` rather than using `unwrap_or(false)`:** a transient store error
/// (SQLITE_BUSY, or NFS IO under concurrent-newt contention) must never read as
/// "absent" and route into `create_with_id`, whose `INSERT OR REPLACE` would
/// destroy the live conversation and CASCADE-drop its turns. An error stays an
/// error.
pub(crate) fn rename_conversation(
    store: &newt_core::ConversationStore,
    conversation_id: &str,
    title: &str,
    persona: Option<&str>,
) -> anyhow::Result<()> {
    let title = title.trim();
    if title.is_empty() {
        anyhow::bail!("a title cannot be empty");
    }
    match store.exists(conversation_id)? {
        true => store.rename(conversation_id, title),
        false => store.create_with_id(conversation_id, title, persona),
    }
}

pub(crate) fn persist_preference_actions(
    store: Option<&newt_core::ConversationStore>,
    conversation_id: &str,
    pending: &mut newt_core::PreferenceActions,
    base_provider: &mut Option<String>,
    base_model: &mut Option<String>,
) -> Result<(), String> {
    let fresh = newt_core::runtime::drain_preference_actions();
    // The operator baseline follows the operator's own acted axes — never the
    // ambient env, which a persona route or an applied pin may have rewritten
    // (review findings 1 and 7).
    if let Some(provider) = &fresh.backend {
        base_provider.clone_from(provider);
    }
    if let Some(model) = &fresh.model {
        base_model.clone_from(model);
    }
    pending.merge(fresh);
    if pending.is_empty() {
        return Ok(());
    }
    let Some(store) = store else {
        // Ephemeral: no store, no pin, nothing held.
        *pending = newt_core::PreferenceActions::default();
        return Ok(());
    };
    let stored = match store.preference_pin(conversation_id) {
        // No durable row yet — hold the actions until there is one.
        Ok(None) => return Ok(()),
        Ok(Some(pin)) => pin,
        Err(e) => {
            *pending = newt_core::PreferenceActions::default();
            return Err(format!(
                "could not read the conversation preference pin ({e}) — \
                 this change applies to the session but is not pinned"
            ));
        }
    };
    let merged = stored.merged(pending);
    *pending = newt_core::PreferenceActions::default();
    if merged == stored {
        return Ok(());
    }
    store
        .update_preference_pin(conversation_id, &merged)
        .map_err(|e| format!("could not persist the conversation preference pin: {e}"))
}

#[cfg(test)]
#[path = "lib_tests/resumed_preference_tests.rs"]
mod resumed_preference_tests;

/// Build a system prompt with workspace context so the model knows the project.
// build_system_prompt_with_soul is used directly now; this wrapper kept for tests.
#[allow(dead_code)]
fn build_system_prompt(workspace: &str, plan_path: &str) -> String {
    build_system_prompt_with_soul(workspace, None, plan_path)
}

/// Seat `persona`'s declared dials (cognition and initiative) as the persona
/// resolution layers, or clear them for `None`. Every persona activation site
/// calls this one function: startup, `/persona set|clear`, a conversation
/// restore and a fresh tab. Re-seating the dials one at a time is how the
/// outgoing persona's tenacity once leaked into restored conversations.
pub(crate) fn seat_persona_dials(persona: Option<&Persona>) {
    let profile = persona.map(|p| &p.profile);
    newt_core::cognition::set_persona_cognition(profile.and_then(|p| p.cognition));
    newt_core::initiative::set_persona_initiative(profile.and_then(|p| p.initiative));
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Persona {
    name: String,
    prompt: String,
    path: std::path::PathBuf,
    /// The parsed role profile. For a plain prompt-only persona (no `+++`
    /// front-matter) every field except `prompt` is `None`, so behavior is
    /// identical to before role profiles existed. When the file carries
    /// front-matter, this surfaces the role's preferred tools, advisory caveats,
    /// and model/tier router policy.
    profile: newt_core::RoleProfile,
}

impl Persona {
    fn description(&self) -> String {
        self.prompt
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty())
            .unwrap_or("")
            .trim_start_matches('#')
            .trim()
            .chars()
            .take(96)
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PersonaSummary {
    name: String,
    description: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PersonaStore {
    dir: std::path::PathBuf,
}

/// Why a [`PersonaStore::save`] did not write — mapped by the config-panel caller
/// to `config_panel::SaveResult` for a visible status line. Rich-tui only (the
/// panel is its only caller).
#[cfg(feature = "rich-tui")]
#[derive(Debug)]
enum PersonaSaveError {
    /// A persona with this name already exists and overwrite was not requested.
    Exists,
    /// The name is not a valid persona file stem.
    InvalidName(String),
    /// The filesystem write failed.
    Io(String),
}

impl PersonaStore {
    const DEFAULT_NAME: &'static str = "coder";

    fn default_dir() -> std::path::PathBuf {
        newt_core::Config::user_config_path()
            .map(|p| p.with_file_name("personas"))
            .unwrap_or_else(|| std::path::PathBuf::from("personas"))
    }

    fn new(dir: impl Into<std::path::PathBuf>) -> Self {
        Self { dir: dir.into() }
    }

    fn default() -> Self {
        Self::new(Self::default_dir())
    }

    /// Atomically write persona `<name>.md`. With `overwrite == false`, refuses an
    /// existing persona ([`PersonaSaveError::Exists`]); with `true`, replaces it
    /// atomically — writes to a temp file in the destination directory then renames
    /// it over the target, so a failed or partial write never truncates or corrupts
    /// the existing persona (review-3 §1). Used only by the config panel's save
    /// action, so it is rich-tui-gated alongside the panel.
    #[cfg(feature = "rich-tui")]
    fn save(
        &self,
        name: &str,
        content: &str,
        overwrite: bool,
    ) -> Result<std::path::PathBuf, PersonaSaveError> {
        self.save_with(name, content, overwrite, |p, c| std::fs::write(p, c))
    }

    /// [`Self::save`] with an injectable byte-writer, so the atomicity guarantee
    /// (a failed write preserves the original) is unit-testable without needing to
    /// provoke a real I/O error.
    #[cfg(feature = "rich-tui")]
    fn save_with<W>(
        &self,
        name: &str,
        content: &str,
        overwrite: bool,
        write_bytes: W,
    ) -> Result<std::path::PathBuf, PersonaSaveError>
    where
        W: Fn(&std::path::Path, &str) -> std::io::Result<()>,
    {
        let name = normalize_persona_name(name)
            .map_err(|e| PersonaSaveError::InvalidName(e.to_string()))?;
        let path = self.dir.join(format!("{name}.md"));
        if !overwrite && path.exists() {
            return Err(PersonaSaveError::Exists);
        }
        std::fs::create_dir_all(&self.dir).map_err(|e| PersonaSaveError::Io(e.to_string()))?;
        // Atomic replace: write a temp file in the SAME dir, then rename over the
        // target. If either step fails we remove the temp and leave the original
        // untouched — never a truncating in-place write.
        let tmp = self
            .dir
            .join(format!(".{name}.md.tmp.{}", std::process::id()));
        if let Err(e) = write_bytes(&tmp, content) {
            let _ = std::fs::remove_file(&tmp);
            return Err(PersonaSaveError::Io(e.to_string()));
        }
        match std::fs::rename(&tmp, &path) {
            Ok(()) => Ok(path),
            Err(e) => {
                let _ = std::fs::remove_file(&tmp);
                Err(PersonaSaveError::Io(e.to_string()))
            }
        }
    }

    fn load(&self, name: &str) -> anyhow::Result<Persona> {
        crate::migration_notices::read(|report| {
            self.ensure_defaults()?;
            let name = normalize_persona_name(name)?;
            let path = self.dir.join(format!("{name}.md"));
            let raw = match newt_core::psyche_import::read_persona_file(&path, report) {
                Ok(raw) => raw,
                Err(_) => anyhow::bail!("unknown persona `{name}`\n{}", self.list_message()?),
            };
            // Parse optional `+++` front-matter into a role profile. A plain `.md`
            // with no front-matter yields a prompt-only profile (backward
            // compatible). The injected `prompt` is the markdown BODY, so
            // front-matter never leaks into the system prompt.
            let profile = newt_core::RoleProfile::parse(&raw)
                .map_err(|e| anyhow::anyhow!("persona `{name}`: {e}"))?;
            if profile.prompt.is_empty() {
                anyhow::bail!("persona `{name}` is empty: {}", path.display());
            }
            Ok(Persona {
                name,
                prompt: profile.prompt.clone(),
                path,
                profile,
            })
        })
    }

    fn list(&self) -> anyhow::Result<Vec<PersonaSummary>> {
        crate::migration_notices::read(|report| {
            self.ensure_defaults()?;
            let mut personas = Vec::new();
            for entry in std::fs::read_dir(&self.dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) != Some("md") {
                    continue;
                }
                let Some(name) = path.file_stem().and_then(|s| s.to_str()) else {
                    continue;
                };
                let raw =
                    newt_core::psyche_import::read_persona_file(&path, report).unwrap_or_default();
                if raw.trim().is_empty() {
                    continue;
                }
                // Skip files whose front-matter is malformed in the listing rather
                // than failing the whole list; `load` surfaces the error on use.
                let Ok(profile) = newt_core::RoleProfile::parse(&raw) else {
                    continue;
                };
                let persona = Persona {
                    name: name.to_string(),
                    prompt: profile.prompt.clone(),
                    path: path.clone(),
                    profile,
                };
                let description = persona.description();
                personas.push(PersonaSummary {
                    name: persona.name,
                    description,
                });
            }
            personas.sort_by(|a, b| a.name.cmp(&b.name));
            Ok(personas)
        })
    }

    fn list_message(&self) -> anyhow::Result<String> {
        let personas = self.list()?;
        let mut out = format!("Available personas in {}:", self.dir.display());
        if personas.is_empty() {
            out.push_str("\n  (none)");
        } else {
            for p in personas {
                out.push_str(&format!("\n  {} - {}", p.name, p.description));
            }
        }
        Ok(out)
    }

    /// Shipped default personas, seeded per-file-idempotently (FR-16, #1000):
    /// each MISSING one is written on any store access, so an upgrade that
    /// predates a new default still receives it (the old empty-dir gate would
    /// strand it forever). `coder` is the doer identity (DEFAULT_SOUL); `coach`
    /// prefers advising first; its `altitude = "coach"` selects COACH_SOUL.
    /// `personal-assistant` specializes in routine automation. Its `skills:`
    /// binding preloads `gila-personal-assistant`, and its `tools:` preferences
    /// prioritize that skill's MCP tools. Explicit permissions still determine
    /// which actions may run for every persona. `steady`,
    /// `direct`, and `sociable` contain only communication-style preferences,
    /// not capability or action-policy settings. A user who deletes a default
    /// gets it back next launch; empty the file to suppress it.
    const DEFAULT_PERSONAS: &'static [(&'static str, &'static str)] = &[
        (Self::DEFAULT_NAME, newt_core::DEFAULT_SOUL),
        ("coach", COACH_PERSONA),
        ("personal-assistant", PERSONAL_ASSISTANT_PERSONA),
        ("steady", include_str!("../../personas/steady.md")),
        ("direct", include_str!("../../personas/direct.md")),
        ("sociable", include_str!("../../personas/sociable.md")),
    ];

    fn ensure_defaults(&self) -> anyhow::Result<()> {
        std::fs::create_dir_all(&self.dir)?;
        for &(name, body) in Self::DEFAULT_PERSONAS {
            let path = self.dir.join(format!("{name}.md"));
            if !path.exists() {
                std::fs::write(&path, body)?;
            }
        }
        Ok(())
    }
}

/// The read-only coach persona shipped as a repo template (FR-16, #1000), so
/// `shipped_role_templates_parse` type-checks its front-matter beside the others.
const COACH_PERSONA: &str = include_str!("../../personas/coach.md");

/// The Personal Assistant persona shipped as a repo template (#1021, FR-PA-3),
/// so `shipped_role_templates_parse` type-checks its front-matter beside the
/// others.
const PERSONAL_ASSISTANT_PERSONA: &str = include_str!("../../personas/personal-assistant.md");

/// FR-4 (#1041): names in `skills` that do NOT resolve to a `SKILL.md` under
/// `search_dirs` — a persona's declared-but-missing skill bindings. Empty when
/// every declared skill resolves (or none are declared). Checked eagerly at
/// activation (not just on the model's first `use_skill` call) so a
/// misconfigured persona surfaces the problem immediately.
fn missing_bound_skills(skills: &[String], search_dirs: &[std::path::PathBuf]) -> Vec<String> {
    if skills.is_empty() {
        return Vec::new();
    }
    let available: std::collections::HashSet<String> = newt_skills::discover_paths(search_dirs)
        .into_iter()
        .map(|s| s.name)
        .collect();
    skills
        .iter()
        .filter(|name| !available.contains(*name))
        .cloned()
        .collect()
}

/// FR-4 (#1041): warn (non-fatal — matches `PersonaStore::list`'s soft-fail
/// style for bad data) when an active persona's `skills:` front-matter names a
/// skill that doesn't resolve under `search_dirs`.
fn warn_on_missing_bound_skills(
    persona: Option<&Persona>,
    search_dirs: &[std::path::PathBuf],
    color: bool,
    verbose: bool,
) {
    let Some(persona) = persona else { return };
    let Some(skills) = &persona.profile.skills else {
        return;
    };
    let missing = missing_bound_skills(skills, search_dirs);
    if !missing.is_empty() {
        print_newt(
            &format!(
                "warning: persona `{}` declares skill(s) not found in any skill search dir: {}",
                persona.name,
                missing.join(", ")
            ),
            color,
            verbose,
        );
    }
}

/// The shipped `gila-personal-assistant` skill (#1021) — coaches on a
/// `modulex` MCP routine report. Seeded into the default skill dir
/// per-file-idempotently, the same shipped-template pattern
/// `PersonaStore::DEFAULT_PERSONAS` uses (FR-16, #1000), so a
/// `personal-assistant` persona's declared `skills:` binding resolves out of
/// the box with no manual `[skills] bundled_dir` opt-in required.
///
/// Sourced from `newt-tui/assets/`, NOT the repo-local `.newt/` config dir:
/// compiled-in assets must never live under a `.newt/` directory, because
/// operators legitimately move `.newt` dirs aside (e.g. to simulate a fresh
/// unboxing) and that must never break `cargo build`.
const GILA_SKILL: &str = include_str!("../assets/bundled-skills/gila-personal-assistant/SKILL.md");

/// Seed [`GILA_SKILL`] into the skill install dir
/// ([`newt_core::Config::skill_install_dir`]: the first `[skills].search`
/// entry, else `~/.newt/skills`) if missing, so the seeded skill is on the
/// search path the persona binding is checked against (#2331). A `None`
/// install dir (unresolvable `$HOME`) is a silent no-op, matching how
/// `current_host_boot`-style host lookups degrade elsewhere in this codebase.
fn ensure_default_skills(cfg: &newt_core::Config) -> anyhow::Result<()> {
    match cfg.skill_install_dir() {
        Some(dir) => seed_gila_skill(&dir),
        None => Ok(()),
    }
}

/// Write [`GILA_SKILL`] to `<skills_root>/gila-personal-assistant/SKILL.md`
/// if missing. Per-file-idempotent like `PersonaStore::ensure_defaults`: a
/// user who deletes it gets it back next launch; an empty file suppresses it.
/// Split out from [`ensure_default_skills`] so the write itself is testable
/// against an explicit temp dir rather than the real `$HOME`.
fn seed_gila_skill(skills_root: &std::path::Path) -> anyhow::Result<()> {
    let skill_dir = skills_root.join("gila-personal-assistant");
    let path = skill_dir.join("SKILL.md");
    if !path.exists() {
        std::fs::create_dir_all(&skill_dir)?;
        std::fs::write(&path, GILA_SKILL)?;
    }
    Ok(())
}

fn normalize_persona_name(name: &str) -> anyhow::Result<String> {
    let name = name.trim().to_ascii_lowercase();
    if name.is_empty()
        || !name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        anyhow::bail!("persona names may only contain letters, numbers, '-' and '_'");
    }
    Ok(name)
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum PersonaCommand {
    List,
    Show,
    Clear,
    /// Swap to persona `name`. `keep_context` (the `--keep-context` flag)
    /// swaps WITHOUT resetting the conversation, per the persistent-actor
    /// principle; the default (`false`) preserves today's reset-on-swap
    /// behavior.
    Set {
        name: String,
        keep_context: bool,
    },
}

#[cfg(test)]
impl PersonaCommand {
    /// Test-only constructor for the common `Set { keep_context: false }` case.
    fn set(name: impl Into<String>) -> Self {
        Self::Set {
            name: name.into(),
            keep_context: false,
        }
    }
}

fn parse_persona_command(input: &str) -> anyhow::Result<PersonaCommand> {
    let body = input.trim().trim_start_matches('/').trim();
    let mut parts = body.split_whitespace();
    match parts.next() {
        Some("persona") => {}
        _ => anyhow::bail!("not a persona command"),
    }

    // Pull `--keep-context` from anywhere in the remaining tokens; collect the
    // rest as positional args.
    let mut keep_context = false;
    let positional: Vec<&str> = parts
        .filter(|tok| {
            if *tok == "--keep-context" {
                keep_context = true;
                false
            } else {
                true
            }
        })
        .collect();
    let mut positional = positional.into_iter();

    match positional.next() {
        None | Some("show") => Ok(PersonaCommand::Show),
        Some("list") => Ok(PersonaCommand::List),
        Some("clear" | "off") => Ok(PersonaCommand::Clear),
        Some("default") => Ok(PersonaCommand::Set {
            name: PersonaStore::DEFAULT_NAME.into(),
            keep_context,
        }),
        // FR-PA-1 (#1021): `switch` is a discoverable alias for `set` — same
        // handling, same usage shape. `/persona <name>` (the bare fallthrough
        // below) already does this too; `switch` just names the verb
        // explicitly for an operator reaching for it by that word.
        Some(verb @ ("set" | "switch")) => match positional.next() {
            Some(name) => Ok(PersonaCommand::Set {
                name: name.to_string(),
                keep_context,
            }),
            None => anyhow::bail!("usage: /persona {verb} <name> [--keep-context]"),
        },
        Some(name) => Ok(PersonaCommand::Set {
            name: name.to_string(),
            keep_context,
        }),
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ConversationCommand {
    List,
    Show(String),
    Restore(String),
    Rename { id: String, title: String },
    Delete(String),
}

/// The conversation a `/conversation …` command would SELECT, if any.
///
/// #1669 PR-A blocker 2: `/conversation restore` is a conversation-selection
/// path, so it must consult the tab-aware adoption seam before it runs —
/// otherwise it can point a second tab at a conversation another tab holds.
/// Parsing is pure and cheap, so the caller asks first and dispatches after.
pub(crate) fn conversation_command_target(input: &str) -> Option<String> {
    match parse_conversation_command(input).ok()? {
        ConversationCommand::Restore(id) => Some(id),
        _ => None,
    }
}

/// Which verb an operator typed to reach the conversation ops.
///
/// #2009 PR6b folded them into `/resume`. The ops are identical either way —
/// the same parser, the same handler — but the VERB decides what a retired
/// mutator is allowed to do: a retired READ still reads, and a retired MUTATOR
/// redirects without mutating (the rule PR3 wrote down, applied per
/// subcommand because `/conversation` is both).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ConversationDoor {
    /// `/resume <sub>` — the replacement, which performs.
    Resume,
    /// `/conversation <sub>` — retired; reads still read.
    Retired,
}

impl ConversationCommand {
    /// Whether this op CHANGES something. A retired verb may still serve the
    /// reads and must not serve these.
    pub(crate) fn mutates(&self) -> bool {
        !matches!(self, Self::List | Self::Show(_))
    }
}

/// Parse a conversation op typed at EITHER door, reporting which one.
fn parse_conversation_command_at(
    input: &str,
) -> anyhow::Result<(ConversationDoor, ConversationCommand)> {
    let body = input.trim().trim_start_matches('/').trim();
    let mut parts = body.split_whitespace();
    let door = match parts.next() {
        Some("conversation") => ConversationDoor::Retired,
        Some("resume") => ConversationDoor::Resume,
        _ => anyhow::bail!("not a conversation command"),
    };
    parse_conversation_rest(door, parts)
}

fn parse_conversation_command(input: &str) -> anyhow::Result<ConversationCommand> {
    Ok(parse_conversation_command_at(input)?.1)
}

/// The named conversation subcommands, reached through `/resume`.
///
/// Bare `/resume` and `/resume <query>` are BROWSE and SEARCH and belong to
/// the resume arm; only these five words route to the conversation ops. The
/// list is data so the predicate, the parser and the help cannot disagree
/// about what `/resume` accepts.
const CONVERSATION_SUBCOMMANDS: &[&str] = &["list", "show", "restore", "rename", "delete", "rm"];

/// Whether `body` is `/resume <one of the conversation subcommands>`.
pub(crate) fn resume_conversation_subcommand(body: &str) -> bool {
    let Some(rest) = body.strip_prefix("resume") else {
        return false;
    };
    // `/resumex list` is not `/resume list`; bare `/resume` is browse. Same
    // whole-word shape as every other parser in this fold, deliberately.
    let rest = match rest.chars().next() {
        None => return false,
        Some(c) if c.is_whitespace() => rest.trim_start(),
        Some(_) => return false,
    };
    // `/resume restored` is a SEARCH, not `restore` with a suffix — the word
    // has to match whole, which `split_whitespace` gives for free.
    rest.split_whitespace()
        .next()
        .is_some_and(|word| CONVERSATION_SUBCOMMANDS.contains(&word))
}

/// What the session loop should DO with a conversation op.
///
/// Split out of the arm so the retirement rule is one decision in one place
/// with its own tests, rather than a shape of nested `if`s inside a 200-line
/// match in `run_chat`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ConversationOpPlan {
    /// Perform it.
    Run,
    /// Ask first, then perform. Carries the question and the id it names.
    Confirm { prompt: String, id: String },
    /// A retired MUTATOR: print this and change nothing.
    Redirect(String),
}

/// Decide how a conversation-op line should be handled (#2009 PR6b).
///
/// Two rules meet here:
///
/// - **A retired mutator must not mutate.** `/conversation restore|rename|
///   delete` redirect and do nothing, the way `/thinking` does, so the shim
///   gets to die instead of half-working forever.
/// - **A retired read may still read.** `/conversation list|show` keep
///   printing, because §3.3 requires reads to work on a pipe and scripts read
///   them today.
/// - **Every destructive op asks first**, at EITHER door — the operator's
///   standing rule for this sweep. `/resume delete` is not exempt for being
///   the new spelling.
pub(crate) fn conversation_op_plan(input: &str) -> anyhow::Result<ConversationOpPlan> {
    let (door, command) = parse_conversation_command_at(input)?;
    if door == ConversationDoor::Retired && command.mutates() {
        let replacement = match &command {
            ConversationCommand::Restore(id) => format!("/resume restore {id}"),
            ConversationCommand::Rename { id, title } => format!("/resume rename {id} {title}"),
            ConversationCommand::Delete(id) => format!("/resume delete {id}"),
            ConversationCommand::List | ConversationCommand::Show(_) => unreachable!(
                "List and Show do not mutate; `mutates()` is the one predicate that says so"
            ),
        };
        return Ok(ConversationOpPlan::Redirect(format!(
            "/conversation is retired — use `{replacement}` (nothing changed)"
        )));
    }
    if let ConversationCommand::Delete(id) = &command {
        return Ok(ConversationOpPlan::Confirm {
            prompt: format!(
                "delete conversation `{id}` and every turn in it? this cannot be undone"
            ),
            id: id.clone(),
        });
    }
    Ok(ConversationOpPlan::Run)
}

/// Ask the delete question through the surface's own seam.
///
/// `true` ONLY for an explicit yes. A cancelled ask — a pipe, EOF, Esc — is a
/// no: §3.3 is explicit that those are outcomes and never an implied answer,
/// and for a destructive op that is the only safe reading.
pub(crate) fn confirm_conversation_delete(ask: SlashAsk<'_>, prompt: &str) -> bool {
    let definition = newt_core::interaction_form::confirm(
        prompt.to_string(),
        "this removes the conversation and its turns",
        "delete it",
        "keep it",
    );
    let interaction =
        newt_core::interaction_surface::SurfaceInteraction::blocking(definition.clone());
    match ask(&interaction) {
        newt_core::HumanQuestionOutcome::Answer(answer) => {
            newt_core::interaction_form::resolve(&definition, answer.trim())
                .is_some_and(|id| id.as_str() == newt_core::interaction_form::YES)
        }
        _ => false,
    }
}

/// The subcommand half, shared by both doors so they cannot diverge on what
/// `rename <id> <title>` means.
fn parse_conversation_rest<'a>(
    door: ConversationDoor,
    mut parts: impl Iterator<Item = &'a str>,
) -> anyhow::Result<(ConversationDoor, ConversationCommand)> {
    let verb = match door {
        ConversationDoor::Resume => "resume",
        ConversationDoor::Retired => "conversation",
    };
    let command = match parts.next() {
        // Bare `/resume` is BROWSE, not a list — the caller handles it before
        // reaching here. Bare `/conversation` is its list, as it always was.
        None | Some("list") => ConversationCommand::List,
        Some("show") => match parts.next() {
            Some(id) => ConversationCommand::Show(id.to_string()),
            None => anyhow::bail!("usage: /{verb} show <id>"),
        },
        Some("restore") => match parts.next() {
            Some(id) => ConversationCommand::Restore(id.to_string()),
            None => anyhow::bail!("usage: /{verb} restore <id>"),
        },
        Some("rename") => {
            let Some(id) = parts.next() else {
                anyhow::bail!("usage: /{verb} rename <id> <title>");
            };
            let title = parts.collect::<Vec<_>>().join(" ");
            if title.trim().is_empty() {
                anyhow::bail!("usage: /{verb} rename <id> <title>");
            }
            ConversationCommand::Rename {
                id: id.to_string(),
                title,
            }
        }
        Some("delete" | "rm") => match parts.next() {
            Some(id) => ConversationCommand::Delete(id.to_string()),
            None => anyhow::bail!("usage: /{verb} delete <id>"),
        },
        Some(other) => anyhow::bail!("unknown conversation command `{other}`"),
    };
    Ok((door, command))
}

/// Build the progressive-disclosure skills index block for the system prompt
/// from the skills found across `skills_dirs` (names + descriptions only, never
/// bodies), or `None` when no skills are installed. Uses the same ordered,
/// first-directory-wins union as discovery. Split out from
/// [`build_system_prompt_with_soul`] so the injection can be unit-tested against
/// controlled directories without mutating the process-wide `$HOME`.
fn skills_index_for_prompt(skills_dirs: &[std::path::PathBuf]) -> Option<String> {
    newt_skills::index_block(&newt_skills::discover_paths(skills_dirs))
}

fn build_system_prompt_with_soul(workspace: &str, soul: Option<&str>, plan_path: &str) -> String {
    build_system_prompt_with_persona(workspace, soul, None, plan_path)
}

/// FR-5 (#999): the minimal persona that carries ONLY an altitude, used when
/// `--altitude` is passed without a `--persona`. No role overlay — just the
/// altitude that selects the base identity — so `--altitude coach` installs
/// COACH_SOUL and nothing else, and `/persona show` names the active altitude.
fn synthetic_altitude_persona(altitude: newt_core::Altitude) -> Persona {
    let name = match altitude {
        newt_core::Altitude::Coach => "coach",
        newt_core::Altitude::Doer => "doer",
    };
    Persona {
        name: name.to_string(),
        prompt: String::new(),
        path: std::path::PathBuf::new(),
        profile: newt_core::RoleProfile {
            altitude: Some(altitude),
            ..Default::default()
        },
    }
}

/// `[tui] narration_intent_line`: the sentence appended when the knob is on.
/// It asks for prose PLUS the call in one reply — prose alone is what the
/// narrate-then-stop rescue nudges — and avoids mechanism words a weak model
/// would echo back.
const NARRATION_INTENT_LINE: &str = "**Say what you are doing.** Before each tool call, state in \
     one short sentence what you are about to do and why; then make the call in the same reply.";

pub(crate) fn narration_intent_line(enabled: bool) -> Option<&'static str> {
    enabled.then_some(NARRATION_INTENT_LINE)
}

fn build_system_prompt_with_persona(
    workspace: &str,
    soul: Option<&str>,
    persona: Option<&Persona>,
    plan_path: &str,
) -> String {
    // FR-5 (#999): the active persona's ALTITUDE selects the base identity. A
    // `Coach` altitude REPLACES the identity with COACH_SOUL (and overrides a
    // doer-flavored soul.md), so a coaching persona's overlay no longer sits on
    // top of a contradictory doer soul. Doer (the default, and every persona
    // that doesn't declare an altitude) keeps today's behavior: the resolved
    // soul.md, else DEFAULT_SOUL. The `--altitude` flag rides here too — it
    // seeds/overrides `active_persona`'s altitude at startup (see `run_code`),
    // so it needs no separate plumbing through the session-management helpers.
    let effective_altitude = persona.and_then(|p| p.profile.altitude).unwrap_or_default();
    let identity = match effective_altitude {
        newt_core::Altitude::Coach => newt_core::COACH_SOUL,
        newt_core::Altitude::Doer => soul.unwrap_or(newt_core::DEFAULT_SOUL),
    };
    let mut ctx = format!(
        "{identity}\n\nWorkspace: {workspace}\n\
         This is the current runtime root. Relative tool paths resolve here; \
         run_command starts here unless its cwd or command selects another directory. \
         Other requested paths remain governed by the session's permissions. \
         Historical notes do not redefine this root.\n"
    );
    if let Some(persona) = persona {
        ctx.push_str(&format!(
            "\nActive persona: {}\n{}\n",
            persona.name, persona.prompt
        ));
        ctx.push_str(
            "\nPersona guidance does not override the operator's explicit task. \
             Treat advice-only wording and preferred tools as defaults; use the tools \
             needed for the requested work. OCAP permissions, explicit postures, and \
             delegation limits still govern every action.\n",
        );
    }

    // Resolved once and shared with the skills index below; the ratchet in
    // newt-core/tests/resolve_publishes_ratchet.rs pins the publishing resolve
    // count per file.
    let cfg = crate::migration_notices::read(|report| newt_core::Config::resolve(report));

    // Per-session plan instruction (issue #220). Injected here, with the
    // resolved per-session path, rather than baked into DEFAULT_SOUL — so the
    // path is dynamic AND custom soul.md users still get the guidance. The path
    // is unique to this conversation, so concurrent newt instances in the same
    // repo never clobber each other's plan.
    ctx.push_str(&format!(
        "\n**Plan before coding.** For any task requiring more than one file \
         change, write a plan to `{plan_path}` first (create it if it does not \
         exist). List the concrete steps and check them off as you complete \
         each one. This plan file is unique to this session — read it when \
         resuming so you can pick up exactly where you left off without \
         re-reading the whole codebase.\n"
    ));

    ctx.push_str(newt_core::agentic::REFACTOR_PUBLISH_GUIDANCE);
    ctx.push('\n');

    // `[tui] narration_intent_line` (opt-in): appended here like the plan
    // sentence, so every identity gets it and no soul text carries it.
    let intent = cfg
        .as_ref()
        .ok()
        .and_then(|c| c.tui.as_ref())
        .is_some_and(|t| t.narration_intent_line);
    if let Some(line) = narration_intent_line(intent) {
        ctx.push_str(&format!("\n{line}\n"));
    }

    // Progressive disclosure: inject ONLY the skills index (one
    // `name: description (when to use: …)` line per installed skill) — never
    // the bodies. Bodies load on demand when the model calls the `use_skill`
    // tool. Skills come from the one resolver `use_skill` also reads (#2331):
    // `[skills].search` (default `~/.newt/skills`), then the bundled dir; a
    // missing dir contributes nothing.
    let skills_dirs = cfg.map(|c| c.skill_search_dirs()).unwrap_or_default();
    if let Some(index) = skills_index_for_prompt(&skills_dirs) {
        ctx.push('\n');
        ctx.push_str(&index);
    }

    // Directory listing (top-level, no hidden files)
    if let Ok(mut entries) = std::fs::read_dir(workspace) {
        let mut names: Vec<String> = entries
            .by_ref()
            .flatten()
            .filter_map(|e| {
                let name = e.file_name().to_string_lossy().into_owned();
                if name.starts_with('.') {
                    None
                } else {
                    Some(name)
                }
            })
            .collect();
        names.sort();
        ctx.push_str("\nFiles:\n");
        for name in names.iter().take(40) {
            ctx.push_str(&format!("  {name}\n"));
        }
    }

    // README (truncated)
    for readme in ["README.md", "readme.md", "README.txt"] {
        let path = std::path::Path::new(workspace).join(readme);
        if let Ok(text) = std::fs::read_to_string(&path) {
            let excerpt: String = text.chars().take(3000).collect();
            ctx.push_str(&format!("\n{readme}:\n{excerpt}\n"));
            if text.len() > 3000 {
                ctx.push_str("...[truncated]\n");
            }
            break;
        }
    }

    ctx
}

// ---------------------------------------------------------------------------
// Tool-use loop — the real agentic core
// ---------------------------------------------------------------------------

fn rebuild_system_prompt(
    workspace: &str,
    memory: &newt_core::MemoryManager,
    persona: Option<&Persona>,
    conversation_id: &str,
) -> String {
    let soul_additions = memory.build_system_prompt_additions();
    let soul_text = if soul_additions.is_empty() {
        None
    } else {
        Some(soul_additions.as_str())
    };
    // Per-session plan path, keyed on the durable conversation id (issue #220).
    let plan_path = newt_core::session_plan_path(conversation_id);
    build_system_prompt_with_persona(workspace, soul_text, persona, &plan_path.to_string_lossy())
}

fn handle_operating_mode_command(
    arg: &str,
    active_mode: &mut OperatingMode,
    mode_states: &ConversationModeStates,
    color: bool,
    verbose: bool,
) {
    match operating_mode_command_lines(arg, active_mode) {
        Ok(mut lines) => {
            let normalized = arg.trim().to_ascii_lowercase();
            if !matches!(normalized.as_str(), "" | "list" | "show" | "status") {
                // An explicit human selection supersedes any stale
                // model-entered plan phase. `/mode plan` has its own
                // read-only enforcement and does not need the legacy flag.
                mode_states.plan.clear();
                // A successful explicit human selection also supersedes any
                // model-selected Auto style. Listing, status, and invalid
                // commands leave both pieces of state untouched.
                mode_states.auto.clear();
            }
            // #2009 PR4b: one writer for the value. `/mode` and
            // `/settings mode` both land in `set_session_operating_mode`, so
            // the verb and the field cannot select different styles.
            newt_core::operating_mode::set_session_operating_mode(*active_mode);
            if let Some(first) = lines.first() {
                print_newt(first, color, verbose);
            }
            for line in lines.drain(1..) {
                println!("{line}");
            }
        }
        Err(error) => print_newt(&error, color, verbose),
    }
}

fn posture_status_lines(
    cfg: &newt_core::Config,
    active_posture: Option<&ActivePosture>,
    include_available: bool,
) -> Vec<String> {
    let active = match active_posture {
        Some(posture) if posture.permission_clamp().is_none() => {
            format!(
                "active permission posture: {} (no permission clamp)",
                posture.name
            )
        }
        Some(posture) => format!(
            "active permission posture: {} — preset '{}' floor: {}",
            posture.name, posture.preset_name, posture.clamp_summary
        ),
        None => "no active permission posture".to_string(),
    };
    let mut lines = vec![active];
    if include_available {
        let names: Vec<&str> = cfg.modes.keys().map(String::as_str).collect();
        lines.push(if names.is_empty() {
            "available permission postures: (none configured — define [modes.<name>] in your newt config)"
                .to_string()
        } else {
            format!("available permission postures: {}", names.join(", "))
        });
    }
    lines
}

/// #307: handle `/posture <name>`. Atomically preloads any named skill body,
/// applies an optional named permission preset as an authority floor, and
/// carries framing into the live per-turn prompt. Installs the shared binding only
/// after every configured component resolves successfully.
fn handle_posture_command(arg: &str, cfg: &newt_core::Config, color: bool, verbose: bool) {
    // Bare `/posture` and `/posture list` are discovery surfaces. `show` and
    // `status` keep the concise active-only form.
    if matches!(arg, "" | "list" | "show" | "status") {
        let include_available = matches!(arg, "" | "list");
        let mut lines = posture_status_lines(
            cfg,
            newt_core::posture::active_posture().as_ref(),
            include_available,
        )
        .into_iter();
        if let Some(first) = lines.next() {
            print_newt(&first, color, verbose);
        }
        for line in lines {
            println!("{line}");
        }
        return;
    }

    // Drop the clamp and its prompt guidance for the rest of the session.
    if matches!(arg, "off" | "clear" | "reset") {
        let was_active = newt_core::posture::active_posture().is_some();
        newt_core::posture::set_active_posture(None);
        if was_active {
            print_newt(
                "permission posture cleared — authority returns to the session base",
                color,
                verbose,
            );
        } else {
            print_newt("no active permission posture to clear", color, verbose);
        }
        return;
    }

    // Resolve + validate WITHOUT mutating. The skill loader reuses the SAME
    // `use_skill` path (`load_body_from` over the configured search dirs) —
    // skill dirs are config-rooted, exactly as the `use_skill` tool resolves.
    let skills_dirs = cfg.skill_search_dirs();
    let posture = build_posture(arg, cfg, |skill_name| {
        newt_skills::load_body_from(&skills_dirs, skill_name)
    });
    let posture = match posture {
        Ok(posture) => posture,
        Err(e) => {
            print_newt(&format!("error: {e}"), color, verbose);
            return;
        }
    };

    if let Some(body) = &posture.skill_body {
        print_newt(
            &format!("loaded skill for permission posture '{arg}':\n{body}"),
            color,
            verbose,
        );
    }
    let report = if posture.permission_clamp().is_none() {
        format!(
            "permission posture '{}' active (no permission clamp)",
            posture.name
        )
    } else {
        format!(
            "permission posture '{}' active — preset '{}' clamps authority (floor): {}",
            posture.name, posture.preset_name, posture.clamp_summary
        )
    };
    newt_core::posture::set_active_posture(Some(posture));
    print_newt(&report, color, verbose);
}

fn persona_status(active: Option<&Persona>) -> String {
    let Some(persona) = active else {
        return "No active persona.".to_string();
    };
    let mut out = format!(
        "Active persona: {} - {} ({})",
        persona.name,
        persona.description(),
        persona.path.display()
    );
    let profile = &persona.profile;
    if let Some(role) = &profile.role {
        out.push_str(&format!("\n  role: {role}"));
    }
    match &profile.tools {
        Some(tools) if !tools.is_empty() => {
            out.push_str(&format!("\n  preferred tools: {}", tools.join(", ")));
        }
        Some(_) => out.push_str("\n  preferred tools: (none)"),
        None => out.push_str("\n  preferred tools: (no preference)"),
    }
    // FR-4 (#1041): list the persona's bound skill names, same shape as `tools`.
    if let Some(skills) = &profile.skills {
        if skills.is_empty() {
            out.push_str("\n  skills: (none)");
        } else {
            out.push_str(&format!("\n  skills: {}", skills.join(", ")));
        }
    }
    if let Some(caveats) = &profile.caveats {
        out.push_str(&format!("\n  advisory caveats: {}", caveats.summary()));
    }
    match (&profile.model, &profile.tier) {
        (Some(m), Some(t)) => out.push_str(&format!("\n  router: model={m} tier={t:?}")),
        (Some(m), None) => out.push_str(&format!("\n  router: model={m}")),
        (None, Some(t)) => out.push_str(&format!("\n  router: tier={t:?}")),
        (None, None) => {}
    }
    // The psyche dials (backend + cognition/initiative/crew), shown only when set.
    if let Some(b) = &profile.backend {
        out.push_str(&format!("\n  backend: {b}"));
    }
    if let Some(c) = profile.cognition {
        out.push_str(&format!("\n  cognition: {}", c.label()));
    }
    if let Some(i) = profile.initiative {
        // An APPLIED resolution layer (set_persona_initiative), not just
        // rendered — it agrees with /psyche's effective_initiative.
        out.push_str(&format!("\n  initiative: {}", i.label()));
    }
    if profile.crew == Some(true) {
        // P1#3: crew is a startup gate (NEWT_TEAM builds the crew runner once at
        // launch), so a declaration can't engage it live. Label it honestly so
        // this status can't claim a control is active while the engine ignores it.
        let runtime = if std::env::var("NEWT_TEAM").is_ok() {
            "on"
        } else {
            "off — a launch gate; start with `newt --obsessive` / NEWT_TEAM to engage"
        };
        out.push_str(&format!("\n  crew: declared on · runtime {runtime}"));
    }
    if !profile.is_role_bound() {
        out.push_str("\n  (prompt-only persona — no role bindings)");
    }
    out
}

fn persona_list(store: &PersonaStore) -> anyhow::Result<String> {
    store.list_message()
}

struct ConversationResetContext<'a> {
    memory: &'a mut newt_core::MemoryManager,
    system: &'a mut String,
    conversation_id: &'a mut String,
    mode_states: &'a ConversationModeStates,
}

fn reset_conversation(
    workspace: &str,
    active_persona: Option<&Persona>,
    ctx: &mut ConversationResetContext<'_>,
) {
    // Every caller of this helper crosses a conversation boundary (`/new`,
    // persona clear, or a persona swap without `--keep-context`). Legacy
    // model-entered plan state belongs to the old conversation and must not
    // survive any of those paths.
    ctx.mode_states.clear();
    ctx.memory.reset_all();
    *ctx.system = rebuild_system_prompt(workspace, ctx.memory, active_persona, ctx.conversation_id);
}

fn new_conversation_message(active_persona: Option<&Persona>) -> String {
    match active_persona {
        Some(persona) => format!(
            "Started a new conversation with persona `{}`.",
            persona.name
        ),
        None => "Started a new conversation.".to_string(),
    }
}

/// The line printed after a `/new` · `/end` · `/restart` · `/start` rotation
/// (#1030). `started` is [`new_conversation_message`]. `/new` keeps its bare
/// historical message; the finalizers (`/end`, `/restart`) note the old
/// conversation is saved and `/resume`-able; `/start` notes it stays OPEN. The
/// old "won't resume next launch" wording is retired — with fresh-on-launch
/// nothing auto-resumes, so `/resume` is how you get back either way.
///
/// `outgoing_durable` is true when a durable conversation row exists: an
/// accepted prompt receipt, a completed turn, or an explicitly titled
/// `/start`. A prompt-only failed/cancelled turn is therefore resumable. It is
/// false only when nothing was recorded or the session is ephemeral.
pub(crate) fn close_out_message(reason: &str, started: &str, outgoing_durable: bool) -> String {
    // #1165/#1170: `/end` must LEAD with the ending regardless of whether the
    // outgoing conversation was durable — the operator typed "end" and
    // expects ending language, not "Started a new conversation." A truly
    // untouched conversation had nothing to save, so drop the "/resume to
    // reopen" that it cannot honor; prompt-only durable content keeps it.
    if reason == "end" {
        return if outgoing_durable {
            "Conversation ended and saved — /resume to reopen it, /exit to leave newt. \
             (A fresh conversation is now open.)"
                .to_string()
        } else {
            "Conversation ended — /exit to leave newt. (A fresh conversation is now open.)"
                .to_string()
        };
    }
    if !outgoing_durable {
        return started.to_string();
    }
    match reason {
        "start" => {
            format!("{started} The previous conversation stays open — /resume to return to it.")
        }
        "new" => started.to_string(),
        // "restart"
        _ => format!("{started} The previous conversation is saved — /resume to reopen it."),
    }
}

/// The per-CONVERSATION live state a boundary must clear.
///
/// #1669 PR-A. Deliberately not the whole session: the semantic index, the
/// experiential ledger, and the nav warmup are **shared across tabs on
/// purpose** (ADR, "Global (shared across tabs)"), so they are task-scoped
/// concerns that `/new` handles and `/tab new` must NOT touch — clearing them
/// would let opening a tab throw away work another tab is relying on.
pub(crate) struct ConversationScopedState<'a> {
    pub scratchpad: &'a dyn newt_core::ScratchpadStore,
    pub step_ledger: &'a dyn newt_core::StepLedger,
    pub active_prompt_context: &'a mut Option<newt_core::TurnPromptContext>,
}

impl ConversationScopedState<'_> {
    /// Drop everything that belonged to the outgoing conversation.
    ///
    /// Step 26.4 (#583) scratchpad, Step 26.6b (#586) plan ledger, and the
    /// prompt receipt. One place, so `/new` and `/tab new` cannot drift: a
    /// fresh tab that inherited any of these would be a new conversation
    /// wearing the previous one's working memory.
    pub fn clear(&mut self) {
        self.scratchpad.clear();
        self.step_ledger.clear();
        *self.active_prompt_context = None;
    }
}

fn handle_new_conversation(
    workspace: &str,
    active_persona: Option<&Persona>,
    ctx: &mut ConversationResetContext<'_>,
    compress_state: &mut newt_core::CompressState,
    session_opted_fresh: &mut bool,
    scoped: &mut ConversationScopedState<'_>,
) -> String {
    // A new conversation gets a fresh id, which rotates the per-session plan
    // path to a new `.scratch/sessions/<id>/` dir (issue #220).
    *ctx.conversation_id = newt_core::new_conversation_id();
    // Re-arm compression anti-thrash (F4): the disable notice promises
    // "start a new conversation to reset" — this is what makes that true.
    compress_state.reset();
    // 17.7: an explicit /new opts this session out of auto-resume for good
    // (`should_auto_resume` consults the flag) — resume never undoes /new.
    *session_opted_fresh = true;
    reset_conversation(workspace, active_persona, ctx);
    scoped.clear();
    new_conversation_message(active_persona)
}

// ---------------------------------------------------------------------------
// Session-start conversation resolution (Step 17.7, issue #246)
// ---------------------------------------------------------------------------

/// What `/conversation` and `/recall` answer in an ephemeral session, and the
/// one-time startup notice — same wording so the mode is unmistakable.
const EPHEMERAL_SESSION_NOTICE: &str =
    "ephemeral session — conversation persistence is off (nothing saved, nothing resumed)";

/// How this session treats conversation persistence. Resolved ONCE at
/// session start by [`resolve_session_start`]; precedence:
/// `--ephemeral`/`NEWT_EPHEMERAL` > `NEWT_CONVERSATION_ID` >
/// `[conversations] resume` (#1030: default FALSE = fresh-on-launch;
/// `resume = true` opts back into auto-resuming the folder's latest).
#[derive(Debug, Clone, PartialEq, Eq)]
enum SessionStart {
    /// No persistence at all: no store handle is constructed, so no
    /// conversation row can be created, no turn appended, and no past
    /// conversation read.
    Ephemeral,
    /// Resume exactly this conversation id (`NEWT_CONVERSATION_ID`). The id
    /// must exist in THIS workspace — the 17.1b workspace fence applies.
    ResumeExact(String),
    /// #1671: resume by NAME (`newt --resume <name>` / `NEWT_RESUME`) — a
    /// title (or id/prefix) resolved against this workspace's conversations
    /// once the store is open. Like `ResumeExact`, errors are hard: a name
    /// that matches nothing (or several) must not silently start fresh.
    ResumeNamed(String),
    /// Auto-resume the workspace's most recently active conversation —
    /// highest §6 activity tick, never a timestamp comparison.
    ResumeLatest,
    /// Persist turns as usual, but start a fresh conversation
    /// (`[conversations] resume = false`).
    Fresh,
}

/// Pure precedence chain (17.7): ephemeral wins outright, then an explicit
/// conversation id, then a name (#1671), then the config default. A blank
/// `NEWT_CONVERSATION_ID` / `NEWT_RESUME` reads as unset rather than as a
/// target that can never exist.
fn resolve_session_start(
    ephemeral: bool,
    forced_id: Option<String>,
    resume_name: Option<String>,
    resume_config: bool,
) -> SessionStart {
    if ephemeral {
        return SessionStart::Ephemeral;
    }
    if let Some(id) = forced_id {
        let id = id.trim().to_string();
        if !id.is_empty() {
            return SessionStart::ResumeExact(id);
        }
    }
    if let Some(name) = resume_name {
        let name = name.trim().to_string();
        if !name.is_empty() {
            return SessionStart::ResumeNamed(name);
        }
    }
    if resume_config {
        SessionStart::ResumeLatest
    } else {
        SessionStart::Fresh
    }
}

/// Structured title-match result — the ONE pure core behind both
/// `resolve_conversation_by_name` (startup `--resume <name>`) and the
/// consolidated `resolve_resume_target` (in-chat `/resume <thing>`), so the
/// title-matching rules can never drift between the two front doors.
///
/// Titles are matched case-insensitively: a unique EXACT match wins; otherwise
/// a unique substring match; several matches are `Ambiguous`; none is `None`.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TitleMatch<'a> {
    One(&'a newt_core::ConversationSummary),
    Ambiguous(Vec<&'a newt_core::ConversationSummary>),
    None,
}

fn title_match<'a>(
    summaries: &'a [newt_core::ConversationSummary],
    needle: &str,
) -> TitleMatch<'a> {
    let needle = needle.trim().to_lowercase();
    let title_of = |s: &newt_core::ConversationSummary| s.title.trim().to_lowercase();
    let exact: Vec<&newt_core::ConversationSummary> =
        summaries.iter().filter(|s| title_of(s) == needle).collect();
    let hits = if exact.is_empty() {
        summaries
            .iter()
            .filter(|s| title_of(s).contains(needle.as_str()))
            .collect::<Vec<_>>()
    } else {
        exact
    };
    match hits.as_slice() {
        [one] => TitleMatch::One(one),
        [] => TitleMatch::None,
        many => TitleMatch::Ambiguous(many.to_vec()),
    }
}

/// The structured title-resolution error — the two failure modes of
/// `resolve_conversation_by_name`, carried as data so the consolidated
/// `resolve_resume_target` can branch on them (FTS fallback vs. candidate
/// listing) instead of parsing a string. `Display` reproduces the exact
/// human-facing messages the slash-command path always printed, so existing
/// `unwrap_err().contains(...)` regression coverage carries over unchanged.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TitleResolveError {
    /// No title matched the query.
    NotFound { query: String },
    /// Several titles matched — name the candidates so the human can pick.
    Ambiguous {
        query: String,
        candidates: Vec<(String, String)>,
    },
}

impl std::fmt::Display for TitleResolveError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotFound { query } => write!(
                f,
                "no conversation titled \"{query}\" in this workspace — run newt and /resume to browse"
            ),
            Self::Ambiguous { query, candidates } => write!(
                f,
                "\"{query}\" matches {} conversations — use an id: {}",
                candidates.len(),
                candidates
                    .iter()
                    .map(|(id, title)| format!("{} \"{title}\"", short_conversation_id(id)))
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    }
}

impl std::error::Error for TitleResolveError {}

/// #1671: resolve `--resume <name>` against this workspace's conversations by
/// TITLE — pure, so the matching rules are unit-testable without a store. A
/// unique exact (case-insensitive) title wins, then a unique substring;
/// ambiguity and misses are hard errors that NAME the candidates (an ambiguous
/// or missing name must never silently open the wrong conversation). Ids are
/// not this function's job — the consolidated `resolve_resume_target` tries
/// id/prefix first, then delegates the title step here.
fn resolve_conversation_by_name(
    summaries: &[newt_core::ConversationSummary],
    name: &str,
) -> Result<String, TitleResolveError> {
    match title_match(summaries, name) {
        TitleMatch::One(one) => Ok(one.id.clone()),
        TitleMatch::None => Err(TitleResolveError::NotFound {
            query: name.trim().to_string(),
        }),
        TitleMatch::Ambiguous(many) => Err(TitleResolveError::Ambiguous {
            query: name.trim().to_string(),
            candidates: many
                .iter()
                .map(|s| (s.id.clone(), s.title.clone()))
                .collect(),
        }),
    }
}

/// The consolidated resume resolver (#1030/#1671): ONE precedence chain
/// shared by startup `--resume <name>` and in-chat `/resume <thing>`, so the
/// two front doors never drift into different matching rules. Pure — it
/// matches against the workspace's conversation summaries, no store needed.
///
/// Precedence:
///   1. exact conversation id
///   2. unique id prefix (byte-case-exact, like `ConversationStore::resolve_id`)
///   3. exact (case-insensitive) title
///   4. unique (case-insensitive) title substring
///   5. ambiguous title match → `Ambiguous` (the caller renders a numbered
///      listing so a follow-up `/resume <n>` selects one)
///   6. nothing matched → `NotFound` (the caller falls back to FTS search)
///
/// Full-text search is deliberately NOT here: it is the listing fallback the
/// in-chat caller renders (and a `/resume <n>` then selects from). Startup
/// `--resume <name>` has no listing to show, so it hard-errors on
/// `Ambiguous`/`NotFound` instead. Keeping FTS out leaves this pure and
/// unit-testable without a store.
#[derive(Debug, Clone, PartialEq, Eq)]
enum ResumeNameResolve {
    /// A single conversation resolved — open it.
    Resolved(String),
    /// Several title matches — present them for numbered selection.
    Ambiguous(Vec<(String, String)>),
    /// Nothing matched by id or title — the caller may fall back to FTS.
    NotFound,
}

fn resolve_resume_target(
    summaries: &[newt_core::ConversationSummary],
    token: &str,
) -> ResumeNameResolve {
    let token = token.trim();
    // 1. exact conversation id.
    if let Some(found) = summaries.iter().find(|s| s.id == token) {
        return ResumeNameResolve::Resolved(found.id.clone());
    }
    // 2. unique id prefix (byte-case-exact; ids are validated ASCII so byte
    //    and char positions coincide, matching `ConversationStore::resolve_id`).
    let prefix: Vec<&newt_core::ConversationSummary> = summaries
        .iter()
        .filter(|s| s.id.starts_with(token))
        .collect();
    if let [one] = prefix.as_slice() {
        return ResumeNameResolve::Resolved(one.id.clone());
    }
    // 3-5. exact title / unique substring / ambiguous — DELEGATED to the
    //      title-only resolver so the matching rules live in ONE place and
    //      the two front doors (startup `--resume <name>` and in-chat
    //      `/resume <thing>`) can never drift.
    match resolve_conversation_by_name(summaries, token) {
        Ok(id) => ResumeNameResolve::Resolved(id),
        Err(TitleResolveError::Ambiguous { candidates, .. }) => {
            ResumeNameResolve::Ambiguous(candidates)
        }
        Err(TitleResolveError::NotFound { .. }) => ResumeNameResolve::NotFound,
    }
}

/// The single gate every auto-resume consult goes through: config-driven
/// resume happens only when the session has NOT explicitly opted fresh via
/// `/new` — auto-resume never undoes an explicit /new (17.7).
fn should_auto_resume(start: &SessionStart, session_opted_fresh: bool) -> bool {
    matches!(start, SessionStart::ResumeLatest) && !session_opted_fresh
}

fn conversation_root_dir() -> std::path::PathBuf {
    newt_core::Config::user_config_path()
        .and_then(|p| p.parent().map(std::path::Path::to_path_buf))
        .unwrap_or_else(|| std::path::PathBuf::from(".newt"))
}

fn conversation_store_for(
    workspace: &str,
    cfg: &newt_core::Config,
) -> anyhow::Result<newt_core::ConversationStore> {
    let max_per_workspace = cfg
        .conversations
        .clone()
        .unwrap_or_default()
        .max_per_workspace;
    newt_core::ConversationStore::new(conversation_root_dir(), workspace, max_per_workspace)
}

fn conversation_title_from_task(task: &str) -> String {
    let title: String = task
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .unwrap_or("Untitled conversation")
        .chars()
        .take(80)
        .collect();
    if title.trim().is_empty() {
        "Untitled conversation".to_string()
    } else {
        title
    }
}

/// What the per-turn persistence seam knows after attempting a save.
///
/// A reply row is appended before scratchpad/plan/claim bookkeeping. Those
/// later updates are useful but must not erase the fact that the transcript is
/// already durable; callers use this distinction to append digest-only
/// provenance honestly.
#[derive(Debug)]
enum TurnSaveState {
    /// The reply and all ancillary session state were saved durably.
    Durable,
    /// The reply is durable, but a later ancillary update failed.
    DurableWithAncillaryWarning(anyhow::Error),
    /// `--ephemeral`: no SQLite row exists, but session-local state is live.
    Ephemeral,
}

#[allow(clippy::too_many_arguments)]
fn save_successful_conversation_turn(
    store: &newt_core::ConversationStore,
    conversation_id: &str,
    active_persona: Option<&Persona>,
    task: &str,
    reply: &str,
    events: &[newt_core::ToolEvent],
    phantom_reaches: &[newt_core::PhantomReach],
    usage: Option<newt_core::TokenUsage>,
    compaction: Option<String>,
    scratchpad: &std::collections::BTreeMap<String, String>,
    plan: &newt_core::PlanSnapshot,
) -> anyhow::Result<TurnSaveState> {
    save_successful_conversation_turn_with_ancillary(
        store,
        conversation_id,
        active_persona,
        task,
        reply,
        events,
        phantom_reaches,
        usage,
        compaction,
        scratchpad,
        plan,
        |store, conversation_id, scratchpad, plan| {
            // #713: snapshot the live scratchpad <state> onto the conversation
            // row so a later interrupt + auto-resume can re-hydrate it.
            store
                .update_scratchpad(conversation_id, scratchpad)
                .context("reply persisted but scratchpad snapshot could not be updated")?;
            // #715: snapshot the live plan ledger onto the conversation row,
            // alongside the scratchpad and under the same discipline.
            store
                .update_plan_snapshot(conversation_id, plan)
                .context("reply persisted but plan snapshot could not be updated")?;
            // #1030: refresh this process's live-owner heartbeat every turn.
            store
                .heartbeat(conversation_id)
                .context("reply persisted but conversation heartbeat could not be refreshed")
        },
    )
}

#[allow(clippy::too_many_arguments)]
fn save_successful_conversation_turn_with_ancillary<F>(
    store: &newt_core::ConversationStore,
    conversation_id: &str,
    active_persona: Option<&Persona>,
    task: &str,
    reply: &str,
    events: &[newt_core::ToolEvent],
    phantom_reaches: &[newt_core::PhantomReach],
    usage: Option<newt_core::TokenUsage>,
    compaction: Option<String>,
    scratchpad: &std::collections::BTreeMap<String, String>,
    plan: &newt_core::PlanSnapshot,
    ancillary: F,
) -> anyhow::Result<TurnSaveState>
where
    F: FnOnce(
        &newt_core::ConversationStore,
        &str,
        &std::collections::BTreeMap<String, String>,
        &newt_core::PlanSnapshot,
    ) -> anyhow::Result<()>,
{
    // The id is pre-assigned for the whole session (issue #220), so the first
    // turn creates the record with that id; later turns just append.
    // `exists()?` — an error must NOT read as "absent": routing a transient
    // failure into create_with_id would overwrite a live conversation.
    if !store.exists(conversation_id)? {
        store.create_with_id(
            conversation_id,
            &conversation_title_from_task(task),
            active_persona.map(|p| p.name.as_str()),
        )?;
    }
    // 18.5 (#247): a compaction summary minted while syncing THIS turn is
    // persisted as its own turn record (user = the marked message, assistant
    // empty, token columns NULL — it is not a backend-measured turn), and it
    // goes in BEFORE the triggering turn: the live boundary's last-user
    // anchor guarantees the triggering turn survived compression, so restore
    // rebuilds `[summary] + [turns from the trigger on]` — the same working
    // set the live session kept.
    if let Some(summary) = compaction {
        // #1786 Phase C: the summary is a DERIVED row and cites the turns it
        // replaced. The producer lives in newt-core beside `restore_turns`,
        // whose cut defines the working set being replaced — the two must
        // agree, so they are not written twice.
        newt_core::persist_compaction_summary(store, conversation_id, &summary)?;
    }
    // 17.6: persist the turn's tool events and the backend-reported token
    // actuals. `usage` is what `chat_complete` returned — input = largest
    // single prompt of the turn, output = sum across rounds (Step 18.1
    // semantics); `None` (backend reported nothing) is stored as NULL.
    // #717: phantom reaches persist alongside the events column.
    // The displayed harness report belongs to the outcome artifact, not the
    // assistant's authored turn. Keep new rows clean; replay also handles old rows.
    let model_reply = newt_core::agentic::model_reply_for_history(reply);
    store.append_turn_full(
        conversation_id,
        task,
        &model_reply,
        events,
        phantom_reaches,
        // A model turn is witnessed, never derived: empty sources always.
        &[],
        usage.map(|u| u.input_tokens),
        usage.map(|u| u.output_tokens),
    )?;
    match ancillary(store, conversation_id, scratchpad, plan) {
        Ok(()) => Ok(TurnSaveState::Durable),
        Err(error) => Ok(TurnSaveState::DurableWithAncillaryWarning(error)),
    }
}

/// The run loop's per-turn save seam (17.7): persistent sessions route to
/// [`save_successful_conversation_turn`]; an ephemeral session has no store
/// (`None`) and this makes no SQLite write. Its caller still receives
/// [`TurnSaveState::Ephemeral`] so it can maintain the process-local prompt
/// artifact ledger, including a compaction checkpoint when appropriate.
#[allow(clippy::too_many_arguments)] // mirrors save_successful_conversation_turn
fn save_turn_if_persistent(
    store: Option<&newt_core::ConversationStore>,
    conversation_id: &str,
    active_persona: Option<&Persona>,
    task: &str,
    reply: &str,
    events: &[newt_core::ToolEvent],
    phantom_reaches: &[newt_core::PhantomReach],
    usage: Option<newt_core::TokenUsage>,
    compaction: Option<String>,
    scratchpad: &std::collections::BTreeMap<String, String>,
    plan: &newt_core::PlanSnapshot,
) -> anyhow::Result<TurnSaveState> {
    match store {
        Some(store) => save_successful_conversation_turn(
            store,
            conversation_id,
            active_persona,
            task,
            reply,
            events,
            phantom_reaches,
            usage,
            compaction,
            scratchpad,
            plan,
        ),
        None => Ok(TurnSaveState::Ephemeral),
    }
}

fn conversation_list_message(store: &newt_core::ConversationStore) -> anyhow::Result<String> {
    let summaries = store.list()?;
    if summaries.is_empty() {
        return Ok("No saved conversations for this workspace.".to_string());
    }

    let mut out = "Saved conversations:".to_string();
    for summary in summaries {
        let persona = summary
            .persona
            .as_deref()
            .map(|p| format!(" persona={p}"))
            .unwrap_or_default();
        out.push_str(&format!(
            "\n  {}  {} ({} turns{})",
            summary.id, summary.title, summary.turn_count, persona
        ));
    }
    Ok(out)
}

fn conversation_show_message(record: &newt_core::ConversationRecord) -> String {
    let persona = record
        .persona
        .as_deref()
        .map(|p| format!("persona: {p}"))
        .unwrap_or_else(|| "persona: none".to_string());
    let mut out = format!(
        "Conversation {}: {}\n{}\nturns: {}",
        record.id,
        record.title,
        persona,
        record.turns.len()
    );
    for (idx, turn) in record.turns.iter().enumerate() {
        out.push_str(&format!(
            "\n\n{}. user:\n{}\n\nassistant:\n{}",
            idx + 1,
            turn.user,
            turn.assistant
        ));
    }
    out
}

struct ConversationCommandContext<'a> {
    store: &'a newt_core::ConversationStore,
    persona_store: &'a PersonaStore,
    workspace: &'a str,
    memory: &'a mut newt_core::MemoryManager,
    system: &'a mut String,
    active_persona: &'a mut Option<Persona>,
    active_conversation_id: &'a mut String,
    /// Session compression anti-thrash state — reset on `/conversation
    /// restore`, which is a conversation boundary like `/new` (F4).
    compress_state: &'a mut newt_core::CompressState,
    /// The live scratchpad `<state>` store (#713). Re-hydrated from
    /// `record.scratchpad` on restore so a resumed `state_get("current_task")`
    /// returns the saved value instead of "no such key".
    scratchpad: &'a dyn newt_core::ScratchpadStore,
    /// The live plan ledger (#715). Re-hydrated from `record.plan` on restore so
    /// a resumed `<plan>` block / `plan_get` returns the saved plan — with the
    /// correct active step and done statuses — instead of an empty ledger.
    step_ledger: &'a dyn newt_core::StepLedger,
    /// Latest submitted prompt metadata for the active conversation. Restore
    /// rehydrates it for addressability, but never turns it into queued input:
    /// resuming a prompt-only conversation still waits for the operator.
    active_prompt_context: &'a mut Option<newt_core::TurnPromptContext>,
    /// A model-selected Auto style is one-shot conversation state. Every
    /// successful restore is a hard boundary and clears it before adopting
    /// the restored conversation, including A→B→A switches.
    mode_states: &'a ConversationModeStates,
}

fn handle_conversation_command(
    input: &str,
    ctx: &mut ConversationCommandContext<'_>,
) -> anyhow::Result<String> {
    match parse_conversation_command(input)? {
        ConversationCommand::List => conversation_list_message(ctx.store),
        ConversationCommand::Show(id) => {
            let record = ctx.store.load(&id)?;
            Ok(conversation_show_message(&record))
        }
        ConversationCommand::Restore(id) => {
            let (record, warning) = restore_conversation_into_session(ctx, &id)?;
            // #2085 PR-E2: the three mutating conversation ops journal HERE,
            // after the store call succeeded, because this is the one place
            // both doors converge — a future door cannot reach the mutation
            // without passing the record. `record.id` is the resolved id, not
            // the prefix an operator typed.
            crate::event_receipt::conversation_op(input, "restore", &record.id);
            let mut message = format!(
                "Restored conversation `{}` ({} turns).",
                record.title,
                record.turns.len()
            );
            if let Some(warning) = warning {
                message.push_str(&format!("\nwarning: {warning}"));
            }
            Ok(message)
        }
        ConversationCommand::Rename { id, title } => {
            let resolved_id = ctx.store.resolve_id(&id)?;
            ctx.store.rename(&resolved_id, &title)?;
            crate::event_receipt::conversation_op(input, "rename", &resolved_id);
            Ok(format!("Renamed conversation `{resolved_id}`."))
        }
        ConversationCommand::Delete(id) => {
            let resolved_id = ctx.store.resolve_id(&id)?;
            if *ctx.active_conversation_id == resolved_id {
                anyhow::bail!("cannot delete the active conversation; use /new first");
            }
            ctx.store.delete(&resolved_id)?;
            crate::event_receipt::conversation_op(input, "delete", &resolved_id);
            Ok(format!("Deleted conversation `{resolved_id}`."))
        }
    }
}

/// THE restore implementation — `/conversation restore`, startup auto-resume
/// (17.7), and the `NEWT_CONVERSATION_ID` override all run through here, so
/// there is exactly one way a stored conversation becomes the live session:
/// history turns replace the session history, the saved persona is restored
/// (cleared with a warning when unavailable), compression anti-thrash
/// re-arms (a restore is a conversation boundary like `/new`, F4), and the
/// conversation's id is adopted BEFORE the system prompt rebuild so the
/// prompt names that conversation's plan file (issue #220) — resuming a
/// conversation resumes its plan.
/// Everything a restore needs, already read and validated — so applying it
/// cannot fail.
///
/// #1669 PR-A (P0): restore used to be one function whose fallible store reads
/// happened to precede its first mutation. That is a correct ORDER but not a
/// transaction: a caller could only preflight what it knew to preflight, and a
/// tab switch preflighted `exists` + `load` while restore also validated the
/// prompt receipt and its context. A conversation whose row loaded but whose
/// receipt did not would therefore fail AFTER the outgoing tab had been
/// deactivated and the active pointer moved.
///
/// Splitting it makes the transaction explicit: PREPARE performs every fallible
/// read and mutates nothing; COMMIT consumes this and performs no fallible
/// store read at all, so it cannot fail and there is no error for a caller to
/// swallow.
pub(crate) struct PreparedConversationRestore {
    record: newt_core::ConversationRecord,
    /// Validated prompt lineage, resolved during prepare.
    prompt_context: Option<newt_core::TurnPromptContext>,
    /// Resolved during prepare too — the persona store is a second fallible
    /// source, and leaving it in commit would keep a read on the apply path.
    persona: Option<Persona>,
    /// Set when the record NAMES a persona that could not be loaded. Not an
    /// error: the restore proceeds with no persona and the caller reports it.
    persona_warning: Option<String>,
}

/// Forces a post-`load` prepare failure for one conversation, on one test
/// thread. Compiled out of the shipped binary.
///
/// Exists because the P0 hazard cannot be reached by corrupting a row: it needs
/// the row to load cleanly and a SUBSEQUENT read — the prompt receipt or its
/// context — to fail. Deterministic, no sleeps, no filesystem surgery.
#[cfg(test)]
pub(crate) mod restore_prepare_seam {
    use std::cell::RefCell;

    thread_local! {
        static FAILING: RefCell<Option<String>> = const { RefCell::new(None) };
    }

    /// Make preparing `id` fail AFTER its row loads.
    pub(crate) fn fail_after_load_for(id: &str) {
        FAILING.with(|f| *f.borrow_mut() = Some(id.to_string()));
    }

    pub(crate) fn clear() {
        FAILING.with(|f| *f.borrow_mut() = None);
    }

    pub(crate) fn forced_failure(id: &str) -> Option<String> {
        FAILING.with(|f| {
            f.borrow()
                .as_deref()
                .filter(|failing| *failing == id)
                .map(|_| "prompt receipt context failed to validate (test seam)".to_string())
        })
    }
}

/// PREPARE — every fallible read for restoring `id`, mutating zero live state.
///
/// Callers that must not half-apply (a tab switch, an adoption) call this
/// BEFORE they deactivate anything. A failure here means nothing has moved.
pub(crate) fn prepare_conversation_restore(
    store: &newt_core::ConversationStore,
    persona_store: &PersonaStore,
    id: &str,
) -> anyhow::Result<PreparedConversationRestore> {
    // Integrity gate (#1785): the record that becomes the model's context is
    // verified and materialized by ONE store operation, from one SQLite read
    // snapshot — `load_verified`, never verify-then-load. Two separate calls
    // would verify one database state and hand back another: a legitimate
    // concurrent append between them reads as corruption, and a real
    // corruption between them reads as clean. Restore is the moment history
    // is about to become the model's context, which is exactly when silently
    // trusting an unverified record would do its damage; it fails the restore
    // while the session is still entirely on the outgoing conversation, the
    // same contract the prompt receipts already follow below.
    //
    // A failure REFUSES the restore and nothing else: no repair, no re-chain,
    // no deletion — the rows stay readable and the error carries the
    // per-turn or tip-witness diagnosis so the damage can be examined rather
    // than papered over.
    let record = store.load_verified(id)?;
    // Test seam modelling the exact P0 hazard: the ROW loads, and a LATER
    // validation fails. Placed after `load` on purpose — a seam before it would
    // only re-prove what a load-only preflight already caught.
    #[cfg(test)]
    if let Some(e) = restore_prepare_seam::forced_failure(id) {
        anyhow::bail!(e);
    }
    // Prompt receipts are a parallel immutable log, not presentation history.
    // Resolving them HERE is the whole point of the split: a corrupt receipt
    // must fail the restore while the session is still entirely on the
    // outgoing conversation.
    let prompt_context = match store.latest_prompt(&record.id)? {
        Some(receipt) => store.turn_prompt_context(&record.id, receipt.id())?,
        None => None,
    };
    let (persona, persona_warning) = match record.persona.as_deref() {
        Some(name) => match persona_store.load(name) {
            Ok(persona) => (Some(persona), None),
            Err(e) => (None, Some(format!("persona `{name}` unavailable: {e}"))),
        },
        None => (None, None),
    };
    Ok(PreparedConversationRestore {
        record,
        prompt_context,
        persona,
        persona_warning,
    })
}

/// What COMMIT is allowed to touch.
///
/// #1669 PR-A. Deliberately **has no `store` and no `persona_store`**. That is
/// the whole guard: the prepare/commit split is only a real transaction while
/// commit performs no fallible read, and a comment saying so decays the first
/// time someone needs "just one more lookup" on the apply path. With no handle
/// to read from, that edit does not compile.
///
/// Every field here is one `ConversationCommandContext` already owns; this is a
/// narrowing reborrow, not a second source of truth.
pub(crate) struct CommitContext<'a> {
    pub workspace: &'a str,
    pub memory: &'a mut newt_core::MemoryManager,
    pub system: &'a mut String,
    pub active_persona: &'a mut Option<Persona>,
    pub active_conversation_id: &'a mut String,
    pub compress_state: &'a mut newt_core::CompressState,
    pub scratchpad: &'a dyn newt_core::ScratchpadStore,
    pub step_ledger: &'a dyn newt_core::StepLedger,
    pub active_prompt_context: &'a mut Option<newt_core::TurnPromptContext>,
    pub mode_states: &'a ConversationModeStates,
}

impl<'a> ConversationCommandContext<'a> {
    /// Narrow to what commit may touch — dropping the two stores.
    pub(crate) fn commit_context(&mut self) -> CommitContext<'_> {
        CommitContext {
            workspace: self.workspace,
            memory: self.memory,
            system: self.system,
            active_persona: self.active_persona,
            active_conversation_id: self.active_conversation_id,
            compress_state: self.compress_state,
            scratchpad: self.scratchpad,
            step_ledger: self.step_ledger,
            active_prompt_context: self.active_prompt_context,
            mode_states: self.mode_states,
        }
    }
}

/// COMMIT — install a prepared restore. Infallible by construction.
///
/// Performs no store read: everything it needs was resolved by
/// [`prepare_conversation_restore`]. That is what lets a caller order
/// prepare → deactivate → switch → commit and know the commit cannot strand it
/// half-way.
pub(crate) fn commit_conversation_restore(
    ctx: &mut CommitContext<'_>,
    prepared: PreparedConversationRestore,
) -> (newt_core::ConversationRecord, Option<String>) {
    let PreparedConversationRestore {
        record,
        prompt_context,
        persona,
        persona_warning,
    } = prepared;
    commit_prepared(ctx, record, prompt_context, persona, persona_warning)
}

fn restore_conversation_into_session(
    ctx: &mut ConversationCommandContext<'_>,
    id: &str,
) -> anyhow::Result<(newt_core::ConversationRecord, Option<String>)> {
    // The un-split entry point every non-tab caller still uses: prepare then
    // commit, so there is exactly ONE restore implementation.
    let prepared = prepare_conversation_restore(ctx.store, ctx.persona_store, id)?;
    Ok(commit_conversation_restore(
        &mut ctx.commit_context(),
        prepared,
    ))
}

fn commit_prepared(
    ctx: &mut CommitContext<'_>,
    record: newt_core::ConversationRecord,
    restored_prompt_context: Option<newt_core::TurnPromptContext>,
    prepared_persona: Option<Persona>,
    warning: Option<String>,
) -> (newt_core::ConversationRecord, Option<String>) {
    // Restore is a conversation boundary. Clear the legacy model-entered plan
    // clamp only after the record and prompt receipt validate, so a failed
    // restore cannot partially mutate the live session.
    ctx.mode_states.clear();
    ctx.memory.restore_turns(&record.turns);
    // #713: re-hydrate the live scratchpad <state> store from the restored
    // record, right next to `restore_turns`, so an interrupt + auto-resume gives
    // the model back its structured working memory — `state_get("current_task")`
    // survives instead of returning "no such key". A restore is a conversation
    // boundary, so clear first (the live store may hold a prior conversation's
    // keys) and then replay the snapshot.
    ctx.scratchpad.clear();
    for (key, value) in &record.scratchpad {
        ctx.scratchpad.set(key, value.clone());
    }
    // #715: re-hydrate the live plan ledger from the restored record, right next
    // to the scratchpad re-hydration, so a resumed `<plan>` block / `plan_get`
    // returns the saved plan instead of an empty ledger. `restore` is a full
    // clear + replace, so it both drops any prior conversation's steps (a
    // restore is a conversation boundary) and reinstates the saved active step +
    // done statuses verbatim.
    ctx.step_ledger.restore(&record.plan);
    // Rehydrate the verified metadata so prompt handles remain resolvable,
    // while leaving the input queue untouched (no auto-execution).
    *ctx.active_prompt_context = restored_prompt_context;
    // Resolved during PREPARE — no fallible read on the apply path.
    *ctx.active_persona = prepared_persona;
    // #1668 review-2 finding 5: `active_persona` is only half of activating a
    // persona — `handle_persona_command` also re-seats the PERSONA DIAL
    // LAYERS that `effective_*` rank beneath the CLI layer. A restore that
    // swapped the struct but left those layers alone carried the OUTGOING
    // conversation's persona dials into the incoming one, so resuming a plain
    // conversation from a `meticulous` persona kept meticulous with nothing on
    // screen naming a persona to explain it.
    //
    // Derived from the persona now installed rather than from `record.persona`,
    // so the load-failure arm (persona named but unavailable) clears the layers
    // instead of leaving stale ones behind a persona that is not active.
    seat_persona_dials(ctx.active_persona.as_ref());
    ctx.compress_state.reset();
    *ctx.active_conversation_id = record.id.clone();
    *ctx.system = rebuild_system_prompt(
        ctx.workspace,
        ctx.memory,
        ctx.active_persona.as_ref(),
        ctx.active_conversation_id,
    );
    (record, warning)
}

/// Resume `id` into the session and return the 17.7 resume banner.
fn resume_session_conversation(
    ctx: &mut ConversationCommandContext<'_>,
    id: &str,
) -> anyhow::Result<String> {
    let (record, warning) = restore_conversation_into_session(ctx, id)?;
    let title = recall_display_title(ctx.store, &record.id, &record.title);
    Ok(auto_resume_banner(&record, &title, warning.as_deref()))
}

/// Auto-resume this workspace's most recently active conversation: highest
/// §6 activity tick — `list()` is tick-ascending, so its LAST entry; never
/// a timestamp comparison. `Ok(None)` when the workspace has no saved
/// conversations yet (fresh start, no banner).
fn auto_resume_latest(ctx: &mut ConversationCommandContext<'_>) -> anyhow::Result<Option<String>> {
    // `latest_open` skips conversations ended via `/end` · `/restart` · `:wq`
    // (their `end_reason` is set) so an explicitly closed-out conversation is
    // never silently re-entered — yet it stays in `list()` for `/recall`. With
    // no open conversation left, the session starts fresh (`Ok(None)`).
    let Some(latest) = ctx.store.latest_open()? else {
        return Ok(None);
    };
    resume_session_conversation(ctx, &latest.id).map(Some)
}

/// `NEWT_CONVERSATION_ID` exact resume (17.7). Exact means exact: no prefix
/// resolution, and the id must belong to THIS workspace — `exists()` is
/// workspace-fenced (17.1b), so a foreign workspace's conversation reads as
/// absent here and can neither be inspected nor resumed across the fence.
fn resume_exact_conversation(
    ctx: &mut ConversationCommandContext<'_>,
    id: &str,
) -> anyhow::Result<String> {
    if !ctx.store.exists(id)? {
        anyhow::bail!(
            "NEWT_CONVERSATION_ID: conversation `{id}` does not exist in this \
             workspace (the workspace fence applies — a conversation belonging \
             to another workspace cannot be resumed here)"
        );
    }
    resume_session_conversation(ctx, id)
}

/// The 17.7 resume banner, printed through the startup notice path. The
/// wall-clock "last active" renders as a display *claim* (`~`-prefixed,
/// the 17.4 convention) — ordering came from the activity tick, never from
/// this timestamp (§6).
fn auto_resume_banner(
    record: &newt_core::ConversationRecord,
    display_title: &str,
    warning: Option<&str>,
) -> String {
    let mut banner = format!(
        "resumed conversation {}  {}  ({} turns, last active ~{}) — /new starts fresh",
        short_conversation_id(&record.id),
        display_title,
        record.turns.len(),
        claim_timestamp(record.updated_at_unix_nanos),
    );
    // #713: tell the model its scratchpad <state> came back, so it reads its
    // task instead of blind-probing `state_get("current_task")` on a store it
    // assumes is empty. Silent when nothing was restored (the OFF/empty case).
    let restored_keys = record.scratchpad.len();
    if restored_keys > 0 {
        banner.push_str(&format!(
            " — restored {restored_keys} <state> key{}",
            if restored_keys == 1 { "" } else { "s" }
        ));
        // #718: an actionable pointer beats a bare key count. If the restored
        // scratchpad carries `current_task`, surface its value so the resumed
        // model reads "where we left off" instead of blind-probing for it.
        if let Some(task) = record.scratchpad.get("current_task") {
            let task = task.trim();
            if !task.is_empty() {
                const MAX: usize = 80;
                let shown: String = task.chars().take(MAX).collect();
                let ellipsis = if task.chars().count() > MAX {
                    "…"
                } else {
                    ""
                };
                banner.push_str(&format!(" — last task: {shown}{ellipsis}"));
            }
        }
    }
    // #715: note a restored plan so the model knows its <plan> / plan_get came
    // back across the resume. Silent when the plan is empty (the OFF/empty case).
    let restored_steps = record.plan.len();
    if restored_steps > 0 {
        banner.push_str(&format!(
            " — restored plan ({restored_steps} step{})",
            if restored_steps == 1 { "" } else { "s" }
        ));
    }
    if let Some(warning) = warning {
        banner.push_str(&format!("\nwarning: {warning}"));
    }
    banner
}

// ---------------------------------------------------------------------------
// /recall — cross-session conversation recall (Step 17.4, issue #246)
// ---------------------------------------------------------------------------

/// Both `/recall` modes show at most this many rows. Browse truncates to the
/// most recent and says so; search passes it as the FTS5 `LIMIT`.
const RECALL_LIMIT: usize = 10;

// `RecallCommand` / `parse_recall_command` / `handle_recall_command` were
// deleted in #2009 PR6. `/recall` retired into `/resume find`, and
// `parse_resume_command` reads both — a second parser kept "for the old verb"
// is how the two doors come to disagree about what `/recall foo bar` means.
// The RENDERERS below are untouched and still do the work; only the parse and
// the dispatch hop are gone.

/// Browse mode: the workspace's conversations, most recently active first.
///
/// "Recently active" is the §6 activity tick — `list()` returns ascending
/// tick, so the reversal here is the whole ordering story; the timestamp
/// shown per row is the display *claim* only (never an ordering key). Zero
/// cost by design: one `list()` query, no FTS work, and the title fallback
/// below only loads a record for the (abnormal) empty-title case.
fn recall_browse_message(store: &newt_core::ConversationStore) -> anyhow::Result<String> {
    let mut summaries = store.list()?;
    if summaries.is_empty() {
        return Ok("No saved conversations for this workspace.".to_string());
    }
    summaries.reverse(); // list() is least-recently-active first (§6 tick).
    let total = summaries.len();
    let mut out = String::from("Recent conversations (most recent first):");
    for summary in summaries.iter().take(RECALL_LIMIT) {
        out.push_str(&format!(
            "\n  {}  {}  ({} turns, last active ~{})",
            short_conversation_id(&summary.id),
            recall_display_title(store, &summary.id, &summary.title),
            summary.turn_count,
            claim_timestamp(summary.updated_at_unix_nanos),
        ));
    }
    if total > RECALL_LIMIT {
        out.push_str(&format!(
            "\n  … {} more — /conversation list shows all.",
            total - RECALL_LIMIT
        ));
    }
    out.push_str("\nRestore with /conversation restore <id>.");
    Ok(out)
}

/// Search mode: FTS5 snippets, best match first (bm25 — the store's order).
///
/// Each hit renders as a `short-id  title  ·  seq N` header with the snippet
/// indented under it. A query the sanitizer rejects ("reduced to nothing" —
/// all operators/punctuation) is a *user* outcome, not an error: it returns
/// a friendly hint instead of bubbling up through the `error:` path.
fn recall_search_message(
    store: &newt_core::ConversationStore,
    query: &str,
) -> anyhow::Result<String> {
    // Pre-flight the sanitizer so its rejection renders friendly; real
    // database errors from search() below still propagate as errors.
    if newt_core::sanitize_fts5_query(query).is_err() {
        return Ok(format!(
            "Nothing searchable in `{query}` — every term was FTS5 syntax or \
             punctuation. Try plain keywords, e.g. /recall tokio panic."
        ));
    }
    let hits = store.search(query, RECALL_LIMIT)?;
    if hits.is_empty() {
        return Ok(format!(
            "No matches for `{query}` in this workspace's conversations."
        ));
    }
    let mut out = format!("Recall matches for `{query}`:");
    for hit in &hits {
        out.push_str(&format!(
            "\n  {}  {}  ·  seq {}\n      {}",
            short_conversation_id(&hit.conversation_id),
            recall_display_title(store, &hit.conversation_id, &hit.title),
            hit.seq,
            readable_snippet(&hit.snippet),
        ));
    }
    out.push_str("\nRestore with /conversation restore <id>.");
    Ok(out)
}

// ── #1030 /resume — find and reopen a past conversation, listed by liveness ──

#[derive(Debug, Clone, PartialEq, Eq)]
enum ResumeCommand {
    /// Bare `/resume` — browse recent conversations, annotated by liveness.
    Browse,
    /// `/resume <n>` — reopen the n-th row from the last listing.
    Select(usize),
    /// `/resume <token>` — an id/prefix to reopen, else an FTS5 search query.
    Query(String),
    /// `/resume find [query]` — search (or browse) and SHOW, never reopen.
    ///
    /// This is what `/recall` was, folded in (#2009 PR6). It is not the same
    /// as `Query`: a bare token that happens to resolve as an id reopens that
    /// conversation, which is the right default for "take me back to work"
    /// and the wrong one for "what do I have about auth?". Keeping the
    /// read-only half addressable is why the fold is a subcommand rather than
    /// an alias.
    Find(String),
}

fn parse_resume_command(input: &str) -> ResumeCommand {
    let body = input.trim().trim_start_matches('/').trim();
    // **The retired verb parses as its replacement.** `/recall` and
    // `/recall <query>` ARE `/resume find`, so they are read here rather than
    // kept as a second arm that could drift from it (#2009 PR6). A retired
    // READ keeps reading — the rule PR3 wrote down — and this is where it
    // keeps reading from.
    // Whole-word, carried over from the parser this replaces: `/recallx` is
    // not `/recall x`. Enforced HERE rather than only at the dispatch guard,
    // so the parser cannot be called into a wrong answer from somewhere else.
    if let Some(rest) = body.strip_prefix("recall") {
        if rest.is_empty() || rest.starts_with(char::is_whitespace) {
            return ResumeCommand::Find(rest.trim().to_string());
        }
    }
    let rest = body.strip_prefix("resume").map(str::trim).unwrap_or("");
    if rest.is_empty() {
        return ResumeCommand::Browse;
    }
    if let Some(query) = rest.strip_prefix("find") {
        // `/resume findings` is a SEARCH for "findings", not an empty find.
        if query.is_empty() || query.starts_with(char::is_whitespace) {
            return ResumeCommand::Find(query.trim().to_string());
        }
    }
    if let Ok(n) = rest.parse::<usize>() {
        // Only a plausible ROW number (1..=RECALL_LIMIT, the most rows a listing
        // shows) is a selection. A larger all-digits token is an id PREFIX — the
        // short id shown per row is the ~19-digit unix-nanos head of the id — so
        // it must fall through to Query/resolve_id, or the displayed handle would
        // be un-typeable (#1030).
        if (1..=RECALL_LIMIT).contains(&n) {
            return ResumeCommand::Select(n);
        }
    }
    ResumeCommand::Query(rest.to_string())
}

/// The liveness marker for a conversation in a `/resume` listing (#1030):
/// `▶` this session's current conversation, `●` open in ANOTHER live newt
/// (reopening it would mix turns — `/resume` refuses), `○` resumable.
fn resume_liveness_marker(
    store: &newt_core::ConversationStore,
    id: &str,
    active_id: &str,
) -> &'static str {
    if id == active_id {
        return "▶";
    }
    match store.live_owner(id) {
        Ok(Some(owner)) if store.is_owner_live(&owner) => "●",
        _ => "○",
    }
}

const RESUME_LEGEND: &str = "\n  ▶ current · ● open in another newt · ○ resumable — \
     reopen with /resume <n> or /resume <id>.";

/// Browse: the workspace's conversations, most recent first, numbered and
/// liveness-annotated. Returns the rendered text plus the ordered ids so
/// `/resume <n>` selects by the number shown.
fn resume_browse_message(
    store: &newt_core::ConversationStore,
    active_id: &str,
) -> anyhow::Result<(String, Vec<String>)> {
    let mut summaries = store.list()?;
    if summaries.is_empty() {
        return Ok((
            "No saved conversations for this workspace.".to_string(),
            Vec::new(),
        ));
    }
    summaries.reverse(); // list() is least-recently-active first (§6 tick).
    let total = summaries.len();
    let mut out = String::from("Conversations (most recent first):");
    let mut ids = Vec::new();
    for (i, s) in summaries.iter().take(RECALL_LIMIT).enumerate() {
        out.push_str(&format!(
            "\n  {:>2}. {}  {}  {}  ({} turns, ~{})",
            i + 1,
            resume_liveness_marker(store, &s.id, active_id),
            short_conversation_id(&s.id),
            recall_display_title(store, &s.id, &s.title),
            s.turn_count,
            claim_timestamp(s.updated_at_unix_nanos),
        ));
        ids.push(s.id.clone());
    }
    if total > RECALL_LIMIT {
        out.push_str(&format!(
            "\n  … {} more — refine with /resume <query>.",
            total - RECALL_LIMIT
        ));
    }
    out.push_str(RESUME_LEGEND);
    Ok((out, ids))
}

/// Search: FTS5 over this workspace's turns, numbered + liveness-annotated,
/// with match snippets. One row per conversation (its first, best hit) so a
/// `/resume <n>` maps to a conversation. Returns the text plus the ordered ids.
fn resume_search_message(
    store: &newt_core::ConversationStore,
    query: &str,
    active_id: &str,
) -> anyhow::Result<(String, Vec<String>)> {
    if newt_core::sanitize_fts5_query(query).is_err() {
        return Ok((
            format!(
                "Nothing searchable in `{query}` — every term was FTS5 syntax or \
                 punctuation. Try plain keywords, e.g. /resume tokio panic."
            ),
            Vec::new(),
        ));
    }
    let hits = store.search(query, RECALL_LIMIT)?;
    if hits.is_empty() {
        return Ok((
            format!("No matches for `{query}` in this workspace's conversations."),
            Vec::new(),
        ));
    }
    let mut out = format!("Matches for `{query}`:");
    let mut ids: Vec<String> = Vec::new();
    for hit in &hits {
        if ids.iter().any(|existing| existing == &hit.conversation_id) {
            continue; // a conversation can match on several turns — show it once
        }
        out.push_str(&format!(
            "\n  {:>2}. {}  {}  {}\n        {}",
            ids.len() + 1,
            resume_liveness_marker(store, &hit.conversation_id, active_id),
            short_conversation_id(&hit.conversation_id),
            recall_display_title(store, &hit.conversation_id, &hit.title),
            readable_snippet(&hit.snippet),
        ));
        ids.push(hit.conversation_id.clone());
    }
    out.push_str(RESUME_LEGEND);
    Ok((out, ids))
}

/// Ambiguous title match — the "candidate selection when ambiguous" step of
/// the shared resolver (#1030/#1671): render the candidates as a numbered,
/// liveness-annotated listing so a follow-up `/resume <n>` picks one, instead
/// of a bare error. Mirrors `resume_browse_message` / `resume_search_message`.
fn resume_ambiguous_message(
    store: &newt_core::ConversationStore,
    query: &str,
    candidates: &[(String, String)],
    active_id: &str,
) -> anyhow::Result<(String, Vec<String>)> {
    let mut out = format!(
        "\"{query}\" matches {} conversations — pick one:",
        candidates.len()
    );
    let mut ids = Vec::new();
    for (i, (id, title)) in candidates.iter().enumerate() {
        out.push_str(&format!(
            "\n  {:>2}. {}  {}  {}",
            i + 1,
            resume_liveness_marker(store, id, active_id),
            short_conversation_id(id),
            recall_display_title(store, id, title),
        ));
        ids.push(id.clone());
    }
    out.push_str(RESUME_LEGEND);
    Ok((out, ids))
}

/// Make a raw FTS5 snippet readable in the TUI: collapse internal whitespace
/// (turn text is multi-line; each snippet must stay on its own row) and
/// replace the store's `>>>`/`<<<` match markers with `«`/`»`, which read as
/// highlights in plain text and survive no-color terminals. Cosmetic edge,
/// accepted: literal `>>>`/`<<<` inside the user's own content is rewritten
/// too — FTS5 marks matches with those exact strings, so they can't be told
/// apart after the fact.
fn readable_snippet(snippet: &str) -> String {
    snippet
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .replace(">>>", "«")
        .replace("<<<", "»")
}

/// First 12 characters of a conversation id (`{unix_nanos}-{uuid}`), enough
/// nanos digits for 10ms granularity — distinct for any two conversations
/// created more than 10ms apart. `resolve_id` accepts any unique prefix, so
/// the short id pastes straight into `/conversation restore`; in the rare
/// ambiguous case, restore lists the full matching ids.
fn short_conversation_id(id: &str) -> &str {
    id.get(..12).unwrap_or(id)
}

/// Render a wall-clock display claim (§6: a *claim*, never an ordering key —
/// hence the `~`-prefix at the call sites). UTC, minute precision.
fn claim_timestamp(unix_nanos: u128) -> String {
    i64::try_from(unix_nanos / 1_000_000_000)
        .ok()
        .and_then(|secs| chrono::DateTime::<chrono::Utc>::from_timestamp(secs, 0))
        .map(|dt| dt.format("%Y-%m-%d %H:%M UTC").to_string())
        .unwrap_or_else(|| "unknown".to_string())
}

/// Render-time title fallback (17.4): conversations created through the TUI
/// always get a heuristic title (`conversation_title_from_task`), but a
/// record created elsewhere can carry an empty one. Fall back to the first
/// user turn's first 60 chars (whitespace-flattened), else `(untitled)` —
/// display only, no schema or stored-title change. The extra `load()` runs
/// only for the empty-title case, so the browse path stays zero-cost.
fn recall_display_title(store: &newt_core::ConversationStore, id: &str, title: &str) -> String {
    let trimmed = title.trim();
    if !trimmed.is_empty() {
        return trimmed.to_string();
    }
    if let Ok(record) = store.load(id) {
        if let Some(turn) = record.turns.first() {
            let fallback: String = turn
                .user
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ")
                .chars()
                .take(60)
                .collect();
            if !fallback.is_empty() {
                return fallback;
            }
        }
    }
    "(untitled)".to_string()
}

// ---------------------------------------------------------------------------
// /compress — manual context compression (Step 18.6, issue #247)
// ---------------------------------------------------------------------------

/// Parse `/compress [focus]`: `Ok(None)` for the bare command, `Ok(Some)`
/// with the free-text focus topic otherwise. `/compressx` is some other
/// (unknown) command, not `/compress x` — the `/recall` parsing contract.
/// The focus is an opaque string here; redaction happens in the pipeline
/// (a user can type a secret into the focus).
fn parse_compress_command(input: &str) -> anyhow::Result<Option<String>> {
    let body = input.trim().trim_start_matches('/').trim();
    // `/compact` is the Claude-Code-parity alias for `/compress`.
    let Some(rest) = body
        .strip_prefix("compress")
        .or_else(|| body.strip_prefix("compact"))
    else {
        anyhow::bail!("not a compress command");
    };
    if !rest.is_empty() && !rest.starts_with(char::is_whitespace) {
        anyhow::bail!("not a compress command");
    }
    let focus = rest.trim();
    Ok((!focus.is_empty()).then(|| focus.to_string()))
}

/// The wire view of the current session history — exactly what the loop
/// would send (system prompt + provider history), minus the trailing task
/// slot `build_messages` appends: `/compress` is maintenance, not a turn.
fn session_wire_view(memory: &newt_core::MemoryManager, system: &str) -> Vec<serde_json::Value> {
    let mut wire: Vec<serde_json::Value> = memory
        .build_messages(system, "")
        .iter()
        .map(|m| serde_json::json!({"role": m.role.as_str(), "content": m.content}))
        .collect();
    if wire
        .last()
        .is_some_and(|m| m["role"] == "user" && m["content"] == "")
    {
        wire.pop();
    }
    wire
}

/// Rebuild provider-shaped turns from the pipeline's assembled wire messages
/// so the compressed working set can be applied back through the existing
/// in-memory replace seam (`MemoryManager::restore_turns` — the same one
/// `/conversation restore` uses). A compaction message (and any unpaired
/// side) becomes a lone-sided turn; the system message is dropped — the TUI
/// owns the system prompt and providers re-add it at build time. Token
/// columns stay `None`: after compression these turns are no longer
/// backend-measured (an estimate is never presented as a measurement).
fn wire_messages_to_turns(messages: &[serde_json::Value]) -> Vec<newt_core::ConversationTurn> {
    let mut out: Vec<newt_core::ConversationTurn> = Vec::new();
    for m in messages {
        let content = m["content"].as_str().unwrap_or_default();
        match m["role"].as_str() {
            Some("user") => out.push(newt_core::ConversationTurn::new(content, "")),
            Some("assistant") => match out.last_mut() {
                Some(last)
                    if last.assistant.is_empty()
                        && !last.user.is_empty()
                        && !last.user.starts_with(newt_core::agentic::SUMMARY_PREFIX) =>
                {
                    last.assistant = content.to_string();
                }
                _ => out.push(newt_core::ConversationTurn::new("", content)),
            },
            // `system` is the TUI's own prompt; `tool` roles cannot occur in
            // a provider wire view (text pairs only) — skip defensively.
            _ => {}
        }
    }
    out
}

/// The `/compress` honesty feedback (18.6): never claim savings that didn't
/// happen. Unchanged pipeline output reports "no compression possible"; a
/// fired run reports the REAL before → after counts and how (LLM summary vs
/// static marker vs structural prune), with hermes's "fewer messages can
/// still raise the estimate" note when token savings didn't materialize.
fn compress_feedback_message(outcome: &newt_core::ManualCompressOutcome) -> String {
    if !outcome.fired {
        return format!(
            "no compression possible — {} message(s), ~{} est. tokens are already \
             protected head/tail or unprunable",
            outcome.messages_before, outcome.tokens_before
        );
    }
    let mut msg = format!(
        "context compressed: {} → {} messages, ~{} → ~{} est. tokens ({})",
        outcome.messages_before,
        outcome.messages_after,
        outcome.tokens_before,
        outcome.tokens_after,
        outcome.how
    );
    if outcome.tokens_after >= outcome.tokens_before {
        msg.push_str(
            "\nnote: no token savings — fewer messages can still raise the \
             estimate (the transcript was rewritten into denser summaries)",
        );
    }
    msg
}

/// The `/memory` anti-thrash section (18.6): read-only surfacing of the
/// session [`newt_core::CompressCounters`]. The "/new resets it" hint shows
/// only on the latched line — and it IS true: `handle_new_conversation`
/// calls `CompressState::reset` (F4, #267).
fn memory_compress_section(c: &newt_core::CompressCounters) -> String {
    let mut line = format!("  compressions this session: {}", c.compressions);
    if let Some(reclaim) = c.last_reclaim {
        // A negative reclaim (the pass GREW the estimate) renders as what it
        // is — clamping to "0%" would claim savings that didn't happen.
        if reclaim >= 0.0 {
            line.push_str(&format!(" (last reclaimed {:.0}%)", reclaim * 100.0));
        } else {
            line.push_str(&format!(
                " (last pass grew the estimate {:.0}%)",
                -reclaim * 100.0
            ));
        }
    }
    let strikes = format!(
        "  ineffective-pass strikes: {}/2 (two latch the disable)",
        c.strikes
    );
    let status = if c.disabled {
        "  auto-compression: disabled — anti-thrash latched; /new resets it"
    } else {
        "  auto-compression: enabled"
    };
    format!("{line}\n{strikes}\n{status}")
}

/// The user-facing line for [`newt_core::ConversationStore::wal_fallback_notice`]
/// (N7, #261 review): `None` when WAL is healthy, `Some(message)` when the
/// store fell back to `journal_mode=DELETE` (typical for `~/.newt` on NFS).
fn wal_fallback_startup_notice(notice: Option<&str>) -> Option<String> {
    notice.map(|cause| {
        format!(
            "conversation store: SQLite WAL unavailable, using the journal_mode=DELETE \
             fallback (typical for NFS homes; concurrent newts may wait on locks). \
             Cause: {cause}"
        )
    })
}

fn handle_persona_command(
    input: &str,
    workspace: &str,
    store: &PersonaStore,
    active_persona: &mut Option<Persona>,
    ctx: &mut ConversationResetContext<'_>,
) -> anyhow::Result<String> {
    match parse_persona_command(input)? {
        PersonaCommand::List => persona_list(store),
        PersonaCommand::Show => Ok(persona_status(active_persona.as_ref())),
        PersonaCommand::Clear => {
            *active_persona = None;
            // P1#3: no persona → no persona-declared dial layers.
            seat_persona_dials(None);
            // Clearing the persona starts a new conversation → fresh id + plan.
            *ctx.conversation_id = newt_core::new_conversation_id();
            reset_conversation(workspace, active_persona.as_ref(), ctx);
            Ok("Started a new conversation with no active persona.".to_string())
        }
        PersonaCommand::Set { name, keep_context } => {
            let persona = store.load(&name)?;
            // P1#3 / review-2: install the persona's declared dials as real
            // resolution layers, so `/persona show`, `/psyche`, and the panel
            // all agree and the loop obeys them.
            seat_persona_dials(Some(&persona));
            *active_persona = Some(persona);
            if keep_context {
                // Persistent-actor swap: rebuild the system prompt for the new
                // role WITHOUT discarding the conversation history — same
                // conversation, same plan file.
                *ctx.system = rebuild_system_prompt(
                    workspace,
                    ctx.memory,
                    active_persona.as_ref(),
                    ctx.conversation_id,
                );
                Ok(persona_swap_kept_context_message(active_persona.as_ref()))
            } else {
                // Swapping without keeping context starts a new conversation.
                *ctx.conversation_id = newt_core::new_conversation_id();
                reset_conversation(workspace, active_persona.as_ref(), ctx);
                Ok(new_conversation_message(active_persona.as_ref()))
            }
        }
    }
}

fn persona_swap_kept_context_message(active_persona: Option<&Persona>) -> String {
    match active_persona {
        Some(persona) => format!(
            "Switched to persona `{}` (kept conversation context).",
            persona.name
        ),
        None => "Switched persona (kept conversation context).".to_string(),
    }
}

/// Resolve the token-based mid-loop trim trigger (issue #223): the per-model
/// override wins over the global `[tui].mid_loop_trim_tokens`. A configured
/// ZERO (from either source) means DISABLED — the old `trim_to_token_budget`
/// zero-is-noop contract, enforced both here and in the trigger itself (F3).
fn effective_mid_loop_trim_tokens(
    model_override: Option<usize>,
    global: Option<usize>,
) -> Option<usize> {
    model_override.or(global).filter(|&t| t > 0)
}

/// Read the legacy pre-execution preview limit (default 20, 0 = unlimited).
/// Completed results use `[tui] spill_lines`.
fn tool_output_lines(cfg: &newt_core::Config) -> usize {
    cfg.tui.as_ref().map(|t| t.tool_output_lines).unwrap_or(20)
}

/// #1235: the spill-view height (`[tui] spill_lines`, default 3 — keep in
/// sync with `default_spill_lines` in newt-core config).
fn spill_lines(cfg: &newt_core::Config) -> usize {
    cfg.tui.as_ref().map(|t| t.spill_lines).unwrap_or(3)
}

/// Seconds between committed `[HH:MM]` transcript markers — mirrors
/// [`spill_lines`], including its "config absent means the documented default"
/// shape.
fn time_marker_secs(cfg: &newt_core::Config) -> u64 {
    cfg.tui.as_ref().map(|t| t.time_marker_secs).unwrap_or(300)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpillCommand {
    Status,
    Set(usize),
    Reset,
    /// #1640 Layer 1: collapse spilled tool results to a one-line marker.
    Summary,
    /// #1640 Layer 1: restore the multi-row excerpt.
    Excerpt,
    /// Open the newest retained completed result.
    Last,
    /// Open one stable, session-local retained result.
    Open(u64),
}

/// Apply a parsed `/spill` command to the two session overrides. Pure and
/// separately pinned (review fix on #1663): `Reset` must clear BOTH knobs —
/// the row override AND the summary/excerpt mode — returning the session to
/// its surface defaults; nothing else touches the knob it doesn't own.
fn apply_spill_command(
    cmd: SpillCommand,
    lines_override: &mut Option<usize>,
    summary_override: &mut Option<bool>,
) {
    match cmd {
        SpillCommand::Status => {}
        SpillCommand::Set(rows) => *lines_override = Some(rows),
        SpillCommand::Summary => *summary_override = Some(true),
        SpillCommand::Excerpt => *summary_override = Some(false),
        SpillCommand::Last | SpillCommand::Open(_) => {}
        SpillCommand::Reset => {
            *lines_override = None;
            *summary_override = None;
        }
    }
}

fn parse_spill_command(input: &str) -> anyhow::Result<SpillCommand> {
    let body = input.trim().trim_start_matches('/').trim();
    let Some(rest) = body.strip_prefix("spill") else {
        anyhow::bail!("not a spill command");
    };
    if !rest.is_empty()
        && !rest
            .chars()
            .next()
            .map(char::is_whitespace)
            .unwrap_or(false)
    {
        anyhow::bail!("not a spill command");
    }

    let arg = rest.trim();
    let normalized = arg.to_ascii_lowercase();
    if let Some(value) = normalized.strip_prefix("open ") {
        let id = value
            .trim()
            .parse::<u64>()
            .map_err(|_| anyhow::anyhow!("/spill open needs a positive result id"))?;
        if id == 0 || value.split_whitespace().count() != 1 {
            anyhow::bail!("/spill open needs one positive result id");
        }
        return Ok(SpillCommand::Open(id));
    }
    match normalized.as_str() {
        "" | "show" | "status" => Ok(SpillCommand::Status),
        "reset" | "default" | "config" | "auto" => Ok(SpillCommand::Reset),
        "summary" | "collapse" => Ok(SpillCommand::Summary),
        "excerpt" | "expand" | "rows" => Ok(SpillCommand::Excerpt),
        "last" => Ok(SpillCommand::Last),
        _ => arg
            .parse::<usize>()
            .map(SpillCommand::Set)
            .map_err(|_| anyhow::anyhow!("unknown /spill argument '{arg}'")),
    }
}

/// #1387 Phase 1 — `/search` cockpit verbs (pure parse; chat owns execution).
#[derive(Debug, Clone, PartialEq, Eq)]
enum SearchCommand {
    /// Run a semantic query (the remainder of the line).
    Query(String),
    Preview(usize),
    Model,
    Rejects,
    Pin(usize),
    Exclude(usize),
    Status,
    Clear,
    Help,
}

fn parse_search_command(input: &str) -> anyhow::Result<SearchCommand> {
    let body = input.trim().trim_start_matches('/').trim();
    let Some(rest) = body.strip_prefix("search") else {
        anyhow::bail!("not a search command");
    };
    if !rest.is_empty()
        && !rest
            .chars()
            .next()
            .map(char::is_whitespace)
            .unwrap_or(false)
    {
        anyhow::bail!("not a search command");
    }
    let arg = rest.trim();
    if arg.is_empty() || matches!(arg, "help" | "--help" | "-h") {
        return Ok(SearchCommand::Help);
    }
    let (verb, tail) = match arg.split_once(char::is_whitespace) {
        Some((v, t)) => (v, t.trim()),
        None => (arg, ""),
    };
    match verb {
        "preview" => Ok(SearchCommand::Preview(if tail.is_empty() {
            1
        } else {
            tail.parse()
                .map_err(|_| anyhow::anyhow!("usage: /search preview [N]"))?
        })),
        "model" | "packet" => Ok(SearchCommand::Model),
        "rejects" | "reject" | "ledger" => Ok(SearchCommand::Rejects),
        "pin" => {
            let n: usize = tail
                .parse()
                .map_err(|_| anyhow::anyhow!("usage: /search pin <N>"))?;
            Ok(SearchCommand::Pin(n))
        }
        "exclude" | "x" => {
            let n: usize = tail
                .parse()
                .map_err(|_| anyhow::anyhow!("usage: /search exclude <N>"))?;
            Ok(SearchCommand::Exclude(n))
        }
        "status" => Ok(SearchCommand::Status),
        "clear" => Ok(SearchCommand::Clear),
        _ => Ok(SearchCommand::Query(arg.to_string())),
    }
}

fn search_help_text() -> &'static str {
    "/search <query>     — semantic search (shared with model code_search)\n\
     /search preview [N] — preview hit N (default 1)\n\
     /search model       — exact <code_evidence> packet the model would see\n\
     /search rejects     — reject ledger (below top_k / budget / excluded)\n\
     /search pin N       — pin hit N into the next inject + tool retrieve\n\
     /search exclude N   — exclude hit N's path from automatic retrieval\n\
     /search status      — index generation, completeness, git HEAD/dirty\n\
     /search clear       — clear session pins/exclusions"
}

/// Best-effort HEAD + dirty bit for lightweight index status (#1387). Runtime
/// glue (not unit-tier) — absence is reported honestly as unavailable.
fn lightweight_git_meta(
    workspace: &str,
    read_scope: &newt_core::Scope<String>,
) -> (Option<String>, Option<bool>) {
    // Confused-deputy-safe (step-7.4): the workspace may be a hostile repo.
    let head = newt_core::git_hardening::metadata_git(
        std::path::Path::new(workspace),
        &["rev-parse", "HEAD"],
        read_scope,
    )
    .and_then(|mut command| command.output())
    .ok()
    .filter(|o| o.status.success())
    .and_then(|o| String::from_utf8(o.stdout).ok())
    .map(|s| s.trim().to_string())
    .filter(|s| !s.is_empty());
    let dirty = newt_core::git_hardening::metadata_git(
        std::path::Path::new(workspace),
        &["status", "--porcelain"],
        read_scope,
    )
    .and_then(|mut command| command.output())
    .ok()
    .filter(|o| o.status.success())
    .map(|o| !o.stdout.is_empty());
    (head, dirty)
}

fn effective_spill_lines(configured: usize, session_override: Option<usize>) -> usize {
    session_override.unwrap_or(configured)
}

/// #1640: how many rows the *committed* tool-output excerpt keeps for THIS
/// surface. The excerpt is only worth truncating when there is an interactive
/// viewport to recover the hidden lines — i.e. the RICH surface. The LEAN
/// surface (`--plain` / `-n` / piped / headless / a non-`rich-tui` build) has
/// no scrollable regions at all (decision: the plain scroller), so its excerpt
/// IS the whole durable record and must be shown in full. Collapsing it there
/// only hides output behind a `/spill N` re-render the lean surface cannot even
/// scroll — the exact regression #1640 reports.
///
/// So: pass the configured height through on rich; force `0` (unbounded) on
/// lean. `0` is `spill_view_lines`' existing "print every line" contract, so no
/// new code path is introduced — this only chooses the argument.
fn committed_spill_lines(surface_is_rich: bool, configured: usize) -> usize {
    if surface_is_rich {
        configured
    } else {
        0
    }
}

/// #1640 Layer 1: whether committed tool results collapse to a one-line
/// summary marker on THIS surface. The default is the surface itself — rich
/// collapses (its viewport + `/spill` vocabulary can recover the detail), lean
/// never does (it shows FULL output, the same reasoning as
/// [`committed_spill_lines`]) — and `/spill summary` / `/spill excerpt` set the
/// session override on the same single-knob pattern as `spill_lines_override`.
fn effective_spill_summary(surface_is_rich: bool, session_override: Option<bool>) -> bool {
    session_override.unwrap_or(surface_is_rich)
}

/// #1434: `--trace` SEEDS the session detail knob instead of sitting beside it.
///
/// newt already has a session-wide detail level — `SPILL_LINES`, config-seeded
/// per turn and runtime-mutable via `/spill N`, with `0` meaning unbounded. What
/// it lacked was a connection to the launch flag, which is exactly the bug pi
/// shipped: `getStartupExpansionState()` is `options.verbose || toolOutputExpanded`
/// and nothing initializes the latter from the former, so **after `pi --verbose`
/// the first toggle press expands instead of collapsing**.
///
/// A launch flag that sits *beside* a runtime toggle has two sources of truth
/// and therefore a phase. Seeding gives one variable and no phase.
fn initial_spill_override(trace: bool) -> Option<usize> {
    // `--trace` means "show me everything"; 0 is this knob's unbounded.
    trace.then_some(0)
}

/// #1434: flip the session detail level between unbounded and the configured
/// height. The single action behind `/detail` (and, once #294's action table
/// exists, behind a chord).
///
/// Returns the new override. Deliberately expressed over the SAME
/// `Option<usize>` the `/spill` command already mutates, so there is no second
/// piece of detail state to drift — see `initial_spill_override`.
fn toggle_spill_detail(current: Option<usize>, configured: usize) -> Option<usize> {
    if effective_spill_lines(configured, current) == 0 {
        // Unbounded → back to the configured height. `max(1)` so a configured
        // 0 cannot make the toggle a no-op that looks broken.
        Some(configured.max(1))
    } else {
        Some(0)
    }
}

/// Why the live spill viewport is, or is not, available right now (#1412).
///
/// The predicate used to be a bare `bool`, so `/spill` could say only
/// "unavailable" — it could not distinguish "stdout is not a TTY" from
/// "`TERM=dumb`" from "the feature was not compiled in". That silence has a
/// measured cost: it is why a **stale install** was reported as a vanished
/// feature. The binary on the reporting machine predated live-spill entirely
/// and contained no `/spill` command at all, but nothing the product could say
/// would have distinguished that from a misconfiguration.
///
/// A refusing gate should name itself.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SpillEligibility {
    /// Every gate passed; the live viewport can render.
    Available,
    /// Not a Unix-family platform (the viewport needs POSIX terminal control).
    UnsupportedPlatform,
    /// Built without the `live-spill` cargo feature — the lean/wyvern tier.
    FeatureDisabled,
    /// stdin is a pipe or file, so no keystrokes can drive the viewport.
    StdinNotTty,
    /// stdout is redirected, so there is no frame to draw into.
    StdoutNotTty,
    /// `TERM=dumb` — the terminal disclaims cursor addressing.
    TermDumb,
    /// The cockpit owns the terminal, so the viewport is deliberately not
    /// built: it paints with cursor motion the presenter drops by design.
    ///
    /// Last in the ladder because it is the one refusal that says nothing is
    /// WRONG — the platform, the build and the terminal are all fine, and the
    /// operator is simply on the surface that does its own drawing. Reporting
    /// it after the others keeps the fixable causes first.
    TerminalOwnedByCockpit,
}

impl SpillEligibility {
    /// Operator-facing phrase for `/spill`. Names the gate AND, where there is
    /// one, the lever that changes it — an unavailability the operator cannot
    /// act on is only marginally better than a bare "unavailable".
    fn explain(self) -> &'static str {
        match self {
            Self::Available => "live interaction available",
            Self::UnsupportedPlatform => {
                "live interaction unavailable: unsupported platform (needs a POSIX terminal)"
            }
            Self::FeatureDisabled => {
                "live interaction unavailable: built without the `live-spill` feature \
                 (this is the lean/wyvern build)"
            }
            Self::StdinNotTty => {
                "live interaction unavailable: stdin is not a terminal (piped or redirected)"
            }
            Self::StdoutNotTty => {
                "live interaction unavailable: stdout is not a terminal (piped or redirected)"
            }
            Self::TermDumb => "live interaction unavailable: TERM=dumb disclaims cursor control",
            Self::TerminalOwnedByCockpit => {
                "live interaction unavailable: the cockpit owns the terminal \
                 (committed results stay full; /spill open <id> reopens one)"
            }
        }
    }
}

fn spill_status(
    configured: usize,
    session_override: Option<usize>,
    summary: bool,
    surface_is_rich: bool,
    eligibility: SpillEligibility,
) -> String {
    let effective = effective_spill_lines(configured, session_override);
    // Review fix (#1663): status must describe what rendering will DO, not
    // just echo the knobs — on lean the committed record is forced full, and
    // collapse cannot engage when the committed view is unbounded (lean, or
    // rich after `/spill 0`), so the mode clause is guarded the same way the
    // renderer is.
    let committed = committed_spill_lines(surface_is_rich, effective);
    let rows = if effective == 0 {
        "unbounded".to_string()
    } else {
        effective.to_string()
    };
    let source = match session_override {
        Some(_) => format!(" this session (config default {configured}"),
        None => " (config default".to_string(),
    };
    // Row count is checked here rather than inside `SpillEligibility` on
    // purpose: zero rows disables the *viewport*, but the terminal is still
    // perfectly capable — and the mouse tier keys off capability, not rows.
    // Folding the two would make `/spill 0` look like a broken terminal.
    let live = if effective == 0 {
        "live viewport disabled: spill_lines is 0 (/spill <n> raises it)"
    } else {
        eligibility.explain()
    };
    let lean_note = if !surface_is_rich && effective != 0 {
        "; committed results always print in full on this surface"
    } else {
        ""
    };
    // #1640 Layer 1: name the committed-result mode so `/spill status` answers
    // "why is my tool output one line" (or "why is it five").
    let mode = if summary && committed != 0 {
        "; results collapse to a summary line (/spill excerpt restores rows)"
    } else {
        ""
    };
    format!("spill rows: {rows}{source}; {live}{lean_note}{mode})")
}

/// Whether the committed-collapse default can honestly engage this session:
/// the rich surface with the completed-spill viewport buildable.
///
/// The old comment claimed sharing this with `/spill status` kept the status
/// line and the turn-head seeding from drifting, and treated "the renderer
/// additionally has to construct" as a harmless remainder. It was not
/// harmless. Under the cockpit — the DEFAULT rich surface — `run_chat`
/// declines to build the renderer at all, so the turn seeded collapse OFF and
/// committed excerpts, while this said the collapse was engaged. `/spill`
/// answered "results collapse to a summary line" and the very next tool result
/// printed a five-row excerpt.
///
/// `terminal_owns_turn` is now part of the eligibility ladder, so both answers
/// come from one walk of it and the remainder is only the genuine
/// constructor-failed case.
fn summary_recovery_available(surface_is_rich: bool, terminal_owns_turn: bool) -> bool {
    // `live_spill_capable` itself only exists under live-spill, so the whole
    // conjunction is cfg-split rather than short-circuited with `cfg!`.
    #[cfg(all(feature = "rich-tui", feature = "live-spill"))]
    {
        surface_is_rich && live_spill_capable(terminal_owns_turn)
    }
    #[cfg(not(all(feature = "rich-tui", feature = "live-spill")))]
    {
        let _ = surface_is_rich;
        let _ = terminal_owns_turn;
        false
    }
}

fn live_spill_eligibility(terminal_owns_turn: bool) -> SpillEligibility {
    let term = std::env::var("TERM").ok();
    spill_eligibility_for(
        cfg!(unix),
        cfg!(feature = "live-spill"),
        std::io::stdin().is_terminal(),
        std::io::stdout().is_terminal(),
        term.as_deref(),
        terminal_owns_turn,
    )
}

/// Yes/no form for the turn-level gate in `chat.rs`, which is itself
/// `#[cfg(feature = "live-spill")]` — hence the matching gate here. Before
/// #1412 this stayed alive in the lean build only because `/spill status`
/// called it; that call now wants the *reason*, so the lean build would
/// otherwise carry it as dead code.
///
/// Not `test`-gated: it probes the real stdin/stdout, so the unit tier drives
/// the injected-bool [`live_spill_capable_for`] instead.
#[cfg(feature = "live-spill")]
fn live_spill_capable(terminal_owns_turn: bool) -> bool {
    live_spill_eligibility(terminal_owns_turn) == SpillEligibility::Available
}

/// Same five gates the old boolean ANDed, but reporting *which* one refused.
///
/// Precedence is deliberate and tested: the gates the operator cannot change
/// without a different binary come first (platform, then cargo feature), then
/// the ones a different invocation fixes (stdin, stdout), then the terminal's
/// own declaration. Reporting the most fundamental refusal first stops
/// `/spill` from sending someone to fix their `TERM` when the feature was
/// never compiled in.
fn spill_eligibility_for(
    platform_supported: bool,
    feature_enabled: bool,
    stdin_terminal: bool,
    stdout_terminal: bool,
    term: Option<&str>,
    terminal_owns_turn: bool,
) -> SpillEligibility {
    if !platform_supported {
        SpillEligibility::UnsupportedPlatform
    } else if !feature_enabled {
        SpillEligibility::FeatureDisabled
    } else if !stdin_terminal {
        SpillEligibility::StdinNotTty
    } else if !stdout_terminal {
        SpillEligibility::StdoutNotTty
    } else if term == Some("dumb") {
        SpillEligibility::TermDumb
    } else if terminal_owns_turn {
        SpillEligibility::TerminalOwnedByCockpit
    } else {
        SpillEligibility::Available
    }
}

/// Boolean façade over [`spill_eligibility_for`], kept because the mouse tier
/// and its acceptance tests ask a yes/no question and should not have to care
/// about the reason. Gated to match its only non-test caller,
/// `mouse_capable_for`, which is `#[cfg(feature = "live-spill")]`.
#[cfg(any(feature = "live-spill", test))]
fn live_spill_capable_for(
    platform_supported: bool,
    feature_enabled: bool,
    stdin_terminal: bool,
    stdout_terminal: bool,
    term: Option<&str>,
    terminal_owns_turn: bool,
) -> bool {
    spill_eligibility_for(
        platform_supported,
        feature_enabled,
        stdin_terminal,
        stdout_terminal,
        term,
        terminal_owns_turn,
    ) == SpillEligibility::Available
}

/// #1303: the mouse-tier opt-in — config-first (`[tui] mouse_viewport`, default
/// false) with a `NEWT_MOUSE` env override (the `NEWT_*` convention, and the
/// seam the acceptance test uses to force the opt-in on while proving the TTY
/// gate still refuses). Mirrors [`spill_lines`]; the config field is always
/// compiled, but this accessor and the capability gate only exist under
/// `live-spill` (the mouse tier rides the spill viewport's own feature, stripped
/// from the wyvern build).
#[cfg(feature = "live-spill")]
fn mouse_viewport(cfg: &newt_core::Config) -> bool {
    if let Ok(v) = std::env::var("NEWT_MOUSE") {
        return matches!(v.as_str(), "1" | "true" | "on" | "yes");
    }
    cfg.tui.as_ref().map(|t| t.mouse_viewport).unwrap_or(false)
}

/// #1303: the mouse-tier capability gate — layered strictly ON TOP of
/// `live_spill_capable()` plus an explicit opt-in. Mouse events arrive on
/// **stdin**, so both stdin and stdout must be terminals (a stdin-piped session
/// never enables capture even when stdout is a TTY).
#[cfg(feature = "live-spill")]
fn mouse_capable(opt_in: bool) -> bool {
    let term = std::env::var("TERM").ok();
    mouse_capable_for(
        cfg!(unix),
        cfg!(feature = "live-spill"),
        std::io::stdin().is_terminal(),
        std::io::stdout().is_terminal(),
        term.as_deref(),
        opt_in,
    )
}

/// Pure predicate behind [`mouse_capable`]: the opt-in AND the full
/// `live_spill_capable_for` predicate. Injected-bool seam for the acceptance-1a
/// table test.
#[cfg(feature = "live-spill")]
fn mouse_capable_for(
    platform_supported: bool,
    feature_enabled: bool,
    stdin_terminal: bool,
    stdout_terminal: bool,
    term: Option<&str>,
    opt_in: bool,
) -> bool {
    opt_in
        && live_spill_capable_for(
            platform_supported,
            feature_enabled,
            stdin_terminal,
            stdout_terminal,
            term,
            // NOT the cockpit gate. That refusal says "this surface draws its
            // own frames", which is a fact about the VIEWPORT; the mouse tier
            // is asking whether the TERMINAL can report clicks, and the
            // cockpit does not take that away. Feeding it in here would
            // silently disable the mouse tier on the default rich surface,
            // which is a behaviour change and not this predicate's business.
            false,
        )
}

/// Initial allowance of tool-call rounds per turn, from `[tui].max_tool_rounds`.
/// Uses the canonical core default when there's no `[tui]` table or config file.
fn max_tool_rounds(cfg: &newt_core::Config) -> usize {
    cfg.tui
        .as_ref()
        .map(|t| t.max_tool_rounds)
        .unwrap_or_else(|| newt_core::TuiConfig::default().max_tool_rounds)
}

/// Renewable progress-aware round increments after `[tui].max_tool_rounds`.
/// Defaults to 5; set to 0 to keep the normal round cap hard.
fn workflow_grace_rounds(cfg: &newt_core::Config) -> usize {
    cfg.tui
        .as_ref()
        .map(|t| t.workflow_grace_rounds)
        .unwrap_or(5)
}

/// Narrate-then-stop rescue budget per turn (`[tui].narration_nudge_cap`).
/// Defaults to 1 — the historical one-shot rescue; weak local models that
/// chronically narrate instead of acting benefit from 2-3 (lever L3).
fn narration_nudge_cap(cfg: &newt_core::Config) -> usize {
    cfg.tui.as_ref().map(|t| t.narration_nudge_cap).unwrap_or(1)
}

const EFFECTIVELY_UNLIMITED_TOOL_ROUNDS: usize = newt_core::tenacity::RELENTLESS_TOOL_ROUND_TARGET;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ToolRoundLimitCommand {
    Show,
    Set(usize),
    Double,
    Reset,
    Configured,
    Unlimited,
}

/// The verb the operator typed and the argument after it.
///
/// The NAME is returned, not just the argument (#1998): `/rounds 320` and
/// `/max-rounds 320` are the same setting reached two ways, and which way is
/// the half of the event a reader cannot reconstruct afterwards — so it is
/// bound into the receipt's address. This shape also hid two aliases from the
/// help text for a long while; returning the name is what lets the receipt
/// name them.
fn tool_round_limit_command(input: &str) -> Option<(&'static str, &str)> {
    let body = input.trim().trim_start_matches('/').trim();
    ["rounds", "tool-rounds", "max-rounds"]
        .iter()
        .find_map(|cmd| {
            let rest = body.strip_prefix(*cmd)?;
            let boundary = rest.is_empty()
                || rest
                    .chars()
                    .next()
                    .map(char::is_whitespace)
                    .unwrap_or(false);
            boundary.then(|| (*cmd, rest.trim()))
        })
}

fn tool_round_limit_command_arg(input: &str) -> Option<&str> {
    tool_round_limit_command(input).map(|(_, arg)| arg)
}

/// Parse `/rounds [show|<n>|double|reset|config|unlimited]`, the
/// human-controlled session override for the agentic loop's tool-call round
/// safety valve. `reset`/`default`/`auto` return to the derived posture default;
/// `config` deliberately chooses the configured/model-tuned number even when
/// explicit Relentless tenacity would otherwise raise it.
fn parse_tool_round_limit_command(input: &str) -> anyhow::Result<ToolRoundLimitCommand> {
    let Some(arg) = tool_round_limit_command_arg(input) else {
        anyhow::bail!("not a tool-round limit command");
    };
    if arg.is_empty() {
        return Ok(ToolRoundLimitCommand::Show);
    }

    let normalized = arg.to_ascii_lowercase();
    match normalized.as_str() {
        "show" | "status" => Ok(ToolRoundLimitCommand::Show),
        "double" | "x2" | "2x" => Ok(ToolRoundLimitCommand::Double),
        "reset" | "default" | "auto" => Ok(ToolRoundLimitCommand::Reset),
        "config" | "configured" => Ok(ToolRoundLimitCommand::Configured),
        "unlimited" | "infinite" | "finish" | "until-finished" | "run-until-finished"
        | "until finished" | "run until finished" => Ok(ToolRoundLimitCommand::Unlimited),
        _ => {
            let n = arg.parse::<usize>().map_err(|_| {
                anyhow::anyhow!(
                    "unknown /rounds argument '{arg}' (use show, <n>, double, reset, config, unlimited)"
                )
            })?;
            if n == 0 {
                anyhow::bail!("tool-call round limit must be at least 1");
            }
            if n > EFFECTIVELY_UNLIMITED_TOOL_ROUNDS {
                anyhow::bail!(
                    "tool-call round limit must be <= {EFFECTIVELY_UNLIMITED_TOOL_ROUNDS}"
                );
            }
            Ok(ToolRoundLimitCommand::Set(n))
        }
    }
}

fn tenacity_tool_round_limit(
    configured: usize,
    explicit_tenacity: Option<newt_core::Tenacity>,
) -> usize {
    newt_core::tenacity::resolve_tool_round_limit(configured, explicit_tenacity, None).rounds
}

/// The cap this turn will run under, WITH its derivation (#1965).
///
/// Returns the whole [`ToolRoundLimit`](newt_core::tenacity::ToolRoundLimit)
/// rather than the number, because the number alone is what made an escalation
/// from 40 to effectively unlimited unrecordable: the caller stamps the
/// derivation into the turn's durable outcome, and cannot do that from a
/// `usize`.
fn effective_tool_round_limit(
    configured: usize,
    explicit_tenacity: Option<newt_core::Tenacity>,
    session_override: Option<usize>,
) -> newt_core::tenacity::ToolRoundLimit {
    newt_core::tenacity::resolve_tool_round_limit(configured, explicit_tenacity, session_override)
}

fn double_tool_round_limit(current: usize) -> usize {
    if current >= EFFECTIVELY_UNLIMITED_TOOL_ROUNDS {
        // The sentinel is an "effectively unlimited" target, not a maximum
        // valid configuration. Never make `/rounds double` lower a larger
        // config/model value.
        current
    } else {
        current
            .saturating_mul(2)
            .clamp(1, EFFECTIVELY_UNLIMITED_TOOL_ROUNDS)
    }
}

/// Resolve a parsed `/rounds` command to the override it lands on. Keeping this
/// transition pure makes the two different reset intents explicit and testable:
/// `Reset` removes the override (so tenacity/config derive the next value),
/// while `Configured` installs the raw config/model number as an override.
///
/// **It performs the derivation; it does not perform the write** (#1998).
/// `double` and `unlimited` are relative operations, which is why `/rounds`
/// stays a verb — but the value they resolve to goes through
/// `settings_form::apply_and_record` like every other setting, so the
/// escalation that produced #1965 now leaves a receipt.
fn apply_tool_round_limit_command(
    configured: usize,
    explicit_tenacity: Option<newt_core::Tenacity>,
    session_override: Option<usize>,
    command: ToolRoundLimitCommand,
) -> Option<usize> {
    match command {
        ToolRoundLimitCommand::Show => session_override,
        ToolRoundLimitCommand::Set(rounds) => Some(rounds),
        ToolRoundLimitCommand::Double => Some(double_tool_round_limit(
            effective_tool_round_limit(configured, explicit_tenacity, session_override).rounds,
        )),
        ToolRoundLimitCommand::Reset => None,
        ToolRoundLimitCommand::Configured => Some(configured),
        ToolRoundLimitCommand::Unlimited => Some(
            effective_tool_round_limit(configured, explicit_tenacity, session_override)
                .rounds
                .max(EFFECTIVELY_UNLIMITED_TOOL_ROUNDS),
        ),
    }
}

fn describe_tool_round_limit(rounds: usize) -> String {
    if rounds >= EFFECTIVELY_UNLIMITED_TOOL_ROUNDS {
        format!("{rounds} (effectively unlimited)")
    } else {
        rounds.to_string()
    }
}

fn tool_round_limit_status(
    configured: usize,
    explicit_tenacity: Option<newt_core::Tenacity>,
    session_override: Option<usize>,
) -> String {
    let posture_default = tenacity_tool_round_limit(configured, explicit_tenacity);
    let explicit_relentless = explicit_tenacity == Some(newt_core::Tenacity::Relentless);
    match session_override {
        Some(rounds) if explicit_relentless => format!(
            "initial tool-call round allowance: {} this session (explicit relentless tenacity default {}; config/model default {})",
            describe_tool_round_limit(rounds),
            describe_tool_round_limit(posture_default),
            describe_tool_round_limit(configured),
        ),
        Some(rounds) => format!(
            "initial tool-call round allowance: {} this session (config/model default {})",
            describe_tool_round_limit(rounds),
            describe_tool_round_limit(configured),
        ),
        None if explicit_relentless => format!(
            "initial tool-call round allowance: {posture_default} (effectively unlimited; explicit relentless tenacity; config/model default {})",
            describe_tool_round_limit(configured),
        ),
        None => format!(
            "initial tool-call round allowance: {} (config/model default)",
            describe_tool_round_limit(configured)
        ),
    }
}

/// Rich `/psyche` applies several controls at once. Pair its resolved posture
/// summary with the exact same round-budget diagnostic `/rounds` uses so a
/// pre-existing session override is never hidden by an "applied" message.
#[cfg_attr(not(feature = "rich-tui"), allow(dead_code))]
fn psyche_apply_summary(
    runtime_summary: &str,
    configured: usize,
    explicit_tenacity: Option<newt_core::Tenacity>,
    session_override: Option<usize>,
) -> String {
    format!(
        "{runtime_summary}\n{}",
        tool_round_limit_status(configured, explicit_tenacity, session_override)
    )
}

/// Ollama context-window cap. Resolution order:
///   1. `NEWT_NUM_CTX` env var (set by `--num-ctx` CLI flag or manually)
///   2. `[tui] num_ctx` in config
///   3. None → Ollama uses the model's compiled-in default
fn num_ctx(cfg: &newt_core::Config) -> Option<u32> {
    if let Ok(val) = std::env::var("NEWT_NUM_CTX") {
        if let Ok(n) = val.trim().parse::<u32>() {
            return Some(n);
        }
    }
    cfg.tui.as_ref().and_then(|t| t.num_ctx)
}

/// Whether to use empirical "real context discovery" (conserve-and-ratchet) for
/// `model`, vs. trusting the declared `/api/show` window. Resolution: per-model
/// `[[model_tuning]] real_context_discovery` wins, else `[tui]
/// real_context_discovery`, else `false` (trust declared — the default).
fn real_context_discovery(cfg: &newt_core::Config, model: &str) -> bool {
    cfg.find_model_tuning(model)
        .and_then(|t| t.real_context_discovery)
        .or_else(|| cfg.tui.as_ref().and_then(|t| t.real_context_discovery))
        .unwrap_or(false)
}

/// TCP connect timeout from `[tui].connect_timeout_secs` (default 5).
fn connect_timeout_secs(cfg: &newt_core::Config) -> u64 {
    cfg.tui
        .as_ref()
        .map(|t| t.connect_timeout_secs)
        .unwrap_or(5)
}

/// Total single-response / streamed idle timeout from
/// `[tui].inference_timeout_secs` (default 120).
fn inference_timeout_secs(cfg: &newt_core::Config) -> u64 {
    cfg.tui
        .as_ref()
        .map(|t| t.inference_timeout_secs)
        .unwrap_or(120)
}

/// Ollama keep_alive from `[tui].keep_alive` (default "5m").
pub(crate) fn keep_alive_str(cfg: &newt_core::Config) -> String {
    cfg.tui
        .as_ref()
        .map(|t| t.keep_alive.clone())
        .unwrap_or_else(|| "5m".to_string())
}

/// Build `SummarizerOpts` from the dedicated [`newt_core::SummarizerConfig`]
/// (Step 24.10; the timeout / retries / fallback knobs moved out of `[tui]`).
/// `keep_alive` falls back to `[tui].keep_alive` when the summarizer file does
/// not pin its own.
fn summarizer_opts(
    sum_cfg: &newt_core::SummarizerConfig,
    cfg: &newt_core::Config,
    num_ctx: Option<u32>,
    color: bool,
) -> SummarizerOpts {
    SummarizerOpts {
        num_ctx,
        keep_alive: sum_cfg
            .keep_alive
            .clone()
            .unwrap_or_else(|| keep_alive_str(cfg)),
        timeout_secs: sum_cfg.timeout_secs,
        retries: sum_cfg.retries,
        fallback_model: sum_cfg.fallback_model.clone(),
        color,
        run_allowance: None,
        // The live-notice decision is ownership, not styling: detect it once
        // here rather than re-deriving it from `color` at three call sites.
        caps: newt_core::tty::LineCaps::detect(),
    }
}

/// The summarizer's DEFAULT backend decision (when the operator pins NO
/// `[summarizer]` override). The anti-regression seam — the test below pins it,
/// so the codebase can't quietly slip back to reusing the session model (which
/// it repeatedly has). See memory `feedback_summarizer_defaults_to_embedded_cpu`.
#[derive(Debug, PartialEq)]
enum SummarizerChoice {
    /// The DEFAULT: the on-host embedded CPU engine (#661 group C), this GGUF.
    Embedded(String),
    /// Embedded is unavailable (feature off / no model pulled) → degrade to
    /// reusing the session model, which contends with the primary model.
    DegradedSession,
}

/// With no override, prefer the embedded CPU engine; only degrade to the
/// session model when no embedded GGUF resolves. REGRESSION GUARD — flipping
/// this to default to the session model fails the test below.
fn default_summarizer_choice(embedded_gguf: Option<String>) -> SummarizerChoice {
    match embedded_gguf {
        Some(path) => SummarizerChoice::Embedded(path),
        None => SummarizerChoice::DegradedSession,
    }
}

/// The default embedded summarizer GGUF, IFF the `embedded` engine is compiled
/// AND the default palette model has been pulled to `~/.newt/models`
/// (`newt models pull`). `None` otherwise → a warned degrade to the session.
fn embedded_summarizer_default() -> Option<String> {
    #[cfg(feature = "embedded")]
    {
        newt_inference::palette::resolve_local(newt_inference::palette::default_model().name)
            .map(|p| p.to_string_lossy().into_owned())
    }
    #[cfg(not(feature = "embedded"))]
    {
        None
    }
}

fn warn_summarizer_once(flag: &std::sync::atomic::AtomicBool, msg: &str) {
    if !flag.swap(true, std::sync::atomic::Ordering::Relaxed) {
        eprintln!("{msg}");
    }
}

/// Resolve the summarizer's effective backend. The DEFAULT is the on-host
/// embedded CPU engine (#661 group C): context compaction must NOT run on the
/// session GPU model — compaction fires under peak load, so reusing the loaded
/// model overloads the GPU and stalls the turn (#979). A `[summarizer]` backend
/// override (session / off-box) is honored but WARNS; if the embedded engine is
/// unavailable (feature not compiled, or no model pulled — `newt models pull`)
/// it degrades to the session model with a loud warning. This default keeps
/// regressing; `default_summarizer_choice` + its test are the guard.
fn resolve_summarizer_backend(
    sum_cfg: &newt_core::SummarizerConfig,
    inf_url: &str,
    inf_model: &str,
    inf_kind: newt_core::BackendKind,
    inf_key: &Option<String>,
    // The resolved embedded-default GGUF path, or `None` when no on-host model is
    // available (→ degrade to session). INJECTED so resolution is hermetic in
    // tests; production passes `embedded_summarizer_default()`, which reads the
    // real `~/.newt/models`. (Reading it inline made this machine-dependent — a
    // provisioned box resolved to embedded and flipped the session-reuse test.)
    embedded_gguf: Option<String>,
) -> (
    String,
    String,
    newt_core::BackendKind,
    Option<String>,
    Option<String>,
) {
    let has_override = sum_cfg.kind.is_some()
        || sum_cfg.endpoint.is_some()
        || sum_cfg.model.is_some()
        || sum_cfg.model_path.is_some();

    if !has_override {
        match default_summarizer_choice(embedded_gguf) {
            SummarizerChoice::Embedded(path) => {
                let model = newt_inference::palette::default_model().name.to_string();
                // url/key are unused for the in-process embedded engine.
                return (
                    String::new(),
                    model,
                    newt_core::BackendKind::Embedded,
                    None,
                    Some(path),
                );
            }
            SummarizerChoice::DegradedSession => {
                static WARNED: std::sync::atomic::AtomicBool =
                    std::sync::atomic::AtomicBool::new(false);
                warn_summarizer_once(&WARNED, "warning: the on-host embedded CPU summarizer is unavailable — context compaction will REUSE THE SESSION MODEL (on the GPU), which contends with the primary model under load and can stall the turn (see #979/#661). Enable it: `newt models pull`, and build with the `embedded` feature.");
            }
        }
    }

    // Override, or degraded fallback: reuse the session backend (or a pinned
    // off-box backend). Each present `summarizer.toml` field overrides the
    // session value; the session params are read live so a mid-session
    // `/backend` switch still carries a session-reusing summarizer along.
    let url = sum_cfg
        .endpoint
        .clone()
        .unwrap_or_else(|| inf_url.to_string());
    let model = sum_cfg
        .model
        .clone()
        .unwrap_or_else(|| inf_model.to_string());
    let kind = sum_cfg.kind.unwrap_or(inf_kind);
    let model_path = sum_cfg.model_path.clone();
    // A bearer token authenticates a specific host. Only inherit the session
    // key when the summarizer reuses the session endpoint; never leak it to a
    // pinned different host.
    let key = if sum_cfg.endpoint.is_some() {
        sum_cfg.resolve_api_key()
    } else {
        sum_cfg.resolve_api_key().or_else(|| inf_key.clone())
    };
    // Warn once when an explicit override picks a NON-embedded backend (embedded
    // is the default; a session/off-box override can contend with the primary).
    if has_override && !matches!(kind, newt_core::BackendKind::Embedded) {
        static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
        warn_summarizer_once(&WARNED, "warning: using a summarizer OVERRIDE (session / off-box) instead of the on-host embedded CPU default — this can contend with the primary model under load (#661). Drop the `[summarizer]` backend override to use the embedded engine.");
    }
    (url, model, kind, key, model_path)
}

#[cfg(test)]
#[path = "lib_tests/summarizer_default_tests.rs"]
mod summarizer_default_tests;

/// Whether a SESSION-INHERITING summarizer — one that resolves onto the active
/// inference backend, including the degraded fallback when the embedded engine
/// is unavailable — must FOLLOW a live `/model` / `/backend` switch, as opposed
/// to an explicitly PINNED one that stays fixed.
///
/// This is the ownership rule made explicit in ONE place; it mirrors
/// [`resolve_summarizer_backend`]'s pinned-vs-inherited decision:
///
/// - No `[summarizer]` override + embedded engine available → the in-process
///   embedded summarizer, independent of the session → does NOT follow.
/// - No override + embedded UNavailable → degraded reuse of the session backend
///   → follows.
/// - A pinned endpoint, a pinned `kind = "embedded"`, or a pinned `model_path`
///   → an independent backend → does NOT follow.
/// - A partial override that leaves the endpoint to inherit `inf_url` (e.g. only
///   a model name pinned) → still targets the session backend → follows.
fn summarizer_follows_session(
    sum_cfg: &newt_core::SummarizerConfig,
    embedded_gguf: Option<String>,
) -> bool {
    let has_override = sum_cfg.kind.is_some()
        || sum_cfg.endpoint.is_some()
        || sum_cfg.model.is_some()
        || sum_cfg.model_path.is_some();
    if !has_override {
        return matches!(
            default_summarizer_choice(embedded_gguf),
            SummarizerChoice::DegradedSession
        );
    }
    sum_cfg.endpoint.is_none()
        && sum_cfg.kind != Some(newt_core::BackendKind::Embedded)
        && sum_cfg.model_path.is_none()
}

/// Build a loop summarizer for the current session backend, applying any
/// `~/.newt/summarizer.toml` backend + knob overrides (Step 24.10). The single
/// seam every summarizer call site goes through.
#[allow(clippy::too_many_arguments)]
fn build_session_summarizer(
    sum_cfg: &newt_core::SummarizerConfig,
    cfg: &newt_core::Config,
    inf_url: &str,
    inf_model: &str,
    inf_kind: newt_core::BackendKind,
    inf_key: &Option<String>,
    num_ctx: Option<u32>,
    color: bool,
    // #2313 b3: the session's shared run allowance (`None` when unconfigured),
    // so this summarizer's own dispatch draws from the same budget the
    // primary loop's `ChatCtx.run_allowance` reserves against.
    run_allowance: Option<std::sync::Arc<newt_core::agentic::run_allowance::RunAllowance>>,
) -> newt_core::Summarizer {
    let (url, model, kind, key, model_path) = resolve_summarizer_backend(
        sum_cfg,
        inf_url,
        inf_model,
        inf_kind,
        inf_key,
        embedded_summarizer_default(),
    );
    let opts = SummarizerOpts {
        run_allowance,
        ..summarizer_opts(sum_cfg, cfg, num_ctx, color)
    };
    let caps = opts.caps;
    let summarizer = make_loop_summarizer(url, model, kind, key, model_path, opts);
    with_summary_progress(summarizer, caps, color)
}

/// One progress row covers warmup, retries, fallback, and embedded inference.
/// The shared spinner releases it when the summary finishes or is cancelled.
fn with_summary_progress(
    summarizer: newt_core::Summarizer,
    caps: newt_core::tty::LineCaps,
    color: bool,
) -> newt_core::Summarizer {
    Box::new(move |prompt| {
        Box::pin(newt_core::tty::with_spinner(
            caps,
            "summarizing context…",
            newt_core::tty::Sink::Stdout,
            color,
            summarizer(prompt),
        ))
    })
}

#[cfg(test)]
#[path = "lib_tests/compaction_progress_tests.rs"]
mod compaction_progress_tests;

/// Build the decision adjudicator (#1749).
///
/// Defaults to the **session** backend: adjudication decides whether the
/// operator delegated a choice, which is the steering model's own job and wants
/// the model that already holds the prompt. It deliberately does NOT ride the
/// summarizer — that one defaults to CPU-local inference precisely to keep
/// compaction load off the inference box, which makes it the wrong host for
/// reading intent.
///
/// `[intake.adjudicator]` overrides it field-by-field for an operator who wants
/// to spread load; `BackendRef::resolve` applies the "never inherit the session
/// key to a pinned host" rule.
pub(crate) fn build_adjudicator(
    cfg: &newt_core::Config,
    inf_url: &str,
    inf_model: &str,
    inf_kind: newt_core::BackendKind,
    inf_key: &Option<String>,
    num_ctx: Option<u32>,
    color: bool,
) -> newt_core::Summarizer {
    let (url, model, kind, key) = cfg
        .intake
        .as_ref()
        .and_then(|intake| intake.adjudicator.as_ref())
        .map_or_else(
            || {
                (
                    inf_url.to_string(),
                    inf_model.to_string(),
                    inf_kind,
                    inf_key.clone(),
                )
            },
            |over| over.resolve(inf_url, inf_model, inf_kind, inf_key),
        );
    let opts = SummarizerOpts {
        num_ctx,
        color,
        caps: newt_core::tty::LineCaps::detect(),
        ..SummarizerOpts::default()
    };
    make_loop_summarizer(url, model, kind, key, None, opts)
}

/// Whether to render assistant Markdown this turn (Step 25.4, #568). The
/// session `/markdown` override wins over `[tui].markdown`; either way the
/// result is gated by `color` (Markdown emits ANSI, so it is off without color).
/// Whether Markdown renders right now.
///
/// # The `session` parameter is gone (#2009 PR4)
///
/// It was a `run_chat` local threaded through nine call sites, which meant the
/// session's override was invisible to anything outside that loop — including
/// `settings_form::apply`, which is exactly what had to see it for `/markdown`
/// to become a field. `session_markdown_mode` owns the precedence now, so this
/// asks it rather than being told.
///
/// `cfg` stays a parameter: callers already hold the resolved config, and the
/// resolver falls back to `Config::resolve()` only when nobody has.
fn markdown_enabled(cfg: &newt_core::Config, color: bool) -> bool {
    let mode = if newt_core::config::markdown_is_session_pinned() {
        crate::migration_notices::read(newt_core::config::session_markdown_mode)
    } else {
        cfg.tui.as_ref().map(|t| t.markdown).unwrap_or_default()
    };
    mode.forced().unwrap_or(color) && color
}

/// Resolve the active context manager (Step 24.8, #559): session override
/// (`/context manager`) → `[context].manager` → `standard`.
fn context_manager(
    cfg: &newt_core::Config,
    session: Option<newt_core::ContextManager>,
) -> newt_core::ContextManager {
    session
        .or_else(|| cfg.context.as_ref().map(|c| c.manager))
        .unwrap_or_default()
}

/// Resolve the automatic-compaction trigger policy: the interactive-session
/// override (`/context compaction`) wins over `[context]`, which in turn falls
/// back to the safe headroom-aware default.
/// The effective compaction trigger policy.
///
/// # The `session` parameter is gone (#2009 PR7)
///
/// It was a `run_chat` local threaded through seven call sites, so the
/// session's override was invisible to anything outside that loop — including
/// `settings_form::apply`, which is exactly what had to see it for
/// `/context compaction` to become a field. `session_compaction_trigger_policy`
/// owns the precedence now, so this asks rather than being told.
fn compaction_trigger_policy(cfg: &newt_core::Config) -> newt_core::CompactionTriggerPolicy {
    if newt_core::config::compaction_trigger_is_session_pinned() {
        return crate::migration_notices::read(
            newt_core::config::session_compaction_trigger_policy,
        );
    }
    configured_compaction_trigger_policy(cfg)
}

/// The policy IGNORING any session pin — what `reset` would fall back to.
///
/// Named rather than expressed as `compaction_trigger_policy(cfg, None)`,
/// which is how it read while the override was a parameter. With the override
/// global there is no `None` to pass, and "resolve as if unpinned" is a real
/// question with one answer instead of an argument someone has to get right.
fn configured_compaction_trigger_policy(
    cfg: &newt_core::Config,
) -> newt_core::CompactionTriggerPolicy {
    cfg.context
        .as_ref()
        .map(|c| c.compaction_trigger_policy)
        .unwrap_or_default()
}

/// Human-readable provenance for [`compaction_trigger_policy`]. A present
/// `[context]` section is the closest provenance the deserialized config can
/// preserve; TOML does not retain whether an individual defaulted field was
/// explicitly written.
fn compaction_trigger_policy_source(cfg: &newt_core::Config) -> &'static str {
    if newt_core::config::compaction_trigger_is_session_pinned() {
        "session"
    } else if cfg.context.is_some() {
        "config"
    } else {
        "default"
    }
}

/// Resolve the effective context-feature set (Step 26.1, #588): the `manager`
/// preset's base bundle → `[context.features]` config overrides → session
/// (`/context feature`) overrides.
fn context_features(
    cfg: &newt_core::Config,
    manager: newt_core::ContextManager,
    session: &newt_core::ContextFeatures,
    kind: newt_core::BackendKind,
) -> newt_core::ContextFeatureSet {
    // Step 27.4: the base depends on the backend — local (Ollama) sessions
    // default the local-assist features (scratchpad + semantic + scheduled) ON;
    // cloud keeps the all-off preset baseline. `[context.features]` config then
    // session overrides still layer on top and win.
    let base = newt_core::ContextFeatureSet::base_for(manager, kind);
    let with_config = cfg
        .context
        .as_ref()
        .map(|c| c.features)
        .unwrap_or_default()
        .apply_to(base);
    session.apply_to(with_config)
}

/// Outcome of a `/context …` command (Step 26.1, #588). Pure — no stdout, no
/// mutation — so the dispatch logic is unit-testable: the caller prints `lines`
/// and applies any `set_manager` / `set_feature` to the session overrides.
#[derive(Debug, Default, PartialEq, Eq)]
struct ContextCommandResult {
    lines: Vec<String>,
    set_manager: Option<newt_core::ContextManager>,
    set_feature: Option<(newt_core::ContextFeature, bool)>,
    /// `/context size <N>` session budget override; `Some(0)` clears it back
    /// to the probed / configured value.
    set_budget: Option<u32>,
    /// `/context compaction …` mutation. The explicit `Reset` variant keeps a
    /// reset distinguishable from a command that simply leaves the override
    /// alone.
    set_compaction_trigger_policy: Option<CompactionTriggerPolicyOverride>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CompactionTriggerPolicyOverride {
    Set(newt_core::CompactionTriggerPolicy),
    Reset,
}

fn handle_context_feature_arg(
    arg: &str,
    features: newt_core::ContextFeatureSet,
    out: &mut ContextCommandResult,
) {
    use newt_core::ContextFeature;
    let mut parts = arg.split_whitespace();
    let name = parts.next().unwrap_or("");
    let toggle = parts.next();
    match ContextFeature::from_keyword(name) {
        Some(f) => match toggle {
            None => {
                let state = if features.get(f) { "on" } else { "off" };
                let tail = if f.available() {
                    String::new()
                } else {
                    format!(" (not yet available — #{})", f.issue())
                };
                out.lines
                    .push(format!("context feature {}: {state}{tail}", f.keyword()));
            }
            Some(t @ ("on" | "off")) => {
                let want = t == "on";
                if f.available() {
                    out.set_feature = Some((f, want));
                    out.lines
                        .push(format!("context feature {} → {t}", f.keyword()));
                } else {
                    // Report the ACTUAL resolved state, not a hardcoded "off" —
                    // config can force an unimplemented feature on, and the
                    // toggle (which we refuse) doesn't change it.
                    let state = if features.get(f) { "on" } else { "off" };
                    out.lines.push(format!(
                        "context feature '{}' is not yet available (see #{}) — staying {state}",
                        f.keyword(),
                        f.issue()
                    ));
                }
            }
            Some(other) => out.lines.push(format!(
                "unknown toggle '{other}' for /context feature — use on|off"
            )),
        },
        None => out.lines.push(format!(
            "unknown context feature '{name}' — use {}",
            ContextFeature::ALL
                .iter()
                .map(|f| f.keyword())
                .collect::<Vec<_>>()
                .join("|")
        )),
    }
}

/// Dispatch `/context [manager <preset> | feature <name> [on|off] | compaction
/// <policy>]` against the current config + session overrides (Step 26.1, #588).
/// `rest` is the text after `context`. Unavailable presets/features report
/// "not yet available" and are NOT applied.
fn handle_context_command(
    rest: &str,
    cfg: &newt_core::Config,
    manager_override: Option<newt_core::ContextManager>,
    feature_override: &newt_core::ContextFeatures,
    kind: newt_core::BackendKind,
) -> ContextCommandResult {
    use newt_core::{ContextFeature, ContextManager};
    let rest = rest.trim();
    let manager = context_manager(cfg, manager_override);
    let features = context_features(cfg, manager, feature_override, kind);
    let compaction_policy = compaction_trigger_policy(cfg);
    let compaction_policy_source = compaction_trigger_policy_source(cfg);
    let mgr_src = if manager_override.is_some() {
        "session"
    } else {
        "config"
    };
    let feat_summary = || {
        let on = features.enabled();
        if on.is_empty() {
            "none".to_string()
        } else {
            // Honest: a feature can be config-forced on before it's implemented;
            // mark those as pending so "on" never implies "actually running".
            on.iter()
                .map(|f| {
                    if f.available() {
                        f.keyword().to_string()
                    } else {
                        format!("{} (pending #{})", f.keyword(), f.issue())
                    }
                })
                .collect::<Vec<_>>()
                .join(", ")
        }
    };
    let mut out = ContextCommandResult::default();

    if rest.is_empty() {
        out.lines.push(format!(
            "context manager: {} ({mgr_src}); features on: {}",
            manager.keyword(),
            feat_summary()
        ));
        out.lines.push(format!(
            "compaction trigger policy: {} ({compaction_policy_source})",
            compaction_policy.keyword()
        ));
        out.lines.push(
            "  /context manager <preset>  ·  /context feature <name> [on|off]  ·  \
             /context compaction [headroom_aware|message_count|reset]  ·  /context stats"
                .to_string(),
        );
    } else if rest == "size" {
        out.lines.push(
            "context size: use /context size <N> to set the per-turn send \
             budget (tokens), or /context size reset to restore the auto-sized value"
                .to_string(),
        );
    } else if let Some(arg) = rest.strip_prefix("size ") {
        let arg = arg.trim();
        if arg == "reset" || arg == "auto" || arg == "0" {
            out.set_budget = Some(0);
            out.lines
                .push("context size → reset (auto-sized budget)".to_string());
        } else {
            match arg.parse::<u32>() {
                Ok(n) if n > 0 => {
                    out.set_budget = Some(n);
                    out.lines
                        .push(format!("context size → {n} tokens (session override)"));
                }
                _ => out.lines.push(format!(
                    "invalid context size '{arg}' — use a positive token count or 'reset'"
                )),
            }
        }
    } else if rest == "manager" {
        out.lines.push(format!(
            "context manager: {} ({mgr_src}) — \
             use /context manager standard|append-only|progressive|distributed",
            manager.keyword()
        ));
    } else if let Some(name) = rest.strip_prefix("manager ") {
        match ContextManager::from_keyword(name.trim()) {
            Some(m) if m.available() => {
                out.set_manager = Some(m);
                out.lines.push(format!("context manager → {}", m.keyword()));
            }
            Some(m) => out.lines.push(format!(
                "context manager '{}' is not yet available (see #546) — staying on {}",
                m.keyword(),
                manager.keyword()
            )),
            None => out.lines.push(format!(
                "unknown context manager '{}' — use standard|append-only|progressive|distributed",
                name.trim()
            )),
        }
    } else if rest == "compaction" {
        out.lines.push(format!(
            "compaction trigger policy: {} ({compaction_policy_source}) — \
             use /context compaction headroom_aware|message_count|reset",
            compaction_policy.keyword()
        ));
    } else if let Some(policy) = rest.strip_prefix("compaction ") {
        let policy = policy.trim();
        if policy.eq_ignore_ascii_case("reset") {
            out.set_compaction_trigger_policy = Some(CompactionTriggerPolicyOverride::Reset);
            // The PREVIEW is deliberately unpinned: this line says what the
            // policy becomes after the reset the caller is about to apply, and
            // the pin is still installed while this runs.
            let reset_policy = configured_compaction_trigger_policy(cfg);
            let reset_source = if cfg.context.is_some() {
                "config"
            } else {
                "default"
            };
            out.lines.push(format!(
                "compaction trigger policy → {} ({reset_source})",
                reset_policy.keyword()
            ));
        } else if let Some(policy) = newt_core::CompactionTriggerPolicy::from_keyword(policy) {
            out.set_compaction_trigger_policy = Some(CompactionTriggerPolicyOverride::Set(policy));
            out.lines.push(format!(
                "compaction trigger policy → {} (session override)",
                policy.keyword()
            ));
        } else {
            out.lines.push(format!(
                "unknown compaction trigger policy '{policy}' — \
                 use headroom_aware|message_count|reset"
            ));
        }
    } else if rest == "feature" || rest == "features" {
        out.lines.push("context features:".to_string());
        for f in ContextFeature::ALL {
            let state = if features.get(f) { "on " } else { "off" };
            let tail = if f.available() {
                String::new()
            } else {
                format!("  (not yet available — #{})", f.issue())
            };
            out.lines.push(format!("  [{state}] {}{tail}", f.keyword()));
        }
    } else if let Some(arg) = rest.strip_prefix("feature ") {
        handle_context_feature_arg(arg, features, &mut out);
    } else if let Some(head) = rest.split_whitespace().next() {
        if ContextFeature::from_keyword(head).is_some() {
            handle_context_feature_arg(rest, features, &mut out);
        } else {
            out.lines.push(format!(
                "unknown /context subcommand '{rest}' — \
                 use /context [manager <preset> | feature <name> [on|off] | \
                 compaction <policy> | size <N> | show | stats]"
            ));
        }
    } else {
        out.lines.push(format!(
            "unknown /context subcommand '{rest}' — \
             use /context [manager <preset> | feature <name> [on|off] | \
             compaction <policy> | size <N> | show | stats]"
        ));
    }
    out
}

/// Render the `/context stats` experimentation dashboard (Step 26.2, #588).
/// Composes the live context budget (the 24.5/24.6 gauge state), the
/// compression counters, the effective automatic-compaction policy, and the
/// resolved feature set with per-feature impact. Pure → unit-testable.
/// `tool_offload_impact` = `(spills, offloaded_chars)` from the session spill
/// store (Step 26.3); other features instrument as they land (26.4+).
#[allow(clippy::too_many_arguments)] // gauge + counters + policy + features + one impact tuple per feature
fn context_stats_text(
    gauge: Option<(u32, Option<u32>)>,
    counters: &newt_core::CompressCounters,
    compaction_policy: newt_core::CompactionTriggerPolicy,
    compaction_policy_source: &str,
    features: newt_core::ContextFeatureSet,
    tool_offload_impact: Option<(u64, u64)>,
    scratchpad_impact: Option<(u64, u64)>,
    semantic_impact: Option<(u64, u64)>,
    experiential_impact: Option<(u64, u64)>,
    scheduled_impact: Option<(u64, u64)>,
) -> Vec<String> {
    let mut lines = vec!["context stats".to_string()];
    // Live send-budget fill (None until a turn has reported usage). #2466:
    // `budget: None` means no context window is known — no percentage to
    // report, just `used/?`.
    match gauge {
        Some((used, Some(budget))) if budget > 0 => {
            let pct = (u64::from(used) * 100 / u64::from(budget)) as u32;
            lines.push(format!(
                "  budget: {} ({pct}% of the send window)",
                newt_core::agentic::fmt_token_gauge(used, Some(budget))
            ));
        }
        Some((used, None)) => lines.push(format!(
            "  budget: {} (no context window known)",
            newt_core::agentic::fmt_token_gauge(used, None)
        )),
        _ => lines.push("  budget: not yet measured (no completed turn)".to_string()),
    }
    lines.push(format!(
        "  automatic compaction: {} ({compaction_policy_source})",
        compaction_policy.keyword()
    ));
    // Compression activity — reuse the /memory anti-thrash section verbatim.
    for l in memory_compress_section(counters).lines() {
        lines.push(l.to_string());
    }
    // Feature states + per-feature impact (the experimentation payoff).
    lines.push("  features:".to_string());
    for f in newt_core::ContextFeature::ALL {
        let state = if features.get(f) { "on " } else { "off" };
        let tail = if f.available() {
            String::new()
        } else {
            format!("  (pending #{})", f.issue())
        };
        let mut line = format!("    [{state}] {}{tail}", f.keyword());
        // Step 26.3: tool_offload's measured impact this session.
        if f == newt_core::ContextFeature::ToolOffload {
            if let Some((spills, chars)) = tool_offload_impact {
                line.push_str(&format!(
                    "  — {spills} offloaded (~{}k chars elided)",
                    chars / 1000
                ));
            }
        }
        // Step 26.4: scratchpad's measured impact this session.
        if f == newt_core::ContextFeature::Scratchpad {
            if let Some((keys, chars)) = scratchpad_impact {
                line.push_str(&format!("  — {keys} keys (~{}k chars)", chars / 1000));
            }
        }
        // Step 26.5: semantic's measured impact this session.
        if f == newt_core::ContextFeature::Semantic {
            if let Some((chunks, chars)) = semantic_impact {
                line.push_str(&format!(
                    "  — {chunks} chunks indexed (~{}k chars)",
                    chars / 1000
                ));
            }
        }
        // Step 26.6a: experiential's measured impact this session.
        if f == newt_core::ContextFeature::Experiential {
            if let Some((n, chars)) = experiential_impact {
                line.push_str(&format!("  — {n} experiences (~{}k chars)", chars / 1000));
            }
        }
        // Step 26.6b: scheduled's plan progress this session.
        if f == newt_core::ContextFeature::Scheduled {
            if let Some((steps, done)) = scheduled_impact {
                line.push_str(&format!("  — {done}/{steps} plan steps done"));
            }
        }
        lines.push(line);
    }
    lines
}

/// Mid-loop message-trim threshold from `[tui].mid_loop_trim_threshold` (default 40).
///
/// Clamped to `max_tool_rounds - 3` so the safety valve always fires before the
/// round ceiling. With both canonical defaults at 40, trimming starts at round
/// 37 instead of colliding with the ceiling.
fn mid_loop_trim_threshold(cfg: &newt_core::Config) -> usize {
    let threshold = cfg
        .tui
        .as_ref()
        .map(|t| t.mid_loop_trim_threshold)
        .unwrap_or_else(|| newt_core::TuiConfig::default().mid_loop_trim_threshold);
    threshold.min(max_tool_rounds(cfg).saturating_sub(3))
}

/// Build-check command from `[tui].build_check_cmd`. `None` means no auto-check.
fn build_check_cmd(cfg: &newt_core::Config) -> Option<String> {
    cfg.tui.as_ref().and_then(|t| t.build_check_cmd.clone())
}

/// Print the telemetry summary line after an inference turn.
fn print_metrics(metrics: &newt_core::TurnMetrics, color: bool) {
    let line = metrics.display_line();
    if color {
        execute!(
            io::stdout(),
            SetForegroundColor(CtColor::DarkGrey),
            Print(format!("  {line}\n")),
            ResetColor,
        )
        .ok();
    } else {
        println!("  {line}");
    }
    io::stdout().flush().ok();
}

fn print_thinking(color: bool) {
    if color {
        // Frame-0 placeholder matching the animated spinner the inference loop
        // takes over (newt-core animates the probe wait in place), so there is
        // no glyph jump between this instant feedback and the live line.
        //
        // #1413: taken from the canonical frame set rather than written as a
        // literal. The "no glyph jump" promise above is only true if this glyph
        // and the one newt-core animates come from the same array — a literal
        // makes that a coincidence maintained by hand.
        execute!(
            io::stdout(),
            SetForegroundColor(CtColor::DarkGrey),
            Print(format!("{} thinking…", newt_core::tty::SPINNER_FRAMES[0])),
            ResetColor,
        )
        .ok();
        io::stdout().flush().ok();
    }
}

fn erase_line() {
    // Clear-to-end-of-line: the animated thinking line ("⏳ ⠋ thinking… 12.3s")
    // can be wider than a fixed blank run, so `\x1b[K` wipes whatever is there.
    //
    // #1413 — STILL ARBITER-BYPASSING, deliberately, and here is why the
    // obvious fix is wrong.
    //
    // This erase pairs with `print_thinking` (~800 lines up in `run_chat`), so
    // the row is ephemeral for the whole turn. The tempting fix is to hold a
    // `Terminal::lease` across that span and let `LineLease::drop` erase. It
    // would deadlock the spinner: `lease` is exclusive on `Inner.line_held`,
    // and `print_thinking`'s own comment says newt-core "takes over" this row —
    // `Spinner::start_with_caps` inside `stream_response` leases it. A
    // turn-length lease here starves that call for `LEASE_WAIT` and it returns
    // `None`: no thinking spinner, every turn. That is the same failure mode
    // rejected for the live-spill viewport in #1410.
    //
    // The real fix is to model the HANDOFF — newt-tui paints a placeholder,
    // newt-core adopts the same row — which is #1312's spinner migration, not a
    // local change. Until then this stays open-coded, and the pairing above is
    // the reason, not an oversight.
    print!("\r\x1b[K");
    io::stdout().flush().ok();
}

// ---------------------------------------------------------------------------
// Esc-to-interrupt: watch the keyboard during a turn and trip a cancel flag.
//
// The turn (`chat_complete`) runs in-place — it borrows half the session, so it
// can't move to a background task. Instead a sibling OS thread watches stdin and
// flips an `AtomicBool` the loop polls at its await checkpoints. The terminal is
// put in *cbreak* (ICANON+ECHO off) so a keypress arrives immediately, but ISIG
// and OPOST stay ON: Ctrl-C still signals as before, and streamed model output
// still gets CR-NL translation (no staircase) while we watch.
// ---------------------------------------------------------------------------

/// A lone `Esc` (`0x1b`) is the interrupt; `Esc [` / `Esc O` begin an arrow /
/// function-key sequence, and `Esc <char>` is an Alt-chord — neither interrupts.
/// Terminals deliver a real Esc press as a single `0x1b` byte, so an exact match
/// cleanly separates it from a multi-byte escape sequence read in one burst.
/// Unix-only: the keyboard watcher (its sole caller) needs termios.
#[cfg(unix)]
fn is_lone_esc(bytes: &[u8]) -> bool {
    bytes == [0x1b]
}

/// Ctrl-C arrives as `ETX` (`0x03`) once ISIG is off (see `CbreakGuard`). We
/// treat an interrupt as `0x03` appearing ANYWHERE in the read buffer, not only
/// as a lone `[0x03]` (#1303 FIX A): a single 64-byte read can coalesce the
/// `0x03` with other bytes — e.g. a trailing SGR-mouse event `ESC[<..M` under
/// motion, or fast typed-ahead — and an exact-match check would silently drop
/// the cancel. `0x03` never occurs inside a legitimate keystroke burst (escape
/// sequences use `0x1b`/`[`/digits; text is printable), so scanning is safe.
/// Unix-only: the keyboard watcher (its sole caller) needs termios.
#[cfg(unix)]
fn is_ctrl_c(bytes: &[u8]) -> bool {
    bytes.contains(&0x03)
}

// The trait itself stays available on every platform: `chat.rs` names
// `Option<&dyn SpillInput>` unconditionally to type the spill handle it
// threads through `with_live_spill_watch`. Only its methods — driven by the
// unix-only keyboard watcher (`dispatch_turn_keys`, `watch_for_interrupt_fd`)
// — are unix-gated, so a non-unix build never has an unused-method warning.
pub(crate) trait SpillInput: Sync {
    #[cfg(unix)]
    fn scroll_up(&self) -> bool;
    #[cfg(unix)]
    fn scroll_down(&self) -> bool;
    #[cfg(unix)]
    fn toggle_expanded(&self) -> bool;
    /// #1704: expand the viewport to half the visible console height.
    #[cfg(unix)]
    fn expand_half(&self) -> bool;
    /// #1704: is the user scrolled back (explore mode, not following the tail)?
    #[cfg(unix)]
    fn is_exploring(&self) -> bool;
    /// #1704: leave explore mode — snap back to following the tail.
    #[cfg(unix)]
    fn exit_explore(&self) -> bool;
    #[cfg(unix)]
    fn refresh_geometry(&self) -> bool;
    // #1303 step 5: editor-mode nav targets (vi `gg`/`G`/`C-d`/`C-u`, emacs
    // paging). Gated with their dispatch arms so the lean build links none.
    #[cfg(all(unix, feature = "live-spill"))]
    fn scroll_to_top(&self) -> bool;
    #[cfg(all(unix, feature = "live-spill"))]
    fn scroll_to_bottom(&self) -> bool;
    #[cfg(all(unix, feature = "live-spill"))]
    fn half_page_up(&self) -> bool;
    #[cfg(all(unix, feature = "live-spill"))]
    fn half_page_down(&self) -> bool;
}

#[cfg(feature = "live-spill")]
impl SpillInput for live_spill::LiveSpillRenderer {
    #[cfg(unix)]
    fn scroll_up(&self) -> bool {
        self.scroll_up()
    }

    #[cfg(unix)]
    fn scroll_down(&self) -> bool {
        self.scroll_down()
    }

    #[cfg(unix)]
    fn toggle_expanded(&self) -> bool {
        self.toggle_expanded()
    }

    #[cfg(unix)]
    fn expand_half(&self) -> bool {
        self.expand_half()
    }

    #[cfg(unix)]
    fn is_exploring(&self) -> bool {
        self.is_exploring()
    }

    #[cfg(unix)]
    fn exit_explore(&self) -> bool {
        self.exit_explore()
    }

    #[cfg(unix)]
    fn refresh_geometry(&self) -> bool {
        self.refresh_geometry()
    }

    #[cfg(unix)]
    fn scroll_to_top(&self) -> bool {
        self.scroll_to_top()
    }

    #[cfg(unix)]
    fn scroll_to_bottom(&self) -> bool {
        self.scroll_to_bottom()
    }

    #[cfg(unix)]
    fn half_page_up(&self) -> bool {
        self.half_page_up()
    }

    #[cfg(unix)]
    fn half_page_down(&self) -> bool {
        self.half_page_down()
    }
}

// ---------------------------------------------------------------------------
// Slash command dispatcher
// ---------------------------------------------------------------------------

/// `(topic, arg)` from a slash line if it is asking for help — `/<cmd> --help`,
/// `/<cmd> -h`, `/<cmd> help`, or `/help <cmd>`. `None` when it's an ordinary
/// command. Pure so the dispatch interception is unit-testable.
fn help_request(task: &str) -> Option<String> {
    let body = task.trim_start_matches('/');
    let mut parts = body.split_whitespace();
    let cmd = parts.next().unwrap_or("");
    let rest: Vec<&str> = parts.collect();
    if cmd == "help" {
        // `/help <cmd>` → that cmd's page; bare `/help` is the full list (None).
        return rest.first().map(|c| c.to_string());
    }
    let is_help_token = |a: &&str| matches!(*a, "--help" | "-h" | "help");
    // #1030: `/start`, `/rename` and its `/name` alias take a free-text TITLE,
    // so a `help`/`-h`/`--help` token INSIDE a title must NOT be read as a help
    // request — only an invocation whose SOLE argument is the help token asks
    // for help (folded to the page documenting each: /start under /new,
    // /rename under /conversation).
    //
    // **`/name` was missing from this list** until #2009 PR5, so `/name help me
    // debug` opened a help page instead of retitling the conversation. A list
    // of verb names is exactly the shape that goes stale when an alias is
    // added, which is why the settings arm below asks the FIELD instead.
    if matches!(cmd, "start" | "rename" | "name") {
        if rest.len() == 1 && is_help_token(&rest[0]) {
            return Some(
                if cmd == "start" {
                    "new"
                } else {
                    "conversation"
                }
                .to_string(),
            );
        }
        return None;
    }
    // The same rule for a free-text SETTING, arriving through a different
    // door: `/settings prompt "help me"` is a template. Asked of the field, so
    // a future `Text` field is covered without editing this.
    if cmd == "settings" {
        if let Some(field) = rest
            .first()
            .and_then(|f| settings_form::Field::from_token(f))
        {
            if field.takes_free_text() {
                if rest.len() == 2 && is_help_token(&rest[1]) {
                    return Some(cmd.to_string());
                }
                return None;
            }
        }
    }
    if rest.iter().any(is_help_token) {
        return Some(cmd.to_string());
    }
    None
}

/// How a slash command that needs an ANSWER reaches the operator.
///
/// The same shape as `permissions.rs`'s `ask_surface` and `crew_form`'s
/// `Ask`, deliberately: a form needs exactly what a permission question needs.
/// Widening the existing seam is the reuse discipline; a second console path
/// is what produced two live prompts on one screen.
pub(crate) type SlashAsk<'a> = &'a dyn Fn(
    &newt_core::interaction_surface::SurfaceInteraction,
) -> newt_core::HumanQuestionOutcome;

/// The fallback ask for a caller that owns the terminal outright (the plain
/// CLI path, and every test). A cockpit session must NOT use this: it writes
/// under a mounted chat editor that keeps repainting its clock and its live
/// chevron over the question. Sessions pass their surface seam instead.
pub(crate) fn ask_on_this_terminal(
    interaction: &newt_core::interaction_surface::SurfaceInteraction,
) -> newt_core::HumanQuestionOutcome {
    let window =
        newt_core::tty::Terminal::suspend_for_prompt(newt_core::tty::TerminalTaker::SlashForm);
    crate::permissions::present_on_terminal(&window, interaction)
}

/// Dispatch a `/command` line. Returns `true` to keep the session alive,
/// `false` to exit.
///
/// Terminal-owning form: any question is asked on THIS terminal. A session
/// with a mounted surface calls [`dispatch_slash_with_ask`] instead.
///
/// Production has exactly one slash call site (`chat.rs`) and it always has a
/// surface, so this convenience form is the test/CLI shape.
#[cfg(test)]
fn dispatch_slash(
    input: &str,
    workspace: &str,
    color: bool,
    verbose: bool,
    markdown: bool,
) -> anyhow::Result<bool> {
    dispatch_slash_with_ask(input, workspace, color, verbose, markdown, None)
}

/// [`dispatch_slash`], with the surface seam a session presents questions
/// through (#1862 C1). `ask = Some(..)` routes a form's questions to the
/// thread that owns the terminal, which is what dims the chat chevron,
/// reserves the modal's rows, and freezes the header clock for the duration.
fn dispatch_slash_with_ask(
    input: &str,
    workspace: &str,
    color: bool,
    verbose: bool,
    markdown: bool,
    ask: Option<SlashAsk<'_>>,
) -> anyhow::Result<bool> {
    let (cmd, arg1, arg2) = slash_parts(input);

    match cmd {
        "exit" | "quit" | "help" | "version" | "workspace" | "config" => {
            commands::meta::dispatch(cmd, arg1, workspace, color, verbose, markdown)
        }
        "prompt" | "vi" | "emacs" | "nano" | "edit-mode" | "thinking" | "nudge" | "tenacity"
        | "cognition" | "psyche" => {
            commands::settings::dispatch(cmd, arg1, input, workspace, color, verbose)
        }
        "models" | "probe" | "model" | "backend" | "backends" | "summarizer" | "dgx" => {
            commands::model::dispatch(cmd, arg1, arg2, color, verbose)
        }
        // #1981: the typed settings form. Absorbs the knob verbs; every route
        // — form, deep link, deprecated verb — lands on `settings_form::apply`.
        "settings" => {
            // The seam the session supplied, or this terminal when there is no
            // session to ask through. ONE ask path either way.
            let fallback = ask_on_this_terminal;
            let ask: SlashAsk<'_> = ask.unwrap_or(&fallback);
            let rest = format!("{arg1} {arg2}");
            for line in settings_form::run(ask, rest.trim()) {
                print_newt(&line, color, verbose);
            }
            Ok(true)
        }
        "crew" => {
            let fallback = ask_on_this_terminal;
            commands::crew::dispatch(arg1, arg2, color, verbose, ask.unwrap_or(&fallback))
        }
        "setup" => commands::setup::dispatch(arg1, color, verbose),
        // #2515: `/discuss` (and its `/chat` alias) is normally intercepted
        // in the chat loop and routed to the pending clarification before
        // dispatch ever sees it. Reaching here means there is no batch to
        // discuss, so this is the answer for that case — never "unknown
        // command" again.
        "discuss" | "chat" => {
            print_newt(
                "there is no pending decision to discuss right now",
                color,
                verbose,
            );
            Ok(true)
        }
        other => {
            print_newt(&slash_registry::fallthrough_message(other), color, verbose);
            Ok(true)
        }
    }
}

/// Split a slash command into its verb and first two arguments.
///
/// Whitespace between fields is syntax, not an empty argument: `/model  name`
/// must take the same path as `/model name`. The final field keeps embedded
/// whitespace so commands whose second argument is free text retain it.
fn slash_parts(input: &str) -> (&str, &str, &str) {
    let body = input.trim_start_matches('/').trim_start();
    let (cmd, rest) = body.split_once(char::is_whitespace).unwrap_or((body, ""));
    let rest = rest.trim_start();
    let (arg1, arg2) = rest.split_once(char::is_whitespace).unwrap_or((rest, ""));
    (cmd, arg1, arg2.trim())
}

/// Fetch model names from an Ollama endpoint's `/api/tags`.
/// Sync model-listing over any backend API (#backend-trait): builds a client
/// and asks `api_for(kind)`, bridging the async trait via block_in_place. The
/// ONE place the TUI lists models — /models, /model, setup, and doctor all
/// route here instead of each matching on `kind`.
pub(crate) fn fetch_models_for(
    url: &str,
    kind: newt_core::BackendKind,
    api_key: Option<&str>,
) -> anyhow::Result<Vec<String>> {
    tokio::task::block_in_place(|| {
        tokio::runtime::Handle::current().block_on(async {
            let client = reqwest::Client::builder()
                .timeout(std::time::Duration::from_secs(10))
                .build()?;
            newt_core::backend_probe::api_for(kind)
                .list_models(&client, url, api_key)
                .await
        })
    })
}

/// Run `newt <args>` as a subprocess using the current executable path so
/// the command works even when newt is not on PATH. stdout/stderr pass
/// through to the terminal unchanged.
pub(crate) fn run_newt_subcmd(args: &[&str], color: bool, verbose: bool) -> anyhow::Result<()> {
    let exe = std::env::current_exe()?;
    let status = std::process::Command::new(&exe).args(args).status()?;
    if !status.success() {
        print_newt(
            &format!("command exited with status {}", status.code().unwrap_or(-1)),
            color,
            verbose,
        );
    }
    Ok(())
}

/// Split a prompt line into the host command after a leading `!`, or `None`
/// when the line is not a bang-escape (or is just `!` with no command).
///
/// The `!` bang-escape is a HUMAN action in the interactive readline loop — the
/// model has no channel to type at the prompt, so it can never invoke this. It
/// runs on the host with the user's own authority (no OCAP/Caveats leash, which
/// governs only *model*-initiated `run_command`), like typing in a shell. Its
/// purpose is interactive logins such as `! pa login` (browser SAML).
fn bang_command(input: &str) -> Option<&str> {
    let rest = input.strip_prefix('!')?.trim();
    if rest.is_empty() {
        None
    } else {
        Some(rest)
    }
}

/// The user's shell + its "run this string" flag, per platform. Honors `$SHELL`
/// (unix) / `%COMSPEC%` (windows), falling back to the system default. Running
/// through a shell (not bare-exec) gives pipes, redirects, `&&`, and env
/// expansion — matching shell muscle memory.
///
/// Unix uses `-c` (**non-interactive**), NOT `-ic`. An interactive shell enables
/// job control (monitor mode): it grabs the terminal's foreground process group
/// via `tcsetpgrp` and does not reliably restore newt's on exit, leaving newt in
/// the background → `SIGTTOU` on its next TTY write → "suspended (tty output)".
/// `-c` avoids that entirely. PATH is still inherited from the shell that
/// launched newt, so binaries (e.g. `pa`) resolve fine; only `.zshrc`/`.bashrc`
/// aliases and shell *functions* are unavailable. Windows `cmd /C`.
fn bang_shell() -> (String, &'static str) {
    #[cfg(windows)]
    {
        let sh = std::env::var("COMSPEC").unwrap_or_else(|_| "cmd".to_string());
        (sh, "/C")
    }
    #[cfg(not(windows))]
    {
        let sh = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
        (sh, "-c")
    }
}

/// Run a `!`-escaped host command interactively: stdio is **inherited** (the
/// child gets the real TTY, so it can prompt and launch a browser — e.g. the
/// `pa login` SAML flow), output scrolls live, and control returns to the
/// prompt. A non-zero exit prints a thin status line; a spawn failure surfaces
/// the error.
///
/// Interruptibility (unix, TTY): the child runs as its **own foreground process
/// group** — like a shell foreground job. `setpgid` in the child (via
/// `pre_exec`) and `tcsetpgrp` before exec hand the terminal to the child, so
/// a terminal `Ctrl-C` is delivered to the *child's* group, not newt's. The
/// child dies; newt reclaims the terminal and returns to the prompt instead of
/// being killed alongside a hung command (e.g. `! pa login` waiting on a SAML
/// browser round-trip that never completes). `SIGTTOU` is ignored only during
/// each foreground transfer so the `tcsetpgrp` calls cannot stop the caller.
fn run_bang_escape(cmd: &str, color: bool, verbose: bool) {
    let (command, shell) = bang_shell_command(cmd);

    #[cfg(unix)]
    {
        run_bang_escape_unix(command, &shell, color, verbose);
    }
    #[cfg(not(unix))]
    {
        let mut command = command;
        match command.status() {
            Ok(status) if status.success() => {}
            Ok(status) => print_newt(
                &format!("exit {}", status.code().unwrap_or(-1)),
                color,
                verbose,
            ),
            Err(e) => print_newt(&format!("! failed to run `{shell}`: {e}"), color, verbose),
        }
    }
}

#[derive(Debug)]
pub(crate) enum OperatorCommand {
    Shell(String),
    Argv(Vec<String>),
}

impl OperatorCommand {
    #[cfg(all(unix, feature = "rich-tui"))]
    fn prepare(&self) -> io::Result<(std::process::Command, String)> {
        match self {
            Self::Shell(command) => Ok(bang_shell_command(command)),
            Self::Argv(argv) => Ok((operator_argv_command(argv)?, argv[0].clone())),
        }
    }
}

fn operator_argv_command(argv: &[String]) -> io::Result<std::process::Command> {
    let program = argv
        .first()
        .filter(|program| !program.trim().is_empty())
        .ok_or_else(|| {
            io::Error::new(io::ErrorKind::InvalidInput, "login argv requires a program")
        })?;
    let mut command = std::process::Command::new(program);
    command.args(&argv[1..]);
    Ok(command)
}

fn run_login_argv(argv: &[String], color: bool, verbose: bool) -> anyhow::Result<bool> {
    let command = operator_argv_command(argv)?;
    #[cfg(unix)]
    {
        Ok(run_bang_escape_unix(command, &argv[0], color, verbose))
    }
    #[cfg(not(unix))]
    {
        let _ = (color, verbose);
        let mut command = command;
        Ok(command.status()?.success())
    }
}

fn bang_shell_command(cmd: &str) -> (std::process::Command, String) {
    let (shell, flag) = bang_shell();
    let mut command = std::process::Command::new(&shell);
    command.arg(flag).arg(cmd);
    (command, shell)
}

/// Unix launch for `run_bang_escape`: put the child in its own process group and
/// give it the controlling terminal so `Ctrl-C` interrupts the *command* and
/// returns to the newt prompt, rather than felling newt itself. Falls back to a
/// plain inherited-stdio `wait` when stdin has no controlling terminal.
#[cfg(unix)]
fn run_bang_escape_unix(
    mut command: std::process::Command,
    shell: &str,
    color: bool,
    verbose: bool,
) -> bool {
    use std::os::unix::process::CommandExt as _;

    let tty = libc::STDIN_FILENO;
    // Capture the actual foreground owner, not an assumption about our group.
    // A PTY without a controlling session has no job-control handoff to make.
    let foreground = unsafe { libc::tcgetpgrp(tty) };
    if foreground >= 0 {
        // Foreground before exec: otherwise a fast child can read before the
        // parent transfers ownership and stop itself with SIGTTIN. Only libc
        // operations (and OS-error construction) run in the post-fork child.
        unsafe {
            command.pre_exec(move || {
                if libc::setpgid(0, 0) != 0 {
                    return Err(io::Error::last_os_error());
                }
                let old = libc::signal(libc::SIGTTOU, libc::SIG_IGN);
                let changed = libc::tcsetpgrp(tty, libc::getpgrp());
                let error = (changed != 0).then(io::Error::last_os_error);
                libc::signal(libc::SIGTTOU, old);
                error.map_or(Ok(()), Err)
            });
        }
    }
    let status = {
        let _foreground = RestoreOnDrop {
            restore: || {
                if foreground >= 0 {
                    // The parent is background while the child owns the tty.
                    // Ignore SIGTTOU only for the reclaim, restoring its exact
                    // prior disposition even on a failed spawn or wait.
                    unsafe {
                        let old = libc::signal(libc::SIGTTOU, libc::SIG_IGN);
                        libc::tcsetpgrp(tty, foreground);
                        libc::signal(libc::SIGTTOU, old);
                    }
                }
            },
        };
        command.status()
    };

    match status {
        Ok(status) if status.success() => true,
        Ok(status) => {
            // A signalled child (e.g. interrupted by Ctrl-C) has no exit code.
            let msg = match status.code() {
                Some(code) => format!("exit {code}"),
                None => "interrupted".to_string(),
            };
            print_newt(&msg, color, verbose);
            false
        }
        Err(e) => {
            print_newt(&format!("! failed to run `{shell}`: {e}"), color, verbose);
            false
        }
    }
}

// ---------------------------------------------------------------------------
// `/cd` is the one human navigation command (#1096): it moves `session_cwd`,
// the local session working dir shown in the prompt, confined below the start
// dir. The bare `cd`/`pwd`/`ls`/`rm`/`mv`/`mkdir`/`env`/`date` verbs were
// retired — bare human text is a message to the model, and `!` runs the shell.

/// Parse a `/cd` line. `Some("")` for a bare `/cd` (return to root), `Some(arg)`
/// for `/cd <arg>`, and `None` for anything else (`/cdx`, the bare `cd` verb, …).
///
/// # Why `trim_start_matches('/')` and not `strip_prefix("/cd")`
///
/// **The old shape was invisible to the interception-site pin** (#2009 PR2).
/// That guard counts `trim_start_matches('/')` occurrences, because every
/// top-level command reaches its handler through one — so a new command shows
/// up as a new site and forces a registry review. `/cd` reached its handler
/// through a bespoke prefix strip instead, which is exactly how it stayed an
/// unregistered ghost outside every ratchet while being a real, shipped,
/// state-mutating command.
///
/// Splitting the verb from the argument also removes the `/cdate` class of
/// near-miss by construction rather than by a second `strip_prefix(' ')`
/// check: `/cdate` has the verb `cdate`, which is simply not `cd`.
fn cd_command(input: &str) -> Option<&str> {
    let trimmed = input.trim();
    // The `/` is required — bare `cd` was retired (#1096) and is a message to
    // the model. Everything after it is trimmed the way every other command's
    // interception trims it, so `//cd` behaves like `//help` rather than
    // being the one verb in the shell that refuses a doubled slash.
    if !trimmed.starts_with('/') {
        return None;
    }
    let slash_verb = trimmed.trim_start_matches('/');
    let (verb, arg) = slash_verb
        .split_once(char::is_whitespace)
        .map_or((slash_verb, ""), |(v, a)| (v, a.trim()));
    (verb == "cd").then_some(arg)
}

/// Lexically resolve `.` / `..` WITHOUT touching the filesystem, so a symlinked
/// workspace keeps its symlink path (matching the confined shell's intent) and
/// `..` can't be used to climb — escapes are then rejected by the root check.
fn lexical_normalize(p: &std::path::Path) -> std::path::PathBuf {
    let mut out = std::path::PathBuf::new();
    for comp in p.components() {
        match comp {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            c => out.push(c.as_os_str()),
        }
    }
    out
}

/// Resolve `arg` against `session_cwd` and CONFINE it under `root` (the session
/// workspace) — the human suite stays inside the same tree the agent is confined
/// to. `None` when the path escapes the root (can't climb above it).
fn confine_under_root(
    root: &std::path::Path,
    session_cwd: &std::path::Path,
    arg: &str,
) -> Option<std::path::PathBuf> {
    let joined = if arg.is_empty() {
        session_cwd.to_path_buf()
    } else {
        let p = std::path::Path::new(arg);
        if p.is_absolute() {
            p.to_path_buf()
        } else {
            session_cwd.join(p)
        }
    };
    let normalized = lexical_normalize(&joined);
    let root_norm = lexical_normalize(root);
    normalized.starts_with(&root_norm).then_some(normalized)
}

/// Execute `/cd` against `session_cwd`. Never touches the agent's `workspace`,
/// the OCAP fence, or the process cwd. The local `session_cwd` supplies the
/// default for subsequent run_command calls, confined under `root`. A bare
/// `/cd` (empty `arg`) returns to the root.
fn run_cd(arg: &str, session_cwd: &mut std::path::PathBuf, root: &str, color: bool, verbose: bool) {
    if matches!(arg, "--help" | "-h") {
        print_newt(
            "/cd [dir] — change the session working dir (below the start dir); bare /cd returns to the root",
            color,
            verbose,
        );
        return;
    }
    let root_path = std::path::Path::new(root);
    if arg.is_empty() {
        // Bare `/cd` returns to the session root.
        *session_cwd = lexical_normalize(root_path);
        return;
    }
    match confine_under_root(root_path, session_cwd, arg) {
        Some(t) if t.is_dir() => *session_cwd = t,
        Some(t) => print_newt(
            &format!("cd: not a directory: {}", t.display()),
            color,
            verbose,
        ),
        None => print_newt(
            "cd: outside the session root (can't climb above it)",
            color,
            verbose,
        ),
    }
}

#[cfg(test)]
#[path = "lib_tests/cd_tests.rs"]
mod cd_tests;

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

fn resolve_workspace(path: Option<&std::path::Path>) -> String {
    path.map(|p| p.to_string_lossy().into_owned())
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .map(|d| d.to_string_lossy().into_owned())
        })
        .unwrap_or_else(|| "(unknown)".into())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

/// Build a prompt-only [`Persona`] (no role bindings) for tests that only care
/// about the prompt overlay. Mirrors how a plain `.md` with no front-matter
/// loads. Top-level (not inside a test module) so every `#[cfg(test)] mod` can
/// reach it via `super::test_persona`.
#[cfg(test)]
fn test_persona(name: &str, prompt: &str, path: std::path::PathBuf) -> Persona {
    Persona {
        name: name.to_string(),
        prompt: prompt.to_string(),
        path,
        profile: newt_core::RoleProfile {
            prompt: prompt.to_string(),
            ..Default::default()
        },
    }
}

#[cfg(test)]
#[path = "lib_tests/core.rs"]
mod tests;

/// Regression tests for the `run_command` → agent-bridle confined-shell unification.
///
/// The headline property: the WHOLE command is confined under the granted
/// `Caveats`, not just the leading token. On the old leading-token + `sh -c`
/// path, `echo ok && rm -rf /` passed the `echo` check and then ran `rm`
/// directly. Routing through agent-bridle's brush interceptor closes that
/// bypass — every external spawn passes the leash's `before_exec` gate.
#[cfg(test)]
#[path = "lib_tests/run_command_confinement_tests.rs"]
mod run_command_confinement_tests;

/// INTERIM (#297) `--disable-ocap` / `--yolo` session-surfacing + bypass
/// tests — the TUI half of the escape hatch: the loud banner, the
/// `ocap-disabled` permission-log record, and the run_command bypass under
/// the same caveat shapes the confinement tests above pin for flag-off.
/// Removed with the bypass when brush upstreams CommandInterceptor
/// (agent-bridle#20).
#[cfg(test)]
#[path = "lib_tests/disable_ocap_session_tests.rs"]
mod disable_ocap_session_tests;

/// `/ocap propose` (#2679): merge-on-save, exact grammar, session scope.
#[cfg(test)]
#[path = "lib_tests/ocap_propose_tests.rs"]
mod ocap_propose_tests;

// ---------------------------------------------------------------------------
// ManagerNoteSink wiring (Step 19.3, #248) — `/remember` and the model's
// `save_note` tool must hit the SAME MemoryManager → NoteStore write path.
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/note_sink_wiring_tests.rs"]
mod note_sink_wiring_tests;

// ---------------------------------------------------------------------------
// Close-time note extraction (Step 19.4, #248) — one tools-disabled
// completion on /new + clean exit, writing through the scanned note path.
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/close_extraction_tests.rs"]
mod close_extraction_tests;

#[cfg(test)]
#[path = "lib_tests/skills_integration.rs"]
mod skills_integration_tests;

// ---------------------------------------------------------------------------
// Operating modes (`/mode`). These are behavior controls, never authority
// grants; permission floors remain the separate `/posture` concern below.
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "lib_tests/operating_mode_tests.rs"]
mod operating_mode_tests;

#[cfg(test)]
#[path = "lib_tests/plan_draft_state_tests.rs"]
mod plan_draft_state_tests;

// ---------------------------------------------------------------------------
// Named permission presets + `/posture` (issue #307). The `build_posture` core is
// pure (config + an injected skill loader), so the atomic preload-skill +
// apply-preset + framing contract is exercised here without a live session.
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "lib_tests/posture_command_tests.rs"]
mod posture_command_tests;

// ---------------------------------------------------------------------------
// Context-window 400 recovery (issue #223) — the one agentic-loop test that
// stays TUI-side after Step 9.7 moved the loop suites to newt-core::agentic:
// it exercises the TUI's `recover_cw_400` hook (`recover_context_window_400`),
// plus the observation-owned probe-cache persistence that follows it.
// ---------------------------------------------------------------------------
#[cfg(test)]
#[path = "lib_tests/tool_round_cap_tests.rs"]
mod tool_round_cap_tests;

// ---------------------------------------------------------------------------
// fd_exhaustion_tests — verify O_CLOEXEC marking and EMFILE detection
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/terminal_probe_tests.rs"]
mod terminal_probe_tests;

#[cfg(all(test, unix))]
#[path = "lib_tests/fd_exhaustion_tests.rs"]
mod fd_exhaustion_tests;

// ---------------------------------------------------------------------------
// Pure / near-pure helper tests — no network, no env mutation, no real HOME
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/helper_fns.rs"]
mod helper_fn_tests;

// ---------------------------------------------------------------------------
// Persona helper tests — store edge cases + command plumbing
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/tenacity_indicator_tests.rs"]
mod tenacity_indicator_tests;

#[cfg(test)]
#[path = "lib_tests/persona_helper_tests.rs"]
mod persona_helper_tests;

// ---------------------------------------------------------------------------
// Env-var resolution tests — serialized behind a lock because the process
// environment is shared across the parallel test runner.
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/env_resolution.rs"]
mod env_resolution_tests;

// ---------------------------------------------------------------------------
// Model-listing HTTP tests against wiremock backends. (The streaming /
// overflow-retry / mid-loop-trim / final-summary / warm-up suites moved to
// newt-core::agentic with the loop in Step 9.7.)
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "lib_tests/http_loop.rs"]
mod http_loop_tests;

// Model: GPT-5 | Harness: Codex | Operator: Shawn Hartsock | Time: 13:18 EDT | Date: 2026-08-12

// Model: GPT-6 | Harness: Codex | Operator: S Hartsock | Time: 12:23 EDT | Date: 2026-09-15

/// Native-test adapter for exercising the real permission gate in a provider loop.
#[cfg(feature = "native-permission-test")]
#[doc(hidden)]
pub mod native_permission_test;