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
//! The harness **config panel** (issue #14) — behind the `rich-tui` feature.
//!
//! A deliberately-opened, transient ratatui `Viewport::Inline` overlay to adjust
//! the psyche **operator dials** — the active persona, cognition, tenacity and
//! initiative —
//! and to SAVE the current posture as a named persona. **Config only** (renders
//! no agent output); applying a dial writes through the same setters the flags /
//! slash commands use, so there is no panel-only state. Per
//! `docs/decisions/harness_config_panel.md` (Accepted 2026-07-28): severable,
//! TTY-only, no alternate screen (inline region, mirroring #416).
//!
//! ## INTERIM SURFACE (review-2 #3)
//! The key handling here is a small, self-contained ex-command reader — it does
//! NOT yet reuse newt's shared vi/emacs editor core (`rich_input` / `vi`). That
//! is deliberate for this first cut; unifying the two onto a shared
//! semantic-command layer (arrow + vi `hjkl`/`gg`/`G` + emacs `C-p/n/b/f`) is
//! tracked as #1495. Until then this panel is an **interim overlay**.
//!
//! ## Transaction semantics (review-3)
//! Editing → saving → applying → cancelling → reporting are explicit, ordered,
//! and internally consistent — the panel never leaves the runtime partially
//! modified or reports abandoned edits as active:
//!
//! - **Save is I/O-injected** ([`run`] takes a `persist` closure) so the file
//!   write happens *inside* the event loop and can keep the panel open on failure.
//!   The panel shows a status from the returned [`SaveResult`] and only records
//!   success once the write actually succeeded.
//! - **`:wq` commit order** — validate → persist the persona file → apply
//!   cognition/tenacity/initiative → (caller) apply persona + reroute backend → (caller)
//!   recompute + report. A failed persist returns `None` from the command, so the
//!   loop never breaks and [`PanelState::apply`] never runs: no dial, persona, or
//!   backend change happens.
//! - **[`PanelOutcome`] distinguishes cancellation from application.** On
//!   cancel the caller prints "cancelled" (or nothing) — never a posture summary
//!   from the abandoned working copy. After an apply the caller builds the summary
//!   from freshly-resolved runtime state, not from panel-local values.
//! - **Persona preview is projected, not stale** (review-3 §3). Selecting a
//!   persona recomputes the projected effective cognition / initiative / backend /
//!   crew from *that* persona's declarations (over the config/family base), with a
//!   provenance label distinguishing an explicit override from an inherited value
//!   (initiative's family base reads `model default`). Save serializes the
//!   projected posture, except that initiative is written only when it was
//!   chosen (an override or the persona's own declaration): baking a family
//!   default into a persona would pin it on every other model.
//!
//! ## Keys (vi-flavoured; save is explicit, Esc always cancels)
//! - `↑`/`↓` select a dial, `←`/`→` change it (incl. `auto`/`inherit`).
//!   The model row (#1666) spins through the active backend's served models;
//!   its pick is applied by the CALLER through the `/model` path.
//! - `Enter` — apply the changed dials + act on the persona choice, close.
//!   With nothing changed (no dirty dial, persona kept), Enter closes silently
//!   — a no-op visit applies nothing and reports nothing (#1665).
//! - `Esc` / `q` — cancel: discard changes, close (never applies).
//! - `Ctrl-S` or `:w <name>` — save the posture as persona `<name>` (`:w!` to
//!   overwrite). `:wq <name>` — save + apply + close. `:q` — cancel + close.
//!
//! [`PanelState`] is pure and unit-tested; the raw-mode loop ([`run`]) is
//! TUI-drive tested.

use std::io;

use crate::panel::Key;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use newt_core::cognition::{cli_cognition, CognitionOverride};
use newt_core::initiative::{cli_initiative, Initiative};
use newt_core::role_profile::{Cognition, PersonalityLevel, PersonalityTrait, PersonalityTraits};
use newt_core::tenacity::{cli_tenacity, Tenacity};

/// The cognition dial's ladder of OVERRIDE positions: auto (inherit persona or
/// none), then off, then every [`Cognition::all`] level — derived, so a level
/// added to the enum cannot be missing from the dial.
fn cognition_ladder() -> Vec<CognitionOverride> {
    let mut v = vec![CognitionOverride::Unset, CognitionOverride::Off];
    v.extend(Cognition::all().into_iter().map(CognitionOverride::Set));
    v
}

/// A dial's ladder: `None` = auto/inherit (clear the override), then the
/// concrete levels, derived from the enum's `all()`.
fn ladder<T: Copy>(levels: impl IntoIterator<Item = T>) -> Vec<Option<T>> {
    std::iter::once(None)
        .chain(levels.into_iter().map(Some))
        .collect()
}

/// The "no persona" option shown at index 0 of the persona selector.
const NONE: &str = "none";

/// The editable rows, in display order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Row {
    Persona,
    Model,
    Cognition,
    Tenacity,
    Initiative,
    Personality(PersonalityTrait),
}

const ROWS: [Row; 10] = [
    Row::Persona,
    Row::Model,
    Row::Cognition,
    Row::Tenacity,
    Row::Initiative,
    Row::Personality(PersonalityTrait::Agreeableness),
    Row::Personality(PersonalityTrait::Extraversion),
    Row::Personality(PersonalityTrait::Warmth),
    Row::Personality(PersonalityTrait::Approachability),
    Row::Personality(PersonalityTrait::ProsocialBehavior),
];

/// One entry in the model spinner (#1666): a model the active backend serves,
/// plus its cached conformance tag (the same symbol `/models` prints; empty
/// when untested). Built by the caller — the panel stays network-free.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ModelChoice {
    pub(crate) name: String,
    pub(crate) tag: String,
}

/// Everything the CALLER resolves before the panel opens — the panel's input
/// record (one struct rather than a positional list that outgrew clippy's
/// argument limit when #1666 added the model spinner): the selectable
/// personas + the active one, the operator baseline backend, the
/// config/family initiative base, and the served-model list + active model.
pub(crate) struct PanelSeed {
    /// The route the operator actually typed — `/psyche` or `/psyche edit`,
    /// both of which open this panel (see `chat.rs`'s `wants_psyche_panel`).
    ///
    /// Carried rather than assumed: it is what the settings receipt records as
    /// `via`, and the whole value of that column is being the half of the
    /// event a reader cannot reconstruct from the resulting state. Hardcoding
    /// `/psyche` here would journal a route the operator never typed for half
    /// the ways in — a false record, which is worse than none.
    pub via: &'static str,
    pub personas: Vec<PersonaChoice>,
    pub current_persona: Option<String>,
    pub backend: Option<String>,
    /// Initiative with no operator choice and no persona layer
    /// ([`newt_core::initiative::base_initiative`]).
    pub base_initiative: Initiative,
    /// Whether that base is the active model family's entry
    /// ([`newt_core::initiative::model_default_initiative`]), shown as
    /// `model default`.
    pub initiative_from_family: bool,
    pub models: Option<Vec<ModelChoice>>,
    pub current_model: String,
    /// Raw overrides owned by the active tab, not a cached persona profile.
    pub personality: PersonalityTraits,
}

/// A value the operator may have changed: `Inherit` (untouched — do NOT write) or
/// `Set` (dirty — write on apply). Shared with the backend panel (#1667), which
/// follows the same dirty-tracking grammar.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Dial<T> {
    Inherit(T),
    Set(T),
}

impl<T: Copy> Dial<T> {
    pub(crate) fn value(self) -> T {
        match self {
            Self::Inherit(v) | Self::Set(v) => v,
        }
    }
    pub(crate) fn is_dirty(self) -> bool {
        matches!(self, Self::Set(_))
    }
    pub(crate) fn set(&mut self, v: T) {
        *self = Self::Set(v);
    }
}

/// Panel modes: normal navigation, or an ex-command line (`:` / `Ctrl-S`).
#[derive(Debug, Clone, PartialEq, Eq)]
enum Mode {
    Normal,
    Command(String),
}

/// A persona the panel can select. Retain the loaded profile so saving a dial
/// change preserves its prompt and restrictions. `None` is an unavailable
/// active persona, which remains selectable but cannot safely be saved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PersonaChoice {
    pub name: String,
    pub profile: Option<newt_core::RoleProfile>,
}

impl From<crate::Persona> for PersonaChoice {
    fn from(persona: crate::Persona) -> Self {
        Self {
            name: persona.name,
            profile: Some(persona.profile),
        }
    }
}

impl PersonaChoice {
    /// Preview the profile actually active in this session, even if its file
    /// changed or disappeared. Other choices remain the freshly loaded ones.
    pub(crate) fn for_panel(
        loaded: Vec<crate::Persona>,
        active: Option<&crate::Persona>,
    ) -> Vec<Self> {
        let mut choices: Vec<Self> = loaded.into_iter().map(Self::from).collect();
        if let Some(active) = active {
            if let Some(choice) = choices.iter_mut().find(|p| p.name == active.name) {
                *choice = active.clone().into();
            } else {
                choices.push(active.clone().into());
            }
        }
        choices
    }
}

/// What the operator chose to do with the persona selector.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PersonaAction {
    /// Leave the active persona as-is.
    Keep,
    /// Clear the active persona (`/persona clear`).
    Clear,
    /// Activate this persona.
    Switch(String),
}

/// The result of a single save attempt — the panel shows a status from this and
/// records success ONLY when the filesystem write actually succeeded (review-3
/// §1). Produced by the caller's `persist` closure (which owns the `PersonaStore`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SaveResult {
    /// The persona file was written.
    Saved { name: String },
    /// A persona `name` already exists and `!`-overwrite was not requested.
    Exists { name: String },
    /// The name was empty / not a valid file stem.
    InvalidName(String),
    /// The write itself failed (I/O error text).
    Failed(String),
}

/// What the panel returned — cancellation is distinguishable from application
/// (review-3 §2), and there is deliberately NO summary string: the caller reports
/// from freshly-resolved runtime state after committing, never from the panel's
/// (possibly abandoned) working copy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum PanelOutcome {
    /// Esc / `q` / `:q`: discard everything. Nothing was applied.
    Cancelled,
    /// Enter / `:wq`-with-no-save: dials were applied; act on `persona`, and
    /// route `model` (the spinner pick, `None` = untouched) through the same
    /// path `/model <name>` takes — the session owns that state (#1666).
    Applied {
        persona: PersonaAction,
        model: Option<String>,
        /// Only edited axes. An untouched old override must not be resurrected
        /// if the persona action starts a new conversation before application.
        personality: Vec<(PersonalityTrait, Option<PersonalityLevel>)>,
    },
    /// `:w` then cancel: the file was persisted, but dials were NOT applied.
    Saved { name: String },
    /// `:wq`: the file was persisted AND dials were applied; act on `persona`
    /// and `model` exactly as in [`PanelOutcome::Applied`].
    SavedAndApplied {
        name: String,
        persona: PersonaAction,
        model: Option<String>,
        personality: Vec<(PersonalityTrait, Option<PersonalityLevel>)>,
    },
}

/// The panel's working state. Pure: no terminal, no I/O; fully unit-testable.
/// Persistence is injected into [`PanelState::run_command`] as a closure.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct PanelState {
    /// The route that opened this panel, recorded as the receipt's `via`.
    via: &'static str,
    sel: usize,
    /// `NONE` at index 0, then the available persona names (parallel to
    /// [`Self::personas`] shifted by one).
    persona_opts: Vec<String>,
    /// The selectable personas with their declarations, for projection.
    personas: Vec<PersonaChoice>,
    persona_idx: usize,
    /// The persona active when the panel opened (for the "(active)" marker + to
    /// tell Keep from Switch/Clear).
    current_persona: Option<String>,
    cognition: Dial<CognitionOverride>,
    tenacity: Dial<Option<Tenacity>>,
    initiative: Dial<Option<Initiative>>,
    personality: [Dial<Option<PersonalityLevel>>; 5],
    /// The active backend's served models (#1666); `None` = the backend could
    /// not be listed when the panel opened — the row renders but won't dial.
    model_opts: Option<Vec<ModelChoice>>,
    /// Spinner position into `model_opts` (meaningless when `model_opts` is
    /// `None`). Dirty = the operator touched the spinner.
    model: Dial<usize>,
    /// The model the session resolved when the panel opened — the "(active)"
    /// marker + the value a no-op visit leaves untouched.
    current_model: String,
    /// Initiative with no CLI override and no persona layer (config per-family /
    /// default / `Measured`) — the value a persona that declares none inherits.
    base_initiative: Initiative,
    initiative_from_family: bool,
    /// The crew launch gate at open (`NEWT_TEAM`) — the base a persona's `crew:`
    /// declaration projects over.
    base_crew: bool,
    /// The operator BASELINE backend (what a no-backend persona reverts to on
    /// apply) — the projection fallback + save default.
    backend: Option<String>,
    mode: Mode,
    /// Transient status / error line (visible feedback for saves + bad commands).
    status: Option<String>,
    /// The name of the most recent SUCCESSFUL save this session (`None` until a
    /// `:w`/`:wq` write actually lands). Distinct from a proposed edit.
    saved: Option<String>,
}

impl PanelState {
    /// Seed from the live overrides via [`PanelSeed`] — the caller resolves
    /// everything; the panel stays network- and config-free.
    pub(crate) fn new(seed: PanelSeed) -> Self {
        let PanelSeed {
            via,
            mut personas,
            current_persona,
            backend,
            base_initiative,
            initiative_from_family,
            models,
            current_model,
            personality,
        } = seed;
        let current_model = current_model.as_str();
        // Same guarantee as the persona ghost below (#1666): the ACTIVE model is
        // always selectable, even when the backend's list omits it (stale list,
        // model just unloaded) — otherwise opening the panel would silently
        // reposition the spinner and Enter could apply an unchosen model. An
        // empty served list degrades to unreachable (nothing to dial).
        let model_opts = models
            .map(|mut list| {
                if !current_model.is_empty() && !list.iter().any(|m| m.name == current_model) {
                    list.push(ModelChoice {
                        name: current_model.to_string(),
                        tag: "(not served)".to_string(),
                    });
                }
                list
            })
            .filter(|list| !list.is_empty());
        let model_idx = model_opts
            .as_ref()
            .and_then(|list| list.iter().position(|m| m.name == current_model))
            .unwrap_or(0);
        // Guarantee the active persona is selectable. If it isn't in the list
        // (e.g. its file failed to load), append it so it renders "(active)" and
        // Enter maps to Keep — never a silent Clear (review-3 follow-up). Its
        // declarations are unknown, so it projects the base (Keep changes nothing).
        if let Some(cur) = &current_persona {
            if !personas.iter().any(|p| &p.name == cur) {
                personas.push(PersonaChoice {
                    name: cur.clone(),
                    profile: None,
                });
            }
        }
        let mut persona_opts = Vec::with_capacity(personas.len() + 1);
        persona_opts.push(NONE.to_string());
        persona_opts.extend(personas.iter().map(|p| p.name.clone()));
        let persona_idx = current_persona
            .as_ref()
            .and_then(|c| persona_opts.iter().position(|n| n == c))
            .unwrap_or(0);
        Self {
            via,
            sel: 0,
            persona_opts,
            personas,
            persona_idx,
            current_persona,
            cognition: Dial::Inherit(cli_cognition()),
            tenacity: Dial::Inherit(cli_tenacity()),
            initiative: Dial::Inherit(cli_initiative()),
            personality: PersonalityTrait::ALL.map(|kind| Dial::Inherit(personality.get(kind))),
            model_opts,
            model: Dial::Inherit(model_idx),
            current_model: current_model.to_string(),
            base_initiative,
            initiative_from_family,
            base_crew: std::env::var("NEWT_TEAM").is_ok(),
            backend,
            mode: Mode::Normal,
            status: None,
            saved: None,
        }
    }

    fn in_command(&self) -> bool {
        matches!(self.mode, Mode::Command(_))
    }

    pub(crate) fn down(&mut self) {
        self.status = None;
        self.sel = (self.sel + 1) % ROWS.len();
    }
    pub(crate) fn up(&mut self) {
        self.status = None;
        self.sel = (self.sel + ROWS.len() - 1) % ROWS.len();
    }

    pub(crate) fn cycle(&mut self, dir: i32) {
        self.status = None;
        match ROWS[self.sel] {
            Row::Persona => {
                self.persona_idx = clamp_step(self.persona_idx, dir, self.persona_opts.len());
            }
            Row::Model => {
                // Unreachable backend → nothing to dial; the row says why.
                if let Some(opts) = &self.model_opts {
                    self.model
                        .set(clamp_step(self.model.value(), dir, opts.len()));
                }
            }
            Row::Cognition => {
                let ladder = cognition_ladder();
                let i = ladder
                    .iter()
                    .position(|o| *o == self.cognition.value())
                    .unwrap_or(0);
                self.cognition.set(ladder[clamp_step(i, dir, ladder.len())]);
            }
            Row::Tenacity => {
                let ladder = ladder(Tenacity::all());
                let i = ladder
                    .iter()
                    .position(|t| *t == self.tenacity.value())
                    .unwrap_or(0);
                self.tenacity.set(ladder[clamp_step(i, dir, ladder.len())]);
            }
            Row::Initiative => {
                let ladder = ladder(Initiative::all());
                let i = ladder
                    .iter()
                    .position(|t| *t == self.initiative.value())
                    .unwrap_or(0);
                self.initiative
                    .set(ladder[clamp_step(i, dir, ladder.len())]);
            }
            Row::Personality(kind) => {
                let (_, dial) = PersonalityTrait::ALL
                    .into_iter()
                    .zip(self.personality.iter_mut())
                    .find(|(candidate, _)| *candidate == kind)
                    .expect("every personality row has one dial");
                let at = dial.value().map_or(0, |level| usize::from(level.get()) + 1);
                let next = clamp_step(at, dir, 102); // auto, then 0..=100
                dial.set((next > 0).then(|| {
                    PersonalityLevel::try_from((next - 1) as u8)
                        .expect("clamped personality position")
                }));
            }
        }
    }

    /// Apply the dials the operator moved — **through the one mutation path,
    /// which is what writes the receipt** (#1965).
    ///
    /// `auto`/`inherit` CLEARS the override so the value returns to
    /// persona/config resolution. Called by [`run`] only after an explicit
    /// apply (Enter / a `:wq` whose save landed).
    ///
    /// This used to call `set_cli_cognition` / `set_cli_tenacity` /
    /// `clear_cli_tenacity` directly. It was the last live bypass of
    /// `settings_form::apply_and_record`, and the worst-placed one: a panel
    /// whose entire job is changing dials, leaving nothing durable behind. The
    /// slash verbs it duplicates (`/psyche cognition`, `/psyche tenacity`) have
    /// been journalling since #1981, so the same change made two ways produced
    /// a record only one way — the exact shape of the audit finding that an
    /// unlimited round cap left no trace.
    ///
    /// `via` is the route the panel was OPENED by — `/psyche` or `/psyche
    /// edit`, both of which land here — carried in on [`PanelSeed`] rather
    /// than hardcoded. The route is the half of the event a reader cannot
    /// reconstruct from the resulting state, so a receipt naming a command the
    /// operator never typed is a false record rather than a rounding error.
    ///
    /// Only DIRTY dials are touched, unchanged: #1668's posture marks say the
    /// operator moved THIS axis, so an untouched row of the panel must pin
    /// nothing — and a receipt for a dial nobody touched would be a false
    /// entry in the journal. (The model spinner's pick is marked on the
    /// `/model` path the caller routes it through, after that path's
    /// served-validation gate.)
    pub(crate) fn apply(&self) {
        if self.cognition.is_dirty() {
            let _ = crate::settings_form::apply_cognition(self.cognition.value(), self.via);
        }
        if self.tenacity.is_dirty() {
            let _ = crate::settings_form::apply_tenacity(self.tenacity.value(), self.via);
        }
        if self.initiative.is_dirty() {
            let _ = crate::settings_form::apply_initiative(self.initiative.value(), self.via);
        }
    }

    /// The persona action the operator chose (Keep / Clear / Switch).
    pub(crate) fn persona_action(&self) -> PersonaAction {
        let selected = &self.persona_opts[self.persona_idx];
        if selected == NONE {
            if self.current_persona.is_some() {
                PersonaAction::Clear
            } else {
                PersonaAction::Keep
            }
        } else if Some(selected) == self.current_persona.as_ref() {
            PersonaAction::Keep
        } else {
            PersonaAction::Switch(selected.clone())
        }
    }

    /// True when applying would change nothing: no dial is dirty and the persona
    /// choice is Keep. [`run`] downgrades an Enter on a no-op panel to a silent
    /// close (#1665) — bare `/psyche` opens the panel, so browsing must never
    /// mutate or report. A dial cycled away and back is dirty (a deliberate
    /// same-value re-apply), so it still counts as a change.
    pub(crate) fn is_noop(&self) -> bool {
        !self.cognition.is_dirty()
            && !self.tenacity.is_dirty()
            && !self.initiative.is_dirty()
            && !self.model.is_dirty()
            && !self.personality.iter().any(|dial| dial.is_dirty())
            && self.persona_action() == PersonaAction::Keep
    }

    /// The model spinner's pick, `None` when untouched (#1666). A touched
    /// spinner is a pick even at the original position — same deliberate
    /// re-apply semantics as the dials — and the CALLER routes it through the
    /// `/model` path (validation gate, persistence rules, warmup); the panel
    /// itself never mutates model state.
    pub(crate) fn chosen_model(&self) -> Option<String> {
        if !self.model.is_dirty() {
            return None;
        }
        self.model_opts
            .as_ref()
            .and_then(|opts| opts.get(self.model.value()))
            .map(|m| m.name.clone())
    }

    fn chosen_personality(&self) -> Vec<(PersonalityTrait, Option<PersonalityLevel>)> {
        PersonalityTrait::ALL
            .into_iter()
            .zip(self.personality)
            .filter_map(|(kind, dial)| match dial {
                Dial::Set(level) => Some((kind, level)),
                Dial::Inherit(_) => None,
            })
            .collect()
    }

    fn model_label(&self) -> String {
        let Some(opts) = &self.model_opts else {
            return "(backend unreachable — /models when it's back)".to_string();
        };
        let m = &opts[self.model.value()];
        let tag = if m.tag.is_empty() {
            String::new()
        } else {
            format!(" {}", m.tag)
        };
        if m.name == self.current_model {
            format!("{}{tag} (active)", m.name)
        } else {
            format!("{}{tag} (pending)", m.name)
        }
    }

    // ── Projection (review-3 §3) ─────────────────────────────────────────
    /// The persona currently highlighted in the selector (`None` = the NONE row).
    fn selected_persona(&self) -> Option<&PersonaChoice> {
        if self.persona_idx == 0 {
            None
        } else {
            self.personas.get(self.persona_idx - 1)
        }
    }

    fn selected_profile(&self) -> Option<&newt_core::RoleProfile> {
        self.selected_persona().and_then(|p| p.profile.as_ref())
    }

    /// The cognition that WILL be in effect for the selected persona after Apply:
    /// an explicit override wins, else the selected persona's declared level, else
    /// none.
    fn projected_cognition(&self) -> Option<Cognition> {
        match self.cognition.value() {
            CognitionOverride::Set(c) => Some(c),
            CognitionOverride::Off => None,
            CognitionOverride::Unset => self.selected_profile().and_then(|p| p.cognition),
        }
    }

    /// The tenacity that WILL be in effect after Apply: an explicit override,
    /// else `Normal` (no persona or config layer feeds tenacity).
    fn projected_tenacity(&self) -> Tenacity {
        self.tenacity.value().unwrap_or_default()
    }

    /// The initiative the operator CHOSE for the selected persona: an explicit
    /// override, else the persona's own declaration. `None` = the base applies.
    fn chosen_initiative(&self) -> Option<Initiative> {
        self.initiative
            .value()
            .or_else(|| self.selected_profile().and_then(|p| p.initiative))
    }

    /// The initiative that WILL be in effect for the selected persona after
    /// Apply: [`Self::chosen_initiative`], else the config/family base.
    fn projected_initiative(&self) -> Initiative {
        self.chosen_initiative().unwrap_or(self.base_initiative)
    }

    fn personality_overrides(&self) -> PersonalityTraits {
        let clears_conversation = self.persona_action() == PersonaAction::Clear;
        let mut traits = PersonalityTraits::default();
        for (kind, dial) in PersonalityTrait::ALL.into_iter().zip(self.personality) {
            if dial.is_dirty() || !clears_conversation {
                traits.set(kind, dial.value());
            }
        }
        traits
    }

    fn projected_personality(&self) -> PersonalityTraits {
        self.personality_overrides()
            .resolve(self.selected_profile().and_then(|p| p.personality))
    }

    /// The backend that WILL be in effect: the selected persona's declared backend,
    /// else the operator baseline (what a no-backend persona reverts to on apply).
    fn projected_backend(&self) -> Option<String> {
        self.selected_profile()
            .and_then(|p| p.backend.clone())
            .or_else(|| self.backend.clone())
    }

    /// The crew launch gate that the selected persona declares, else the base.
    fn projected_crew(&self) -> bool {
        self.selected_profile()
            .and_then(|p| p.crew)
            .unwrap_or(self.base_crew)
    }

    // ── Command line ─────────────────────────────────────────────────────
    fn begin_command(&mut self, prefill: &str) {
        self.status = None;
        self.mode = Mode::Command(prefill.to_string());
    }
    fn command_char(&mut self, c: char) {
        if let Mode::Command(buf) = &mut self.mode {
            buf.push(c);
        }
    }
    fn command_backspace(&mut self) {
        if let Mode::Command(buf) = &mut self.mode {
            buf.pop();
        }
    }
    fn cancel_command(&mut self) {
        self.mode = Mode::Normal;
    }

    /// Run the current ex-command, using `persist` for any file write. Returns the
    /// close intent: `Some(true)` apply + close, `Some(false)` cancel + close,
    /// `None` stay open (with a status line on error / save confirmation). The
    /// `persist` closure is the ONLY I/O — injected so this is unit-testable and so
    /// a failed write keeps the panel open with edits intact (review-3 §1).
    fn run_command(
        &mut self,
        persist: &mut dyn FnMut(&str, &str, bool) -> SaveResult,
    ) -> Option<bool> {
        let cmd = match &self.mode {
            Mode::Command(buf) => buf.trim().to_string(),
            Mode::Normal => return None,
        };
        self.mode = Mode::Normal;
        let mut it = cmd.split_whitespace();
        let raw = it.next().unwrap_or("");
        let overwrite = raw.ends_with('!');
        let verb = raw.trim_end_matches('!');
        let name = it.next();
        match verb {
            "" => None,
            "q" => Some(false),
            "w" => {
                self.try_save(name, overwrite, persist);
                None
            }
            "wq" | "x" => {
                if self.try_save(name, overwrite, persist) {
                    Some(true)
                } else {
                    None // save refused (no name / exists / failed) — stay, show why
                }
            }
            other => {
                self.status = Some(format!("unknown command ':{other}' (:w <name> | :wq | :q)"));
                None
            }
        }
    }

    /// Persist the projected posture as persona `name` via `persist`. Returns
    /// whether it saved; sets a status line from the [`SaveResult`] either way
    /// (visible feedback — review-2 #5 / review-3 §1). Nothing is recorded as saved
    /// until the write actually succeeds.
    fn try_save(
        &mut self,
        name: Option<&str>,
        overwrite: bool,
        persist: &mut dyn FnMut(&str, &str, bool) -> SaveResult,
    ) -> bool {
        let name = sanitize_name(name.unwrap_or(""));
        if name.is_empty() {
            self.status = Some("save needs a name: :w <name>".to_string());
            return false;
        }
        let content = match self.persona_content(&name) {
            Ok(content) => content,
            Err(err) => {
                self.status = Some(format!("save failed: {err}"));
                return false;
            }
        };
        match persist(&name, &content, overwrite) {
            SaveResult::Saved { name } => {
                self.status = Some(format!("saved persona '{name}'"));
                self.saved = Some(name);
                true
            }
            SaveResult::Exists { name } => {
                self.status = Some(format!("'{name}' exists — :w! / :wq! to overwrite"));
                false
            }
            SaveResult::InvalidName(msg) => {
                self.status = Some(format!("invalid name: {msg}"));
                false
            }
            SaveResult::Failed(err) => {
                self.status = Some(format!("save failed: {err}"));
                false
            }
        }
    }

    /// The EFFECTIVE cognition to serialize on save — the PROJECTED value for the
    /// selected persona (auto → the persona's declared level, or none).
    fn cognition_for_save(&self) -> Option<Cognition> {
        self.projected_cognition()
    }

    fn persona_content(&self, name: &str) -> anyhow::Result<String> {
        let mut profile = match self.selected_persona() {
            Some(persona) => persona.profile.clone().ok_or_else(|| {
                anyhow::anyhow!(
                    "persona '{}' is unavailable; its unknown profile cannot be saved",
                    persona.name
                )
            })?,
            None => newt_core::RoleProfile {
                role: Some(name.to_string()),
                prompt: format!(
                    "# {name}\n\nSaved from the psyche panel — the dials above define this persona's posture."
                ),
                ..Default::default()
            },
        };
        profile.backend = self.projected_backend();
        profile.cognition = self.cognition_for_save();
        // Only a chosen initiative: the base is a family/config default, and
        // baking it in would pin it for every model this persona runs on.
        profile.initiative = self.chosen_initiative();
        profile.crew = profile.crew.or_else(|| self.base_crew.then_some(true));
        let personality = self.projected_personality();
        if personality != PersonalityTraits::default() || profile.personality.is_some() {
            profile.personality = Some(personality);
        }
        profile.to_markdown()
    }

    // ── Rendering ────────────────────────────────────────────────────────
    /// `(value, provenance)` for the cognition row. Provenance distinguishes an
    /// explicit override from a value inherited from the selected persona / base.
    fn cognition_cell(&self) -> (String, String) {
        match self.cognition.value() {
            CognitionOverride::Set(c) => (c.label().to_string(), "override".to_string()),
            CognitionOverride::Off => ("off".to_string(), "override".to_string()),
            CognitionOverride::Unset => {
                let proj = self.projected_cognition();
                let val = format!("auto → {}", proj.map_or("off", Cognition::label));
                (val, self.inherit_provenance(proj.is_some()))
            }
        }
    }
    fn tenacity_cell(&self) -> (String, String) {
        match self.tenacity.value() {
            Some(t) => (t.label().to_string(), "override".to_string()),
            None => (
                format!("auto → {}", self.projected_tenacity().label()),
                "base".to_string(),
            ),
        }
    }
    fn initiative_cell(&self) -> (String, String) {
        match self.initiative.value() {
            Some(i) => (i.label().to_string(), "override".to_string()),
            None => {
                let val = format!("auto → {}", self.projected_initiative().label());
                let from_persona = self.chosen_initiative().is_some();
                let provenance = if !from_persona && self.initiative_from_family {
                    "model default".to_string()
                } else {
                    self.inherit_provenance(from_persona)
                };
                (val, provenance)
            }
        }
    }
    /// Provenance for an inherited (non-override) value: attribute it to the
    /// selected persona when that persona declares the dial, else the base.
    fn inherit_provenance(&self, from_persona: bool) -> String {
        match (from_persona, self.selected_persona()) {
            (true, Some(p)) => format!("persona: {}", p.name),
            _ => "base".to_string(),
        }
    }
    fn persona_label(&self) -> String {
        let name = &self.persona_opts[self.persona_idx];
        if Some(name) == self.current_persona.as_ref() {
            format!("{name} (active)")
        } else if name == NONE {
            if self.current_persona.is_some() {
                "none (clears active)".to_string()
            } else {
                "none".to_string()
            }
        } else {
            format!("{name} (pending)")
        }
    }

    fn view_rows(&self) -> Vec<RowView> {
        let (cog_val, cog_prov) = self.cognition_cell();
        let (ten_val, ten_prov) = self.tenacity_cell();
        let (ini_val, ini_prov) = self.initiative_cell();
        let mut rows = vec![
            RowView {
                label: "persona",
                value: self.persona_label(),
                provenance: String::new(),
                selected: ROWS[self.sel] == Row::Persona,
                editable: true,
            },
            RowView {
                label: "model",
                value: self.model_label(),
                provenance: if self.model_opts.is_some() {
                    "active backend".to_string()
                } else {
                    String::new()
                },
                selected: ROWS[self.sel] == Row::Model,
                editable: self.model_opts.is_some(),
            },
            RowView {
                label: "cognition",
                value: cog_val,
                provenance: cog_prov,
                selected: ROWS[self.sel] == Row::Cognition,
                editable: true,
            },
            RowView {
                label: "tenacity",
                value: ten_val,
                provenance: ten_prov,
                selected: ROWS[self.sel] == Row::Tenacity,
                editable: true,
            },
            RowView {
                label: "initiative",
                value: ini_val,
                provenance: ini_prov,
                selected: ROWS[self.sel] == Row::Initiative,
                editable: true,
            },
            RowView {
                label: "provider",
                value: self.projected_backend().unwrap_or_else(|| "—".to_string()),
                provenance: self.backend_provenance(),
                selected: false,
                editable: false,
            },
            RowView {
                label: "crew",
                value: format!(
                    "{} (launch gate)",
                    if self.projected_crew() { "on" } else { "off" }
                ),
                provenance: self.crew_provenance(),
                selected: false,
                editable: false,
            },
        ];
        let overrides = self.personality_overrides();
        let projected = self.projected_personality();
        let traits = PersonalityTrait::ALL.into_iter().map(|kind| {
            let (value, provenance) = match overrides.get(kind) {
                Some(level) => (format!("{}/100", level.get()), "override".into()),
                None => (
                    format!(
                        "auto → {}",
                        projected.get(kind).map_or_else(
                            || "unspecified".into(),
                            |level| format!("{}/100", level.get())
                        )
                    ),
                    self.inherit_provenance(projected.get(kind).is_some()),
                ),
            };
            RowView {
                label: kind.label(),
                value,
                provenance,
                selected: ROWS[self.sel] == Row::Personality(kind),
                editable: true,
            }
        });
        // The style rows follow the dials, just before `provider`.
        let at = rows
            .iter()
            .position(|r| r.label == "provider")
            .unwrap_or(rows.len());
        rows.splice(at..at, traits);
        rows
    }

    fn backend_provenance(&self) -> String {
        match self.selected_persona() {
            Some(p) if p.profile.as_ref().is_some_and(|p| p.backend.is_some()) => {
                format!("persona: {}", p.name)
            }
            // No declared backend → the selection reverts to the operator baseline
            // on apply (NOT the outgoing persona's backend).
            _ => "base".to_string(),
        }
    }
    fn crew_provenance(&self) -> String {
        match self.selected_persona() {
            Some(p) if p.profile.as_ref().is_some_and(|p| p.crew.is_some()) => {
                format!("declaration: {}; applies next launch", p.name)
            }
            _ => "current launch gate".to_string(),
        }
    }
}

/// A rendered row: label, value, provenance, and display flags. Shared with the
/// backend panel (#1667) so every panel renders rows the same way.
pub(crate) struct RowView {
    pub(crate) label: &'static str,
    pub(crate) value: String,
    pub(crate) provenance: String,
    pub(crate) selected: bool,
    pub(crate) editable: bool,
}

fn sanitize_name(s: &str) -> String {
    s.trim()
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect()
}

/// Clamped (non-wrapping) spinner step — shared by every panel dial.
///
/// **Total, including on an empty list.** The obvious form,
/// `(i + dir).clamp(0, len - 1)`, PANICS at `len == 0`: that is `clamp(0, -1)`,
/// and `clamp` requires `min <= max`. No caller reaches it today, and each one
/// is safe for a different reason — the backend chooser always carries two
/// unremovable kind fallbacks, the psyche panel filters an empty model list to
/// `None`, the settings panel guards both dial paths, and the ladders are
/// consts. Four accidents of construction, none of them stated, all of them
/// one refactor from being wrong.
///
/// So the helper is made total rather than each caller made careful: an empty
/// list has no positions, and the only honest answer for "where is the cursor"
/// is 0. That is CLAUDE.md's rule — prefer making a bug unrepresentable over
/// fixing each site — applied to the one place that can enforce it.
pub(crate) fn clamp_step(i: usize, dir: i32, len: usize) -> usize {
    let Some(last) = len.checked_sub(1) else {
        return 0;
    };
    let n = i32::try_from(last).unwrap_or(i32::MAX);
    (i32::try_from(i).unwrap_or(i32::MAX) + dir).clamp(0, n) as usize
}

/// Editable rows + provider/crew, a footer, and the two border rows.
pub(crate) const PANEL_HEIGHT: u16 = ROWS.len() as u16 + 5;

fn draw(f: &mut ratatui::Frame, state: &PanelState) {
    let bottom = if let Mode::Command(buf) = &state.mode {
        command_line(buf)
    } else if let Some(status) = &state.status {
        status_line(status)
    } else {
        hint_line(
            "↑↓ select · ←→ change (auto=inherit) · Enter apply · Esc cancel · Ctrl-S/:w <name> save",
        )
    };
    render_panel(
        f,
        " psyche — operator dials ",
        &state.view_rows(),
        bottom,
        19,
        26,
    );
}

/// The shared panel chrome (#1667): bordered block + title, one line per
/// [`RowView`] (selected rows get the `❯` marker and `‹ ›` dial chrome, dim
/// provenance column), and the caller's bottom line. `label_w`/`val_w` are the
/// per-panel column widths.
pub(crate) fn render_panel(
    f: &mut ratatui::Frame,
    title: &str,
    rows: &[RowView],
    bottom: Line,
    label_w: usize,
    val_w: usize,
) {
    render_panel_with_styles(f, title, rows, bottom, label_w, val_w, |_| {
        (Style::default(), Style::default())
    });
}

/// Shared chrome with optional per-row value and annotation styling.
pub(crate) fn render_panel_with_styles(
    f: &mut ratatui::Frame,
    title: &str,
    rows: &[RowView],
    bottom: Line,
    label_w: usize,
    val_w: usize,
    styles: impl Fn(&RowView) -> (Style, Style),
) {
    // The edge comes from `modal::frame`, which every dialog now shares. The
    // panel used to own the only border in the crate; making it the SHARED one
    // is how the pagers and the permission prompt got an edge at all.
    let inner = crate::modal::frame(
        f,
        f.area(),
        &crate::modal::Chrome {
            title: title.trim(),
            ..crate::modal::Chrome::default()
        },
    );

    let visible = usize::from(inner.height.saturating_sub(1));
    let selected = rows.iter().position(|row| row.selected).unwrap_or(0);
    let top = crate::list_cursor::ListCursor::new(rows.len(), visible, selected).top();
    let mut lines: Vec<Line> = Vec::new();
    for row in rows.iter().skip(top).take(visible) {
        let marker = if row.selected { "❯ " } else { "  " };
        let name = format!("{marker}{:<label_w$}", row.label);
        let val = if row.selected && row.editable {
            format!("‹ {} ›", row.value)
        } else {
            row.value.clone()
        };
        let (name_style, val_style) = row_styles(row.selected, row.editable);
        let (value_override, annotation_override) = styles(row);
        let val_style = val_style.patch(value_override);
        let mut spans = vec![
            Span::styled(name, name_style),
            Span::styled(format!("{val:<val_w$}"), val_style),
        ];
        if !row.provenance.is_empty() {
            spans.push(Span::styled(
                row.provenance.clone(),
                crate::theme::style(crate::theme::Role::Dim).patch(annotation_override),
            ));
        }
        lines.push(Line::from(spans));
    }
    // The hint sits on the box's last line, not under the last row: a hint
    // floating mid-box reads as "that is everything" when the list scrolls.
    lines.resize(visible, Line::default());
    lines.push(bottom);
    render_scroll_gutter(f, inner, rows.len(), top, visible);

    let para = Paragraph::new(lines);
    f.render_widget(
        para,
        Rect {
            x: inner.x + 1,
            y: inner.y,
            width: inner.width.saturating_sub(1),
            height: inner.height,
        },
    );
}

/// A left-edge scrollbar in the column `render_panel` leaves free, drawn only
/// when the rows outrun the window. Left, because newt's layouts are
/// left-heavy: the right edge is where a narrow terminal trims. The glyphs are
/// `scrollbar`'s shared set (`▲` more above, `▼` more below, `▓` thumb,
/// `▒` track), the same the spill viewport draws.
fn render_scroll_gutter(
    f: &mut ratatui::Frame,
    inner: Rect,
    len: usize,
    top: usize,
    visible: usize,
) {
    use crate::scrollbar::{SCROLL_ABOVE, SCROLL_BELOW, SCROLL_THUMB, SCROLL_TRACK};
    if len <= visible || visible == 0 {
        return;
    }
    let thumb = crate::scrollbar::thumb_row(top, len - visible, visible);
    let glyphs: Vec<Line> = (0..visible)
        .map(|row| {
            let glyph = if row == 0 && top > 0 {
                SCROLL_ABOVE
            } else if row + 1 == visible && top + visible < len {
                SCROLL_BELOW
            } else if Some(row) == thumb {
                SCROLL_THUMB
            } else {
                SCROLL_TRACK
            };
            Line::from(Span::styled(
                glyph.to_string(),
                crate::theme::style(crate::theme::Role::Dim),
            ))
        })
        .collect();
    f.render_widget(
        Paragraph::new(glyphs),
        Rect {
            height: u16::try_from(visible).unwrap_or(inner.height),
            width: 1,
            ..inner
        },
    );
}

/// The `:…▏` ex-command bottom line — shared panel chrome (#1667).
pub(crate) fn command_line(buf: &str) -> Line<'static> {
    Line::from(Span::styled(
        format!(":{buf}▏"),
        crate::theme::style(crate::theme::Role::Ok),
    ))
}

/// The status bottom line — shared panel chrome (#1667).
pub(crate) fn status_line(status: &str) -> Line<'static> {
    Line::from(Span::styled(
        status.to_string(),
        crate::theme::style(crate::theme::Role::Identity),
    ))
}

/// The dim key-hint bottom line — shared panel chrome (#1667).
pub(crate) fn hint_line(hint: &'static str) -> Line<'static> {
    // Every panel is run by `panel::drive`, which owns the sizing keys and the
    // meta prefix (`panel_controls`), so every hint advertises them — one
    // place, not eight.
    Line::from(Span::styled(
        format!(
            "{hint} · ⇧↑↓ size · {} ? keys",
            crate::prefix::active_label()
        ),
        crate::theme::style(crate::theme::Role::Dim),
    ))
}

/// Row styling shared across panels (#1667): selected = bold label/value,
/// read-only = dim.
///
/// The four colours this file hardcoded — Cyan, Yellow, Green, Magenta — are
/// where `SelectedLabel`, `SelectedValue`, `Ok` and `Identity` came from: the
/// colour census that minted those roles read this panel and then never wired
/// them back, so they sat in `theme.rs` with zero consumers while the literals
/// they were named after stayed put. Same bytes, now themeable.
pub(crate) fn row_styles(selected: bool, editable: bool) -> (Style, Style) {
    if selected {
        (
            crate::theme::style(crate::theme::Role::SelectedLabel),
            crate::theme::style(crate::theme::Role::SelectedValue),
        )
    } else if editable {
        (
            crate::theme::style(crate::theme::Role::Text),
            crate::theme::style(crate::theme::Role::Text),
        )
    } else {
        (
            crate::theme::style(crate::theme::Role::Dim),
            crate::theme::style(crate::theme::Role::Dim),
        )
    }
}

/// Open the panel, drive its raw-mode inline event loop, and return the outcome.
/// `persist` writes a persona file and reports the [`SaveResult`] — it is called
/// during `:w`/`:wq` BEFORE any dial is applied, so a failed write leaves the
/// runtime untouched and the panel open (review-3 §1). Dials apply ONLY on an
/// explicit apply (Enter / a `:wq` whose save landed); Esc / `q` / `:q` discard.
/// An Enter with nothing changed ([`PanelState::is_noop`]) downgrades to
/// [`PanelOutcome::Cancelled`] — bare `/psyche` opens this panel (#1665), so a
/// browse-and-leave visit must be indistinguishable from never opening it.
pub(crate) fn run(
    seed: PanelSeed,
    persist: impl FnMut(&str, &str, bool) -> SaveResult,
    window: Option<crate::session_worker::PanelWindow>,
) -> io::Result<PanelOutcome> {
    let mut screen = PsycheScreen {
        state: PanelState::new(seed),
        persist,
    };
    // Scoped inside `panel::drive`, whose raw-mode guard restores exactly
    // where the old bare `disable_raw_mode()` statement did (#1889).
    let applied = crate::panel::drive(&mut screen, PANEL_HEIGHT, window.as_ref())?;

    // Commit order (review-3 §1): the persona file was already persisted inside
    // the loop (via `persist`). Now apply the dials — but ONLY on an explicit
    // apply — then hand the persona action to the caller, which applies it, reroutes
    // the backend, recomputes, and reports from fresh runtime state.
    Ok(close_outcome(applied, &screen.state))
}

/// The psyche panel as a [`crate::panel::Screen`]: its state, its writer, and
/// its key table. Everything else the loop used to do is the driver's.
struct PsycheScreen<P: FnMut(&str, &str, bool) -> SaveResult> {
    state: PanelState,
    persist: P,
}

impl<P: FnMut(&str, &str, bool) -> SaveResult> crate::panel::Screen for PsycheScreen<P> {
    fn draw(&self, frame: &mut ratatui::Frame) {
        draw(frame, &self.state);
    }

    fn key(&mut self, key: Key) -> crate::panel::Flow {
        use crate::panel::Flow;
        if self.state.in_command() {
            match key {
                // `Char` is now a PLAIN character by construction, so a second
                // Ctrl-S while the line is open no longer types a literal `s`
                // into the line Ctrl-S opened.
                Key::Char(c) => self.state.command_char(c),
                Key::Backspace => self.state.command_backspace(),
                Key::Esc => self.state.cancel_command(),
                Key::Enter => {
                    if let Some(apply) = self.state.run_command(&mut self.persist) {
                        return Flow::Close(apply);
                    }
                }
                _ => {}
            }
            return Flow::Stay;
        }
        match key {
            Key::Up => self.state.up(),
            Key::Down => self.state.down(),
            Key::Left => self.state.cycle(-1),
            Key::Right => self.state.cycle(1),
            // An explicit control binding, said in the pattern rather than in
            // a guard beside it.
            Key::Ctrl('s') => self.state.begin_command("w "),
            Key::Char(':') => self.state.begin_command(""),
            Key::Enter => return Flow::Close(true),
            Key::Esc | Key::Char('q') => return Flow::Close(false),
            _ => {}
        }
        Flow::Stay
    }
}

/// The panel's exit contract, factored out of the raw-mode loop so it is
/// unit-testable without a TTY (adversarial-review finding on #1665): given
/// whether the operator explicitly applied (Enter / a `:wq` whose save landed)
/// and the final working state, produce the [`PanelOutcome`] — running
/// [`PanelState::apply`] as a side effect ONLY on a real (non-noop) apply.
/// The noop downgrade lives HERE: Enter with nothing changed maps to
/// `Cancelled` (or `Saved` after a lone `:w`, so the save is still reported).
fn close_outcome(applied: bool, state: &PanelState) -> PanelOutcome {
    if applied && !state.is_noop() {
        state.apply();
        let persona = state.persona_action();
        let model = state.chosen_model();
        let personality = state.chosen_personality();
        match state.saved.clone() {
            Some(name) => PanelOutcome::SavedAndApplied {
                name,
                persona,
                model,
                personality,
            },
            None => PanelOutcome::Applied {
                persona,
                model,
                personality,
            },
        }
    } else {
        match state.saved.clone() {
            Some(name) => PanelOutcome::Saved { name },
            None => PanelOutcome::Cancelled,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    // The setters the panel no longer calls: tests still use them to ARRANGE
    // runtime state, which is not the same as writing a setting.
    use newt_core::cognition::set_cli_cognition;
    use newt_core::tenacity::{clear_cli_tenacity, set_cli_tenacity};
    use newt_core::test_guard::GlobalSettingsGuard;

    /// The panel is newt's only bordered box, and it shipped with no
    /// `border_style` — so the frame around a dialog that had TAKEN THE
    /// KEYBOARD drew in whatever the terminal last set, i.e. exactly like
    /// ordinary output. This pins that the frame, the title, and the selected
    /// row all read their colour from the theme rather than a literal.
    ///
    /// It also guards the failure that motivated the change: `SelectedLabel`,
    /// `SelectedValue`, `Ok` and `Identity` were minted from this file's
    /// hardcoded Cyan/Yellow/Green/Magenta and then never wired back, so they
    /// sat in `theme.rs` with zero consumers. A role with no consumer is a
    /// theme that silently does nothing.
    #[test]
    fn panel_chrome_reads_its_colours_from_the_theme() {
        use crate::theme::Role;
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let rows = vec![
            RowView {
                label: "persona",
                value: "sol".to_string(),
                provenance: String::new(),
                selected: true,
                editable: true,
            },
            RowView {
                label: "backend",
                value: "dgx".to_string(),
                provenance: String::new(),
                selected: false,
                editable: false,
            },
        ];

        let mut term = Terminal::new(TestBackend::new(48, 6)).unwrap();
        term.draw(|f| render_panel(f, " settings ", &rows, hint_line("q quit"), 10, 12))
            .unwrap();
        let buf = term.backend().buffer().clone();

        // The frame. Top-left corner is border, and it is NOT the terminal
        // default — which is the whole bug.
        let corner = buf.cell((0, 0)).unwrap();
        assert_eq!(
            corner.symbol(),
            "╭",
            "the box draws, now through the SHARED chrome — rounded, like every \
             other modal, which is the point of the shared edge"
        );
        assert_eq!(
            corner.fg,
            crate::theme::color(Role::ModalBorder),
            "the border is themed, not left at the terminal default"
        );
        assert_ne!(
            corner.fg,
            ratatui::style::Color::Reset,
            "an unstyled border is the defect this test exists for"
        );

        // The title, somewhere along the top edge.
        let titled = (1..47)
            .map(|x| buf.cell((x, 0)).unwrap())
            .find(|c| c.symbol() == "s")
            .expect("the title renders on the top edge");
        assert_eq!(titled.fg, crate::theme::color(Role::ModalTitle));

        // The selected row's label and value take the two roles this file's
        // literals originally named.
        let row: Vec<_> = (0..48).map(|x| buf.cell((x, 1)).unwrap()).collect();
        let label = row
            .iter()
            .find(|c| c.symbol() == "p")
            .expect("the selected label renders");
        assert_eq!(label.fg, crate::theme::color(Role::SelectedLabel));
        let value = row
            .iter()
            .find(|c| c.symbol() == "‹")
            .expect("the selected row carries dial chrome");
        assert_eq!(value.fg, crate::theme::color(Role::SelectedValue));
    }

    /// The two shared bottom lines take the other two once-orphaned roles.
    #[test]
    fn bottom_lines_read_their_colours_from_the_theme() {
        use crate::theme::Role;

        let ex = command_line("w");
        assert_eq!(ex.spans[0].style.fg, Some(crate::theme::color(Role::Ok)));
        let status = status_line("saved");
        assert_eq!(
            status.spans[0].style.fg,
            Some(crate::theme::color(Role::Identity))
        );
    }

    fn rendered_panel_lines(
        rows: &[RowView],
        bottom: Line<'static>,
        width: u16,
        height: u16,
    ) -> Vec<String> {
        use ratatui::{backend::TestBackend, Terminal};
        let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
        terminal
            .draw(|frame| render_panel(frame, " panel ", rows, bottom.clone(), 10, 12))
            .unwrap();
        let buffer = terminal.backend().buffer();
        (0..height)
            .map(|y| {
                (0..width)
                    .map(|x| buffer.cell((x, y)).unwrap().symbol())
                    .collect()
            })
            .collect()
    }

    fn render_test_rows(selected: Option<usize>) -> Vec<RowView> {
        [
            "row-00", "row-01", "row-02", "row-03", "row-04", "row-05", "row-06", "row-07",
            "row-08", "row-09", "row-10",
        ]
        .into_iter()
        .enumerate()
        .map(|(index, label)| RowView {
            label,
            value: "value".into(),
            provenance: String::new(),
            selected: selected == Some(index),
            editable: true,
        })
        .collect()
    }

    #[test]
    fn shared_panel_reveals_every_selected_row_and_keeps_the_exit_hint() {
        for height in [4, 7, 14] {
            for selected in 0..11 {
                let rows = render_test_rows(Some(selected));
                let lines = rendered_panel_lines(&rows, hint_line("Esc cancel"), 48, height);
                let screen = lines.join("\n");
                assert!(
                    lines
                        .iter()
                        .any(|line| line.contains(&format!("❯ row-{selected:02}"))),
                    "height={height}, selected={selected}:\n{screen}"
                );
                assert!(screen.contains("Esc cancel"), "{screen}");
                assert_eq!(screen.matches('❯').count(), 1, "{screen}");
            }
        }
    }

    #[test]
    fn shared_panel_keeps_command_and_status_footers_with_empty_or_unselected_rows() {
        for rows in [
            Vec::new(),
            render_test_rows(None),
            render_test_rows(Some(10)),
        ] {
            for height in [3, 7] {
                for (bottom, expected) in [
                    (command_line("w copy"), ":w copy▏"),
                    (status_line("save refused"), "save refused"),
                ] {
                    let screen = rendered_panel_lines(&rows, bottom, 48, height).join("\n");
                    assert!(screen.contains(expected), "height={height}:\n{screen}");
                    if height == 3 {
                        assert!(!screen.contains("row-"), "footer owns the only body row");
                    } else if !rows.is_empty() && rows.iter().all(|row| !row.selected) {
                        assert!(screen.contains("row-00"), "no selection starts at the top");
                    }
                }
            }
        }
    }

    #[test]
    fn shared_panel_zero_and_tiny_rectangles_are_safe() {
        for width in [0, 1, 2, 48] {
            for height in 0..=3 {
                for rows in [Vec::new(), render_test_rows(Some(10))] {
                    let lines = rendered_panel_lines(&rows, hint_line("Esc cancel"), width, height);
                    assert_eq!(lines.len(), usize::from(height));
                    if width == 48 && height == 3 {
                        assert!(lines[1].contains("Esc cancel"), "{lines:?}");
                        assert!(!lines[1].contains("row-"), "footer precedes hidden rows");
                    }
                }
            }
        }
    }

    fn choice(
        name: &str,
        cognition: Option<Cognition>,
        initiative: Option<Initiative>,
    ) -> PersonaChoice {
        PersonaChoice {
            name: name.to_string(),
            profile: Some(newt_core::RoleProfile {
                prompt: format!("# {name}"),
                cognition,
                initiative,
                backend: Some("sol".to_string()),
                ..Default::default()
            }),
        }
    }

    fn model_choices(names: &[&str]) -> Vec<ModelChoice> {
        names
            .iter()
            .map(|n| ModelChoice {
                name: n.to_string(),
                tag: String::new(),
            })
            .collect()
    }

    fn seed(
        current: Option<&str>,
        personas: Vec<PersonaChoice>,
        base_ini: Initiative,
        models: Option<Vec<ModelChoice>>,
        current_model: &str,
    ) -> PanelSeed {
        PanelSeed {
            via: "/psyche",
            personas,
            current_persona: current.map(str::to_string),
            backend: Some("sol".to_string()),
            base_initiative: base_ini,
            initiative_from_family: false,
            models,
            current_model: current_model.to_string(),
            personality: PersonalityTraits::default(),
        }
    }

    fn panel(
        current: Option<&str>,
        personas: Vec<PersonaChoice>,
        base_ini: Initiative,
    ) -> PanelState {
        PanelState::new(seed(
            current,
            personas,
            base_ini,
            Some(model_choices(&["m1", "m2", "m3"])),
            "m2",
        ))
    }

    fn two_personas() -> Vec<PersonaChoice> {
        vec![choice("bob", None, None), choice("obsessive", None, None)]
    }

    /// A `persist` closure that always succeeds (records nothing to disk).
    fn ok_persist() -> impl FnMut(&str, &str, bool) -> SaveResult {
        |name: &str, _content: &str, _overwrite: bool| SaveResult::Saved {
            name: name.to_string(),
        }
    }

    #[test]
    fn untouched_dials_are_never_written_on_apply() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let s = panel(None, two_personas(), Initiative::Measured);
        s.apply();
        assert_eq!(
            cli_tenacity(),
            None,
            "untouched tenacity stays un-overridden"
        );
        assert_eq!(cli_cognition(), CognitionOverride::Unset);
    }

    /// #1668: a panel apply marks a posture ACTION for exactly its DIRTY dials
    /// — so browsing the panel (bare `/psyche` opens it) can never pin, and a
    /// one-dial edit cannot drag the other dial's ambient value into the pin.
    /// **The dial step is total**, including on the empty list no caller
    /// reaches today.
    ///
    /// The naive `clamp(0, len - 1)` panics at `len == 0` — `clamp` requires
    /// `min <= max`. Every current caller is safe for a DIFFERENT reason (two
    /// unremovable kind fallbacks; an empty model list filtered to `None`; two
    /// guarded dial paths; const ladders), which is four unstated accidents
    /// rather than one enforced rule. This is the rule.
    #[test]
    fn the_dial_step_is_total_and_clamps_at_both_ends() {
        // The case that used to panic.
        assert_eq!(clamp_step(0, 1, 0), 0, "an empty list has no positions");
        assert_eq!(clamp_step(0, -1, 0), 0);
        assert_eq!(clamp_step(7, 1, 0), 0, "even from a stale index");

        // A one-item list is a fixed point in both directions.
        assert_eq!(clamp_step(0, 1, 1), 0);
        assert_eq!(clamp_step(0, -1, 1), 0);

        // And the ordinary case still clamps rather than wrapping.
        assert_eq!(clamp_step(0, -1, 3), 0, "the floor holds");
        assert_eq!(clamp_step(2, 1, 3), 2, "the ceiling holds");
        assert_eq!(clamp_step(1, 1, 3), 2);
        assert_eq!(clamp_step(1, -1, 3), 0);

        // A stale index above the end walks back into range rather than
        // reaching further out — the shape a shrinking list produces.
        assert_eq!(clamp_step(9, -1, 3), 2);
        assert_eq!(clamp_step(9, 1, 3), 2);
    }

    /// **The panel cannot reach a dial except through the recorder** (#1965).
    ///
    /// `PanelState::apply` used to call `set_cli_cognition` /
    /// `set_cli_tenacity` / `clear_cli_tenacity` directly — the last live
    /// bypass of `settings_form`'s one mutation path, and the worst-placed
    /// one: a panel whose whole job is moving dials, leaving nothing durable
    /// behind, while the slash verbs it duplicates had been journalling since
    /// #1981.
    ///
    /// Counted over PRODUCTION source because the property is "no other path
    /// exists", and absence is not observable by calling something. The
    /// behavioural half — that the dials still move, and that only the dirty
    /// ones pin a preference — is the test below and
    /// `close_outcome_downgrades_a_noop_enter_and_applies_a_real_one`.
    #[test]
    fn the_panel_writes_dials_only_through_the_recorded_path() {
        let source = crate::production_source(include_str!("config_panel.rs"));
        for setter in [
            "set_cli_cognition(",
            "set_cli_tenacity(",
            "clear_cli_tenacity(",
            "set_cli_initiative(",
            "clear_cli_initiative(",
            "mark_cognition_choice(",
            "mark_tenacity_choice(",
            "mark_initiative_choice(",
        ] {
            assert_eq!(
                source.matches(setter).count(),
                0,
                "`{setter}` writes a setting with no receipt; go through \
                 settings_form::apply_cognition / apply_tenacity / apply_initiative"
            );
        }
        assert!(
            source.contains("settings_form::apply_cognition")
                && source.contains("settings_form::apply_tenacity")
                && source.contains("settings_form::apply_initiative"),
            "the panel must apply its dials through the recording path"
        );
    }

    #[test]
    fn apply_marks_a_preference_action_only_for_the_dirty_dials() {
        use newt_core::runtime::drain_preference_actions;
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let _ = drain_preference_actions();

        // A browse-and-apply with nothing touched marks nothing.
        let s = panel(None, two_personas(), Initiative::Measured);
        s.apply();
        assert!(
            drain_preference_actions().is_empty(),
            "an untouched panel must not pin"
        );

        // Touch ONLY cognition → only the cognition axis is marked.
        let mut s = panel(None, two_personas(), Initiative::Measured);
        s.down(); // → model
        s.down(); // → cognition
        s.cycle(1);
        assert!(s.cognition.is_dirty() && !s.tenacity.is_dirty());
        s.apply();
        let a = drain_preference_actions();
        assert_eq!(a.cognition, Some(s.cognition.value()));
        assert_eq!(a.tenacity, None, "an untouched dial must not be pinned");
        assert_eq!((a.backend, a.model), (None, None), "panel owns dials only");

        // Touch ONLY tenacity, to its `auto` position → the axis is UNPINNED.
        let mut s = panel(None, two_personas(), Initiative::Measured);
        s.down();
        s.down();
        s.down(); // → tenacity
        for _ in 0..ladder(Tenacity::all()).len() {
            s.cycle(-1);
        }
        assert_eq!(s.tenacity.value(), None, "reached auto");
        s.apply();
        let a = drain_preference_actions();
        assert_eq!(a.tenacity, Some(None), "auto unpins the axis");
        assert_eq!(a.cognition, None);
        assert_eq!(a.initiative, None, "an untouched initiative is not pinned");

        // Touch ONLY initiative → only its axis is marked.
        let mut s = panel(None, two_personas(), Initiative::Measured);
        for _ in 0..4 {
            s.down(); // → initiative
        }
        s.cycle(1);
        assert!(s.initiative.is_dirty() && !s.tenacity.is_dirty());
        s.apply();
        let a = drain_preference_actions();
        assert_eq!(a.initiative, Some(s.initiative.value()));
        assert_eq!(a.tenacity, None);
    }

    #[test]
    fn auto_position_clears_the_tenacity_override() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_tenacity(Tenacity::Relentless);
        let mut s = panel(None, two_personas(), Initiative::Measured);
        s.down(); // → model
        s.down(); // → cognition
        s.down(); // → tenacity (currently Some(relentless) via cli_tenacity seed)
                  // Cycle left to the `auto` (None) position, then apply → override cleared.
        for _ in 0..ladder(Tenacity::all()).len() {
            s.cycle(-1);
        }
        assert_eq!(s.tenacity.value(), None, "reached auto");
        s.apply();
        assert_eq!(cli_tenacity(), None, "auto cleared the override");
    }

    #[test]
    fn projection_follows_the_selected_persona() {
        // review-3 §3: selecting a persona projects ITS declarations, never the
        // previously-active persona's effective values.
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let personas = vec![
            choice("bob", Some(Cognition::Rational), Some(Initiative::Measured)),
            choice(
                "obsessive",
                Some(Cognition::Meticulous),
                Some(Initiative::Eager),
            ),
        ];
        let mut s = panel(Some("bob"), personas, Initiative::Patient);
        // Opens on bob → projects bob's declarations.
        assert_eq!(s.projected_cognition(), Some(Cognition::Rational));
        assert_eq!(s.projected_initiative(), Initiative::Measured);
        // Select obsessive → projection switches to obsessive's, not bob's.
        s.cycle(1); // bob
        s.cycle(1); // obsessive
        assert_eq!(s.projected_cognition(), Some(Cognition::Meticulous));
        assert_eq!(s.projected_initiative(), Initiative::Eager);
        let (ini_val, ini_prov) = s.initiative_cell();
        assert!(ini_val.contains("eager"), "shows projected level");
        assert_eq!(ini_prov, "persona: obsessive", "attributes it to obsessive");
        // Tenacity has no persona layer: it projects `normal`.
        assert_eq!(s.projected_tenacity(), Tenacity::Normal);
    }

    #[test]
    fn projection_base_shows_when_the_persona_declares_nothing() {
        let _g = GlobalSettingsGuard::acquire();
        newt_core::initiative::clear_cli_initiative();
        // obsessive declares no initiative → inherits the config/family base.
        let personas = vec![choice("obsessive", None, None)];
        let mut s = panel(None, personas.clone(), Initiative::Decisive);
        s.cycle(1); // NONE → obsessive
        assert_eq!(
            s.projected_initiative(),
            Initiative::Decisive,
            "inherits base"
        );
        assert_eq!(s.initiative_cell().1, "base");
        // A base that is the model family's entry says so (the design's
        // `initiative: decisive (model default)`).
        let mut family = seed(None, personas, Initiative::Decisive, None, "");
        family.initiative_from_family = true;
        let s = PanelState::new(family);
        assert_eq!(
            s.initiative_cell(),
            ("auto → decisive".to_string(), "model default".to_string())
        );
    }

    #[test]
    fn save_serializes_the_projected_posture() {
        // review-2 #1 / review-3 §3: saving reproduces the PROJECTED effective
        // posture of the selected persona, not an empty field.
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let personas = vec![choice(
            "bob",
            Some(Cognition::Meticulous),
            Some(Initiative::Eager),
        )];
        let mut s = panel(Some("bob"), personas, Initiative::Measured);
        let mut persist = ok_persist();
        s.begin_command("w clone");
        assert_eq!(s.run_command(&mut persist), None);
        assert_eq!(s.saved.as_deref(), Some("clone"));
        // The content passed to persist reproduces the projection.
        let content = s.persona_content("clone").unwrap();
        let rp = newt_core::RoleProfile::parse(&content).unwrap();
        assert_eq!(rp.cognition, Some(Cognition::Meticulous));
        assert_eq!(rp.initiative, Some(Initiative::Eager));
    }

    /// Regression (slice 1b): a panel save writes initiative only when it was
    /// chosen. The old save always wrote the projected tenacity, baking the
    /// model family's default (e.g. nemotron's) into the persona, where it
    /// then pinned every other model the persona ran on.
    #[test]
    fn save_never_bakes_in_the_model_default_initiative() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        newt_core::initiative::clear_cli_initiative();
        let mut family = seed(None, two_personas(), Initiative::Eager, None, "");
        family.initiative_from_family = true;
        let s = PanelState::new(family);
        assert_eq!(s.projected_initiative(), Initiative::Eager, "shown");
        let rp = newt_core::RoleProfile::parse(&s.persona_content("fresh").unwrap()).unwrap();
        assert_eq!(rp.initiative, None, "a family default is not a choice");

        // Moving the dial IS a choice, and is saved.
        let mut s = panel(None, two_personas(), Initiative::Eager);
        for _ in 0..4 {
            s.down(); // → initiative
        }
        s.cycle(1); // auto → patient
        let rp = newt_core::RoleProfile::parse(&s.persona_content("fresh").unwrap()).unwrap();
        assert_eq!(rp.initiative, Some(Initiative::Patient));
    }

    #[test]
    fn active_persona_absent_from_the_list_is_kept_not_silently_cleared() {
        // review-3 follow-up: if the active persona isn't in the projected list
        // (e.g. its file failed to load), it must still show "(active)" and Enter
        // must map to Keep — never a silent Clear at index 0.
        let _g = GlobalSettingsGuard::acquire();
        let s = panel(Some("ghost"), two_personas(), Initiative::Measured);
        assert!(s.persona_label().contains("ghost"));
        assert!(s.persona_label().contains("(active)"));
        assert_eq!(s.persona_action(), PersonaAction::Keep);
    }

    #[test]
    fn saving_an_unavailable_persona_refuses_instead_of_replacing_its_unknown_profile() {
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(Some("unavailable"), two_personas(), Initiative::Measured);
        let mut writes = 0;
        let mut persist = |name: &str, _content: &str, _overwrite: bool| {
            writes += 1;
            SaveResult::Saved { name: name.into() }
        };
        s.begin_command("wq! unavailable");
        assert_eq!(s.run_command(&mut persist), None, "keep the draft open");
        assert_eq!(writes, 0, "unknown restrictions must never be overwritten");
        assert!(s.saved.is_none());
        assert!(s
            .status
            .as_deref()
            .is_some_and(|s| s.contains("unavailable")));
    }

    #[test]
    fn saved_persona_preserves_explicit_false_and_escapes_backend_names() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let backend = "local \"quoted\" \\ route";
        let personas = vec![PersonaChoice {
            name: "quiet".into(),
            profile: Some(newt_core::RoleProfile {
                prompt: "# Quiet".into(),
                backend: Some(backend.into()),
                crew: Some(false),
                ..Default::default()
            }),
        }];
        let s = panel(Some("quiet"), personas, Initiative::Measured);
        let saved = newt_core::RoleProfile::parse(&s.persona_content("quiet-copy").unwrap())
            .expect("the panel must serialize valid TOML, including quoted values");
        assert_eq!(saved.backend.as_deref(), Some(backend));
        assert_eq!(
            saved.crew,
            Some(false),
            "explicit false must not become inherit"
        );
    }

    /// Grounds serialization refusal in the same real store used by panel
    /// saves: even an explicit overwrite must not replace a valid restricted
    /// persona with a document that the shared metadata reader cannot reload.
    #[test]
    #[serial_test::serial(real_fs)]
    fn saving_invalid_metadata_never_overwrites_an_existing_persona() {
        let _guard = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let original = "+++\ntools = [\"read_file\"]\n[caveats]\nfs_write = \"none\"\nexec = \"none\"\n+++\n\nKeep these restrictions and this prose.\n";
        for (case, backend) in [
            ("multiline fence", "first\n+++\nlast".to_string()),
            (
                "oversized header",
                "x".repeat(newt_core::markup::MAX_ENVELOPE_BYTES + 1),
            ),
        ] {
            let tmp = tempfile::tempdir().unwrap();
            let store = crate::PersonaStore::new(tmp.path());
            let path = store.save("protected", original, false).unwrap();
            let before = store.load("protected").unwrap();
            let mut state = panel(
                Some("candidate"),
                vec![PersonaChoice {
                    name: "candidate".into(),
                    profile: Some(newt_core::RoleProfile {
                        prompt: "Candidate body remains in the draft.".into(),
                        backend: Some(backend),
                        ..Default::default()
                    }),
                }],
                Initiative::Measured,
            );
            let mut writes = 0;
            let mut persist = |name: &str, content: &str, overwrite: bool| {
                writes += 1;
                match store.save(name, content, overwrite) {
                    Ok(_) => SaveResult::Saved { name: name.into() },
                    Err(err) => SaveResult::Failed(format!("{err:?}")),
                }
            };
            state.begin_command("wq! protected");
            let outcome = state.run_command(&mut persist);
            assert_eq!(std::fs::read_to_string(&path).unwrap(), original, "{case}");
            assert_eq!(
                writes, 0,
                "invalid metadata must not reach persistence: {case}"
            );
            assert_eq!(outcome, None, "failed save keeps the draft open: {case}");
            assert!(state.saved.is_none(), "{case}");
            assert!(
                state
                    .status
                    .as_deref()
                    .is_some_and(|s| s.contains("save failed")),
                "{case}: {:?}",
                state.status
            );
            assert_eq!(store.load("protected").unwrap(), before, "{case}");
            assert_eq!(state.persona_action(), PersonaAction::Keep, "{case}");
        }
    }

    /// Grounds the injected save tests in the real store and the same loaded-
    /// persona conversion used by the chat loop: a save must preserve the body
    /// and every restriction, not just the panel's projected dials.
    #[test]
    #[serial_test::serial(real_fs)]
    fn saving_a_loaded_persona_preserves_its_full_restrictive_profile() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let tmp = tempfile::tempdir().unwrap();
        let store = crate::PersonaStore::new(tmp.path());
        let document = r#"+++
role = "reviewer"
tools = ["read_file"]
skills = ["code-review"]
model = "review-model"
tier = "REVIEW"
altitude = "coach"
backend = "review-backend"
cognition = "rational"
tenacity = "relaxed"
crew = false

[caveats]
fs_read = ["src/"]
fs_write = "none"
exec = "none"
net = "none"
max_calls = 3
+++

# Restricted reviewer

Read the code and explain findings. Do not edit files or run commands.
"#;
        store.save("restricted", document, false).unwrap();
        let original = store.load("restricted").unwrap();
        let mut s = panel(
            Some("restricted"),
            vec![PersonaChoice::from(original.clone())],
            Initiative::Measured,
        );
        let mut persist = |name: &str, content: &str, overwrite: bool| match store
            .save(name, content, overwrite)
        {
            Ok(_) => SaveResult::Saved { name: name.into() },
            Err(err) => SaveResult::Failed(format!("{err:?}")),
        };
        s.begin_command("w restricted-copy");
        assert_eq!(
            s.run_command(&mut persist),
            None,
            "save alone does not apply"
        );
        assert_eq!(s.saved.as_deref(), Some("restricted-copy"));
        let saved = store.load("restricted-copy").unwrap();
        assert_eq!(saved.profile, original.profile);
        assert_eq!(saved.prompt, original.prompt);
        assert_eq!(store.load("restricted").unwrap(), original);
    }

    /// Grounds the full-posture save contract in the real persona store: a
    /// style-only draft snapshots unrelated projected dials, but never drops
    /// the source profile's prose or non-panel restriction metadata.
    #[test]
    #[serial_test::serial(real_fs)]
    fn style_only_draft_save_snapshots_projected_posture_and_preserves_restrictions() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Set(Cognition::Meticulous));
        set_cli_tenacity(Tenacity::Relentless);
        newt_core::initiative::set_cli_initiative(Initiative::Decisive);
        newt_core::process_env::set_var("NEWT_TEAM", "1");
        let _ = newt_core::runtime::drain_preference_actions();
        let tmp = tempfile::tempdir().unwrap();
        let store = crate::PersonaStore::new(tmp.path());
        let document = "+++\nrole = \"reviewer\"\ntools = [\"read_file\"]\n\
            skills = [\"code-review\"]\nmodel = \"review-model\"\ntier = \"REVIEW\"\n\
            altitude = \"coach\"\n[caveats]\nfs_read = [\"src/\"]\n\
            fs_write = \"none\"\nexec = \"none\"\nnet = \"none\"\nmax_calls = 3\n\
            +++\n\n# Sparse reviewer\n\nRead the code and explain findings without editing.\n";
        let original_path = store.save("sparse", document, false).unwrap();
        let original = store.load("sparse").unwrap();
        assert!(original.profile.backend.is_none() && original.profile.crew.is_none());
        assert!(original.profile.cognition.is_none() && original.profile.initiative.is_none());
        let mut s = panel(
            Some("sparse"),
            vec![PersonaChoice::from(original.clone())],
            Initiative::Measured,
        );
        for _ in 0..7 {
            s.down(); // warmth: leave cognition, tenacity and model untouched
        }
        s.cycle(1); // auto -> explicit zero
        assert_eq!(s.persona_action(), PersonaAction::Keep);
        assert!(!s.cognition.is_dirty() && !s.tenacity.is_dirty() && !s.model.is_dirty());
        let mut persist = |name: &str, content: &str, overwrite: bool| match store
            .save(name, content, overwrite)
        {
            Ok(_) => SaveResult::Saved { name: name.into() },
            Err(err) => SaveResult::Failed(format!("{err:?}")),
        };
        s.begin_command("w sparse-copy");
        assert_eq!(
            s.run_command(&mut persist),
            None,
            "save alone does not apply"
        );
        assert_eq!(s.saved.as_deref(), Some("sparse-copy"));
        let mut expected = original.profile.clone();
        expected.backend = Some("sol".into()); // the fixture's operator baseline
        expected.cognition = Some(Cognition::Meticulous);
        // Tenacity is not a persona dial; a set initiative is snapshotted.
        expected.initiative = Some(Initiative::Decisive);
        expected.crew = Some(true);
        expected.personality = Some(PersonalityTraits {
            warmth: Some(PersonalityLevel::try_from(0).unwrap()),
            ..Default::default()
        });
        let saved = store.load("sparse-copy").unwrap();
        assert_eq!(
            saved.profile, expected,
            "only projected panel fields change"
        );
        assert_eq!(saved.prompt, original.prompt);
        assert_eq!(std::fs::read_to_string(original_path).unwrap(), document);
        assert_eq!(store.load("sparse").unwrap(), original);
        assert_eq!(
            cli_cognition(),
            CognitionOverride::Set(Cognition::Meticulous)
        );
        assert_eq!(cli_tenacity(), Some(Tenacity::Relentless));
        assert!(newt_core::runtime::drain_preference_actions().is_empty());
    }

    #[test]
    fn personality_controls_are_independent_named_rows() {
        let _g = GlobalSettingsGuard::acquire();
        let s = panel(None, two_personas(), Initiative::Measured);
        let rows = s.view_rows();
        for label in [
            "agreeableness",
            "extraversion",
            "warmth",
            "approachability",
            "prosocial behavior",
        ] {
            let matches: Vec<_> = rows.iter().filter(|row| row.label == label).collect();
            assert_eq!(matches.len(), 1, "one operator dial for {label}");
            assert!(matches[0].editable, "{label} is an operator control");
        }
    }

    #[test]
    fn personality_panel_keeps_the_selected_dial_and_exit_hint_visible_when_short() {
        use ratatui::{backend::TestBackend, Terminal};
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        for _ in 0..9 {
            s.down();
        }
        let mut term = Terminal::new(TestBackend::new(100, 7)).unwrap();
        term.draw(|f| draw(f, &s)).unwrap();
        let buf = term.backend().buffer();
        let screen: String = buf.content.iter().map(|cell| cell.symbol()).collect();
        assert!(screen.contains("❯ prosocial behavior"), "{screen}");
        assert!(screen.contains("Esc cancel"), "{screen}");
    }

    #[test]
    fn personality_apply_returns_only_edited_axes_after_an_explicit_apply() {
        use newt_core::role_profile::{PersonalityLevel, PersonalityTrait, PersonalityTraits};
        let _g = GlobalSettingsGuard::acquire();
        let mut initial = seed(None, two_personas(), Initiative::Measured, None, "");
        initial.personality = PersonalityTraits {
            warmth: Some(PersonalityLevel::try_from(73).unwrap()),
            ..Default::default()
        };
        let mut s = PanelState::new(initial);
        assert_eq!(close_outcome(true, &s), PanelOutcome::Cancelled);
        for _ in 0..5 {
            s.down();
        }
        s.cycle(1);
        assert_eq!(close_outcome(false, &s), PanelOutcome::Cancelled);
        assert_eq!(
            close_outcome(true, &s),
            PanelOutcome::Applied {
                persona: PersonaAction::Keep,
                model: None,
                personality: vec![(
                    PersonalityTrait::Agreeableness,
                    Some(PersonalityLevel::try_from(0).unwrap()),
                )],
            }
        );
    }

    #[test]
    fn personality_clear_does_not_reapply_untouched_overrides_to_the_new_conversation() {
        use newt_core::role_profile::{PersonalityLevel, PersonalityTrait, PersonalityTraits};
        let _g = GlobalSettingsGuard::acquire();
        let mut initial = seed(Some("bob"), two_personas(), Initiative::Measured, None, "");
        initial.personality = PersonalityTraits {
            warmth: Some(PersonalityLevel::try_from(73).unwrap()),
            ..Default::default()
        };
        let mut s = PanelState::new(initial);
        s.cycle(-1); // clear persona, which starts a new conversation
        for _ in 0..5 {
            s.down();
        }
        s.cycle(1);
        assert_eq!(
            close_outcome(true, &s),
            PanelOutcome::Applied {
                persona: PersonaAction::Clear,
                model: None,
                personality: vec![(
                    PersonalityTrait::Agreeableness,
                    Some(PersonalityLevel::try_from(0).unwrap()),
                )],
            }
        );
        let saved = newt_core::RoleProfile::parse(&s.persona_content("copy").unwrap()).unwrap();
        assert_eq!(
            saved.personality.unwrap().warmth,
            None,
            "the saved preview agrees with the new-conversation reset"
        );
    }

    #[test]
    fn personality_dials_save_each_axis_without_switching_persona_or_other_dials() {
        use newt_core::role_profile::{PersonalityLevel, PersonalityTrait};
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        for (index, kind) in PersonalityTrait::ALL.into_iter().enumerate() {
            let mut s = panel(
                Some("base"),
                vec![choice("base", None, None)],
                Initiative::Measured,
            );
            for _ in 0..5 + index {
                s.down();
            }
            s.cycle(1); // inherit -> explicit 0, never an implicit midpoint
            assert_eq!(s.persona_action(), PersonaAction::Keep, "{}", kind.key());
            assert!(!s.cognition.is_dirty() && !s.tenacity.is_dirty());
            assert!(!s.is_noop(), "moving {} is an explicit edit", kind.key());
            let saved = newt_core::RoleProfile::parse(&s.persona_content("copy").unwrap()).unwrap();
            let traits = saved.personality.expect("save the projected style");
            for other in PersonalityTrait::ALL {
                let expected = (other == kind).then(|| PersonalityLevel::try_from(0).unwrap());
                assert_eq!(
                    traits.get(other),
                    expected,
                    "{} / {}",
                    kind.key(),
                    other.key()
                );
            }
            assert_eq!(close_outcome(false, &s), PanelOutcome::Cancelled);
        }
    }

    #[test]
    fn personality_dial_projects_persona_inheritance_and_validated_endpoints() {
        use newt_core::role_profile::{PersonalityLevel, PersonalityTrait};
        let _g = GlobalSettingsGuard::acquire();
        let profile = newt_core::RoleProfile::parse(
            "+++\n[personality]\nagreeableness = 73\n+++\nKeep the review evidence-based.",
        )
        .unwrap();
        let mut s = panel(
            Some("reviewer"),
            vec![PersonaChoice {
                name: "reviewer".into(),
                profile: Some(profile.clone()),
            }],
            Initiative::Measured,
        );
        let saved = |s: &PanelState| {
            newt_core::RoleProfile::parse(&s.persona_content("copy").unwrap()).unwrap()
        };
        assert_eq!(
            saved(&s).personality,
            profile.personality,
            "untouched inherits"
        );
        for _ in 0..5 {
            s.down();
        }
        s.cycle(1);
        assert_eq!(
            saved(&s)
                .personality
                .unwrap()
                .get(PersonalityTrait::Agreeableness),
            Some(PersonalityLevel::try_from(0).unwrap())
        );
        for _ in 0..110 {
            s.cycle(1);
        }
        assert_eq!(
            saved(&s)
                .personality
                .unwrap()
                .get(PersonalityTrait::Agreeableness),
            Some(PersonalityLevel::try_from(100).unwrap())
        );
        for _ in 0..110 {
            s.cycle(-1);
        }
        assert_eq!(
            saved(&s).personality,
            profile.personality,
            "inherit releases the override"
        );
        assert_eq!(
            saved(&s).prompt,
            profile.prompt,
            "style edits retain the body"
        );
    }

    #[test]
    fn a_noop_visit_is_detected_so_enter_closes_silently() {
        // #1665: bare /psyche opens the panel, so browsing-then-Enter must be a
        // no-op — nothing applied, nothing reported. Moving the selection is
        // not a change; touching a dial (even back to its original value) is.
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(Some("bob"), two_personas(), Initiative::Measured);
        assert!(s.is_noop(), "fresh panel: nothing to apply");
        s.down();
        s.up();
        assert!(s.is_noop(), "row selection alone is not a change");
        // Touch the cognition dial: dirty even after cycling back — a deliberate
        // same-value re-apply is still an operator action.
        s.down(); // persona → model
        s.down(); // model → cognition
        s.cycle(1);
        assert!(!s.is_noop(), "a touched dial is a change");
        s.cycle(-1);
        assert!(!s.is_noop(), "cycled back is still dirty (re-apply)");
        // A persona switch is a change too.
        let mut p = panel(Some("bob"), two_personas(), Initiative::Measured);
        while p.persona_idx != 0 {
            p.cycle(-1);
        }
        assert!(!p.is_noop(), "persona Clear is a change");
        // A touched model spinner is a change too (#1666).
        let mut m = panel(Some("bob"), two_personas(), Initiative::Measured);
        m.down(); // persona → model
        m.cycle(1);
        assert!(!m.is_noop(), "a touched model spinner is a change");
    }

    #[test]
    fn model_spinner_dials_served_models_and_reports_only_a_touched_pick() {
        // #1666: the spinner opens ON the active model, ←/→ moves through the
        // served list, and chosen_model() reports None until touched.
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        assert_eq!(s.chosen_model(), None, "untouched spinner picks nothing");
        assert!(
            s.model_label().contains("m2") && s.model_label().contains("(active)"),
            "opens on the active model: {}",
            s.model_label()
        );
        s.down(); // persona → model
        s.cycle(1); // m2 → m3
        assert_eq!(s.chosen_model().as_deref(), Some("m3"));
        // The pick rides the outcome through the REAL exit path.
        assert_eq!(
            close_outcome(true, &s),
            PanelOutcome::Applied {
                persona: PersonaAction::Keep,
                model: Some("m3".to_string()),
                personality: vec![],
            }
        );
        assert!(
            s.model_label().contains("(pending)"),
            "a non-active position renders pending: {}",
            s.model_label()
        );
        // Touched-back-to-original is still a deliberate re-apply pick.
        s.cycle(-1);
        assert_eq!(s.chosen_model().as_deref(), Some("m2"));
        // Left edge clamps (no wrap): m2 → m1 → m1.
        s.cycle(-1);
        s.cycle(-1);
        assert_eq!(s.chosen_model().as_deref(), Some("m1"));
    }

    #[test]
    fn an_active_model_missing_from_the_served_list_is_appended_not_lost() {
        // #1666: same guarantee as the persona ghost — the panel must open ON
        // the active model even when the backend's list omits it, or Enter
        // could apply a silently repositioned spinner.
        let _g = GlobalSettingsGuard::acquire();
        let s = PanelState::new(seed(
            None,
            two_personas(),
            Initiative::Measured,
            Some(model_choices(&["m1", "m2"])),
            "ghost-model",
        ));
        assert!(
            s.model_label().contains("ghost-model")
                && s.model_label().contains("(not served)")
                && s.model_label().contains("(active)"),
            "{}",
            s.model_label()
        );
        assert_eq!(s.chosen_model(), None, "still untouched");
    }

    #[test]
    fn an_unreachable_backend_disables_the_model_dial() {
        // #1666: no served list → the row says why, won't dial, never picks.
        let _g = GlobalSettingsGuard::acquire();
        let mut s = PanelState::new(seed(None, two_personas(), Initiative::Measured, None, "m2"));
        assert!(
            s.model_label().contains("unreachable"),
            "{}",
            s.model_label()
        );
        s.down(); // persona → model
        s.cycle(1);
        assert_eq!(s.chosen_model(), None, "cycling a dead row picks nothing");
        assert!(s.is_noop(), "a dead model row cannot dirty the visit");
    }

    #[test]
    fn no_backend_persona_projects_the_operator_baseline() {
        // review-3 §3: a persona that declares no backend projects the operator
        // BASELINE (the revert target), not the outgoing persona's backend.
        let _g = GlobalSettingsGuard::acquire();
        let personas = vec![PersonaChoice {
            name: "alice".to_string(),
            profile: Some(newt_core::RoleProfile {
                prompt: "# Alice".into(),
                ..Default::default()
            }),
        }];
        let mut s = PanelState::new(seed(None, personas, Initiative::Measured, None, ""));
        s.cycle(1); // none → alice
        assert_eq!(
            s.projected_backend().as_deref(),
            Some("sol"),
            "no-backend persona reverts to the baseline"
        );
        assert_eq!(s.backend_provenance(), "base");
    }

    #[test]
    fn persona_row_shows_active_and_maps_none_to_clear() {
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(Some("bob"), two_personas(), Initiative::Measured);
        assert_eq!(
            s.persona_action(),
            PersonaAction::Keep,
            "opens on the active"
        );
        assert!(s.persona_label().contains("(active)"));
        // Cycle to `none` → Clear (there is an active persona to clear).
        while s.persona_idx != 0 {
            s.cycle(-1);
        }
        assert_eq!(s.persona_action(), PersonaAction::Clear);
        assert!(s.persona_label().contains("clears active"));
        // Cycle to obsessive → Switch + "(pending)".
        s.cycle(1); // bob
        s.cycle(1); // obsessive
        assert_eq!(
            s.persona_action(),
            PersonaAction::Switch("obsessive".to_string())
        );
        assert!(s.persona_label().contains("(pending)"));
    }

    #[test]
    fn wq_success_saves_then_signals_apply() {
        // review-3 §1: :wq whose save lands → close-with-apply, and `saved` records.
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        let mut persist = ok_persist();
        s.begin_command("wq alice");
        assert_eq!(
            s.run_command(&mut persist),
            Some(true),
            ":wq closes with apply"
        );
        assert_eq!(s.saved.as_deref(), Some("alice"));
    }

    #[test]
    fn wq_failed_save_does_not_apply_and_stays_open() {
        // review-3 §1: a failed persist must NOT close/apply; the panel stays open
        // with a visible error and records nothing as saved.
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        // change a dial so we can prove it was NOT applied
        s.down(); // model
        s.down(); // cognition
        s.cycle(1); // auto → off (dirty)
        assert!(s.cognition.is_dirty());
        let mut persist =
            |_n: &str, _c: &str, _o: bool| SaveResult::Failed("disk full".to_string());
        s.begin_command("wq alice");
        assert_eq!(
            s.run_command(&mut persist),
            None,
            "failed :wq does NOT close (so the caller never applies)"
        );
        assert!(s.saved.is_none(), "nothing recorded as saved");
        assert!(
            s.status.as_deref().unwrap().contains("disk full"),
            "the failure is visible"
        );
        // The dirty dial is untouched in the working copy; apply() was never called.
        assert!(s.cognition.is_dirty(), "edits intact for a retry");
    }

    #[test]
    fn wq_exists_without_bang_is_refused_visibly() {
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        let mut persist = |name: &str, _c: &str, overwrite: bool| {
            if overwrite {
                SaveResult::Saved {
                    name: name.to_string(),
                }
            } else {
                SaveResult::Exists {
                    name: name.to_string(),
                }
            }
        };
        s.begin_command("wq bob");
        assert_eq!(s.run_command(&mut persist), None, "exists → stay open");
        assert!(s.status.as_deref().unwrap().contains("exists"));
        assert!(s.saved.is_none());
        // With the bang it overwrites and applies.
        s.begin_command("wq! bob");
        assert_eq!(s.run_command(&mut persist), Some(true));
        assert_eq!(s.saved.as_deref(), Some("bob"));
    }

    #[test]
    fn ex_commands_validate_visibly() {
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        let mut persist = ok_persist();
        // :wq with no name → refuse, stay open, visible status.
        s.begin_command("wq");
        assert_eq!(
            s.run_command(&mut persist),
            None,
            ":wq without a name does not close"
        );
        assert!(s.status.as_deref().unwrap().contains("needs a name"));
        assert!(s.saved.is_none());
        // Unknown command → visible error.
        s.begin_command("banana");
        assert_eq!(s.run_command(&mut persist), None);
        assert!(s.status.as_deref().unwrap().contains("unknown command"));
        // :q → cancel + close.
        s.begin_command("q");
        assert_eq!(s.run_command(&mut persist), Some(false));
    }

    #[test]
    fn w_then_cancel_is_saved_not_applied() {
        // Driving `run` needs a TTY, so assert the OUTCOME mapping directly: a save
        // happened (`saved` set) but the loop was cancelled (applied = false) →
        // PanelOutcome::Saved, never a posture summary from the working copy.
        let _g = GlobalSettingsGuard::acquire();
        let mut s = panel(None, two_personas(), Initiative::Measured);
        let mut persist = ok_persist();
        s.begin_command("w keep");
        s.run_command(&mut persist);
        assert_eq!(s.saved.as_deref(), Some("keep"));
        // The REAL exit path (close_outcome), not a hand-copied match: a save
        // happened but the loop was cancelled → Saved, never a posture summary.
        assert_eq!(
            close_outcome(false, &s),
            PanelOutcome::Saved {
                name: "keep".to_string()
            }
        );
        // And an Enter AFTER a lone :w with no dial/persona change: still Saved
        // (the save is reported; the noop "apply" stays silent), NOT
        // SavedAndApplied.
        assert_eq!(
            close_outcome(true, &s),
            PanelOutcome::Saved {
                name: "keep".to_string()
            }
        );
    }

    #[test]
    fn close_outcome_downgrades_a_noop_enter_and_applies_a_real_one() {
        // Adversarial-review findings on #1665: (1) the Enter downgrade
        // `applied && !is_noop()` must be exercised through the REAL exit path;
        // (2) each dial term of is_noop needs a dial-ONLY dirty case —
        // dropping `!self.tenacity.is_dirty()` from is_noop silently discarded
        // a tenacity-only edit (apply() skipped, Cancelled returned).
        use newt_core::cognition::{set_cli_cognition, CognitionOverride};
        use newt_core::initiative::{cli_initiative, set_cli_initiative};
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        set_cli_tenacity(Tenacity::Normal);
        set_cli_initiative(Initiative::Measured);

        // Noop visit: Enter and Esc are indistinguishable — both Cancelled.
        let s = panel(None, two_personas(), Initiative::Measured);
        assert_eq!(close_outcome(true, &s), PanelOutcome::Cancelled);
        assert_eq!(close_outcome(false, &s), PanelOutcome::Cancelled);
        assert_eq!(cli_tenacity(), Some(Tenacity::Normal), "nothing applied");

        let applied = PanelOutcome::Applied {
            persona: PersonaAction::Keep,
            model: None,
            personality: vec![],
        };
        // Tenacity-ONLY dirty + Enter → a real Applied, and the override is
        // actually written through apply().
        let mut t = panel(None, two_personas(), Initiative::Measured);
        t.down(); // persona → model
        t.down(); // model → cognition
        t.down(); // cognition → tenacity
        t.cycle(1); // normal → relentless (dirty)
        assert_eq!(close_outcome(true, &t), applied);
        assert_eq!(
            cli_tenacity(),
            Some(Tenacity::Relentless),
            "the tenacity-only edit was applied, not silently discarded"
        );
        set_cli_tenacity(Tenacity::Normal);
        assert_eq!(close_outcome(false, &t), PanelOutcome::Cancelled);
        assert_eq!(cli_tenacity(), Some(Tenacity::Normal));

        // Initiative-ONLY dirty: the same, for the dial the split added.
        let mut i = panel(None, two_personas(), Initiative::Measured);
        for _ in 0..4 {
            i.down(); // → initiative
        }
        i.cycle(1); // measured → decisive (dirty)
        assert_eq!(close_outcome(true, &i), applied);
        assert_eq!(cli_initiative(), Some(Initiative::Decisive));
    }

    #[test]
    fn panel_choices_use_the_loaded_active_profile_instead_of_changed_disk_content() {
        let mut active = crate::test_persona("reviewer", "The loaded prompt.", "loaded.md".into());
        active.profile.tools = Some(vec!["read_file".into()]);
        active.profile.crew = Some(false);
        let disk = crate::test_persona("reviewer", "A later disk edit.", "edited.md".into());
        let other = crate::test_persona("writer", "Another persona.", "writer.md".into());

        let choices = PersonaChoice::for_panel(vec![disk, other.clone()], Some(&active));

        assert_eq!(choices.len(), 2, "the active name must not be duplicated");
        assert_eq!(
            choices.iter().find(|p| p.name == "reviewer"),
            Some(&PersonaChoice::from(active)),
            "Keep previews the profile already loaded by the chat loop"
        );
        assert_eq!(
            choices.iter().find(|p| p.name == "writer"),
            Some(&PersonaChoice::from(other)),
            "unselected disk candidates remain unchanged"
        );
    }

    /// Grounds the candidate-merge rule in a real save/reload: deleting the
    /// source file does not make an already loaded, known profile a ghost.
    #[test]
    #[serial_test::serial(real_fs)]
    fn panel_choices_keep_a_missing_but_loaded_active_persona_saveable() {
        let _g = GlobalSettingsGuard::acquire();
        set_cli_cognition(CognitionOverride::Unset);
        clear_cli_tenacity();
        let tmp = tempfile::tempdir().unwrap();
        let store = crate::PersonaStore::new(tmp.path());
        store
            .save(
                "reviewer",
                r#"+++
role = "reviewer"
tools = ["read_file"]
backend = "sol"
tenacity = "standard"
crew = false
[caveats]
fs_write = "none"
exec = "none"
net = "none"
[personality]
warmth = 73
+++

Keep this loaded prompt and its restrictions.
"#,
                false,
            )
            .unwrap();
        let active = store.load("reviewer").unwrap();
        std::fs::remove_file(&active.path).unwrap();
        assert!(store.load("reviewer").is_err(), "the source is absent");
        let choices = PersonaChoice::for_panel(Vec::new(), Some(&active));
        assert_eq!(choices, vec![PersonaChoice::from(active.clone())]);
        let mut s = panel(Some("reviewer"), choices, Initiative::Measured);
        let mut persist = |name: &str, content: &str, overwrite: bool| match store
            .save(name, content, overwrite)
        {
            Ok(_) => SaveResult::Saved { name: name.into() },
            Err(err) => SaveResult::Failed(format!("{err:?}")),
        };

        s.begin_command("w reviewer-copy");
        assert_eq!(s.run_command(&mut persist), None, "save is not Apply");
        assert_eq!(s.saved.as_deref(), Some("reviewer-copy"));
        let saved = store.load("reviewer-copy").unwrap();
        assert_eq!(saved.profile, active.profile);
        assert_eq!(saved.prompt, active.prompt);
    }

    #[test]
    fn panel_choices_without_an_active_persona_preserve_all_loaded_candidates() {
        let mut first = crate::test_persona("first", "First prompt.", "first.md".into());
        first.profile.crew = Some(false);
        let mut second = crate::test_persona("second", "Second prompt.", "second.md".into());
        second.profile.tools = Some(vec!["read_file".into()]);
        let expected = vec![
            PersonaChoice::from(first.clone()),
            PersonaChoice::from(second.clone()),
        ];

        assert_eq!(
            PersonaChoice::for_panel(vec![first, second], None),
            expected
        );
    }
}