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
//! Interactive OCAP decisions. One typed [`newt_core::Question`] supplies both
//! terminal and web rendering, parsing, and the set of actions that may pass.

use std::io;
#[cfg(feature = "rich-tui")]
use std::io::IsTerminal as _;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use crate::danger;
use crate::mint_operating_key;
use newt_core::agentic::{newt_line, print_newt};
use newt_core::interaction_adapter::{action_for_option, role_of, DECISION_CONTROL};
use newt_core::interaction_surface::SurfaceInteraction;
use newt_core::markup::plain;
use newt_core::tty::{
    modal_prompt_controls, read_prompt_window_line, ControlReader, Echo, PromptLine as ModalLine,
    PromptWindow, Terminal, MODAL_CONTROL_HINT, MODAL_INPUT_GLYPH,
};
use newt_core::HumanQuestionOutcome;
#[path = "permission_workflow.rs"]
mod workflow;
pub(crate) use newt_core::PermissionAction as PromptChoice;
pub(crate) use workflow::{load_session_grants, PermissionWorkflow};
// D0 (#1878): the legacy form is not named here at all any more. C0a moved
// rendering off it; C3c removed the web card's reconstruction; D0 moved the
// decode onto `newt_interaction::binding::resolve_typed` and deleted the
// reverse adapter. The `#[cfg(test)]` that stood here belonged to the
// `newt_core::Question` import beside it — both are gone, and these protocol
// types are production imports.
use newt_interaction::{
    Audience, ChoiceOption, Control, ControlId, ControlKind, InteractionDefinition,
    InteractionKind, OptionId, Requirement,
};

/// The reserved control id of the free-text form's single answer field.
///
/// Sibling of `interaction_adapter::DECISION_CONTROL`, kept here because
/// the free-text form is `newt-tui`'s, not the adapter's. D0 owns promoting
/// it when `request_user_input` moves onto the controller.
const ANSWER_CONTROL: &str = "answer";

// ---------------------------------------------------------------------------

/// Whether prompted permissions were explicitly enabled for this session.
pub(crate) fn permission_prompting_configured(
    env_flag: bool,
    tui: Option<&newt_core::TuiConfig>,
) -> bool {
    env_flag || tui.is_some_and(|t| t.permissions.prompt)
}

/// Match the trusted prefix of Config's base precedence. An ambient newt.toml
/// shadows user config while its own permissions are stripped as untrusted.
pub(crate) fn durable_permission_config_target(
    pinned: Option<std::path::PathBuf>,
    ambient_base_exists: bool,
    user: Option<std::path::PathBuf>,
) -> Option<std::path::PathBuf> {
    pinned.or(if ambient_base_exists { None } else { user })
}

const INTERACTIVE_PROMPT_DEFAULT: bool = true;

/// Headless/non-TTY and explicit-off are fail-closed; interactive defaults on.
pub(crate) fn should_prompt_permissions(
    configured_on: bool,
    explicit_off: bool,
    interactive: bool,
    headless: bool,
) -> bool {
    if headless || !interactive {
        return false;
    }
    if explicit_off {
        return false;
    }
    configured_on || INTERACTIVE_PROMPT_DEFAULT
}
#[cfg(unix)]
pub(crate) use newt_core::tty::try_watch_stdin;

pub(crate) fn reason_is_model_authored(req: &newt_core::PermissionRequest) -> bool {
    // #2636 finding 4: use the typed harness_bound field, not the string prefix
    // check. The model can forge BOUND_REASON_PREFIX in its reason text; it
    // cannot set harness_bound, which is only set by execute_request_permissions.
    req.tool == "request_permissions" && !req.harness_bound
}

/// How long the gate waits for a web decision before failing closed.
///
/// **Load bearing, and until B0b-1 untested** (#1842): this must be
/// SHORTER than `ConversationStore::PERMISSION_REQUEST_TTL_NANOS`, or the
/// gate could still be waiting on an offer the store has already aged out
/// — and a decision could land against a row nothing will honour. The two
/// numbers used to live in different crates with nothing relating them
/// (a literal here, a constant there);
/// `b0b::the_gate_timeout_is_shorter_than_the_store_ttl` now asserts the
/// relationship instead of leaving it to coincidence.
pub(crate) const WEB_DECISION_TIMEOUT: Duration = Duration::from_secs(4 * 60);

/// One action this policy offers, already decided.
///
/// The POLICY half hands these to the MARSHALLING half. The split is what
/// lets tier and audience be consulted TOGETHER — they decide the action
/// list *and* the note text in the same branches, exactly as before — while
/// the construction of protocol records stays mechanical.
struct OfferedAction {
    action: PromptChoice,
    key: &'static str,
    label: &'static str,
}

/// **The POLICY half** (B0a, #1841): which actions this `(tier, audience)`
/// pair offers, and the note that accompanies them.
///
/// This is a RESTRUCTURING of the old `permission_question_for`, not a
/// relocation: the high-tier arms produce genuinely different per-surface
/// text, and the durable grants are terminal-only, so tier and audience
/// must still be known simultaneously.
fn permission_policy(
    req: &newt_core::PermissionRequest,
    danger: &danger::DangerTable,
    audience: Audience,
) -> (Vec<OfferedAction>, Option<String>) {
    use newt_core::DenialKind;
    let tier = danger.classify(req.kind, &req.target);
    // ONE audience test, bound once. The A0 shape asked it twice; the two
    // asks were always the same question, so the ratchet baseline goes
    // DOWN by one branch rather than up.
    let terminal = matches!(audience, Audience::Terminal);

    let mut actions = vec![OfferedAction {
        action: PromptChoice::AllowOnce,
        key: "a",
        label: "allow once",
    }];
    // dec1-build-grant (F30): `Build` stays High tier — the blast-radius
    // banner below still fires — but IS session-allowable. It is not an
    // open-ended interpreter/broad-root grant; it is bounded by the
    // calibrated `build_tool_caveats` fence (workspace + toolchain reads,
    // workspace-only writes, network denied), the same confinement an
    // allow-once already grants. Refusing the session scope bought no extra
    // safety, only a prompt on every build/test/check in a session (up to 7
    // times observed in one run — NOTES-2483 F30).
    // #2595: the harness's own dependency fetch (`lifecycle` + net) is a
    // one-shot `cargo fetch`. A recorded session/permanent grant would flow
    // into `recalled_caveats` and widen the shell worker's net to crates.io,
    // which the prompt does not say. Offer allow-once/deny only.
    let one_shot = req.tool == "lifecycle" && req.kind == DenialKind::Net;
    if !one_shot && (tier == danger::DangerTier::Low || req.kind == DenialKind::Build) {
        actions.push(OfferedAction {
            action: PromptChoice::AllowSession,
            key: "s",
            label: "session allow",
        });
        // #2535/#2524 PR1: every durable-store kind offers permanent allow
        // now, not just net — `persist_approve` signs whichever of
        // exec/fs/net the answer names into `approve.toml`.
        if terminal
            && matches!(
                req.kind,
                DenialKind::Exec | DenialKind::FsRead | DenialKind::FsWrite | DenialKind::Net
            )
        {
            actions.push(OfferedAction {
                action: PromptChoice::AllowPermanent,
                key: "A",
                label: "Allow permanently (signs a durable grant)",
            });
        }
    }
    actions.push(OfferedAction {
        action: PromptChoice::Deny,
        key: "d",
        label: "deny",
    });
    if terminal {
        actions.push(OfferedAction {
            action: PromptChoice::DenyAlways,
            key: "D",
            label: "Deny always",
        });
        actions.push(OfferedAction {
            action: PromptChoice::DenyPermanent,
            key: "P",
            label: "Permanently deny",
        });
    }

    // `Audience` is `#[non_exhaustive]`, so this crate cannot match it
    // exhaustively and the wildcard is forced by the language rather than
    // chosen. The tripwire that a third variant needs thinking about lives
    // where the enum is DEFINED —
    // `newt_interaction::binding::model_fidelity` (#1837).
    let note = match (tier, audience) {
        (danger::DangerTier::High, Audience::Terminal) if req.kind == DenialKind::Build => Some(
            format!("confined build authority: session allow covers build/test/check for this workspace this session\n{MODAL_CONTROL_HINT}"),
        ),
        (danger::DangerTier::High, Audience::Web) if req.kind == DenialKind::Build => Some(
            format!("Confined build authority: session authorization is available.\n{MODAL_CONTROL_HINT}"),
        ),
        (danger::DangerTier::High, Audience::Terminal) => Some(format!(
            "high-danger: session allow refused; key allow / step-up is the future path, P3\n{MODAL_CONTROL_HINT}"
        )),
        (danger::DangerTier::High, Audience::Web) => Some(format!(
            "High danger: session authorization is unavailable.\n{MODAL_CONTROL_HINT}"
        )),
        _ => Some(MODAL_CONTROL_HINT.into()),
    };
    (actions, note)
}

/// **The MARSHALLING half** (B0a, #1841): the policy's decisions as ONE
/// [`InteractionDefinition`].
///
/// This is the single form both surfaces build. The prompt text itself is
/// audience-independent; only the action list and the note are not.
pub(crate) fn permission_definition(
    req: &newt_core::PermissionRequest,
    danger: &danger::DangerTable,
    audience: Audience,
) -> InteractionDefinition {
    permission_definition_with_default(req, danger, audience, PromptChoice::Deny).0
}

pub(crate) fn permission_interaction(
    req: &newt_core::PermissionRequest,
    danger: &danger::DangerTable,
    configured_default: PromptChoice,
) -> SurfaceInteraction {
    let configured_default = if req.tool == "mcp connect" && req.kind == newt_core::DenialKind::Net
        || matches!(
            configured_default,
            PromptChoice::AllowOnce | PromptChoice::Deny
        ) {
        configured_default
    } else {
        PromptChoice::Deny
    };
    let (definition, default) = if configured_default == PromptChoice::Deny {
        (
            permission_definition(req, danger, Audience::Terminal),
            PromptChoice::Deny,
        )
    } else {
        permission_definition_with_default(req, danger, Audience::Terminal, configured_default)
    };
    SurfaceInteraction::blocking(definition)
        .with_default_option(OptionId::new(default.as_str()).expect(WIRE_NAMES_ARE_OPTION_IDS))
}

fn permission_definition_with_default(
    req: &newt_core::PermissionRequest,
    danger: &danger::DangerTable,
    audience: Audience,
    default: PromptChoice,
) -> (InteractionDefinition, PromptChoice) {
    use newt_core::DenialKind;
    let (verb, axis) = match req.kind {
        DenialKind::Exec => ("run", "outside the granted exec allowlist"),
        DenialKind::FsRead => ("read", "outside the granted fs_read scope"),
        DenialKind::FsWrite => ("write", "outside the granted fs_write scope"),
        DenialKind::Net if req.tool == "mcp connect" => {
            ("reach", "MCP connection requires a named host grant")
        }
        DenialKind::Net => ("reach", "outside the granted net allowlist"),
        DenialKind::RemoteTool => ("call", "requires operator permission"),
        DenialKind::Build => ("build/test", "requires confined build authority"),
        DenialKind::GitWrite => (
            "commit/stage via git",
            "outside the granted git-write authority",
        ),
    };

    let axis = if req.tool == "request_permissions" {
        "model requested permission"
    } else {
        axis
    };

    let blast = match danger.blast_radius(req.kind, &req.target) {
        Some(line) => format!("{line}\n"),
        None => String::new(),
    };
    let reason = if req.reason.is_empty() {
        String::new()
    } else if reason_is_model_authored(req) {
        format!(
            "  model says (model-authored, unverified): \"{}\"\n",
            req.reason
        )
    } else {
        format!("  ({})\n", req.reason)
    };

    let (offered, note) = permission_policy(req, danger, audience);
    // A configured default cannot introduce an action the policy withheld.
    let default = if offered.iter().any(|offer| offer.action == default) {
        default
    } else {
        PromptChoice::Deny
    };
    let options = offered
        .into_iter()
        .map(|offer| ChoiceOption {
            // The WIRE name is the option's identity; the key is a
            // presentation affordance. Both survive, which is what makes
            // the adapter round trip field-identical.
            id: OptionId::new(offer.action.as_str()).expect(WIRE_NAMES_ARE_OPTION_IDS),
            role: role_of(offer.action),
            label: if offer.action == default {
                format!("{} (default)", offer.label)
            } else {
                offer.label.to_string()
            },
            key: offer.key.to_string(),
            aliases: Vec::new(),
        })
        .collect();

    let controls = vec![Control {
        id: ControlId::new(DECISION_CONTROL).expect(WIRE_NAMES_ARE_OPTION_IDS),
        kind: ControlKind::Choice { options },
        label: String::new(),
        // A permission prompt requires an answer; input loss is never consent.
        requirement: Requirement::Required,
    }];
    // DERIVED, not hardcoded (#1912). The offered actions vary by denial kind,
    // tier and audience, so a permission question may carry two options or
    // five. Hardcoding `Choice` labelled every TWO-action permission as a pick
    // from a displayed set when it is a binary decision — and the kind is
    // bound into the definition's identity, so the label was wrong in the
    // content-addressed record too.
    let kind = if newt_interaction::controls_are_decision_shaped(&controls) {
        InteractionKind::Confirm
    } else {
        InteractionKind::Choice
    };
    let mut definition = InteractionDefinition::new(
        kind,
        format!(
            "\u{2298} {} wants to {verb} `{}` \u{2014} {axis}.\n{blast}{reason}",
            req.tool, req.target
        )
        .trim_end(),
        controls,
    );
    definition.note = note;
    (definition, default)
}

/// Why the `expect`s above cannot fire.
///
/// Every `PermissionAction` wire name, and `DECISION_CONTROL`, is drawn
/// from `[A-Za-z0-9_-]`, and that set is frozen.
/// `b0a::every_offered_action_is_a_valid_option_id` walks every
/// `(DenialKind, tier, audience)` combination this policy can produce and
/// asserts the definition builds, so this branch is unreachable rather
/// than merely unlikely.
const WIRE_NAMES_ARE_OPTION_IDS: &str =
    "every PermissionAction wire name is a valid option id (frozen set; see \
     b0a::every_offered_action_is_a_valid_option_id)";

/// The legacy typed form for one request, **for tests only**.
///
/// B0b-2 (#1846) took this off the production path; C0a (#1856) took
/// RENDERING off it too. What remains is a convenience for the tests that
/// assert on the adapted form — the alias/ambiguity parse properties, and
/// the web card's model reconstruction. Production reaches
/// `permission_definition` directly and renders it with
/// [`plain::render`].
/// The actions a definition offers, in presentation order.
#[cfg(test)]
pub(crate) fn offered_actions(definition: &InteractionDefinition) -> Vec<PromptChoice> {
    definition
        .controls
        .iter()
        .find_map(|c| match &c.kind {
            ControlKind::Choice { options } => Some(options),
            _ => None,
        })
        .map(|options| {
            options
                .iter()
                .filter_map(|o| action_for_option(o.id.as_str()))
                .collect()
        })
        .unwrap_or_default()
}

/// Whether a definition offers `action`, by wire id.
///
/// D0 (#1878): replaces the `question_for` test helper, which reconstructed a
/// legacy `Question` through the now-deleted reverse adapter purely so a test
/// could ask "is this action offered". The definition answers that directly.
#[cfg(test)]
pub(crate) fn offers(definition: &InteractionDefinition, action: PromptChoice) -> bool {
    definition.controls.iter().any(|c| match &c.kind {
        ControlKind::Choice { options } => options.iter().any(|o| o.id.as_str() == action.as_str()),
        _ => false,
    })
}

/// Facade P1b: the production [`danger::DangerTable`] — the built-in
/// interpreter set plus this environment's broad fs roots (`$HOME` and the
/// current workspace dir), which a plain `[s]ession allow` must never grant
/// wholesale (§7-F3/F4). The env read happens once, here, at gate construction;
/// unit tests build a table by hand (`DangerTable::builtin().with_fs_root(...)`)
/// and never touch the real env (the no-real-fs-in-unit-tests rule).
pub(crate) fn production_danger_table() -> danger::DangerTable {
    let mut table = danger::DangerTable::builtin();
    if let Some(home) = std::env::var_os("HOME") {
        table = table.with_fs_root(std::path::PathBuf::from(home));
    }
    if let Ok(cwd) = std::env::current_dir() {
        table = table.with_fs_root(cwd);
    }
    table
}

/// The #1207 blessing judgment, exported as the ONE narrow seam `newt doctor
/// --sign-ocap` (newt-cli) needs from this subsystem: is an ocap-store target
/// high-danger by the production danger table? Passed to
/// [`newt_core::ocap_store::sign_approves`] as its `validate_approve`
/// predicate, so the blessing ceremony can never launder an interpreter or a
/// broad fs root into `approve.toml`. Fs classifies as a WRITE — the
/// conservative reading of a durable fs grant, and the table's High tier is
/// about broad roots on either axis. So this write-time fence is a SUPERSET of
/// the recall-time check (`recalled_grants` classifies by the grant's own
/// kind): anything recall would refuse, the writer already refused.
pub fn ocap_high_danger_predicate() -> impl Fn(newt_core::ocap_store::CapabilityClass, &str) -> bool
{
    let table = production_danger_table();
    move |class, target| {
        let kind = match class {
            newt_core::ocap_store::CapabilityClass::Exec => newt_core::DenialKind::Exec,
            newt_core::ocap_store::CapabilityClass::Fs => newt_core::DenialKind::FsWrite,
            newt_core::ocap_store::CapabilityClass::Net => newt_core::DenialKind::Net,
        };
        table.classify(kind, target) == danger::DangerTier::High
    }
}

/// Read a terminal form. Unknown input and I/O failure fail closed.
///
/// **C0a (#1856): renders through [`plain::render`], not through the
/// semantic type.** The definition itself is what reaches the operator, so
/// the bytes displayed and the authority the answer is checked against are
/// the same value — there is no longer an intermediate form that could
/// drift from it.
///
/// The input glyph gets its OWN final line. `tty::modal::render` repaints
/// only the text after the last `\n`, so this composition is load bearing:
/// it is what makes a keystroke redraw the answer row rather than the menu.
pub(crate) fn prompt_permission_choice(
    w: &PromptWindow,
    interaction: &SurfaceInteraction,
) -> PromptChoice {
    let definition = &interaction.definition;
    let prompt = format!("{}\n{MODAL_INPUT_GLYPH}", plain::render(definition));
    // A permission menu offers visible options; there is nothing to mask.
    match read_prompt_window_line(w, &prompt, Echo::Chars) {
        Ok(ModalLine::Line(answer)) => {
            decode_answer(definition, interaction.answer_or_default(&answer))
        }
        Ok(ModalLine::Back) => PromptChoice::Back,
        Ok(ModalLine::Exit) => PromptChoice::Exit,
        Ok(ModalLine::Eof) | Err(_) => PromptChoice::Deny,
    }
}

/// Decode one operator keystroke to a candidate action.
///
/// **Deliberately still the adapter.** C0a extracts RENDERING; decoding
/// stays exactly where B0b-1 put it — `Question::parse`, reached through
/// `newt_interaction::binding::resolve_typed` — the ONE implementation of the
/// canonical-first / alias / ambiguity-denial rules, and the half
/// `NewtPolicy.PromptForm`'s Lean theorems and TLA+ `AuthorizationDisplayed`
/// govern (BHV-PROMPT-001).
///
/// D0 (#1878) moved that resolution out of `Question::parse` and into the
/// binding module rather than writing a second decoder against
/// `InteractionDefinition` — which would have been the third answer-parser
/// this slice's deletion gate exists to prevent. The rules did not change;
/// only where they live did, and now one place holds them.
///
/// **Fails closed with a CONSTANT, not with a role.** An unresolvable answer
/// denies, and the deny is `PromptChoice::Deny` written here — never an option
/// picked out of the definition by looking for `role == Deny`. A definition can
/// come from untrusted markup and `role` is author-assigned, so deriving the
/// failure mode from it would hand the author the failure mode (A3).
///
/// It denies rather than panicking because this runs with the operator's
/// answer already in hand; a panic here would take the session down
/// mid-decision.
/// The typed line resolved against the definition's own option set, or
/// `None` when it names no offered option.
///
/// Split out of [`decode_answer`] rather than duplicated: the key policy
/// ("a" is allow-once, "A" is allow-permanently, case-exact) lives in
/// `resolve_typed` and must have exactly one reader. The two callers differ
/// only in what they do with an unrecognized line.
fn resolve_answer(definition: &InteractionDefinition, answer: &str) -> Option<PromptChoice> {
    let options = definition.controls.iter().find_map(|c| match &c.kind {
        newt_core::ControlKind::Choice { options } => Some(options),
        _ => None,
    })?;
    newt_interaction::binding::resolve_typed(options, answer)
        .and_then(|option| action_for_option(option.as_str()))
}

fn decode_answer(definition: &InteractionDefinition, answer: &str) -> PromptChoice {
    // The TERMINAL-ONLY path, where the operator is blocked on answering and
    // a bare Enter is the documented "deny (default)".
    resolve_answer(definition, answer).unwrap_or(PromptChoice::Deny)
}

/// Everything `run_web_wait` touches outside the store and the window.
///
/// Bundled rather than passed loose because there are now four of them and
/// they are one idea: the world the wait loop runs against. Each exists so a
/// test can drive the loop with no terminal, no wall clock and no real sleep
/// — and, since C4b, no real stdout either, so "the losing operator was
/// told" is provable in the mocked tier rather than only in a PTY.
struct WebWaitIo<'a, 'w> {
    /// Re-arm the control reader; a fresh one after a transient failure.
    reacquire: &'a mut dyn FnMut() -> io::Result<Box<dyn ControlReader + 'w>>,
    /// The clock. Injected so deadline tests need no wall clock (#1953).
    now: &'a dyn Fn() -> Instant,
    /// Pace the loop.
    sleep: &'a mut dyn FnMut(Duration),
    /// Speak to the operator.
    notify: &'a mut dyn FnMut(&str),
}

/// What a losing terminal operator is told.
///
/// Pure, so the wording is testable without a terminal; the EMISSION is
/// proven separately by injecting the sink, because a message nobody sends
/// is the same defect as no message at all.
fn lost_to_web_message(mine: PromptChoice, winner: PromptChoice) -> String {
    format!(
        "the web answered first — `{}` was applied, not your `{}`",
        winner.as_str(),
        mine.as_str()
    )
}

/// The durable `approve.toml` entry a `[A]llow permanently` answer for
/// `(kind, target)` would write, or the refusal reason for a shape the store
/// must never accept (#2535/#2524 PR1).
///
/// `None` for a kind the durable store has no vocabulary for (`RemoteTool`,
/// `GitWrite`, `Build`) — those keep the session-only fallback. `Some(Err)`
/// for an exec target that names a path (contains a separator) without being
/// absolute: `agent-bridle-core`'s `ExecEntry.target` matches verbatim, so a
/// relative path like `./build.sh` would silently mean "whatever `./` is at
/// match time", never what the operator approved.
fn approve_entry_for(
    kind: newt_core::DenialKind,
    target: &str,
) -> Option<Result<newt_core::ocap_store::ApproveEntry, String>> {
    use newt_core::ocap_store::ApproveEntry;
    match kind {
        newt_core::DenialKind::Exec => {
            let is_path = target.contains('/') || target.contains('\\');
            if is_path && !std::path::Path::new(target).is_absolute() {
                return Some(Err(format!(
                    "permanent allow refused: `{target}` is a relative path — grant a \
                     bare command name or an absolute path instead"
                )));
            }
            Some(Ok(ApproveEntry::Exec {
                target: target.to_string(),
            }))
        }
        newt_core::DenialKind::FsRead => Some(Ok(ApproveEntry::Fs {
            path: target.to_string(),
            write: false,
        })),
        newt_core::DenialKind::FsWrite => Some(Ok(ApproveEntry::Fs {
            path: target.to_string(),
            write: true,
        })),
        newt_core::DenialKind::Net => Some(Ok(ApproveEntry::Net {
            host: target.to_string(),
        })),
        newt_core::DenialKind::RemoteTool
        | newt_core::DenialKind::GitWrite
        | newt_core::DenialKind::Build => None,
    }
}

/// The target `AllowPermanent`'s danger check and refusal notice should use:
/// for `FsRead`/`FsWrite`, the target [`newt_core::ocap_store::persist_approve`]
/// would actually normalize and write (#2524 follow-up item 2) — `/ws/..`
/// classified and named as `/`, never the raw string that hides how
/// dangerous the request is. Reuses `ocap_store`'s own normalizer (never a
/// second copy); falls back to the raw target when normalization itself
/// fails (a relative or climbing path) — that case is refused downstream by
/// `persist_approve`'s own check, with its own message. Exec/net targets are
/// not paths and pass through unchanged.
fn normalized_danger_target(kind: newt_core::DenialKind, target: &str) -> String {
    match kind {
        newt_core::DenialKind::FsRead | newt_core::DenialKind::FsWrite => {
            newt_core::ocap_store::normalize_fs_path(target).unwrap_or_else(|_| target.to_string())
        }
        _ => target.to_string(),
    }
}

/// The notice for `AllowPermanent`'s "no root key resolves" fallback (#2524
/// follow-up item 1): names the ACTUAL configured path — or that none is
/// configured at all — rather than printing the literal word `key_path`,
/// which told the operator nothing about what to go check.
fn no_key_notice(key_path: Option<&std::path::Path>) -> String {
    let key_path_desc = key_path
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "no key_path configured".to_string());
    format!(
        "permanent allow unavailable (no root key at `{key_path_desc}` in this \
         session): granted for this session only — run `newt doctor` or restore \
         ~/.newt/identity.pem"
    )
}

/// Operator-facing axis name for the "permanently allowed" notice.
fn axis_label(kind: newt_core::DenialKind) -> &'static str {
    match kind {
        newt_core::DenialKind::Exec => "exec",
        newt_core::DenialKind::FsRead => "fs (read)",
        newt_core::DenialKind::FsWrite => "fs (write)",
        newt_core::DenialKind::Net => "net",
        newt_core::DenialKind::RemoteTool => "remote tool",
        newt_core::DenialKind::GitWrite => "git write",
        newt_core::DenialKind::Build => "build",
    }
}

fn decision_scope(choice: PromptChoice) -> &'static str {
    match choice {
        PromptChoice::AllowOnce => "once",
        PromptChoice::AllowSession => "session",
        PromptChoice::AllowPermanent => "permanent",
        PromptChoice::Deny => "once",
        PromptChoice::DenyAlways => "session",
        PromptChoice::DenyPermanent => "permanent",
        PromptChoice::Back | PromptChoice::Exit => "control",
    }
}

/// A small named-choice form for one question, as an interaction: the
/// decision shape a permission prompt has, offered to any asker with a few
/// named answers (a plan approval's yes / no / discuss). The first option is
/// the default a blank submission resolves to.
pub(crate) fn choice_form(
    question: &str,
    options: &[newt_core::agentic::ChoiceSpec],
) -> SurfaceInteraction {
    let choices: Vec<ChoiceOption> = options
        .iter()
        .map(|option| ChoiceOption {
            id: OptionId::new(option.id).expect(WIRE_NAMES_ARE_OPTION_IDS),
            role: option.role,
            label: option.label.to_string(),
            key: option.key.to_string(),
            aliases: Vec::new(),
        })
        .collect();
    let controls = vec![Control {
        id: ControlId::new(DECISION_CONTROL).expect(WIRE_NAMES_ARE_OPTION_IDS),
        kind: ControlKind::Choice { options: choices },
        label: String::new(),
        requirement: Requirement::Required,
    }];
    let kind = if newt_interaction::controls_are_decision_shaped(&controls) {
        InteractionKind::Confirm
    } else {
        InteractionKind::Choice
    };
    let definition = InteractionDefinition {
        note: Some(MODAL_CONTROL_HINT.into()),
        ..InteractionDefinition::new(kind, question.to_string(), controls)
    };
    let interaction = SurfaceInteraction::blocking(definition);
    match options.first() {
        Some(first) => interaction
            .with_default_option(OptionId::new(first.id).expect(WIRE_NAMES_ARE_OPTION_IDS)),
        None => interaction,
    }
}

/// The free-text form for one question, as a definition.
///
/// Split out by C1 (#1862) so the SESSION can build the semantic form while
/// the TERMINAL renders it — the two now happen on different threads.
pub(crate) fn free_text_form(question: &str) -> InteractionDefinition {
    // C0a (#1856): the free-text form is an `InteractionDefinition` too, so
    // it renders through the ONE plain projection rather than through a
    // second type. A `Text` control contributes no choices line, so the
    // rendering is body + note. `Prompt —` names the transient input surface
    // in words: a bare leading `?` looked like stray punctuation, especially
    // when the actual question already ended in `?`.
    InteractionDefinition {
        note: Some(MODAL_CONTROL_HINT.into()),
        ..InteractionDefinition::new(
            InteractionKind::Prompt,
            format!("Prompt — {question}"),
            vec![Control {
                id: ControlId::new(ANSWER_CONTROL).expect(
                    "`answer` is a valid control id (non-empty, drawn from \
                     [A-Za-z0-9_-]); it is a const, so this cannot vary at \
                     runtime",
                ),
                kind: ControlKind::Text,
                label: String::new(),
                requirement: Requirement::Required,
            }],
        )
    }
}

/// **The chat surface's terminal adapter**: `newt_core`'s one adapter, plus
/// the slash-command back-out.
///
/// F0a (#1922) moved the adapter itself down to
/// [`newt_core::interaction_terminal`], because it needed nothing from this
/// crate and `newt-cli`'s command flows had no route to the typed path while
/// it was `pub(crate)` here. What stayed is the only part that was ever
/// TUI-specific: a leading slash at a prompt is a COMMAND, not an answer, and
/// the operator is sent back to the chat prompt to use it. `newt dock
/// approve` has no chat prompt to be sent back to, which is exactly why this
/// half did not travel.
///
/// Back-out rather than refusal: `Cancelled` is what the core adapter already
/// reports for Esc, and a slash typed at a prompt means the same thing —
/// "not this, take me out".
pub(crate) fn present_on_terminal(
    w: &PromptWindow,
    interaction: &SurfaceInteraction,
) -> HumanQuestionOutcome {
    let outcome = newt_core::interaction_terminal::present_on_terminal(w, interaction);
    let (outcome, notice) = apply_chat_prompt_policy(outcome);
    if let Some(notice) = notice {
        w.notice(notice).ok();
    }
    outcome
}

/// Cockpit variant of [`present_on_terminal`]: the core terminal adapter
/// manually wraps only the immutable plain body to the available width. The
/// editable answer row stays unwrapped and anchored while this wrapper keeps
/// the chat-only slash-command policy in exactly one place.
///
/// `unix`, not just `rich-tui`: its sole caller is `cockpit::presenter`,
/// which is unix-only by construction (`openpty`/`dup2`/termios — see
/// `cockpit/mod.rs`). The gate follows the caller, not the platform, per
/// #1986's precedent for the same Windows-clippy shape
/// (`InlineTerminal::new`/`with_lease`) — an `#[allow(dead_code)]` here
/// would say "trust me" where the cfg says which caller, and goes stale the
/// moment a Windows cockpit lands.
#[cfg(all(unix, feature = "rich-tui"))]
pub(crate) fn present_on_terminal_with_width(
    w: &PromptWindow,
    interaction: &SurfaceInteraction,
    width: usize,
) -> (HumanQuestionOutcome, Option<&'static str>) {
    let outcome =
        newt_core::interaction_terminal::present_on_terminal_with_width(w, interaction, width);
    // The cockpit repaints the mounted chat region as soon as this blocking
    // window closes. Return the policy notice to that owner so it can commit
    // the row into durable transcript space after teardown; writing it through
    // `w` here would place it under the viewport and immediately erase it.
    apply_chat_prompt_policy(outcome)
}

pub(crate) const SLASH_COMMAND_PROMPT_NOTICE: &str =
    "(slash commands aren't answers; press Esc, then use the command at the chat prompt)";

pub(crate) fn apply_chat_prompt_policy(
    outcome: HumanQuestionOutcome,
) -> (HumanQuestionOutcome, Option<&'static str>) {
    // The answer is inspected VERBATIM — leading/trailing whitespace can be
    // meaningful (an indented code line, a spacing-sensitive value, an
    // intentionally blank-but-submitted answer). Detection reads a trim_start
    // VIEW without mutating the answer.
    if let HumanQuestionOutcome::Answer(line) = &outcome {
        if is_slash_command_at_prompt(line) {
            return (
                HumanQuestionOutcome::Cancelled,
                Some(SLASH_COMMAND_PROMPT_NOTICE),
            );
        }
    }
    (outcome, None)
}

/// A leading-slash answer at a `request_user_input` prompt is a TUI command
/// intent, not an answer to hand to the model. Pure, so it's unit-testable.
fn is_slash_command_at_prompt(answer: &str) -> bool {
    answer.trim_start().starts_with('/')
}

#[cfg(test)]
#[path = "permissions_tests/slash_prompt_tests.rs"]
mod slash_prompt_tests;

#[cfg(test)]
#[path = "permissions_tests/build_grant_tests.rs"]
mod build_grant_tests;

#[cfg(test)]
#[path = "permissions_tests/workspace_protection.rs"]
mod workspace_protection_tests;

/// Session decisions remain separate from the never-widened operating key.
#[derive(Default)]
pub(crate) struct PermissionPromptState {
    /// Immutable operator resources excluded from all permission expansions.
    pub(crate) protection:
        Option<std::sync::Arc<newt_core::workspace_protection::WorkspaceProtection>>,
    pub(crate) prompt_default: Option<PromptChoice>,
    /// Trusted configured terminal MCP default; None uses the shipped choice.
    pub(crate) mcp_net_prompt_default: Option<PromptChoice>,
    /// Opt-in attach-surface decision channel; `None` uses the terminal.
    pub(crate) web_store: Option<newt_core::ConversationStore>,
    /// The workspace fence this session is confined to (B0b-1, #1842).
    ///
    /// Supplied by the CALLER and compared against the fence the offer
    /// carries, so `Refusal::WorkspaceMismatch` is a check that can fail
    /// rather than a tautology. Empty in tests that do not exercise the
    /// fence, which is why `authorize` compares two independently
    /// supplied values instead of one value with itself.
    pub(crate) workspace_key: String,
    session_grants: std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    pub(crate) durable_grants: newt_core::durable_grants::GrantSet,
    /// Invalid recalled approvals stay quarantined until the next session.
    rejected_durable_grants: std::cell::RefCell<newt_core::durable_grants::GrantSet>,
    session_denials: std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    /// Durable deny-only entries loaded at session start.
    persistent_denials: std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    /// One-shot grants carried from `request_permissions` to its retry.
    pending_once_grants: std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    pub(crate) decisions: Vec<newt_core::PermissionRecord>,
    /// Durable approve/deny policy, read-only during the session.
    pub(crate) ocap_policy: newt_core::ocap_store::PolicySet,
}

/// Normalize legacy denials only; executable approvals stay exact.
pub(crate) fn exec_grant_basename(cmd: &str) -> &str {
    cmd.rsplit(['/', '\\'])
        .find(|p| !p.is_empty())
        .unwrap_or(cmd)
}

/// Whether an inherited ceiling can be shown to permit one request.
///
/// Only the four caveat axes can express authority, so only they can express a
/// *bound* on it. `RemoteTool` and `GitWrite` deliberately widen no axis
/// (`widen_caveats` skips both): a remote-tool allow means "proceed with this
/// call" and a git-write allow re-dispatches under a projected surface. That
/// makes them inexpressible in a signed ceiling — there is no axis in which to
/// read whether the parent granted them — so a delegated session **fails
/// closed** on both rather than treating "no axis to check" as "nothing to
/// check". `GitWrite` gets the sharper answer it can support: the ceiling's own
/// projected `GitCaveats`, the same predicate the preset floor already uses a
/// few lines below.
///
/// This is the fail-closed law applied to a gap in the vocabulary, not a
/// judgement that these two are dangerous. If a later axis makes either
/// expressible, this is the one place that changes.
fn ceiling_permits(
    ceiling: &newt_core::Caveats,
    kind: newt_core::DenialKind,
    target: &str,
) -> bool {
    use newt_core::caveats::CaveatsExt as _;
    match kind {
        newt_core::DenialKind::Exec => ceiling.permits_exec(target),
        newt_core::DenialKind::FsRead => ceiling.permits_fs_read(target),
        newt_core::DenialKind::FsWrite => ceiling.permits_fs_write(target),
        newt_core::DenialKind::Net => ceiling.permits_net(target),
        newt_core::DenialKind::GitWrite => {
            newt_core::git_caveats::GitCaveats::from_session(ceiling).permits_commit()
        }
        newt_core::DenialKind::RemoteTool => false,
        newt_core::DenialKind::Build => {
            newt_core::confined_exec::build_tool_caveats(std::path::Path::new(target)).leq(ceiling)
        }
    }
}

/// Match the exact approved target, without treating a basename as a path grant.
///
/// One exception (dec1-build-grant, F30): a session `Build` grant — the
/// fully-fenced confined-build authority, `build_tool_caveats` — also covers a
/// later `Exec` request for a build-tool binary (`cargo`/`just`/`make`, see
/// [`newt_core::confined_exec::is_build_tool_exec`]). This is one-directional
/// on purpose: `lifecycle_build_request`'s doc comment is explicit that no
/// `Exec` grant (including `exec:cargo`) may silently acquire `Build`
/// authority. The reverse is safe — `Build` is the STRONGER, calibrated fence,
/// so a prior `Build` session grant already covers running that same tool
/// through the `run_command` / routed-`build_exec` lane. One session grant,
/// not three.
pub(crate) fn session_grant_covers(
    grants: &std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    req: &newt_core::PermissionRequest,
) -> bool {
    grants.contains(&(req.kind, req.target.clone()))
        || (req.kind == newt_core::DenialKind::Exec
            && newt_core::confined_exec::is_build_tool_exec(&req.target)
            && grants
                .iter()
                .any(|(kind, _)| *kind == newt_core::DenialKind::Build))
}

/// dec1-build-grant round 2 (Reviewer, item 3): which session `Build` grant
/// covers a request running under `baseline` — the grant whose workspace
/// CONTAINS the call's cwd, not just the first `Build` grant found. A
/// multi-root session can hold more than one; clamping to the wrong
/// workspace's fence would deny (or, worse, over-grant) an otherwise-lawful
/// call. `baseline.fs_write` is the caller's own write scope for THIS call —
/// it is anchored to the effective cwd (`workspace_confined_caveats`,
/// `build_tool_caveats`), so a `Build` grant is a match when its workspace is
/// an ancestor of (or equal to) one of those write roots. Falls back to the
/// first `Build` grant found when nothing matches (the prior behavior) —
/// better an approximate clamp than none.
fn covering_build_grant_workspace<'a>(
    grants: &'a std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    baseline: &newt_core::Caveats,
) -> Option<&'a str> {
    let cwd_roots: Vec<&str> = match &baseline.fs_write {
        newt_core::Scope::Only(set) => set.iter().map(String::as_str).collect(),
        newt_core::Scope::All => Vec::new(),
    };
    let build_workspaces = || {
        grants
            .iter()
            .filter(|(kind, _)| *kind == newt_core::DenialKind::Build)
            .map(|(_, ws)| ws.as_str())
    };
    build_workspaces()
        .find(|ws| {
            cwd_roots
                .iter()
                .any(|root| std::path::Path::new(root).starts_with(ws))
        })
        .or_else(|| build_workspaces().next())
}

/// Consume only the exact pending target; other requests leave it available.
pub(crate) fn take_pending_once(
    pending: &mut std::collections::BTreeSet<(newt_core::DenialKind, String)>,
    req: &newt_core::PermissionRequest,
) -> Option<(newt_core::DenialKind, String)> {
    pending.take(&(req.kind, req.target.clone()))
}

impl PermissionPromptState {
    fn denied(&self, kind: newt_core::DenialKind, target: &str) -> bool {
        let denied = |target: &str| {
            let key = (kind, target.to_string());
            self.rejected_durable_grants.borrow().contains(&key)
                || self.session_denials.contains(&key)
                || self.persistent_denials.contains(&key)
                || newt_core::ocap_store::evaluate_request(&self.ocap_policy, kind, target)
                    == Some(newt_core::ocap_store::Verdict::Deny)
        };
        // Older exec prompts stored basenames. Preserve those refusals when a
        // new prompt names an exact path, without widening any approval.
        denied(target)
            || (kind == newt_core::DenialKind::Exec && denied(exec_grant_basename(target)))
    }

    /// Scope has no exclusions. Do not recall a broad grant that would let a
    /// denied target bypass the gate; leave independently configured authority
    /// unchanged. The same check rejects an unreplayable promotion snapshot.
    fn recall_conflicts_with_denial(&self, kind: newt_core::DenialKind, target: &str) -> bool {
        use newt_core::{ocap_store::Verdict, DenialKind};
        let overlaps = |denied: &str| match kind {
            DenialKind::FsRead | DenialKind::FsWrite => newt_core::caveats::permits_path(
                &newt_core::caveats::Scope::only([target.to_string()]),
                denied,
            ),
            DenialKind::Exec => {
                target == exec_grant_basename(denied) || denied == exec_grant_basename(target)
            }
            _ => target == denied,
        };
        self.denied(kind, target)
            || self
                .session_denials
                .iter()
                .chain(&self.persistent_denials)
                .any(|(denied_kind, denied)| *denied_kind == kind && overlaps(denied))
            || self
                .ocap_policy
                .files
                .get(&Verdict::Deny)
                .is_some_and(|policy| match kind {
                    DenialKind::FsRead | DenialKind::FsWrite => {
                        policy.fs.iter().any(|entry| overlaps(&entry.path))
                    }
                    DenialKind::Exec => policy.exec.iter().any(|entry| overlaps(&entry.target)),
                    _ => false,
                })
    }

    fn recalled_grants<'a>(
        &'a self,
        danger: &'a danger::DangerTable,
    ) -> impl Iterator<Item = &'a (newt_core::DenialKind, String)> {
        self.session_grants
            .iter()
            .chain(&self.durable_grants)
            .filter(|(kind, target)| {
                !self.recall_conflicts_with_denial(*kind, target)
                    && danger.classify(*kind, target) != danger::DangerTier::High
                    && self.protection.as_ref().is_none_or(|guard| {
                        match guard.validate_request(*kind, target) {
                            Ok(()) => true,
                            Err(error) => {
                                self.reject_durable_grant(*kind, target, &error);
                                false
                            }
                        }
                    })
            })
    }

    /// Fold this session's VERIFIED OCAP approve-store entries (#2524 item 1:
    /// `~/.newt/ocap/approve.toml`, signed by the operator's root key) into
    /// the recalled durable grants — the same `durable_grants` set the v1
    /// `/permissions` promotion writes, so a signed store entry reaches
    /// [`Self::recalled_caveats`] (and hence a spawned MCP child's caveats,
    /// `chat.rs`'s `startup_caveats`) exactly like a promoted durable grant.
    ///
    /// `self.ocap_policy` must already be the output of
    /// [`newt_core::ocap_store::load_store`], which drops any unsigned or
    /// bad-signature `approve.toml` entry loudly at load (fail-closed); this
    /// only re-shapes whatever survived that check
    /// ([`newt_core::ocap_store::approved_grants`] is a pure re-listing), so
    /// it can never itself widen past what the signature covers. Called at
    /// session start, and again after every mid-session `AllowPermanent`
    /// reload ([`newt_core::ocap_store::persist_approve`]'s caller).
    /// Returns the number of grants folded in, for the session-start
    /// permission-log line (#2532 review, item 3).
    ///
    /// **Deliberately monotonic** (#2524 follow-up item 4): this only ever
    /// `extend`s `durable_grants`, never rebuilds it from the current fold.
    /// If a later reload drops an entry that an earlier one admitted (the
    /// operator hand-edited or truncated `approve.toml` mid-session, or a
    /// previously-valid signature somehow stopped verifying), that entry's
    /// grant is kept for the rest of THIS session rather than revoked live.
    /// This is the same posture as a promoted durable grant or a session
    /// grant: authority admitted once under verification is not silently
    /// clawed back mid-turn. It is also the only option available here
    /// without a wider change — `durable_grants` is a flat
    /// `(DenialKind, String)` set shared with the legacy `/permissions`
    /// promotion path (`recalled_grants`), so nothing at this call site can
    /// tell an ocap-sourced entry apart from one promoted another way in
    /// order to rebuild just its own contribution; a full rebuild here would
    /// risk dropping grants this function never added. Revocation of a
    /// dropped `approve.toml` entry takes effect on the NEXT session start,
    /// where `ocap_policy`/`durable_grants` are rebuilt fresh from `load_store`.
    pub(crate) fn fold_ocap_approvals(&mut self) -> usize {
        let grants = newt_core::ocap_store::approved_grants(&self.ocap_policy);
        let count = grants.len();
        self.durable_grants.extend(grants);
        count
    }

    pub(crate) fn recalled_caveats(
        &self,
        base: &newt_core::Caveats,
        ceiling: Option<&newt_core::Caveats>,
    ) -> anyhow::Result<newt_core::Caveats> {
        // Invalid configured authority is still fatal. Only recalled durable
        // approvals can be discarded, and only before committing their widening.
        let clamp = |policy: newt_core::Caveats| {
            ceiling.map_or_else(|| policy.clone(), |ceiling| policy.meet(ceiling))
        };
        let mut policy = clamp(base.clone());
        self.validate_caveats(&policy)?;
        for (kind, target) in self.recalled_grants(&production_danger_table()) {
            let candidate = clamp(newt_core::widen_caveats(
                &policy,
                &[(*kind, target.clone())],
            ));
            match self.validate_caveats(&candidate) {
                Ok(()) => policy = candidate,
                Err(error) if self.reject_durable_grant(*kind, target, &error) => {}
                Err(error) => return Err(error),
            }
        }
        Ok(policy)
    }

    fn reject_durable_grant(
        &self,
        kind: newt_core::DenialKind,
        target: &str,
        error: &anyhow::Error,
    ) -> bool {
        let grant = (kind, target.to_owned());
        if !self.durable_grants.contains(&grant) {
            return false;
        }
        let mut rejected = self.rejected_durable_grants.borrow_mut();
        let reported = rejected.iter().any(|(_, path)| path == target);
        rejected.insert(grant);
        if !reported {
            let reason = error.to_string();
            let suffix = format!("; {}", newt_core::ocap_store::REPAIR_HINT);
            let reason = reason.strip_suffix(&suffix).unwrap_or(&reason);
            eprintln!("warning: dropped durable grant {target:?} for this session: {reason:?}; inspect ~/.newt/ocap/approve.toml; {}", newt_core::ocap_store::REPAIR_HINT);
        }
        true
    }

    fn widen_caveats(
        &self,
        base: &newt_core::Caveats,
        grants: &[(newt_core::DenialKind, String)],
    ) -> newt_core::Caveats {
        newt_core::widen_caveats(base, grants)
    }

    fn validate_caveats(&self, caveats: &newt_core::Caveats) -> anyhow::Result<()> {
        if let Some(protection) = &self.protection {
            protection.validate_caveats(caveats)?;
        }
        Ok(())
    }

    pub(crate) fn retained_net_hosts(&self) -> Vec<String> {
        self.recalled_grants(&production_danger_table())
            .filter(|(kind, _)| *kind == newt_core::DenialKind::Net)
            .map(|(_, target)| target.clone())
            .collect()
    }

    pub(crate) fn session_allow_count(&self) -> usize {
        self.session_grants.len()
    }

    pub(crate) fn terminal_default(&self) -> PromptChoice {
        self.prompt_default.unwrap_or(PromptChoice::AllowOnce)
    }

    /// Load the persistent denylist from `path` into a fresh state (#904). A
    /// missing file yields an empty denylist. Called once at session start.
    pub(crate) fn with_persistent_denials(path: Option<&std::path::Path>) -> Self {
        let persistent_denials = path
            .map(|p| newt_core::load_denials(p).into_iter().collect())
            .unwrap_or_default();
        Self {
            persistent_denials,
            ..Self::default()
        }
    }
}

/// Prompts, records, and re-mints from the user root without widening the live key.
pub(crate) struct PromptPermissionGate<
    'a,
    F: FnMut(&PromptWindow, &SurfaceInteraction) -> PromptChoice,
> {
    /// Owned by this turn gate; dropping it expires every unused approval.
    /// Exact command/cwd content identities, never basename aliases or standing grants.
    pub(crate) pending_command_retries: std::collections::BTreeMap<
        (newt_identity::RawContentId, newt_identity::RawContentId),
        Vec<(newt_core::DenialKind, String)>,
    >,
    pub(crate) state: &'a mut PermissionPromptState,
    /// Enforced caveats at turn start.
    pub(crate) base: newt_core::Caveats,
    pub(crate) key_path: Option<std::path::PathBuf>,
    pub(crate) conversation_id: String,
    pub(crate) log_path: Option<std::path::PathBuf>,
    pub(crate) denials_path: Option<std::path::PathBuf>,
    pub(crate) config_path: Option<std::path::PathBuf>,
    /// Re-applied after widening so grants cannot pierce a named preset.
    pub(crate) preset_clamp: Option<newt_core::Caveats>,
    /// Immutable inherited ceiling, independent of the current posture.
    pub(crate) delegation: Option<&'a newt_identity::VerifiedDelegation>,
    pub(crate) danger: danger::DangerTable,
    pub(crate) color: bool,
    pub(crate) verbose: bool,
    /// Whether interactive AUTHORIZATION prompting is enabled this session. This
    /// is ORTHOGONAL to whether a human is present: the gate is built whenever
    /// the session has a usable TTY, so `ask_question` (the human-question seam)
    /// stays available even when this is false. When false, [`Self::ask`] denies
    /// every request immediately WITHOUT opening a prompt — disabling permission
    /// prompts must never erase the operator from `request_user_input`.
    pub(crate) authorization_prompts_enabled: bool,
    pub(crate) web_decision_timeout: Duration,
    /// Nested-form controls feed the same turn cancellation path as the watcher.
    pub(crate) cancel: Option<&'a AtomicBool>,
    pub(crate) exit: Option<&'a AtomicBool>,
    pub(crate) ask_human: F,
    /// **C1 (#1862): how this gate reaches the surface that owns the terminal.**
    ///
    /// `Some` under the two-thread split (`run_chat`): the session asks the UI
    /// thread, which acquires the `PromptWindow`. `None` where the gate IS on
    /// the terminal-owning thread — the single-threaded CLI entry points —
    /// and may take it directly. Those are two situations, not two
    /// implementations of one situation: the rendering and the read happen in
    /// `present_on_terminal` either way.
    ///
    /// `&dyn Fn` rather than a second generic parameter, so adding the seam
    /// does not propagate a type parameter through every construction site.
    pub(crate) ask_surface: Option<&'a dyn Fn(&SurfaceInteraction) -> HumanQuestionOutcome>,
    /// A web-shared decision keeps its CAS wait on the session while its
    /// terminal owner lends the modal rows and parks until this loan closes.
    #[cfg(feature = "rich-tui")]
    pub(crate) open_panel: Option<&'a dyn Fn(u16) -> Option<crate::session_worker::PanelWindow>>,
}

/// Only the direct, terminal-owning route uses stdout. A mounted cockpit
/// instead lends its rows before `PanelWindow::prompt_window` acquires input.
fn direct_authorization_window() -> PromptWindow {
    Terminal::suspend_for_prompt(newt_core::tty::TerminalTaker::PermissionAuthorization)
}

impl<F: FnMut(&PromptWindow, &SurfaceInteraction) -> PromptChoice> PromptPermissionGate<'_, F> {
    #[cfg(feature = "rich-tui")]
    pub(crate) fn retained_net_hosts(&self) -> Vec<String> {
        self.state.retained_net_hosts()
    }

    /// Reuse the permission gate for MCP startup, preserving the lifetime of
    /// the operator's grant without changing the session capability.
    pub(crate) fn ask_mcp_net_grant(
        &mut self,
        request: &newt_core::PermissionRequest,
    ) -> Option<(newt_core::Caveats, Vec<String>, bool)> {
        if request.kind != newt_core::DenialKind::Net {
            return None;
        }
        match newt_core::PermissionGate::ask(self, std::slice::from_ref(request)) {
            newt_core::PermissionDecision::Allow(caveats) => {
                use newt_core::CaveatsExt as _;
                if !caveats.permits_net(&request.target) {
                    return None;
                }
                let mut hosts: Vec<_> = self
                    .state
                    .recalled_grants(&self.danger)
                    .filter(|(kind, _)| *kind == newt_core::DenialKind::Net)
                    .filter(|(_, host)| caveats.permits_net(host))
                    .map(|(_, host)| host.clone())
                    .collect();
                if !hosts.contains(&request.target) {
                    hosts.push(request.target.clone());
                }
                Some((
                    caveats,
                    hosts,
                    session_grant_covers(&self.state.session_grants, request)
                        || self
                            .state
                            .durable_grants
                            .contains(&(request.kind, request.target.clone())),
                ))
            }
            newt_core::PermissionDecision::Deny => None,
        }
    }

    /// Record one decision: into the session list (for `/permissions`) and
    /// appended to the durable log. A log-write failure is reported but
    /// never blocks the decision — the record is a review artifact, not a
    /// gate.
    fn record(&mut self, req: &newt_core::PermissionRequest, decision: &str, scope: &str) {
        let rec = newt_core::PermissionRecord::new(
            &self.conversation_id,
            &req.tool,
            req.kind,
            &req.target,
            decision,
            scope,
        );
        if let Some(path) = self.log_path.as_deref() {
            if let Err(e) = newt_core::permission_journal::append_record(path, rec.clone()) {
                print_newt(
                    &format!("warning: permission log write failed: {e}"),
                    self.color,
                    self.verbose,
                );
            }
        }
        self.state.decisions.push(rec);
    }

    /// Derive the final policy without reading keys or recording a decision.
    fn policy_with_grants(
        &self,
        base: &newt_core::Caveats,
        once_grants: &[(newt_core::DenialKind, String)],
    ) -> anyhow::Result<newt_core::Caveats> {
        let mut grants: Vec<(newt_core::DenialKind, String)> =
            self.state.recalled_grants(&self.danger).cloned().collect();
        grants.extend(once_grants.iter().cloned());
        let mut policy = self.state.widen_caveats(base, &grants);
        // Re-clamping is load-bearing: widening may repopulate an emptied scope.
        if let Some(clamp) = &self.preset_clamp {
            policy = policy.meet(clamp);
        }
        // The inherited ceiling clamps AFTER the preset and independently of
        // it. A preset is a posture the operator can name off; a delegation is
        // authority this session was never granted in the first place, so an
        // operator sitting at this prompt cannot approve past it — approving
        // what you do not hold is amplification, not consent. This is the same
        // widening path `preset_clamp` guards, which is why the clamp belongs
        // here rather than only at `establish`: `mint` re-derives caveats from
        // `base` plus grants, so a ceiling applied only at session start would
        // be re-widened away on the first granted prompt.
        if let Some(d) = self.delegation {
            policy = policy.meet(d.caveats());
        }
        self.state.validate_caveats(&policy)?;
        Ok(policy)
    }

    /// Re-mint baseline plus grants from the root; never widen the live key.
    fn mint(
        &self,
        base: &newt_core::Caveats,
        once_grants: &[(newt_core::DenialKind, String)],
    ) -> anyhow::Result<newt_core::Caveats> {
        let policy = self.policy_with_grants(base, once_grants)?;
        // A delegated session never re-roots a grant through the operator key.
        if self.delegation.is_some() {
            return Ok(policy);
        }
        let policy = match self
            .key_path
            .as_deref()
            .and_then(|p| mint_operating_key(p, &policy).ok())
        {
            Some(key) => newt_identity::enforced_caveats(&key).unwrap_or(policy),
            None => policy,
        };
        // Key creation can resolve a previously absent name. Check the actual
        // returned authority again, rather than relying on the pre-mint shape.
        self.state.validate_caveats(&policy)?;
        Ok(policy)
    }

    /// Live policy, through the same grant and delegation clamps as tool calls.
    pub(crate) fn current_caveats(&self) -> anyhow::Result<newt_core::Caveats> {
        self.mint(&self.base, &[])
    }

    /// Publish the same typed form the web renders and poll for its answer.
    fn await_web_decision(
        &self,
        store: &newt_core::ConversationStore,
        req: &newt_core::PermissionRequest,
    ) -> (PromptChoice, &'static str) {
        // B0b-2 (#1846): publish the OFFER — the definition AND the instance
        // that binds it — so the answer is validated against the offer that
        // was actually published, not one minted at answer time.
        // C4b (#1944): the offer is open to BOTH surfaces, and its option set
        // is scoped to the NARROWER of them.
        //
        // #1894 framed this as publishing the terminal SUPERSET and having
        // each view filter what it renders. The inverse is smaller and
        // safer. One instance means one definition, because the definition
        // digest is inside the instance's `ContentId` — so the choice is
        // which audience's option set both surfaces share. Scoping to the
        // INTERSECTION makes every rendered option answerable by whoever is
        // looking at it, which turns `binding.rs:462`'s `ActionNotEligible`
        // from a backstop that fires in normal use into a refusal that is
        // unreachable by construction. The superset would instead put
        // `Allow permanently` on the web card and refuse it on submit — a
        // button that always fails, which is #1536's defect, not a cosmetic
        // one.
        //
        // Nothing regresses. Until now the terminal operator could not
        // answer AT ALL while the web was attached — only Back/Exit — so
        // gaining allow-once / session / deny is a strict improvement over
        // zero. The durable actions (`A`, `D`, `P`) remain available on the
        // web-detached path, where they always were. Widening the offer to
        // carry them for BOTH surfaces means a per-view render filter and
        // moving the web card's goldens; that is a separate slice with its
        // own visible change, not a rider on this one.
        let definition = permission_definition(req, &self.danger, Audience::Web);
        // D0 (#1878): the renderability precondition that stood here is GONE,
        // on the authority of its own comment — "this is a renderability
        // PRECONDITION, and it retires with C3's removal of the
        // reconstruction". C3c (#1870) removed that reconstruction: the web
        // builds its card from the `InteractionDefinition` directly, so there
        // is no longer a legacy form it could fail to reconstruct. The check
        // was guarding a rendering path that no longer exists.
        let tier = if self.danger.classify(req.kind, &req.target) == danger::DangerTier::High {
            newt_core::interaction_offer::OfferDanger::High
        } else {
            newt_core::interaction_offer::OfferDanger::Low
        };
        let request_id = match store.publish_interaction_offer(
            &self.conversation_id,
            &definition,
            tier,
            &[Audience::Terminal, Audience::Web],
        ) {
            Ok(id) => id,
            Err(_) => return (PromptChoice::Deny, "web-unavailable"),
        };
        #[cfg(feature = "rich-tui")]
        let interaction = {
            let mut displayed = definition.clone();
            let context = "You or the web may answer; whoever answers first decides.";
            displayed.note = Some(match displayed.note.take() {
                Some(note) => format!("{context}\n{note}"),
                None => context.into(),
            });
            SurfaceInteraction::blocking(displayed)
        };
        #[cfg(feature = "rich-tui")]
        let panel = self.open_panel.and_then(|open| {
            let cols = crossterm::terminal::size().map_or(80, |(cols, _)| cols);
            open(crate::interaction_view::requested_rows(&interaction, cols))
        });
        #[cfg(feature = "rich-tui")]
        if self.open_panel.is_some() && panel.is_none() {
            // A cockpit that could not lend its rows still owns stdin. Close
            // our offer through the same CAS, preserving any web winner.
            return self
                .web_abort_choice(
                    store,
                    &self.conversation_id,
                    &request_id,
                    PromptChoice::Deny,
                )
                .unwrap_or((PromptChoice::Deny, "web-unavailable"));
        }
        // Acquire stdin only after the terminal owner has parked and lent its
        // rows. The window drops before the panel loan releases that owner.
        #[cfg(feature = "rich-tui")]
        let window = match panel.as_ref() {
            Some(panel) => match panel.prompt_window() {
                Ok(window) => window,
                Err(_) => {
                    return self
                        .web_abort_choice(
                            store,
                            &self.conversation_id,
                            &request_id,
                            PromptChoice::Deny,
                        )
                        .unwrap_or((PromptChoice::Deny, "web-unavailable"));
                }
            },
            None => direct_authorization_window(),
        };
        #[cfg(not(feature = "rich-tui"))]
        let window = direct_authorization_window();
        let w = &window;
        #[cfg(feature = "rich-tui")]
        if panel.is_some() || (io::stdin().is_terminal() && io::stdout().is_terminal()) {
            let mut notices = Vec::new();
            let result = self.run_web_wait(
                store,
                &request_id,
                &definition,
                w,
                &mut WebWaitIo {
                    reacquire: &mut || {
                        match panel.as_ref() {
                            Some(panel) => panel.terminal().and_then(|terminal| {
                                crate::interaction_view::reader_for_shared_decision(
                                    terminal,
                                    &interaction,
                                )
                            }),
                            None => {
                                crate::interaction_view::reader_for_shared_decision_on_terminal(
                                    &interaction,
                                )
                            }
                        }
                        .map(|reader| Box::new(reader) as Box<dyn ControlReader>)
                    },
                    now: &Instant::now,
                    sleep: &mut std::thread::sleep,
                    notify: &mut |message| notices.push(message.to_string()),
                },
            );
            // The reader has now erased its standalone viewport. A loaned
            // viewport is still mounted, so its owner captures these rows and
            // commits them after removing the modal and restoring the composer.
            for message in notices {
                self.notice(panel.is_none().then_some(w), &message);
            }
            return result;
        }
        let note = definition
            .note
            .as_deref()
            .map_or(MODAL_CONTROL_HINT.to_string(), |note| {
                if note.contains(MODAL_CONTROL_HINT) {
                    note.to_string()
                } else {
                    format!("{note}\n{MODAL_CONTROL_HINT}")
                }
            });
        // C4b (#1944): RENDER the offer, not just an "awaiting…" line.
        //
        // The operator can now answer this, and a capability nobody can see
        // is the failure this epic keeps paying for. Until now the terminal
        // showed only that it was waiting, because waiting was all it could
        // do. It shows the options because it can now act on them, through
        // the same canonical projection the terminal-only path renders (C0a)
        // — one definition, one rendering, whichever surface is looking.
        w.notice(&newt_line(
            &format!(
                "{}\n`{}` — you or the web; whoever answers first decides.\n{note}",
                plain::render(&definition),
                req.target
            ),
            self.color,
            self.verbose,
        ))
        .ok();
        // Delegate the wait loop to the injectable core so reader-recovery is
        // unit-testable with a scripted reader, a fake clock, and a no-op sleep.
        self.run_web_wait(
            store,
            &request_id,
            &definition,
            w,
            &mut WebWaitIo {
                reacquire: &mut move || {
                    modal_prompt_controls(w).map(|r| Box::new(r) as Box<dyn ControlReader + '_>)
                },
                now: &Instant::now,
                sleep: &mut std::thread::sleep,
                notify: &mut |message| {
                    w.notice(&newt_line(message, self.color, self.verbose)).ok();
                },
            },
        )
    }

    /// The web-decision wait loop with an INJECTABLE control-reader lifecycle.
    ///
    /// A transient terminal read error must never permanently disable local
    /// controls (the defect this replaces set `controls = None` forever after a
    /// single error). Here the reader runs a small state machine:
    /// `Live` → poll it; an [`io::ErrorKind::Interrupted`] error is transient and
    /// retries the SAME reader; any other error drops it and moves to `Retrying`
    /// (emitting at most one concise warning), which re-arms via `reacquire` at a
    /// bounded `reacquire_backoff` cadence — never busy-spinning. The gate is
    /// only built for an interactive session, so ANY acquisition failure —
    /// including `Unsupported` (a terminal-loss race between session setup and
    /// the first prompt) — also enters paced `Retrying`, never a permanent dead
    /// end; there is no "genuinely headless" path here to latch off.
    ///
    /// Through every reader state the web store poll and the fail-closed
    /// `deadline` keep running, and a recovered `Back`/`Exit` still resolves
    /// through [`Self::web_abort_choice`]'s exactly-once CAS — so a local abort
    /// and a web verdict can never both win. `reacquire`/`now`/`sleep` are
    /// injected so tests drive the loop deterministically without a real
    /// terminal or wall clock.
    fn run_web_wait<'w>(
        &self,
        store: &newt_core::ConversationStore,
        request_id: &str,
        definition: &InteractionDefinition,
        w: &'w newt_core::tty::PromptWindow,
        io_: &mut WebWaitIo<'_, 'w>,
    ) -> (PromptChoice, &'static str) {
        let WebWaitIo {
            reacquire,
            now,
            sleep,
            notify,
        } = io_;
        enum ReaderState<'a> {
            Live(Box<dyn ControlReader + 'a>),
            Retrying { next_attempt: Instant },
        }

        let control_poll_timeout = Duration::from_millis(200);
        let reacquire_backoff = Duration::from_millis(200);
        let deadline = now() + self.web_decision_timeout;

        let mut warned = false;
        let mut state: ReaderState<'w> = match reacquire() {
            Ok(reader) => ReaderState::Live(reader),
            // ANY acquisition failure — including `Unsupported`, which here is a
            // terminal-loss race between the interactive session's setup and the
            // first prompt, NOT a genuinely headless session — enters paced retry
            // rather than permanently disabling the local controls. Warn once.
            Err(_) => {
                warned = true;
                self.notice_control_warning(w);
                ReaderState::Retrying {
                    next_attempt: now() + reacquire_backoff,
                }
            }
        };

        loop {
            // Advance the reader. `blocked` = we spent ~one poll timeout blocking,
            // so we should NOT also sleep this tick.
            let poll_result = match &mut state {
                ReaderState::Live(reader) => Some(reader.poll(control_poll_timeout)),
                _ => None,
            };
            let mut blocked = false;
            match poll_result {
                Some(Ok(Some(ModalLine::Back))) => {
                    return self
                        .web_abort_choice(
                            store,
                            &self.conversation_id,
                            request_id,
                            PromptChoice::Back,
                        )
                        .unwrap_or((PromptChoice::Back, "web-aborted"));
                }
                Some(Ok(Some(ModalLine::Exit))) => {
                    return self
                        .web_abort_choice(
                            store,
                            &self.conversation_id,
                            request_id,
                            PromptChoice::Exit,
                        )
                        .unwrap_or((PromptChoice::Exit, "web-aborted"));
                }
                // C4b (#1944): a typed line that names an offered option is
                // the operator DECIDING, and it contends for the same CAS the
                // web does.
                //
                // Only a RESOLVABLE line decides. An empty line or an
                // unrecognized key stays ignored, as it is today — this path
                // deliberately does NOT reuse `decode_answer`'s fail-closed
                // default. At a terminal-only prompt the operator is blocked
                // on answering and a bare Enter meaning "deny (default)" is
                // the documented contract; here there is a second responder
                // and a deadline, so a bumped Enter silently denying a
                // request would be a new way to lose work.
                Some(Ok(Some(ModalLine::Line(answer)))) => {
                    if let Some(action) = resolve_answer(definition, &answer) {
                        return self.terminal_answer_choice(store, notify, request_id, action);
                    }
                    blocked = true;
                }
                // EOF, or a control we do not act on here; we polled.
                Some(Ok(_)) => blocked = true,
                Some(Err(e)) => {
                    if e.kind() == io::ErrorKind::Interrupted {
                        // Transient (EINTR): keep the SAME reader and retry. This
                        // error returns IMMEDIATELY (it does not consume the poll
                        // timeout), so leave `blocked` false and let the paced
                        // sleep below run — otherwise repeated EINTR busy-spins.
                    } else {
                        // Broken reader: drop it, re-arm at a bounded cadence.
                        if !warned {
                            warned = true;
                            self.notice_control_warning(w);
                        }
                        state = ReaderState::Retrying {
                            next_attempt: now() + reacquire_backoff,
                        };
                    }
                }
                None => {
                    // Not live: try to re-arm when the backoff elapses. This gate
                    // was built for an interactive session, so a reader that once
                    // worked may return again (detach/reattach, PTY swap) — an
                    // `Unsupported` reacquire here is NOT terminal; keep retrying
                    // (bounded) until the deadline. There is no permanent
                    // "no terminal" state to latch: one reader-state transition
                    // must never permanently remove the escape hatch.
                    if let ReaderState::Retrying { next_attempt } = &mut state {
                        if now() >= *next_attempt {
                            match reacquire() {
                                Ok(reader) => state = ReaderState::Live(reader),
                                Err(_) => *next_attempt = now() + reacquire_backoff,
                            }
                        }
                    }
                }
            }

            match store.take_interaction_decision(&self.conversation_id, request_id) {
                Ok(Some(action)) => return (action, decision_scope(action)),
                Ok(None) if now() >= deadline => {
                    // Claim through the SAME CAS a web answer contends for.
                    // If a web answer won the race, take that answer;
                    // otherwise the timeout is a fail-closed denial. Expiry
                    // itself synthesizes nothing — the Deny below is the
                    // gate's fixed default, not a decision read out of the
                    // offer.
                    return match store.cancel_interaction_offer(&self.conversation_id, request_id) {
                        Ok(true) => (PromptChoice::Deny, "web-timeout"),
                        Ok(false) => match store
                            .take_interaction_decision(&self.conversation_id, request_id)
                        {
                            Ok(Some(action)) => (action, decision_scope(action)),
                            Ok(None) | Err(_) => (PromptChoice::Deny, "web-timeout"),
                        },
                        Err(_) => (PromptChoice::Deny, "web-timeout"),
                    };
                }
                Ok(None) => {}
                Err(_) => return (PromptChoice::Deny, "web-store-error"),
            }

            if !blocked {
                let remaining = deadline.saturating_duration_since(now());
                sleep(remaining.min(Duration::from_millis(200)));
            }
        }
    }

    /// Emit the single, concise "controls interrupted, retrying" warning used by
    /// [`Self::run_web_wait`] when a live control reader breaks mid-wait.
    fn notice_control_warning(&self, w: &newt_core::tty::PromptWindow) {
        w.notice(&newt_line(
            "terminal controls temporarily unavailable — retrying; the web decision and timeout still apply",
            self.color,
            self.verbose,
        ))
        .ok();
    }

    /// **The accept/deny decision** (B0b-1, #1842).
    ///
    /// `Question::parse` has already DECODED the operator's keystroke into
    /// a candidate action — aliases, ambiguity denial, case-distinct keys.
    /// It no longer authorizes. This does, through
    /// `newt_interaction::validate_response`, against the definition the
    /// form was rendered from and a registry of executable actions the
    /// definition cannot influence.
    ///
    /// Fails CLOSED: any refusal, and any failure to mint the offer, is a
    /// deny. There is no second opinion to consult.
    fn authorize(
        &self,
        definition: &InteractionDefinition,
        audience: Audience,
        decoded: PromptChoice,
    ) -> Result<PromptChoice, newt_interaction::Refusal> {
        // Back and Exit are local CONTROLS, not decisions: they are not
        // options of the form, they authorize nothing, and routing them
        // through the authorizer would refuse them as unknown options and
        // silently turn a cancellation into a denial.
        if matches!(decoded, PromptChoice::Back | PromptChoice::Exit) {
            return Ok(decoded);
        }
        let Ok((instance, lifecycle)) = newt_core::interaction_gate::mint_offer(
            definition,
            &self.state.workspace_key,
            &self.conversation_id,
            std::slice::from_ref(&audience),
            newt_core::interaction_gate::now_tick(),
        ) else {
            return Err(newt_interaction::Refusal::MissingRequiredControl {
                control: "decision".to_string(),
            });
        };
        newt_core::interaction_gate::authorize_action(
            definition,
            &instance,
            &lifecycle,
            &self.state.workspace_key,
            &newt_core::interaction_gate::permission_registry(audience.clone()),
            decoded,
            audience,
        )
    }

    /// Record an authorizer refusal, keeping the operator-facing message
    /// the fixed-enum code produced for the cases that have one.
    ///
    /// The DECISION is now `validate_response`'s — a high-danger session
    /// allow is refused because the form does not offer that option, not
    /// because a downstream `match` arm re-checked the tier. But the
    /// operator still gets the same sentence, and the audit record still
    /// carries the same specific reason, because a refusal that reads as
    /// a generic deny is a worse refusal.
    fn note_refusal(
        &mut self,
        w: Option<&PromptWindow>,
        req: &newt_core::PermissionRequest,
        decoded: PromptChoice,
        refusal: &newt_interaction::Refusal,
    ) {
        let high = self.danger.classify(req.kind, &req.target) == danger::DangerTier::High;
        let (scope, message) = match decoded {
            PromptChoice::AllowSession if high => (
                "session-allow-refused-high-danger",
                Some(format!(
                    "session allow refused for high-danger `{}` — \
                     allow once per op or deny (step-up is the future path)",
                    req.target
                )),
            ),
            PromptChoice::AllowPermanent if high => (
                "permanent-allow-refused-high-danger",
                Some(format!(
                    "permanent allow refused for high-danger `{}`",
                    req.target
                )),
            ),
            _ => ("unauthorized", None),
        };
        // INERT-CODE-RATCHET: F18 WIRE: permission refusal detail is promised to audit but explicitly discarded.
        let _ = refusal;
        self.record(req, "deny", scope);
        if let Some(message) = message {
            self.notice(w, &message);
        }
    }

    /// Direct prompts keep the arbiter until their notices are written. A
    /// surface-owned prompt has already closed; stdout is captured by that
    /// owner and committed to the transcript after its modal is removed.
    fn notice(&self, window: Option<&PromptWindow>, message: &str) {
        match window {
            Some(window) => {
                window
                    .notice(&newt_line(message, self.color, self.verbose))
                    .ok();
            }
            None => print_newt(message, self.color, self.verbose),
        }
    }

    fn web_abort_choice(
        &self,
        store: &newt_core::ConversationStore,
        conversation_id: &str,
        request_id: &str,
        fallback: PromptChoice,
    ) -> Option<(PromptChoice, &'static str)> {
        // The SAME single CAS the web answer contends for: whoever flips
        // `outcome` from NULL wins, and the loser reads the winner's answer.
        if store
            .cancel_interaction_offer(conversation_id, request_id)
            .ok()?
        {
            return Some((fallback, decision_scope(fallback)));
        }
        store
            .take_interaction_decision(conversation_id, request_id)
            .ok()
            .and_then(|action| action.map(|a| (a, decision_scope(a))))
    }

    /// Answer the offer AS THE TERMINAL, through the one CAS the web
    /// contends for.
    ///
    /// The mirror of [`Self::web_abort_choice`], and deliberately built the
    /// same way: try the transition, and if it was already resolved read the
    /// winner rather than inventing an outcome. What differs is the second
    /// half — a losing ABORT can hand back the winner's action silently,
    /// because the operator asked to leave rather than to decide. A losing
    /// ANSWER cannot: the operator made a decision, and letting the winner's
    /// verdict pass as theirs is C3b's defect (#1536) with the surfaces
    /// swapped. So the loser is told, on the terminal, before the value is
    /// returned.
    fn terminal_answer_choice(
        &self,
        store: &newt_core::ConversationStore,
        notify: &mut dyn FnMut(&str),
        request_id: &str,
        action: PromptChoice,
    ) -> (PromptChoice, &'static str) {
        let outcome = store.answer_interaction_offer(
            &self.conversation_id,
            request_id,
            action,
            Audience::Terminal,
        );
        match outcome {
            Ok(newt_core::store::AnswerOutcome::Answered) => (action, decision_scope(action)),
            Ok(_) => {
                // Lost the race, or the offer expired underneath us. Read the
                // winner in the same way the abort path does.
                match store.take_interaction_decision(&self.conversation_id, request_id) {
                    Ok(Some(winner)) => {
                        notify(&lost_to_web_message(action, winner));
                        (winner, decision_scope(winner))
                    }
                    // Resolved with no readable answer (a cancel, or an
                    // expiry): fail closed rather than guess.
                    _ => (PromptChoice::Deny, "web-raced"),
                }
            }
            Err(_) => (PromptChoice::Deny, "web-store-error"),
        }
    }

    fn apply_control(&self, action: PromptChoice) {
        if let Some(cancel) = self.cancel {
            cancel.store(true, Ordering::Relaxed);
        }
        if action == PromptChoice::Exit {
            if let Some(exit) = self.exit {
                exit.store(true, Ordering::Relaxed);
            }
        }
    }
}

impl<F: FnMut(&PromptWindow, &SurfaceInteraction) -> PromptChoice> newt_core::PermissionGate
    for PromptPermissionGate<'_, F>
{
    fn refresh_caveats(&mut self, baseline: &newt_core::Caveats) -> newt_core::PermissionDecision {
        self.mint(baseline, &[]).map_or(
            newt_core::PermissionDecision::Deny,
            newt_core::PermissionDecision::Allow,
        )
    }

    fn ask(&mut self, requests: &[newt_core::PermissionRequest]) -> newt_core::PermissionDecision {
        self.ask_with_caveats(&self.base.clone(), requests)
    }

    fn consume_pending_once(&mut self, kind: newt_core::DenialKind, target: &str) {
        self.state
            .pending_once_grants
            .remove(&(kind, target.to_string()));
    }

    fn queue_pending_once(&mut self, kind: newt_core::DenialKind, target: &str) {
        self.state
            .pending_once_grants
            .insert((kind, target.to_string()));
    }

    fn queue_command_retry(
        &mut self,
        command: &str,
        cwd: &str,
        requests: &[newt_core::PermissionRequest],
    ) {
        let key = (
            newt_identity::RawContentId::from_content(command.as_bytes()),
            newt_identity::RawContentId::from_content(cwd.as_bytes()),
        );
        self.pending_command_retries.insert(
            key,
            requests
                .iter()
                .map(|request| (request.kind, request.target.clone()))
                .collect(),
        );
    }

    fn apply_command_retry(
        &mut self,
        command: &str,
        cwd: &str,
        base: &newt_core::Caveats,
    ) -> newt_core::Caveats {
        let key = (
            newt_identity::RawContentId::from_content(command.as_bytes()),
            newt_identity::RawContentId::from_content(cwd.as_bytes()),
        );
        let Some(grants) = self.pending_command_retries.get(&key) else {
            return base.clone();
        };
        if grants
            .iter()
            .any(|(kind, target)| self.state.denied(*kind, target))
        {
            self.pending_command_retries.remove(&key);
            return base.clone();
        }
        let Ok(policy) = self.mint(base, grants) else {
            return base.clone();
        };
        use newt_core::CaveatsExt as _;
        if !grants.iter().all(|(kind, target)| {
            *kind == newt_core::DenialKind::Exec && policy.permits_exec(target)
        }) {
            return base.clone();
        }
        self.pending_command_retries.remove(&key);
        policy
    }

    fn apply_pending_once(
        &mut self,
        kind: newt_core::DenialKind,
        target: &str,
        baseline: &newt_core::Caveats,
    ) -> newt_core::Caveats {
        let key = (kind, target.to_string());
        if !self.state.pending_once_grants.contains(&key) {
            return baseline.clone();
        }
        match self.mint(baseline, std::slice::from_ref(&key)) {
            Ok(policy) => {
                self.state.pending_once_grants.remove(&key);
                policy
            }
            // Mint can fail for reasons unrelated to this grant (e.g. key
            // minting); never drop a queued grant the operator already
            // approved just because this particular refresh could not apply
            // it — leave it queued for the next attempt.
            Err(_) => baseline.clone(),
        }
    }

    fn ask_with_caveats(
        &mut self,
        baseline: &newt_core::Caveats,
        requests: &[newt_core::PermissionRequest],
    ) -> newt_core::PermissionDecision {
        self.ask_scoped(baseline, requests, false)
    }

    fn ask_dependency_fetch(
        &mut self,
        prepared: &newt_core::Caveats,
        request: &newt_core::PermissionRequest,
    ) -> newt_core::PermissionDecision {
        self.ask_scoped(prepared, std::slice::from_ref(request), true)
    }

    fn ask_question(&mut self, question: &str) -> HumanQuestionOutcome {
        // C1 (#1862): the SESSION builds the semantic form; whichever surface
        // owns the terminal renders and reads it. Previously this thread called
        // `Terminal::suspend_for_prompt` itself — taking stdin and writing
        // prompt bytes from the session thread, which is what
        // `session_worker`'s law 1 ("a worker never writes terminal bytes")
        // forbids and what the cockpit made observable.
        //
        // Blocking on the operator still surfaces to the cockpit through the
        // tty arbiter's Blocked/Unblocked, because `suspend_for_prompt` still
        // happens — just on the other side of the seam.
        let interaction = SurfaceInteraction::blocking(free_text_form(question));
        let outcome = match self.ask_surface {
            Some(ask) => ask(&interaction),
            None => {
                let w =
                    Terminal::suspend_for_prompt(newt_core::tty::TerminalTaker::PermissionQuestion);
                present_on_terminal(&w, &interaction)
            }
        };
        // The CONTROL side effects are the session's, not the terminal's: only
        // this side owns the turn's cancel/exit flags. `present_on_terminal`
        // reports what happened and applies nothing.
        match outcome {
            // Esc / slash-command back-out: cancel the turn, report Cancelled
            // (never "headless"). The adapter rewrites a typed `/cmd` into a
            // back-out, so that lands here too.
            HumanQuestionOutcome::Cancelled => {
                self.apply_control(PromptChoice::Back);
                HumanQuestionOutcome::Cancelled
            }
            // Ctrl-C / Ctrl-D: cancel the turn AND request exit.
            HumanQuestionOutcome::ExitRequested => {
                self.apply_control(PromptChoice::Exit);
                HumanQuestionOutcome::ExitRequested
            }
            other => other,
        }
    }

    fn ask_choice(
        &mut self,
        question: &str,
        options: &[newt_core::agentic::ChoiceSpec],
    ) -> HumanQuestionOutcome {
        // Same seam as `ask_question`: the session builds the form, whichever
        // surface owns the terminal renders and reads it, and the control
        // side effects stay here.
        let interaction = choice_form(question, options);
        let outcome = match self.ask_surface {
            Some(ask) => ask(&interaction),
            None => {
                let w =
                    Terminal::suspend_for_prompt(newt_core::tty::TerminalTaker::PermissionQuestion);
                present_on_terminal(&w, &interaction)
            }
        };
        match outcome {
            // A blank submission is the default option, never an empty answer.
            HumanQuestionOutcome::Answer(answer) => {
                HumanQuestionOutcome::Answer(interaction.answer_or_default(&answer).to_string())
            }
            HumanQuestionOutcome::Cancelled => {
                self.apply_control(PromptChoice::Back);
                HumanQuestionOutcome::Cancelled
            }
            HumanQuestionOutcome::ExitRequested => {
                self.apply_control(PromptChoice::Exit);
                HumanQuestionOutcome::ExitRequested
            }
            other => other,
        }
    }
}

impl<F: FnMut(&PromptWindow, &SurfaceInteraction) -> PromptChoice> PromptPermissionGate<'_, F> {
    fn ask_scoped(
        &mut self,
        baseline: &newt_core::Caveats,
        requests: &[newt_core::PermissionRequest],
        operation_only: bool,
    ) -> newt_core::PermissionDecision {
        use newt_core::PermissionDecision::{Allow, Deny};
        if operation_only
            && (requests.len() != 1
                || requests[0].tool != "lifecycle"
                || requests[0].kind != newt_core::DenialKind::Net
                || baseline.net != newt_core::Scope::All)
        {
            return Deny;
        }
        if requests.is_empty() {
            return Deny;
        }
        if let Some(protection) = &self.state.protection {
            // Preflight the whole batch before consuming pending grants,
            // showing a prompt, or writing a permanent approval. Checking only
            // each path misses an allowed read alias plus its writable parent.
            let proposed = requests
                .iter()
                .map(|request| (request.kind, request.target.clone()))
                .collect::<Vec<_>>();
            if protection.validate_caveats(baseline).is_err()
                || requests.iter().any(|request| {
                    protection
                        .validate_request(request.kind, &request.target)
                        .is_err()
                })
                || self.policy_with_grants(baseline, &proposed).is_err()
            {
                return Deny;
            }
        }
        // A prepared build request carries its exact projected fence. Check
        // that fence before prompting as well as the named Build capability;
        // returned authority is clamped again by mint().
        if (operation_only
            || requests
                .iter()
                .any(|request| request.kind == newt_core::DenialKind::Build))
            && (self
                .preset_clamp
                .as_ref()
                .is_some_and(|ceiling| !baseline.leq(ceiling))
                || self
                    .delegation
                    .is_some_and(|delegation| !baseline.leq(delegation.caveats())))
        {
            return Deny;
        }
        // A filesystem manifest must not consume lawful pending siblings
        // before discovering that another target cannot survive the preset.
        let filesystem_batch = requests.iter().any(|request| {
            matches!(
                request.kind,
                newt_core::DenialKind::FsRead | newt_core::DenialKind::FsWrite
            )
        });
        if let Some(clamp) = &self.preset_clamp {
            if filesystem_batch
                && requests.iter().any(|request| {
                    matches!(
                        request.kind,
                        newt_core::DenialKind::FsRead
                            | newt_core::DenialKind::FsWrite
                            | newt_core::DenialKind::Exec
                            | newt_core::DenialKind::Net
                    ) && !ceiling_permits(clamp, request.kind, &request.target)
                })
            {
                return Deny;
            }
        }
        // A delegated session's inherited ceiling is preflighted over the WHOLE
        // batch, before any prompt is opened, any cache is consulted, and any
        // durable approval is honoured. Clamping the result afterwards would be
        // too late: prompting, granting and persisting are side effects, and a
        // child asking its operator to approve authority the child never held
        // is the amplification this exists to prevent. One forbidden request
        // denies the batch — a lawful sibling must not buy a side effect for a
        // request that cannot be granted.
        if let Some(d) = self.delegation {
            let ceiling = d.caveats();
            if requests
                .iter()
                .any(|r| !ceiling_permits(ceiling, r.kind, &r.target))
            {
                for r in requests {
                    self.record(r, "deny", "delegated-ceiling");
                }
                return Deny;
            }
        }
        // Previously recorded session, permanent, and OCAP denials short-circuit.
        if requests
            .iter()
            .any(|r| self.state.denied(r.kind, &r.target))
        {
            return Deny;
        }
        let mut once_grants: Vec<(newt_core::DenialKind, String)> = Vec::new();
        // dec1-build-grant round 2: a request covered by the Build-grant
        // fallback in `session_grant_covers` (an Exec of a build tool, e.g.
        // `cargo`, covered by a session Build grant rather than an exact
        // stored Exec grant) must retain the calibrated build filesystem
        // fence and the invocation's existing network scope. Build approval
        // adds no networking, and replayed session grants cannot restore a
        // host the invocation attenuated away. Clamp after minting because
        // `widen_caveats` only adds grants; it cannot enforce these ceilings.
        let mut build_covered_clamp: Option<newt_core::Caveats> = None;
        let web = self.state.web_store.clone();
        for req in requests {
            // Build grants are non-axis but still bounded by an explicit
            // posture ceiling; a prompt cannot expand that ceiling.
            if req.kind == newt_core::DenialKind::Build
                && self
                    .preset_clamp
                    .as_ref()
                    .is_some_and(|floor| !ceiling_permits(floor, req.kind, &req.target))
            {
                self.record(req, "deny", "preset-floor-build");
                return Deny;
            }
            // GitWrite is non-axis, so enforce the readonly preset before minting.
            if req.kind == newt_core::DenialKind::GitWrite {
                if let Some(clamp) = &self.preset_clamp {
                    if !newt_core::git_caveats::GitCaveats::from_session(clamp).permits_commit() {
                        self.record(req, "deny", "preset-floor-git-readonly");
                        return Deny;
                    }
                }
            }
            // #2720: asking for authority already held is not a denial.
            // Explicit denies and delegation checks above still win. Only
            // proactive requests qualify: actual writes and bound replays
            // retain their independent consent prompts.
            if req.tool == "request_permissions"
                && !req.harness_bound
                && matches!(
                    req.kind,
                    newt_core::DenialKind::Exec
                        | newt_core::DenialKind::Net
                        | newt_core::DenialKind::FsRead
                        | newt_core::DenialKind::FsWrite
                )
                && self
                    .policy_with_grants(baseline, &[])
                    .is_ok_and(|policy| ceiling_permits(&policy, req.kind, &req.target))
            {
                continue;
            }
            if !operation_only && session_grant_covers(&self.state.session_grants, req) {
                // An exact match needs no further widening — it is already
                // reachable through `recalled_grants` in `mint`. The
                // build-tool fallback in `session_grant_covers` is NOT itself
                // a stored grant, so fold it into this call's `once_grants`
                // or the returned caveats would never widen `exec`/`fs_read`
                // for it (dec1-build-grant, F30/F35).
                if !self
                    .state
                    .session_grants
                    .contains(&(req.kind, req.target.clone()))
                {
                    once_grants.push((req.kind, req.target.clone()));
                    // This IS the build-tool fallback (an exact match took
                    // the branch above), so pin the clamp to the covering
                    // Build grant's workspace fence — the grant whose
                    // workspace contains this call's cwd, when more than one
                    // is held.
                    if let Some(workspace) =
                        covering_build_grant_workspace(&self.state.session_grants, baseline)
                    {
                        let mut fence = newt_core::confined_exec::build_tool_caveats(
                            std::path::Path::new(workspace),
                        );
                        fence.net = baseline.net.clone();
                        if self.state.validate_caveats(&fence).is_err() {
                            return Deny;
                        }
                        build_covered_clamp = Some(match build_covered_clamp.take() {
                            Some(existing) => existing.meet(&fence),
                            None => fence,
                        });
                    }
                }
                continue;
            }
            if !operation_only
                && self
                    .state
                    .durable_grants
                    .contains(&(req.kind, req.target.clone()))
                && self.danger.classify(req.kind, &req.target) != danger::DangerTier::High
            {
                self.record(req, "allow", "encrypted-permanent");
                continue;
            }
            // Durable approval pre-answers only a low-danger request.
            if !operation_only
                && newt_core::ocap_store::evaluate_request(
                    &self.state.ocap_policy,
                    req.kind,
                    &req.target,
                ) == Some(newt_core::ocap_store::Verdict::Approve)
                && self.danger.classify(req.kind, &req.target) != danger::DangerTier::High
            {
                self.record(req, "allow", "ocap-approve");
                once_grants.push((req.kind, req.target.clone()));
                continue;
            }
            // #2716: one worker invocation can report the same resolved exec
            // denial many times (e.g. a loop). Reuse this batch's exact-path
            // approval; nothing survives this call or changes replay policy.
            if req.tool == "run_command"
                && req.kind == newt_core::DenialKind::Exec
                && std::path::Path::new(&req.target).is_absolute()
                && once_grants
                    .iter()
                    .any(|(kind, target)| *kind == req.kind && target == &req.target)
            {
                self.record(req, "allow", "once");
                continue;
            }
            // Only the eventual operation consumes a request_permissions grant.
            if !operation_only && req.tool != "request_permissions" {
                if let Some(key) = take_pending_once(&mut self.state.pending_once_grants, req) {
                    self.record(req, "allow", "once");
                    once_grants.push(key);
                    continue;
                }
            }
            // Disabling prompts forbids new interactive grants, while verified
            // standing authority still works after the preflights above. Keep
            // this gate for `ask_question`, which is not an authorization.
            if !self.authorization_prompts_enabled {
                self.record(req, "deny", "authorization-prompts-disabled");
                return Deny;
            }
            // The session hands semantic authorization to its terminal owner,
            // just as `ask_question` does. Taking stdin on this worker would
            // race the cockpit and leave its composer over the permission menu.
            let mut window = None;
            let (choice, scope) = match &web {
                Some(store) => self.await_web_decision(store, req),
                None => {
                    // ONE definition: rendered to the operator, and the
                    // authority the answer is checked against. No store is
                    // touched — see `b0b::the_default_terminal_path_
                    // performs_no_store_write`.
                    //
                    // C0a (#1856): the definition goes to the reader whole.
                    // It used to be flattened to a `Question` here first,
                    // which meant the value displayed and the value
                    // authorized against were two objects that happened to
                    // agree; now they are one.
                    let interaction = permission_interaction(
                        req,
                        &self.danger,
                        self.state.prompt_default.unwrap_or_else(|| {
                            if req.tool == "mcp connect" && req.kind == newt_core::DenialKind::Net {
                                self.state.mcp_net_prompt_default.unwrap_or(
                                    newt_core::ToolPermissions::default().mcp_net_prompt_default,
                                )
                            } else {
                                PromptChoice::AllowOnce
                            }
                        }),
                    );
                    let decoded = match self.ask_surface {
                        Some(ask) => match ask(&interaction) {
                            HumanQuestionOutcome::Answer(answer) => decode_answer(
                                &interaction.definition,
                                interaction.answer_or_default(&answer),
                            ),
                            HumanQuestionOutcome::Cancelled => PromptChoice::Back,
                            HumanQuestionOutcome::ExitRequested => PromptChoice::Exit,
                            HumanQuestionOutcome::InputClosed
                            | HumanQuestionOutcome::InputFailed
                            | HumanQuestionOutcome::Unavailable => PromptChoice::Deny,
                        },
                        None => (self.ask_human)(
                            window.insert(direct_authorization_window()),
                            &interaction,
                        ),
                    };
                    match self.authorize(&interaction.definition, Audience::Terminal, decoded) {
                        Ok(choice) => (choice, decision_scope(choice)),
                        Err(refusal) => {
                            self.note_refusal(window.as_ref(), req, decoded, &refusal);
                            return Deny;
                        }
                    }
                }
            };
            match choice {
                PromptChoice::AllowOnce => {
                    self.record(req, "allow", scope);
                    once_grants.push((req.kind, req.target.clone()));
                    // Carry proactive allow-once to the model's separate retry.
                    if req.tool == "request_permissions" {
                        self.state
                            .pending_once_grants
                            .insert((req.kind, req.target.clone()));
                    }
                }
                PromptChoice::AllowSession => {
                    // The form omits this action for high danger; enforce it
                    // too — except `Build` (dec1-build-grant, F30), which the
                    // form DOES offer for session scope: it is bounded by the
                    // calibrated `build_tool_caveats` fence, not open-ended.
                    if self.danger.classify(req.kind, &req.target) == danger::DangerTier::High
                        && req.kind != newt_core::DenialKind::Build
                    {
                        self.record(req, "deny", "session-allow-refused-high-danger");
                        self.notice(
                            window.as_ref(),
                            &format!(
                                "session allow refused for high-danger `{}` — \
                                 allow once per op or deny (step-up is the future path)",
                                req.target
                            ),
                        );
                        return Deny;
                    }
                    self.record(req, "allow", scope);
                    self.state
                        .session_grants
                        .insert((req.kind, req.target.clone()));
                }
                PromptChoice::AllowPermanent => {
                    // The danger refusal must run BEFORE any write attempt for
                    // ALL FOUR durable-store kinds — a real bug fix (#2535):
                    // this used to run only for net.
                    //
                    // #2524 follow-up item 2: classify (and name, below) the
                    // NORMALIZED target, not the raw one — `/ws/..` must be
                    // judged and reported as `/`, the path the writer would
                    // actually persist, not a raw string that hides it.
                    let danger_target = normalized_danger_target(req.kind, &req.target);
                    if self.danger.classify(req.kind, &danger_target) == danger::DangerTier::High {
                        self.record(req, "deny", "permanent-allow-refused-high-danger");
                        self.notice(
                            window.as_ref(),
                            &format!("permanent allow refused for high-danger `{danger_target}`"),
                        );
                        return Deny;
                    }
                    let entry = match approve_entry_for(req.kind, &req.target) {
                        None => {
                            // Kinds outside the durable store's vocabulary
                            // (RemoteTool/GitWrite/Build) keep the prior
                            // session-only behavior.
                            self.record(req, "allow", scope);
                            self.state
                                .session_grants
                                .insert((req.kind, req.target.clone()));
                            continue;
                        }
                        Some(Err(reason)) => {
                            self.record(req, "deny", "permanent-allow-refused-relative-exec-path");
                            self.notice(window.as_ref(), &reason);
                            return Deny;
                        }
                        Some(Ok(entry)) => entry,
                    };
                    // #2524 round 2 item 3: three distinct causes collapsed into
                    // one message used to leave the operator guessing which one
                    // applied and what to do about it. Checked in this order so
                    // each gets its own notice.
                    let persistent_scope = if self.delegation.is_some() {
                        // #2535 item 6: a delegated session never establishes
                        // its own root — reading `key_path` under one anyway
                        // would be the dangerous shape this repo's OCAP
                        // doctrine calls out (a key visible on disk,
                        // deliberately not rooted in).
                        self.notice(
                            window.as_ref(),
                            "permanent allow unavailable (a delegated session never \
                             establishes its own root key): granted for this session only",
                        );
                        "session"
                    } else if self.config_path.is_none() {
                        self.notice(
                            window.as_ref(),
                            "permanent allow unavailable (no trusted config path for this \
                             session): granted for this session only",
                        );
                        "session-no-config"
                    } else {
                        let root = self
                            .key_path
                            .as_deref()
                            .and_then(|p| newt_identity::load_user_key(p).ok());
                        match (root, self.config_path.as_deref()) {
                            (Some(root), Some(config_path)) => {
                                match newt_core::ocap_store::persist_approve(
                                    config_path,
                                    entry,
                                    ocap_high_danger_predicate(),
                                    |payload| root.sign(payload).to_bytes(),
                                ) {
                                    Ok(had_comments) => {
                                        // BLOCKER (#2524 round 2 item 1): the
                                        // write just appended ONE freshly-signed
                                        // entry beside whatever else already sat
                                        // in `approve.toml` — including, in the
                                        // adversary's case, a pre-existing
                                        // unsigned or tampered entry nothing on
                                        // this path has verified. Folding the
                                        // written `PolicyFile` straight in would
                                        // launder that entry into live authority
                                        // the moment ANY grant is persisted.
                                        // Reload through the SAME verifying path
                                        // startup uses instead — an unsigned/
                                        // bad-signature entry drops loudly here,
                                        // never reaching `fold_ocap_approvals`.
                                        let root_vk = Some(root.public().as_bytes());
                                        let (policy, warnings) =
                                            newt_core::ocap_store::load_store(config_path, root_vk);
                                        self.state.ocap_policy = policy;
                                        for w in &warnings {
                                            self.notice(
                                                window.as_ref(),
                                                &format!("warning: OCAP policy: {w}"),
                                            );
                                        }
                                        self.state.fold_ocap_approvals();
                                        let approve_path = config_path.with_file_name("ocap").join(
                                            newt_core::ocap_store::Verdict::Approve.filename(),
                                        );
                                        self.notice(
                                            window.as_ref(),
                                            &format!(
                                                "permanently allowed: {} `{}` (signed → {})",
                                                axis_label(req.kind),
                                                req.target,
                                                approve_path.display()
                                            ),
                                        );
                                        // #2524 follow-up item 3: `to_toml`
                                        // re-serialises the whole file, which
                                        // drops any hand-written TOML comment
                                        // — `newt doctor --sign-ocap` already
                                        // says so; this path did not.
                                        if had_comments {
                                            self.notice(
                                                window.as_ref(),
                                                "note: re-saving approve.toml dropped any \
                                                 hand-written comments it had (TOML \
                                                 comments are not preserved across a write)",
                                            );
                                        }
                                        "permanent"
                                    }
                                    Err(e) => {
                                        self.notice(
                                            window.as_ref(),
                                            &format!(
                                                "warning: could not persist permanent grant: {e} \
                                             (granted for this session only)"
                                            ),
                                        );
                                        "permanent-persist-failed"
                                    }
                                }
                            }
                            _ => {
                                self.notice(
                                    window.as_ref(),
                                    &no_key_notice(self.key_path.as_deref()),
                                );
                                "session-no-key"
                            }
                        }
                    };
                    self.record(req, "allow", persistent_scope);
                    self.state
                        .session_grants
                        .insert((req.kind, req.target.clone()));
                }
                PromptChoice::Deny => {
                    self.record(req, "deny", scope);
                    return Deny;
                }
                PromptChoice::DenyAlways => {
                    self.record(req, "deny", "session");
                    self.state
                        .session_denials
                        .insert((req.kind, req.target.clone()));
                    return Deny;
                }
                PromptChoice::DenyPermanent => {
                    self.record(req, "deny", "permanent");
                    if let Some(path) = self.denials_path.as_deref() {
                        if let Err(e) = newt_core::append_denial(path, req.kind, &req.target) {
                            print_newt(
                                &format!("warning: permission denylist write failed: {e}"),
                                self.color,
                                self.verbose,
                            );
                        }
                    }
                    self.state
                        .persistent_denials
                        .insert((req.kind, req.target.clone()));
                    return Deny;
                }
                control @ (PromptChoice::Back | PromptChoice::Exit) => {
                    self.apply_control(control);
                    return Deny;
                }
            }
        }
        let Ok(minted) = self.mint(baseline, &once_grants) else {
            return Deny;
        };
        let allowed = match build_covered_clamp {
            Some(fence) => minted.meet(&fence),
            None => minted,
        };
        if self.state.validate_caveats(&allowed).is_err() {
            return Deny;
        }
        if operation_only {
            // Recalled grants cannot add unrelated authority to the prepared
            // operation, and a clamp may not silently remove its needed fence.
            if !baseline.leq(&allowed) {
                return Deny;
            }
            Allow(allowed.meet(baseline))
        } else {
            Allow(allowed)
        }
    }
}

#[cfg(test)]
#[path = "permissions_tests/permission_prompt_tests.rs"]
mod permission_prompt_tests;

#[cfg(test)]
#[path = "permissions_tests/session_promotion.rs"]
mod session_promotion;

#[cfg(test)]
#[path = "permissions_tests/ocap_grant_fold.rs"]
mod ocap_grant_fold;

#[cfg(test)]
#[path = "permissions_tests/permanent_grant_writer.rs"]
mod permanent_grant_writer;

/// **A0 byte goldens (#1823, epic #1803): the plain permission-prompt
/// rendering, frozen verbatim.** These strings ARE the current contract —
/// including the deliberately DIFFERENT terminal/web action matrices (web
/// omits every durable grant; net+low+terminal is the only permanent-allow) —
/// and epic law 1 says a later slice must keep the plain fallback. C0a
/// (#1856) extracted the rendering out of the semantic type and these
/// strings did not move, which is what "extracted" is allowed to mean —
/// they are now produced by `markup::plain::render`. An intentional
/// rendering change updates these strings in the same PR, listed as an
/// intentional diff (unlisted golden drift is a bug, per the epic's F0 rule).
#[cfg(test)]
#[path = "permissions_tests/a0_freeze_goldens.rs"]
mod a0_freeze_goldens;

/// **C0a (#1856, epic #1803): the plain renderer reproduces the frozen
/// bytes, and the operator-visible prompt is pinned for the first time.**
///
/// A0 froze `terminal_text()`'s output; C0a moves that rendering to
/// `newt_core::markup::plain::render` and deletes the method. The whole
/// proof of correctness is byte-identity, so the goldens are restated here
/// a third time, deliberately, under A0's own duplication discipline: each
/// copy independently catches an accidental edit to another.
///
/// What this copy adds that the other two do not: it pins the **composed**
/// string `prompt_permission_choice` actually hands the terminal — the
/// rendering plus `MODAL_INPUT_GLYPH` on its own final line. The A0 sweep
/// recorded that nothing per-PR covered that composition (the only test
/// that saw it end to end is the real-PTY one, `#[ignore]`d to the weekly
/// tier), and it is exactly the shape `tty::modal::render` depends on when
/// it repaints only the text after the last `\n`.
#[cfg(test)]
#[path = "permissions_tests/c0a.rs"]
mod c0a;

/// **B0a (#1841): one definition builder for both surfaces.**
///
/// A0 froze the rendered strings; these tests prove the DEFINITION path
/// reproduces them and that the per-surface action matrices live in the
/// definition rather than in a renderer. The golden strings are repeated
/// here deliberately: A0's copy freezes the contract, this copy proves the
/// new construction path reaches it, and an accidental edit to one copy is
/// caught by the other.
///
/// **`Question::parse` remains the authoritative accept/deny path.**
/// Nothing here uses `binding::validate_response` — that move, with the
/// behavior-map and formal-model updates it requires, is #1842.
#[cfg(test)]
#[path = "permissions_tests/b0a.rs"]
mod b0a;

/// **B0b-1 (#1842): the accept/deny decision, on the A3 controller.**
///
/// `Question::parse` is KEPT and demoted to input decoding — aliases,
/// ambiguity denial, case-distinct keys. `validate_response` authorizes.
/// These tests pin the four facts that move, and the two that must not.
#[cfg(test)]
#[path = "permissions_tests/b0b.rs"]
mod b0b;

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

// Model: GPT-6 | Harness: Codex CLI v0.154.0 | Operator: S Hartsock | Time: 22:06 EDT | Date: 2026-09-17