tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
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
#!/usr/bin/env bash
# tirith bash hook
# Two modes controlled by TIRITH_BASH_MODE:
#   enter (default outside SSH): bind -x Enter override. Can block + intercept paste.
#     Startup health gate + pending-not-consumed detection auto-degrade to preexec.
#   preexec: DEBUG trap warn-only. Cannot block. No paste interception.

# Establish trusted builtin lookup before reading or clearing any security
# state. Bash normally resolves functions before builtins, so an exported
# `BASH_FUNC_unset%%`, `BASH_FUNC_builtin%%`, or `BASH_FUNC_shopt%%` can shadow
# even an explicit `builtin ...` invocation. Assigning POSIXLY_CORRECT enters
# POSIX mode without a command lookup; in that mode the special `unset`
# builtin has precedence over functions. Use that one grammar-level foothold
# to remove every builtin name this hook relies on, then restore the caller's
# POSIX mode and POSIXLY_CORRECT value exactly. Backslashes suppress aliases
# while this bootstrap is in progress.
_TIRITH_BOOTSTRAP_WAS_POSIX=0
[[ -o posix ]] && _TIRITH_BOOTSTRAP_WAS_POSIX=1
_TIRITH_BOOTSTRAP_POSIXLY_SET="${POSIXLY_CORRECT+x}"
_TIRITH_BOOTSTRAP_POSIXLY_VALUE="${POSIXLY_CORRECT-}"
POSIXLY_CORRECT=y
if [[ -o posix ]]; then
\unset -f \
  alias bind builtin cd command declare disown enable eval exec exit export \
  false getopts hash history jobs kill local printf read readonly return set shift \
  shopt source test trap true type typeset ulimit umask unalias unset wait 2>/dev/null
\unalias \
  alias bind builtin cd command declare disown enable eval exec exit export \
  false getopts hash history jobs kill local printf read readonly return set shift \
  shopt source test trap true type typeset ulimit umask unalias unset wait 2>/dev/null
if [[ "$_TIRITH_BOOTSTRAP_POSIXLY_SET" == "x" ]]; then
  POSIXLY_CORRECT="$_TIRITH_BOOTSTRAP_POSIXLY_VALUE"
else
  \unset POSIXLY_CORRECT
fi
if [[ "$_TIRITH_BOOTSTRAP_WAS_POSIX" == "0" ]]; then
  \set +o posix
fi
unset _TIRITH_BOOTSTRAP_WAS_POSIX _TIRITH_BOOTSTRAP_POSIXLY_SET _TIRITH_BOOTSTRAP_POSIXLY_VALUE

# Guard against double-loading (session-local only).
# If inherited from environment (exported by attacker/parent), ignore it.
if [[ -n "$_TIRITH_BASH_LOADED" ]]; then
  if [[ "$(declare -p _TIRITH_BASH_LOADED 2>/dev/null)" =~ ^declare\ -[a-zA-Z]*x ]]; then
    unset _TIRITH_BASH_LOADED  # Inherited from env — ignore and load fresh
  else
    return  # Set in this session — genuine double-source guard
  fi
fi
_TIRITH_BASH_LOADED=1

# Clear attacker-controllable env vars before any hooks are installed.
# A pre-set value would be eval'd on the first prompt.
unset _TIRITH_PENDING_EVAL
unset _TIRITH_PENDING_RECEIPT _TIRITH_PENDING_COMMAND
# _TIRITH_TEST_*: only clear if inherited from environment (exported by parent).
# Session-local values (set without export) are trusted test overrides.
[[ "$(declare -p _TIRITH_TEST_SKIP_HEALTH 2>/dev/null)" =~ ^declare\ -[a-zA-Z]*x ]] && unset _TIRITH_TEST_SKIP_HEALTH
[[ "$(declare -p _TIRITH_TEST_FAIL_HEALTH 2>/dev/null)" =~ ^declare\ -[a-zA-Z]*x ]] && unset _TIRITH_TEST_FAIL_HEALTH

# Hook state that is READ before this session ever writes it. Everything below
# is session-local by contract: Tirith only ever hands these to a child as a
# command prefix on its own `tirith` invocations, so an interactive shell that
# starts with one already in its environment received it from somewhere else.
#
# `_TIRITH_BASH_INTERNAL=1` is the load-bearing one — it is the first line of
# `_tirith_preexec`, so a parent process that exports it turns off command
# interception for the whole session without touching a config file, a policy,
# or the hook itself. The rest are the same shape: a pre-seeded per-line
# decision cache (an allow verdict Tirith never issued), the DEBUG-chaining
# slot the trampoline evals, and the one-shot latches that would swallow the
# downgrade banners a user needs to see.
#
# These values are private implementation state, not configuration. Reset them
# unconditionally on a fresh load: testing whether they were exported before
# clearing them creates a second attacker-controlled read and is unnecessary.
for _tirith_inherited_state in \
  _TIRITH_BASH_INTERNAL \
  _tirith_last_key _tirith_last_rc _tirith_last_cmd \
  _TIRITH_PREV_DEBUG_TRAP \
  _TIRITH_DEGRADE_WARNED _TIRITH_OFF_WARNED _TIRITH_PREEXEC_WARNED _TIRITH_RECEIPT_DEGRADE_WARNED \
  _TIRITH_BINDS_INSTALLED _TIRITH_PREEXEC_PROMPT_STATUS \
  _TIRITH_PROTECTED_KEYMAPS _TIRITH_SAVED_CTRL_O_KINDS _TIRITH_SAVED_CTRL_O_BINDINGS
do
  unset "$_tirith_inherited_state"
done
unset _tirith_inherited_state

# Session tracking: generate ID per shell session if not inherited
if [[ -z "${TIRITH_SESSION_ID:-}" ]]; then
  builtin printf -v TIRITH_SESSION_ID '%x-%x-%x-%x' \
    "$$" "${SECONDS:-0}" "${RANDOM:-0}" "${RANDOM:-0}"
  export TIRITH_SESSION_ID
fi

# Pin the executable before any repository command can mutate PATH. Resolve
# the containing directory with shell builtins so this security initialization
# does not itself execute a PATH-controlled helper.
_TIRITH_BASH_BIN="${BASH:-}"
case "$_TIRITH_BASH_BIN" in
  /*) [[ -x "$_TIRITH_BASH_BIN" ]] || _TIRITH_BASH_BIN="" ;;
  *) _TIRITH_BASH_BIN="" ;;
esac
_tirith_resolved_bin="$(type -P tirith 2>/dev/null || true)"
_TIRITH_BIN=""
if [[ -n "$_tirith_resolved_bin" ]]; then
  _tirith_bin_name="${_tirith_resolved_bin##*/}"
  _tirith_bin_dir="${_tirith_resolved_bin%/*}"
  [[ "$_tirith_bin_dir" == "$_tirith_resolved_bin" ]] && _tirith_bin_dir="."
  _TIRITH_BIN="$(
    builtin cd -P -- "$_tirith_bin_dir" 2>/dev/null \
      && printf '%s/%s' "$PWD" "$_tirith_bin_name"
  )"
fi
unset _tirith_resolved_bin _tirith_bin_name _tirith_bin_dir
if [[ $- == *i* && ( -z "$_TIRITH_BIN" || ! -x "$_TIRITH_BIN" ) ]]; then
  printf '%s\n' "tirith: executable not found; bash hooks disabled" >&2
  TIRITH_STATUS=off
  return
fi

# Stock macOS Bash 3.2 runs an external command inside `$(...)` from a subshell.
# Protocol-v3 receipt operations bind Tirith to its exact parent shell PID, so a
# command-substitution capture would make the helper subshell (not this
# long-lived interactive shell) Tirith's parent. Capture Tirith stdout in a
# private temporary file instead: Tirith remains a direct child, parsing happens
# in this shell, and every caller removes the file immediately.
_TIRITH_MKTEMP_BIN=""
[[ -f /usr/bin/mktemp && -x /usr/bin/mktemp ]] && _TIRITH_MKTEMP_BIN=/usr/bin/mktemp
[[ -z "$_TIRITH_MKTEMP_BIN" && -f /bin/mktemp && -x /bin/mktemp ]] && _TIRITH_MKTEMP_BIN=/bin/mktemp
_TIRITH_RM_BIN=""
[[ -f /bin/rm && -x /bin/rm ]] && _TIRITH_RM_BIN=/bin/rm
[[ -z "$_TIRITH_RM_BIN" && -f /usr/bin/rm && -x /usr/bin/rm ]] && _TIRITH_RM_BIN=/usr/bin/rm
_TIRITH_MKDIR_BIN=""
[[ -f /bin/mkdir && -x /bin/mkdir ]] && _TIRITH_MKDIR_BIN=/bin/mkdir
[[ -z "$_TIRITH_MKDIR_BIN" && -f /usr/bin/mkdir && -x /usr/bin/mkdir ]] && _TIRITH_MKDIR_BIN=/usr/bin/mkdir
_TIRITH_WC_BIN=""
[[ -f /usr/bin/wc && -x /usr/bin/wc ]] && _TIRITH_WC_BIN=/usr/bin/wc
[[ -z "$_TIRITH_WC_BIN" && -f /bin/wc && -x /bin/wc ]] && _TIRITH_WC_BIN=/bin/wc
_TIRITH_STTY_BIN=""
[[ -f /bin/stty && -x /bin/stty ]] && _TIRITH_STTY_BIN=/bin/stty
[[ -z "$_TIRITH_STTY_BIN" && -f /usr/bin/stty && -x /usr/bin/stty ]] && _TIRITH_STTY_BIN=/usr/bin/stty

_tirith_new_capture_file() {
  [[ -n "$_TIRITH_MKTEMP_BIN" && -n "$_TIRITH_RM_BIN" ]] || return 1
  local base="${TMPDIR:-/tmp}"
  case "$base" in
    *$'\n'*|*$'\r'*) return 1 ;;
  esac
  [[ -d "$base" ]] || return 1
  (umask 077; builtin command "$_TIRITH_MKTEMP_BIN" "${base%/}/tirith-bash.XXXXXXXX")
}

_tirith_capture_file_is_private() {
  local file="${1:-}"
  [[ -n "$file" && -f "$file" && ! -L "$file" && -O "$file" ]]
}

_tirith_remove_capture_file() {
  local file="${1:-}"
  [[ -n "$file" && -n "$_TIRITH_RM_BIN" ]] || return 1
  builtin command "$_TIRITH_RM_BIN" -f -- "$file"
}

_tirith_restore_terminal_state() {
  local state="${1:-}"
  [[ -n "$state" && -n "$_TIRITH_STTY_BIN" ]] || return 0
  builtin command "$_TIRITH_STTY_BIN" "$state" 2>/dev/null || true
}

# Bash 3.2 predates `exec {var}` dynamic descriptor allocation. Allocate one
# unused descriptor from a small fixed range without interpolating payload text
# into `eval`; each writer receives its bytes as a quoted data argument.
_tirith_fixed_fd_is_valid() {
  case "${1:-}" in
    10|11|12|13|14|15|16|17|18|19) return 0 ;;
    *) return 1 ;;
  esac
}

# Receipt stdin frames must be byte-exact: no sentinel and no extra newline.
# The consumer blocks on the anonymous pipe until the writer supplies the frame,
# while Tirith itself remains a direct child of the long-lived Bash process.
_tirith_open_exact_input_pipe() {
  local payload="$1" candidate
  local previous_internal="${_TIRITH_BASH_INTERNAL:-0}"
  _TIRITH_OPENED_FD=""
  for candidate in 19 18 17 16 15 14 13 12 11 10; do
    [[ -e "/dev/fd/$candidate" ]] && continue
    _TIRITH_PIPE_BYTES="$payload"
    _TIRITH_BASH_INTERNAL=1
    if builtin eval "exec ${candidate}< <(builtin printf '%s' \"\$_TIRITH_PIPE_BYTES\")"; then
      _TIRITH_BASH_INTERNAL="$previous_internal"
      _TIRITH_OPENED_FD="$candidate"
      unset _TIRITH_PIPE_BYTES
      return 0
    fi
    _TIRITH_BASH_INTERNAL="$previous_internal"
  done
  _TIRITH_BASH_INTERNAL="$previous_internal"
  unset _TIRITH_PIPE_BYTES
  return 1
}

_tirith_close_pending_fd() {
  local pending_fd="${1:-}"
  _tirith_fixed_fd_is_valid "$pending_fd" || return 1
  builtin eval "exec ${pending_fd}<&-"
}

# Read exactly one text line without a command substitution. The result is
# returned in `_TIRITH_CAPTURE_LINE`; empty, unterminated, or multi-line files
# fail closed.
_tirith_read_single_capture_line() {
  local file="$1" line="" count=0 terminated=0 read_rc=0 byte_count="" expected_bytes=0
  _TIRITH_CAPTURE_LINE=""
  _tirith_capture_file_is_private "$file" || return 1
  while :; do
    line=""
    IFS= read -r line
    read_rc=$?
    [[ $read_rc -ne 0 && -z "$line" ]] && break
    count=$((count + 1))
    [[ $count -eq 1 ]] && _TIRITH_CAPTURE_LINE="$line"
    if [[ $read_rc -eq 0 ]]; then
      terminated=1
    else
      terminated=0
    fi
    [[ $count -gt 1 || $read_rc -ne 0 ]] && break
  done < "$file"
  [[ $count -eq 1 && $terminated -eq 1 && -n "$_TIRITH_WC_BIN" ]] || return 1
  byte_count="$(builtin command "$_TIRITH_WC_BIN" -c < "$file" 2>/dev/null)" || return 1
  byte_count="${byte_count//[^0-9]/}"
  [[ -n "$byte_count" ]] || return 1
  expected_bytes=$((${#_TIRITH_CAPTURE_LINE} + 1))
  [[ "$byte_count" == "$expected_bytes" ]]
}

# Parse the complete protocol-v3 stdout contract for one receipt-enabled check.
# Returns 0 for an executable rc=0/2 response carrying exactly one already-armed
# token, 1 for a valid rc=1 block with empty stdout, and 2 for every malformed or
# unsupported rc/stdout combination. A recoverable token is exposed for cleanup.
_tirith_parse_v3_receipt_response() {
  local file="$1" check_rc="$2" line_ok=0
  _TIRITH_PARSED_RECEIPT=""
  _tirith_capture_file_is_private "$file" || return 2
  if _tirith_read_single_capture_line "$file"; then
    line_ok=1
    if [[ "$_TIRITH_CAPTURE_LINE" =~ ^TIRITH_EXECUTION_RECEIPT=([0-9a-f]{64})$ ]]; then
      _TIRITH_PARSED_RECEIPT="${BASH_REMATCH[1]}"
    fi
  fi
  case "$check_rc" in
    0|2)
      [[ $line_ok -eq 1 && -n "$_TIRITH_PARSED_RECEIPT" ]] && return 0
      return 2
      ;;
    1)
      [[ ! -s "$file" ]] && return 1
      return 2
      ;;
    *) return 2 ;;
  esac
}

# Validate the exact readline buffer without Bash 3.2's here-string temp file.
# The command remains shell data passed through an anonymous pipe. Capture the
# parser's status explicitly: a user-enabled pipefail or a writer-side SIGPIPE
# must never replace the `bash -n` verdict.
_tirith_check_command_syntax() {
  local command_text="$1"
  _TIRITH_SYNTAX_ERROR="$(
    set +o pipefail
    builtin printf '%s\n' "$command_text" \
      | builtin command "$_TIRITH_BASH_BIN" -n 2>&1
    exit "${PIPESTATUS[1]}"
  )"
  _TIRITH_SYNTAX_RC=$?
}

_TIRITH_RECEIPT_PROTOCOL=0
_TIRITH_RECEIPT_INSTANCE=""
_TIRITH_RECEIPT_SHELL_PID="$$"
_TIRITH_RECEIPT_FAMILY="bash"

# `$$` intentionally remains the top-level shell PID in Bash subshells. With
# functrace (`set -T`), however, an inherited DEBUG trap can run from a process
# whose actual PID/parent relation differs from the registered shell. Never
# make a strict receipt claim from that context.
_tirith_receipt_parent_context_is_valid() {
  [[ "${BASH_SUBSHELL:-0}" == "0" \
     && "$$" == "$_TIRITH_RECEIPT_SHELL_PID" ]]
}

_tirith_receipt_capture_file=""
_tirith_receipt_error_file=""
_TIRITH_RECEIPT_REGISTER_ERROR=""
if [[ $- == *i* ]]; then
  _tirith_receipt_capture_file="$(_tirith_new_capture_file 2>/dev/null)" || _tirith_receipt_capture_file=""
  _tirith_receipt_error_file="$(_tirith_new_capture_file 2>/dev/null)" || _tirith_receipt_error_file=""
  if [[ -n "$_tirith_receipt_capture_file" && -n "$_tirith_receipt_error_file" ]] \
     && builtin command "$_TIRITH_BIN" __execution-receipt capability \
          >|"$_tirith_receipt_capture_file" 2>/dev/null \
     && _tirith_read_single_capture_line "$_tirith_receipt_capture_file" \
     && [[ "$_TIRITH_CAPTURE_LINE" == "TIRITH_EXECUTION_RECEIPT_PROTOCOL=3" ]]; then
    : >| "$_tirith_receipt_capture_file"
    if builtin command "$_TIRITH_BIN" __execution-receipt register \
         --family bash --shell-pid "$_TIRITH_RECEIPT_SHELL_PID" \
         >|"$_tirith_receipt_capture_file" 2>|"$_tirith_receipt_error_file" \
       && _tirith_read_single_capture_line "$_tirith_receipt_capture_file"; then
      _TIRITH_RECEIPT_INSTANCE="$_TIRITH_CAPTURE_LINE"
    fi
    if [[ "$_TIRITH_RECEIPT_INSTANCE" =~ ^[0-9a-f]{64}$ ]]; then
      _TIRITH_RECEIPT_PROTOCOL=3
    else
      _TIRITH_RECEIPT_INSTANCE=""
      # Keep the first line of the rejection so the one-shot degrade warning
      # can say WHY instead of silently downgrading (issue #221).
      IFS= read -r _TIRITH_RECEIPT_REGISTER_ERROR \
        < "$_tirith_receipt_error_file" 2>/dev/null || :
    fi
  fi
  [[ -n "$_tirith_receipt_capture_file" ]] \
    && _tirith_remove_capture_file "$_tirith_receipt_capture_file" >/dev/null 2>&1
  [[ -n "$_tirith_receipt_error_file" ]] \
    && _tirith_remove_capture_file "$_tirith_receipt_error_file" >/dev/null 2>&1
fi
unset _tirith_receipt_capture_file _tirith_receipt_error_file _TIRITH_CAPTURE_LINE

# M8 ch2 — surface "this shell is on the remote side of an SSH session" to
# `tirith prompt-status` (planned for M8 ch6) and any other downstream
# consumer. Set NOW so chunk 6 can read it without a follow-up hook patch.
# Standard SSH env vars: SSH_CONNECTION, SSH_CLIENT, SSH_TTY.
if [[ -z "${TIRITH_SSH_REMOTE:-}" ]] \
   && { [[ -n "${SSH_CONNECTION:-}" ]] || [[ -n "${SSH_CLIENT:-}" ]] || [[ -n "${SSH_TTY:-}" ]]; }; then
  TIRITH_SSH_REMOTE=1
  export TIRITH_SSH_REMOTE
fi

# M9 ch4 — record a shell-start environment snapshot for `tirith env diff`.
# Exec a hidden tirith subcommand that reads ITS OWN inherited environment and
# writes ONLY variable names + an 8-char value-hash prefix (never raw values,
# never a recoverable hash) to <state-dir>/env_snapshot.json. The child
# inherits this shell's exported env, so no value crosses an argv boundary or a
# temp file. Interactive-only and backgrounded so it never blocks the prompt.
# Sourced once per session (guarded above), so this runs once per shell start.
if [[ $- == *i* ]]; then
  builtin command "$_TIRITH_BIN" env snapshot >/dev/null 2>&1 &
  disown 2>/dev/null || true
fi

# Output helper: write to stderr by default.
# Override via TIRITH_OUTPUT=tty to write to /dev/tty instead.
_tirith_output() {
  if [[ "${TIRITH_OUTPUT:-}" == "tty" ]]; then
    printf '%s\n' "$@" >/dev/tty
  else
    printf '%s\n' "$@" >&2
  fi
}

_tirith_escape_preview() {
  printf '%q' "$1"
}

_tirith_receipt_discard() {
  local channel="$1" token="$2"
  [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 && -n "$token" ]] || return 0
  _tirith_receipt_parent_context_is_valid || return 1
  local input_fd rc
  _tirith_open_exact_input_pipe "$token" || return 1
  input_fd="$_TIRITH_OPENED_FD"
  unset _TIRITH_OPENED_FD
  _TIRITH_RECEIPT_INSTANCE="$_TIRITH_RECEIPT_INSTANCE" \
    _TIRITH_RECEIPT_SHELL_PID="$_TIRITH_RECEIPT_SHELL_PID" \
    _TIRITH_RECEIPT_FAMILY="$_TIRITH_RECEIPT_FAMILY" \
    _TIRITH_BASH_INTERNAL=1 builtin command "$_TIRITH_BIN" __execution-receipt discard \
    --channel "$channel" <&"$input_fd" >/dev/null 2>&1
  rc=$?
  _tirith_close_pending_fd "$input_fd" 2>/dev/null || rc=1
  return "$rc"
}

_tirith_receipt_consume() {
  local channel="$1" token="$2" command_text="$3"
  [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 && -n "$token" && -n "$command_text" ]] || return 1
  _tirith_receipt_parent_context_is_valid || return 1
  local input_fd rc
  _tirith_open_exact_input_pipe "$token"$'\n'"$command_text" || return 1
  input_fd="$_TIRITH_OPENED_FD"
  unset _TIRITH_OPENED_FD
  _TIRITH_RECEIPT_INSTANCE="$_TIRITH_RECEIPT_INSTANCE" \
    _TIRITH_RECEIPT_SHELL_PID="$_TIRITH_RECEIPT_SHELL_PID" \
    _TIRITH_RECEIPT_FAMILY="$_TIRITH_RECEIPT_FAMILY" \
    _TIRITH_BASH_INTERNAL=1 builtin command "$_TIRITH_BIN" __execution-receipt consume \
    --channel "$channel" <&"$input_fd" >/dev/null
  rc=$?
  _tirith_close_pending_fd "$input_fd" 2>/dev/null || rc=1
  return "$rc"
}

_tirith_receipt_reconcile() {
  local channel="$1" token="$2"
  [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 && -n "$token" ]] || return 1
  _tirith_receipt_parent_context_is_valid || return 1
  local input_fd rc
  _tirith_open_exact_input_pipe "$token" || return 1
  input_fd="$_TIRITH_OPENED_FD"
  unset _TIRITH_OPENED_FD
  _TIRITH_RECEIPT_INSTANCE="$_TIRITH_RECEIPT_INSTANCE" \
    _TIRITH_RECEIPT_SHELL_PID="$_TIRITH_RECEIPT_SHELL_PID" \
    _TIRITH_RECEIPT_FAMILY="$_TIRITH_RECEIPT_FAMILY" \
    _TIRITH_BASH_INTERNAL=1 builtin command "$_TIRITH_BIN" __execution-receipt reconcile \
    --channel "$channel" <&"$input_fd" >/dev/null 2>&1
  rc=$?
  _tirith_close_pending_fd "$input_fd" 2>/dev/null || rc=1
  return "$rc"
}


# Parse approval temp file. On success, sets _tirith_ap_* variables.
# On failure (missing/unreadable/corrupt), returns 1 with fail-closed defaults.
_tirith_parse_approval() {
  local file="$1"
  _tirith_ap_required="no"
  _tirith_ap_timeout=0
  _tirith_ap_fallback="block"
  _tirith_ap_rule=""
  _tirith_ap_desc=""

  if [[ ! -r "$file" ]]; then
    _tirith_output "tirith: warning: approval file missing or unreadable, failing closed"
    _tirith_remove_capture_file "$file" >/dev/null 2>&1  # delete on all paths
    _tirith_ap_required="yes"
    _tirith_ap_fallback="block"
    _tirith_ap_timeout=0
    return 1
  fi

  local valid_keys=0
  while IFS='=' read -r key value; do
    case "$key" in
      TIRITH_REQUIRES_APPROVAL) _tirith_ap_required="$value"; valid_keys=$((valid_keys + 1)) ;;
      TIRITH_APPROVAL_TIMEOUT) _tirith_ap_timeout="$value" ;;
      TIRITH_APPROVAL_FALLBACK) _tirith_ap_fallback="$value" ;;
      TIRITH_APPROVAL_RULE) _tirith_ap_rule="$value" ;;
      TIRITH_APPROVAL_DESCRIPTION) _tirith_ap_desc="$value" ;;
    esac
  done < "$file"

  # Delete temp file after reading
  _tirith_remove_capture_file "$file" >/dev/null 2>&1

  # Corrupt file (no valid keys) → fail closed (reset all fields)
  if [[ $valid_keys -eq 0 ]]; then
    _tirith_output "tirith: warning: approval file corrupt, failing closed"
    _tirith_ap_required="yes"
    _tirith_ap_fallback="block"
    _tirith_ap_timeout=0
    return 1
  fi
  return 0
}


_tirith_parse_warn_ack() {
  local file="$1"
  _tirith_wa_findings=0
  _tirith_wa_max_severity=""

  if [[ ! -r "$file" ]]; then
    _tirith_remove_capture_file "$file" >/dev/null 2>&1
    return 1
  fi

  while IFS='=' read -r key value; do
    case "$key" in
      TIRITH_WARN_ACK_FINDINGS) _tirith_wa_findings="$value" ;;
      TIRITH_WARN_ACK_MAX_SEVERITY) _tirith_wa_max_severity="$value" ;;
    esac
  done < "$file"

  _tirith_remove_capture_file "$file" >/dev/null 2>&1
  return 0
}


# Trim whitespace to match Rust policy.rs:state_dir() behavior
_TIRITH_STATE_DIR="${XDG_STATE_HOME:-}"
_TIRITH_STATE_DIR="${_TIRITH_STATE_DIR#"${_TIRITH_STATE_DIR%%[![:space:]]*}"}"
_TIRITH_STATE_DIR="${_TIRITH_STATE_DIR%"${_TIRITH_STATE_DIR##*[![:space:]]}"}"
_TIRITH_STATE_DIR="${_TIRITH_STATE_DIR:-$HOME/.local/state}/tirith"
_TIRITH_SAFE_MODE_FLAG="$_TIRITH_STATE_DIR/bash-safe-mode"

_tirith_check_safe_mode() { [[ -f "$_TIRITH_SAFE_MODE_FLAG" ]]; }

_tirith_persist_safe_mode() {
  if [[ -z "$_TIRITH_MKDIR_BIN" ]] \
     || ! builtin command "$_TIRITH_MKDIR_BIN" -p -- "$_TIRITH_STATE_DIR" 2>/dev/null \
     || ! builtin printf '1\n' > "$_TIRITH_SAFE_MODE_FLAG" 2>/dev/null; then
    builtin printf '%s\n' "tirith: warning: could not persist safe-mode flag" >&2
  fi
}

# --- Enter-mode capability cache (issues #111, #224) ------------------------
#
# A bare `bind -x` on Enter runs the bound function but does NOT then accept the
# line on stock bash, so the pending command was never delivered and was
# silently eaten (#111). Enter mode now binds Enter to a MACRO that runs the
# checker and then a guarded accept-line (see the install block below), which
# delivers and blocks on every stock bash tested (5.2, 5.3). The self-test is
# retained as a fail-closed gate: if the macro mechanism ever fails to deliver
# or block on some exotic build, the probe records that and the hook falls back
# to preexec rather than risk eating a command.
#
# `tirith setup` / `tirith doctor` run a PTY self-test that PROVES whether
# enter-mode delivery works, and write the verdict to a cache file. This hook
# is sourced on every interactive shell, so it must not run that probe — it
# only READS the cache (one small-file read, fast enough for startup). When the
# cache proves enter mode works for the running bash, the default mode is
# enter; otherwise the hook falls back to the safe default, preexec.
#
# Cache freshness is gated on (a) the schema number and (b) the bash identity
# (version + path). The SCHEMA is the cross-tirith-version invalidator: any
# change to the probe semantics or the cache format that could make an old
# verdict wrong must bump `cli::bash_capability::CACHE_SCHEMA`, which a stale
# cache then fails. Enter-mode delivery itself is a bash-build property — it
# does not change with the tirith version — so the cache is keyed on bash, not
# on tirith. (`tirith_version` is still recorded in the file for diagnostics.)
_TIRITH_ENTER_CAP_SCHEMA=2
_TIRITH_ENTER_CAP_FILE="$_TIRITH_STATE_DIR/bash-enter-capability"

# Read the enter-mode capability cache and decide whether enter mode is proven
# to work for THIS bash. Returns 0 only when the cache exists, parses, its
# schema matches, its recorded bash version AND bash path match the running
# shell, and the verdict is `works`. Any other state (missing, malformed,
# stale, broken) returns non-zero so the caller falls back to the safe
# default. Fails closed.
_tirith_enter_capability_proven() {
  [[ -r "$_TIRITH_ENTER_CAP_FILE" ]] || return 1

  # Guard against a junk/oversized file masquerading as the cache. `wc -c`
  # pads its count with leading whitespace on BSD/macOS, so strip everything
  # but digits before the numeric check.
  local size
  [[ -n "$_TIRITH_WC_BIN" ]] || return 1
  size="$(builtin command "$_TIRITH_WC_BIN" -c < "$_TIRITH_ENTER_CAP_FILE" 2>/dev/null)" \
    || return 1
  size="${size//[^0-9]/}"
  [[ -n "$size" ]] || return 1
  (( size > 4096 )) && return 1

  local schema="" cache_bash_version="" cache_bash_path="" capability=""
  local cache_bash_fingerprint=""
  local key value
  while IFS='=' read -r key value; do
    case "$key" in
      schema)           schema="$value" ;;
      bash_version)     cache_bash_version="$value" ;;
      bash_path)        cache_bash_path="$value" ;;
      bash_fingerprint) cache_bash_fingerprint="$value" ;;
      enter_capability) capability="$value" ;;
    esac
  done < "$_TIRITH_ENTER_CAP_FILE"

  # Schema must match exactly — a format or probe-semantics change bumps it,
  # invalidating caches written by a different tirith.
  [[ "$schema" == "$_TIRITH_ENTER_CAP_SCHEMA" ]] || return 1

  # The verdict must be an explicit `works`. `broken`, `inconclusive`, an empty
  # value, or anything unrecognised all mean "do not use enter mode".
  [[ "$capability" == "works" ]] || return 1

  # The cache is bash-version specific: readline's bind-x behaviour can change
  # across builds, so a verdict for a different bash must not be trusted.
  [[ -n "$cache_bash_version" ]] || return 1
  [[ "$cache_bash_version" == "$BASH_VERSION" ]] || return 1

  # The verdict is also bound to the bash *binary* the self-test measured — the
  # capability is a property of the build, not just the version string. The
  # cache records `command -v bash`; require the running shell ($BASH) to be
  # that same binary. A mismatch (a different bash now on PATH) is treated as
  # stale and falls back to preexec — fail-safe.
  [[ -n "$cache_bash_path" ]] || return 1
  [[ "$cache_bash_path" == "${BASH:-}" ]] || return 1

  # repo-0211: an in-place rebuild keeps path and version — also require the
  # recorded mtime:size fingerprint to match the live binary.
  [[ -n "$cache_bash_fingerprint" ]] || return 1
  local live_mtime live_size live_fp
  if live_mtime="$(builtin command stat -Lf %m "${BASH:-/dev/null}" 2>/dev/null)"; then
    :
  else
    live_mtime="$(builtin command stat -Lc %Y "${BASH:-/dev/null}" 2>/dev/null)" || return 1
  fi
  if live_size="$(builtin command stat -Lf %z "${BASH:-/dev/null}" 2>/dev/null)"; then
    :
  else
    live_size="$(builtin command stat -Lc %s "${BASH:-/dev/null}" 2>/dev/null)" || return 1
  fi
  [[ -n "$live_mtime" && -n "$live_size" ]] || return 1
  live_fp="${live_mtime}:${live_size}"
  [[ "$cache_bash_fingerprint" == "$live_fp" ]] || return 1

  return 0
}
# --- end enter-mode capability cache ----------------------------------------


# Read the most recent history entry as "<index>|<cmd>" on stdout. Returns 1
# with empty stdout when history is unavailable, disabled, or malformed.
# HISTTIMEFORMAT is neutralised with a function-local empty value so bash
# restores the user's outer setting on return.
_tirith_read_history_entry() {
  local HISTTIMEFORMAT=''
  local raw
  raw="$(builtin history 1 2>/dev/null)" || return 1
  [[ -z "$raw" ]] && return 1
  if [[ "$raw" =~ ^[[:space:]]*([0-9]+)[[:space:]]+(.*)$ ]]; then
    printf '%s|%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
    return 0
  fi
  return 1
}

# Collapse runs of whitespace and trim spacing around shell operators.
# Used to bridge cosmetic spacing differences (`>/dev/null` vs `> /dev/null`)
# between BASH_COMMAND and the history line in enforcement mode.
_tirith_normalize_spacing() {
  local input="$1" s="" pending_space=0 i char next op restore_patsub=0
  local default_stdout_fd=' 1>' default_stdin_fd=' 0<'
  for ((i=0; i<${#input}; i++)); do
    char="${input:i:1}"
    next="${input:i+1:1}"
    if [[ "$char" == "\\" && "$next" == $'\n' ]]; then
      [[ -n "$s" ]] && pending_space=1
      i=$((i + 1))
      continue
    fi
    case "$char" in
      [[:space:]])
        [[ -n "$s" ]] && pending_space=1
        ;;
      *)
        [[ $pending_space -eq 1 ]] && s+=" "
        s+="$char"
        pending_space=0
        ;;
    esac
  done
  # Bash 5.2 added `patsub_replacement`, under which an unescaped `&` in the
  # replacement expands to the matched text. The `&` operator pass below would
  # then make no progress (`" &"` -> `" &"`) and loop forever after a command
  # containing `&&`. Disable it only for these literal replacements and restore
  # the caller's option exactly; older Bash versions simply report it absent.
  if shopt -q patsub_replacement 2>/dev/null; then
    shopt -u patsub_replacement
    restore_patsub=1
  fi
  for op in '|' '&' ';' '>' '<'; do
    while [[ "$s" == *" $op"* ]]; do s="${s//" $op"/$op}"; done
    while [[ "$s" == *"$op "* ]]; do s="${s//"$op "/$op}"; done
  done
  # Bash makes the default file descriptor explicit in BASH_COMMAND. Limit
  # this normalization to token boundaries so an argument ending in a digit is
  # not rewritten (`version1>file` is a word plus a redirect, not fd syntax).
  while [[ "$s" == *"$default_stdout_fd"* ]]; do s="${s//$default_stdout_fd/>}"; done
  while [[ "$s" == *"$default_stdin_fd"* ]]; do s="${s//$default_stdin_fd/<}"; done
  [[ "$s" == 1\>* ]] && s="${s#1}"
  [[ "$s" == 0\<* ]] && s="${s#0}"
  [[ $restore_patsub -eq 1 ]] && shopt -s patsub_replacement
  printf '%s' "$s"
}

# Return 0 when $1 (BASH_COMMAND) is an actual top-level command segment in $2
# (history_line). Quotes and comments are data, never evidence that a command
# name appeared in executable syntax. This deliberately rejects ambiguous
# compound syntax instead of authenticating an alias expansion from a token in
# a comment, string, heredoc body, or unused argument.
_tirith_cmd_is_in_line() {
  local needle="$1" haystack="$2"
  [[ -z "$needle" || -z "$haystack" ]] && return 1
  local n_needle n_haystack n_segment segment="" quote="" escaped=0 at_word_start=1
  local i char next previous
  n_needle="$(_tirith_normalize_spacing "$needle")"
  [[ -n "$n_needle" ]] || return 1
  n_haystack="$(_tirith_normalize_spacing "$haystack")"
  [[ "$n_haystack" == "$n_needle" ]] && return 0
  # Heredoc bodies are data, but locating their delimiter safely requires the
  # full Bash grammar. Refuse segment authentication for any such line; exact
  # whole-line equality above still permits an ordinary standalone heredoc.
  [[ "$haystack" == *'<<'* ]] && return 1

  for ((i=0; i<=${#haystack}; i++)); do
    char="${haystack:i:1}"
    next="${haystack:i+1:1}"
    previous="${haystack:i-1:1}"
    if [[ $i -eq ${#haystack} ]]; then
      char=$'\n'
    fi

    if [[ $escaped -eq 1 ]]; then
      segment+="$char"
      escaped=0
      at_word_start=0
      continue
    fi
    if [[ "$quote" == "'" ]]; then
      segment+="$char"
      [[ "$char" == "'" ]] && quote=""
      at_word_start=0
      continue
    fi
    if [[ "$quote" == '"' ]]; then
      segment+="$char"
      if [[ "$char" == "\\" ]]; then
        escaped=1
      elif [[ "$char" == '"' ]]; then
        quote=""
      fi
      at_word_start=0
      continue
    fi

    case "$char" in
      "\\") segment+="$char"; escaped=1; at_word_start=0; continue ;;
      "'"|'"') segment+="$char"; quote="$char"; at_word_start=0; continue ;;
      '#')
        if [[ $at_word_start -eq 1 ]]; then
          char=$'\n'
        else
          segment+="$char"
          at_word_start=0
          continue
        fi
        ;;
    esac

    case "$char" in
      ' '|$'\t'|$'\r') segment+="$char"; at_word_start=1; continue ;;
      '&')
        if [[ "$next" == '>' || "$previous" == '>' || "$previous" == '<' ]]; then
          segment+="$char"
          at_word_start=0
          continue
        fi
        ;;
      '>'|'<') segment+="$char"; at_word_start=1; continue ;;
      ';'|'|'|'('|')'|$'\n') ;;
      *) segment+="$char"; at_word_start=0; continue ;;
    esac

    n_segment="$(_tirith_normalize_spacing "$segment")"
    if [[ -n "$n_segment" ]]; then
      [[ "$n_segment" == "$n_needle" ]] && return 0
      # Control-flow keywords belong to the surrounding grammar rather than
      # BASH_COMMAND. Remove only a leading reserved word from the already
      # isolated executable segment, never from comments or quoted data.
      case "$n_segment" in
        if\ *|then\ *|elif\ *|while\ *|until\ *|do\ *|else\ *)
          n_segment="${n_segment#* }"
          [[ "$n_segment" == "$n_needle" ]] && return 0
          ;;
      esac
    fi
    segment=""
    at_word_start=1
    [[ "$char" == $'\n' ]] && break
  done
  return 1
}

# Install-time gate for preexec enforcement. Hostile history configurations
# cannot provide a trustworthy whole-line view, so the hook stays in
# warn-only rather than claim protection it cannot deliver.
_tirith_history_is_trustworthy_for_enforcement() {
  case ":${HISTCONTROL:-}:" in
    *:ignorespace:*|*:ignoredups:*|*:ignoreboth:*) return 1 ;;
  esac
  [[ -n "${HISTIGNORE:-}" ]] && return 1
  if ! shopt -oq history 2>/dev/null; then
    return 1
  fi
  return 0
}

# `extdebug` makes a non-zero DEBUG-trap result skip the command about to run,
# but it also inherits DEBUG into every function, command substitution, and
# subshell on modern Bash. Leaving it enabled therefore turns prompt functions
# and function bodies into fake user commands. Keep it OFF while an allowed
# line runs and enable it lazily only when Tirith has already decided to block
# the complete typed line. The prompt-begin sentinel below turns it off again.
#
# Return values from `_tirith_prepare_extdebug_block`:
#   0 — Tirith owns extdebug (newly enabled or already active for this block)
#   1 — extdebug could not be enabled
#   2 — extdebug is active but user-owned; the current skip can work, but the
#       session must visibly leave enforcement because Tirith cannot restore it
_tirith_prepare_extdebug_block() {
  if shopt -q extdebug; then
    [[ "${_TIRITH_OWNS_EXTDEBUG:-0}" == "1" ]] && return 0
    return 2
  fi
  shopt -s extdebug || return 1
  _TIRITH_OWNS_EXTDEBUG=1
  return 0
}

_tirith_disable_owned_extdebug() {
  [[ "${_TIRITH_OWNS_EXTDEBUG:-0}" == "1" ]] || return 0
  shopt -u extdebug || return 1
  _TIRITH_OWNS_EXTDEBUG=0
  return 0
}

# Run the captured user DEBUG handler in its own frame. A DEBUG trap body is
# ordinarily evaluated at the top level, where `return` is a no-op, so real
# handlers use it freely as an early exit — `bash-preexec.sh` (oh-my-bash,
# Atuin, iTerm2 shell integration) opens with exactly that shape. Evaluating
# such a body inline would make its `return` leave the TRAMPOLINE before
# Tirith ever scans, silently disabling interception for the whole session.
# Giving it a frame of its own means the early exit ends the chained handler
# and nothing else.
_tirith_run_chained_debug_trap() {
  builtin eval -- "$_TIRITH_PREV_DEBUG_TRAP"
}

# Idempotent DEBUG-trap installer. Chains through any pre-existing user DEBUG
# trap via a trampoline so warn-only + enforcement do not clobber the user's
# own instrumentation. Second and later calls are no-ops.
#
# We capture the caller's line number (BASH_LINENO[0] here, since the
# trampoline IS the topmost function called from the trap) and pass it
# explicitly to _tirith_preexec — otherwise preexec would see only its own
# call frame's line, not the user-typed line.
_tirith_debug_trampoline() {
  # Pin the command before chaining a user DEBUG trap: that trap may run
  # arbitrary shell code and change the live BASH_COMMAND value before Tirith
  # gets control back.
  local _user_bash_command="$BASH_COMMAND"
  local _user_line_id="${BASH_LINENO[0]:-0}"
  # Structural execution depth, not a function-name allowlist. At a top-level
  # DEBUG fire this trampoline is the sole FUNCNAME frame; extdebug-inherited
  # fires have at least one caller frame. `_tirith_preexec` only skips a nested
  # fire after the containing typed line has crossed the top-level decision.
  local _user_call_depth="${#FUNCNAME[@]}"
  if [[ -n "${_TIRITH_PREV_DEBUG_TRAP:-}" ]]; then
    # Status is discarded on purpose: under a Tirith-owned extdebug block a
    # non-zero DEBUG result skips the command, and that decision belongs to
    # Tirith alone, not to a chained handler.
    _tirith_run_chained_debug_trap || true
  fi
  _tirith_preexec "$_user_line_id" "$_user_call_depth" "$_user_bash_command"
}

_tirith_extract_trap_body() {
  local specification="${1:-}" signal="${2:-}"
  local prefix="trap -- '" suffix="' $signal" encoded quote_escape quartet char i=0
  _TIRITH_EXTRACTED_TRAP=""
  [[ "$signal" == "DEBUG" && "$specification" == "$prefix"*"$suffix" ]] || return 1
  encoded="${specification#"$prefix"}"
  encoded="${encoded%"$suffix"}"

  # `trap -p` emits a reusable shell single-quoted word. An embedded apostrophe
  # is serialized as the four-character boundary `\'\''`; stripping only the
  # outer quotes leaves those boundaries behind and later `eval` either changes
  # the handler or raises a syntax error. Validate every quote boundary, then
  # evaluate the canonical word only as the right-hand side of an assignment;
  # the handler itself is data here and is not executed.
  quote_escape="'\\''"
  while (( i < ${#encoded} )); do
    char="${encoded:i:1}"
    if [[ "$char" == "'" ]]; then
      quartet="${encoded:i:4}"
      [[ "$quartet" == "$quote_escape" ]] || return 1
      i=$((i + 4))
    else
      i=$((i + 1))
    fi
  done
  builtin eval -- "_TIRITH_EXTRACTED_TRAP='$encoded'"
}

_tirith_read_debug_trap_capture() {
  local file="$1" captured="" line="" first=1 marker="trap -- '" candidate
  _TIRITH_CAPTURED_DEBUG_TRAP_SPEC=""
  _tirith_capture_file_is_private "$file" || return 1
  while IFS= read -r line || [[ -n "$line" ]]; do
    if [[ $first -eq 1 ]]; then
      captured="$line"
      first=0
    else
      captured+=$'\n'"$line"
    fi
  done < "$file"
  [[ -z "$captured" ]] && return 0

  # The previous DEBUG handler itself runs immediately before `trap -p` and
  # may write to the command's redirected stdout. Bash's own specification is
  # the final `trap -- '...' DEBUG` record, so discard any preceding handler
  # output and validate the record before retaining it.
  [[ "$captured" == *"$marker"* ]] || return 1
  candidate="${marker}${captured##*"$marker"}"
  [[ "$candidate" == "$marker"*"' DEBUG" ]] || return 1
  _tirith_extract_trap_body "$candidate" DEBUG || return 1
  _TIRITH_CAPTURED_DEBUG_TRAP_SPEC="$candidate"
  return 0
}

_tirith_install_debug_trap() {
  [[ "${_TIRITH_DEBUG_TRAP_CAPTURE_READY:-0}" == "1" ]] || return 1
  local current="${_TIRITH_CAPTURED_DEBUG_TRAP_SPEC:-}"
  if [[ "$current" == "trap -- '_tirith_debug_trampoline' DEBUG" ]]; then
    _TIRITH_DEBUG_TRAP_INSTALLED=1
    return 0
  fi
  # A wrapper, comment, or string that merely mentions the private function is
  # not proof of ownership. Chaining it could recurse into Tirith or let an
  # unrelated handler impersonate an already-installed hook.
  [[ "$current" == *"_tirith_debug_trampoline"* ]] && return 1

  _TIRITH_PREV_DEBUG_TRAP=""
  if [[ -n "$current" ]]; then
    _tirith_extract_trap_body "$current" DEBUG || return 1
    _TIRITH_PREV_DEBUG_TRAP="$_TIRITH_EXTRACTED_TRAP"
  fi
  builtin trap '_tirith_debug_trampoline' DEBUG || return 1
  _TIRITH_DEBUG_TRAP_INSTALLED=1
  return 0
}

_tirith_verify_debug_trap_ownership() {
  _TIRITH_DEBUG_TRAP_OWNERSHIP_OK=0
  local file="${_TIRITH_DEBUG_OWNERSHIP_FILE:-}"
  if [[ -n "$file" ]] \
     && _tirith_read_debug_trap_capture "$file" \
     && [[ "${_TIRITH_CAPTURED_DEBUG_TRAP_SPEC:-}" == "trap -- '_tirith_debug_trampoline' DEBUG" ]]; then
    _TIRITH_DEBUG_TRAP_OWNERSHIP_OK=1
    return 0
  fi
  _tirith_session_lost_debug_trap
  return 1
}

_tirith_prepare_debug_trap_capture() {
  [[ "${_TIRITH_DEBUG_TRAP_CAPTURE_READY:-0}" == "0" ]] || return 0
  [[ -n "${_TIRITH_DEBUG_CAPTURE_FILE:-}" ]] && return 0
  _TIRITH_DEBUG_CAPTURE_FILE="$(_tirith_new_capture_file 2>/dev/null)" || _TIRITH_DEBUG_CAPTURE_FILE=""
  [[ -n "$_TIRITH_DEBUG_CAPTURE_FILE" ]]
}

_tirith_finalize_debug_trap_capture() {
  [[ "${_TIRITH_DEBUG_TRAP_CAPTURE_READY:-0}" == "0" ]] || return 0
  local capture_ok=0
  if [[ -n "${_TIRITH_DEBUG_CAPTURE_FILE:-}" ]] \
     && _tirith_read_debug_trap_capture "$_TIRITH_DEBUG_CAPTURE_FILE"; then
    capture_ok=1
  fi
  if [[ -n "${_TIRITH_DEBUG_CAPTURE_FILE:-}" ]]; then
    _tirith_remove_capture_file "$_TIRITH_DEBUG_CAPTURE_FILE" >/dev/null 2>&1 || capture_ok=0
  fi
  _TIRITH_DEBUG_CAPTURE_FILE=""

  if [[ $capture_ok -ne 1 ]]; then
    _TIRITH_DEBUG_TRAP_CAPTURE_READY=2
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_ENFORCE=0
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: bash preexec hook was not installed because the existing DEBUG trap could not be preserved safely; existing debugger state was left unchanged"
    return 1
  fi

  _TIRITH_DEBUG_TRAP_CAPTURE_READY=1
  _TIRITH_DEBUG_OWNERSHIP_FILE="$(_tirith_new_capture_file 2>/dev/null)" \
    || _TIRITH_DEBUG_OWNERSHIP_FILE=""
  if [[ -z "$_TIRITH_DEBUG_OWNERSHIP_FILE" ]]; then
    _TIRITH_DEBUG_TRAP_CAPTURE_READY=2
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_ENFORCE=0
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: bash preexec hook was not installed because DEBUG-trap ownership could not be checked safely"
    return 1
  fi
  if ! _tirith_install_debug_trap; then
    _tirith_remove_capture_file "$_TIRITH_DEBUG_OWNERSHIP_FILE" >/dev/null 2>&1 || true
    _TIRITH_DEBUG_OWNERSHIP_FILE=""
    _TIRITH_DEBUG_TRAP_CAPTURE_READY=2
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_ENFORCE=0
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: bash preexec hook was not installed because the existing DEBUG trap could not be chained safely; existing debugger state was left unchanged"
    return 1
  fi

  if [[ "${_TIRITH_PREEXEC_ENFORCE_PENDING:-0}" == "1" ]]; then
    _TIRITH_PREEXEC_ENFORCE_PENDING=0
    _TIRITH_PREEXEC_ENFORCE=1
    export TIRITH_BASH_EFFECTIVE_PROTECTION="blocks"
    _tirith_set_status "blocks"
  else
    export TIRITH_BASH_EFFECTIVE_PROTECTION="warn-only"
    [[ "${TIRITH_STATUS:-}" == "degraded" ]] || _tirith_set_status "warn-only"
  fi
  return 0
}

_tirith_discard_pending_debug_trap_capture() {
  [[ "${_TIRITH_DEBUG_TRAP_CAPTURE_READY:-0}" == "0" ]] || return 0
  local capture_file="${_TIRITH_DEBUG_CAPTURE_FILE:-}"
  _TIRITH_DEBUG_CAPTURE_FILE=""
  [[ -n "$capture_file" ]] || return 0
  # A non-prompt interactive invocation (`bash -i -c`) can exit before the
  # bootstrap consumes this file. Remove only a still-private regular file;
  # never follow a replacement symlink or touch an activated trap's state.
  _tirith_capture_file_is_private "$capture_file" || return 0
  _tirith_remove_capture_file "$capture_file" >/dev/null 2>&1 || true
}

# --- Preexec prompt-boundary state machine ---------------------------------
# Bash exposes no native "currently running PROMPT_COMMAND" flag. Bracket the
# user's existing prompt commands with exact Tirith sentinels instead. Their
# position preserves user ordering, and returning the captured `$?` preserves
# the status the first/last user prompt command would otherwise observe.
_tirith_preexec_prompt_begin() {
  local previous_status=$?
  _TIRITH_PREEXEC_PROMPT_STATUS="$previous_status"
  [[ "${_TIRITH_PREEXEC_PHASE:-}" == "off" ]] && return "$previous_status"
  _TIRITH_PREEXEC_PHASE="prompt"
  _TIRITH_PREEXEC_AWAITING_USER=0
  _TIRITH_DEBUG_TRAP_OWNERSHIP_OK=0
  _TIRITH_PREEXEC_PROMPT_MUTATED=0
  return "$previous_status"
}

_tirith_restore_prompt_status() {
  return "${_TIRITH_PREEXEC_PROMPT_STATUS:-0}"
}

# Run a scalar PROMPT_COMMAND as data inside its own frame. Never splice user
# text between Tirith's sentinels: an incomplete operator such as `false &&`
# would otherwise consume the end guard, and `return` could leave Tirith's
# wrapper before it publishes the next input boundary.
_tirith_eval_user_prompt_command() {
  builtin eval -- "$_TIRITH_PREEXEC_USER_PROMPT_COMMAND"
}

_tirith_run_user_prompt_command() {
  local previous_status=$?
  local expected_user_prompt="${_TIRITH_PREEXEC_USER_PROMPT_COMMAND:-}"
  [[ -n "${_TIRITH_PREEXEC_USER_PROMPT_COMMAND:-}" ]] \
    || return "$previous_status"
  _tirith_restore_prompt_status
  _tirith_eval_user_prompt_command
  local prompt_rc=$?
  if [[ "${PROMPT_COMMAND:-}" != "${_TIRITH_PREEXEC_SCALAR_WRAPPER:-}" ]] \
     || [[ "${_TIRITH_PREEXEC_USER_PROMPT_COMMAND:-}" != "$expected_user_prompt" ]]; then
    _TIRITH_PREEXEC_PROMPT_MUTATED=1
    _TIRITH_PREEXEC_USER_PROMPT_COMMAND="$expected_user_prompt"
  fi
  return "$prompt_rc"
}

_tirith_preexec_prompt_end() {
  local previous_status=$?
  unset _TIRITH_PREEXEC_PROMPT_STATUS
  [[ "${_TIRITH_PREEXEC_PHASE:-}" == "off" ]] && return "$previous_status"
  if [[ "${_TIRITH_PREEXEC_ENFORCE:-0}" == "1" ]] \
     && [[ "${_TIRITH_OWNS_EXTDEBUG:-0}" != "1" ]] \
     && shopt -q extdebug; then
    _tirith_session_degrade_to_warn_only \
      "tirith: extdebug became enabled by prompt code outside Tirith; enforcement is disabled because user debugger state cannot be safely restored"
  fi
  # The top-level bootstrap serializes the live DEBUG handler every cycle.
  # Refuse the next input boundary unless that exact record named Tirith's
  # canonical trampoline; a writable scalar heartbeat is not ownership proof.
  if [[ "${_TIRITH_DEBUG_TRAP_INSTALLED:-0}" == "1" ]]; then
    if [[ "${_TIRITH_DEBUG_TRAP_OWNERSHIP_OK:-0}" != "1" ]]; then
      _tirith_session_lost_debug_trap
      return "$previous_status"
    fi
  fi
  if [[ "${_TIRITH_PREEXEC_PROMPT_GUARDS:-0}" == "1" ]] \
     && { [[ "${_TIRITH_PREEXEC_PROMPT_MUTATED:-0}" == "1" ]] \
          || ! _tirith_preexec_prompt_guards_attached; }; then
    _TIRITH_PREEXEC_PROMPT_GUARDS=0
    _TIRITH_PREEXEC_PHASE="unbracketed"
    _tirith_session_degrade_to_warn_only \
      "tirith: PROMPT_COMMAND changed while the prompt was running; enforcement is disabled before the next input boundary"
    return "$previous_status"
  fi
  _TIRITH_PREEXEC_PHASE="user"
  _TIRITH_PREEXEC_AWAITING_USER=1
  return "$previous_status"
}

_tirith_prompt_command_array_supported() {
  # Bash accepted ordinary indexed arrays long before it learned to execute
  # every PROMPT_COMMAND array element. That prompt behavior was added in 5.1;
  # wrapping an array on older Bash would run the begin guard but never the end
  # guard and silently strand the hook in prompt phase.
  (( BASH_VERSINFO[0] > 5 \
     || (BASH_VERSINFO[0] == 5 && BASH_VERSINFO[1] >= 1) ))
}

_tirith_prompt_command_attrs_safe() {
  local attrs="$1"
  # Export/trace/indexed-array attributes do not change assignment semantics.
  # Readonly, associative, integer, case-transforming, and nameref variables
  # either cannot be wrapped or would mutate/coerce state Tirith does not own.
  [[ "$attrs" != *[rAilnu]* ]]
}

_tirith_preexec_prompt_guards_attached() {
  local pc_decl pc_attrs
  pc_decl="$(declare -p PROMPT_COMMAND 2>/dev/null)" || return 1
  pc_attrs="${pc_decl#declare }"
  pc_attrs="${pc_attrs%% *}"
  _tirith_prompt_command_attrs_safe "$pc_attrs" || return 1
  if [[ "$pc_attrs" == *a* ]]; then
    _tirith_prompt_command_array_supported || return 1
    local count="${#PROMPT_COMMAND[@]}"
    [[ "$count" -ge 3 ]] || return 1
    [[ "${PROMPT_COMMAND[0]}" == "_tirith_preexec_prompt_begin" ]] || return 1
    [[ "${PROMPT_COMMAND[1]}" == "$_TIRITH_PREEXEC_BOOTSTRAP_COMMAND" ]] || return 1
    [[ "${PROMPT_COMMAND[$((count - 1))]}" == "_tirith_preexec_prompt_end" ]]
    return
  fi
  [[ "${PROMPT_COMMAND:-}" == "${_TIRITH_PREEXEC_SCALAR_WRAPPER:-}" ]]
}

_tirith_install_preexec_prompt_guards() {
  if _tirith_preexec_prompt_guards_attached; then
    _TIRITH_PREEXEC_PROMPT_GUARDS=1
    return 0
  fi

  local pc_decl pc_attrs
  pc_decl="$(declare -p PROMPT_COMMAND 2>/dev/null)" || pc_decl=""
  pc_attrs="${pc_decl#declare }"
  pc_attrs="${pc_attrs%% *}"
  # Never provoke or mask Bash's own readonly-assignment failure. Refuse before
  # mutation and leave the user's scalar/array value and attributes untouched.
  _tirith_prompt_command_attrs_safe "$pc_attrs" || return 1
  if [[ "$pc_attrs" == *a* ]]; then
    _tirith_prompt_command_array_supported || return 1
    PROMPT_COMMAND=(
      _tirith_preexec_prompt_begin
      "$_TIRITH_PREEXEC_BOOTSTRAP_COMMAND"
      "${PROMPT_COMMAND[@]}"
      _tirith_preexec_prompt_end
    ) 2>/dev/null || return 1
  else
    local existing="${PROMPT_COMMAND:-}"
    if [[ -n "$existing" ]]; then
      _tirith_check_command_syntax "$existing"
      if [[ "${_TIRITH_SYNTAX_RC:-1}" -ne 0 ]] \
         || [[ "${_TIRITH_SYNTAX_ERROR:-}" == *"here-document at line"*"delimited by end-of-file"* ]] \
         || [[ "$existing" == *\\ ]] \
         || [[ "$existing" == *'<<'* ]]; then
        unset _TIRITH_SYNTAX_ERROR _TIRITH_SYNTAX_RC
        return 1
      fi
      unset _TIRITH_SYNTAX_ERROR _TIRITH_SYNTAX_RC
    fi
    _TIRITH_PREEXEC_USER_PROMPT_COMMAND="$existing"
    _TIRITH_PREEXEC_SCALAR_WRAPPER="_tirith_preexec_prompt_begin"$'\n'"$_TIRITH_PREEXEC_BOOTSTRAP_COMMAND"$'\n'"_tirith_run_user_prompt_command"$'\n'"_tirith_preexec_prompt_end"
    PROMPT_COMMAND="$_TIRITH_PREEXEC_SCALAR_WRAPPER" 2>/dev/null || return 1
  fi
  _tirith_preexec_prompt_guards_attached || return 1
  _TIRITH_PREEXEC_PROMPT_GUARDS=1
  return 0
}

# --- Protection-status indicator + one-shot degrade banner -----------------
#
# `TIRITH_STATUS` is a small public contract a user can reference in their PS1
# to surface tirith's live protection level in their prompt. tirith itself
# prints NOTHING per-prompt — it only sets the variable; wiring it into a
# prompt is opt-in (see docs/prompt-status.md). Values:
#   blocks     enter mode (or enforced preexec) — a blocked command is stopped
#   warn-only  preexec warn-only — commands are observed but not blocked
#   degraded   protection was DOWNGRADED mid-session from a stronger level
#   off        the hook installed nothing
#
# `degraded` is deliberately distinct from `warn-only`: a shell that simply
# *starts* in preexec warn-only is `warn-only`, but a shell that *loses* a
# stronger guarantee at runtime is `degraded` — a state the user should notice.
#
# It is a plain shell variable, deliberately NOT exported: the prompt runs in
# THIS interactive shell, which reads a non-exported variable fine (PS1 /
# PROMPT_COMMAND), and a non-interactive child process has no tirith
# protection — so it must not inherit a status that would misrepresent it.
# (`TIRITH_BASH_EFFECTIVE_*` below are exported on purpose: `tirith doctor` is
# a child process and can only see exported vars.) An assignment inside a
# function with no matching `local` writes the global, so this is the shell's
# session-global `TIRITH_STATUS`.
_tirith_set_status() {
  TIRITH_STATUS="$1"
}

# Emit the one-time degraded-protection warning. Fires at most once per shell
# session (guarded by `_TIRITH_DEGRADE_WARNED`), is interactive-only, and is
# deliberately terse — a single consolidated message, never naggy. The optional
# `$1` is an extra detail line appended under the headline.
_tirith_warn_degraded_once() {
  [[ -n "${_TIRITH_DEGRADE_WARNED:-}" ]] && return 0
  _TIRITH_DEGRADE_WARNED=1
  [[ $- == *i* ]] || return 0
  _tirith_output "tirith: protection downgraded to warn-only (does not block) — run 'tirith doctor' for details"
  [[ -n "${1:-}" ]] && _tirith_output "  $1"
  return 0
}

# Cache-then-degrade: flip the session to warn-only mode and re-export the
# effective protection string so a subsequent `tirith doctor` sees the truth.
# Callers that already know a history index should pin the cache BEFORE
# invoking this helper so the current line's remaining DEBUG fires stay
# blocked. Any Tirith-owned extdebug state is released at the next prompt.
_tirith_session_degrade_to_warn_only() {
  local reason="$1"
  _TIRITH_PREEXEC_ENFORCE=0
  _TIRITH_WARN_ONLY_USE_BASH_COMMAND=1
  # Once the whole-line/history contract is lost, simple-command fragments are
  # still useful warnings but are not honest typed-line execution evidence.
  _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
  _TIRITH_PREEXEC_WARNED=1   # suppress the generic warn-only banner
  export TIRITH_BASH_EFFECTIVE_PROTECTION="warn-only"
  _tirith_set_status "degraded"
  # One consolidated headline, then the path-specific reason as the detail line.
  _tirith_warn_degraded_once "$reason"
}

# A replaced or removed DEBUG trap is not a downgrade to warn-only — it is the
# total loss of interception, because nothing calls into Tirith any more. Say
# so, and deliberately do NOT reinstall: whichever tool took the trap owns it
# now, and clobbering it back would start the same fight from the other side.
_tirith_session_lost_debug_trap() {
  _TIRITH_PREEXEC_PHASE="off"
  _TIRITH_PREEXEC_ENFORCE=0
  _TIRITH_PREEXEC_ENFORCE_PENDING=0
  _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
  _TIRITH_DEBUG_TRAP_WATCH=0
  _TIRITH_PREEXEC_WARNED=1
  export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
  _tirith_set_status "degraded"
  # Its own latch, deliberately not `_TIRITH_DEGRADE_WARNED`. That one belongs
  # to the warn-only downgrade, and a session that already paid that banner must
  # still hear about this one: warn-only to off is the transition that matters
  # most, and sharing the latch made it the one transition that stayed silent.
  [[ -n "${_TIRITH_OFF_WARNED:-}" ]] && return 0
  _TIRITH_OFF_WARNED=1
  [[ $- == *i* ]] || return 0
  _tirith_output "tirith: protection is OFF for this shell — run 'tirith doctor' for details"
  _tirith_output "  another tool replaced or removed Tirith's DEBUG trap; commands are no longer being checked. Tirith did not take the trap back. Restart your shell, or load tirith after that tool."
  return 0
}

_tirith_preexec_receipt_check() {
  local scan_target="$1" warn_only="$2"
  _tirith_receipt_parent_context_is_valid || return 1
  local -a render_args
  render_args=()
  [[ "$warn_only" == "yes" ]] && render_args=(--warn-only)
  local stdout_file rc
  stdout_file="$(_tirith_new_capture_file 2>/dev/null)" || return 1
  [[ -n "$stdout_file" ]] || return 1
  _TIRITH_HOOK=1 _TIRITH_BASH_INTERNAL=1 \
    _TIRITH_RECEIPT_INSTANCE="$_TIRITH_RECEIPT_INSTANCE" \
    _TIRITH_RECEIPT_SHELL_PID="$_TIRITH_RECEIPT_SHELL_PID" \
    _TIRITH_RECEIPT_FAMILY="$_TIRITH_RECEIPT_FAMILY" \
    builtin command "$_TIRITH_BIN" check --approval-check --execution-receipt bash-preexec \
    --non-interactive --interactive --shell posix "${render_args[@]}" -- "$scan_target" \
    >|"$stdout_file"
  rc=$?

  local parse_rc token
  _tirith_parse_v3_receipt_response "$stdout_file" "$rc"
  parse_rc=$?
  token="$_TIRITH_PARSED_RECEIPT"
  _tirith_remove_capture_file "$stdout_file" >/dev/null 2>&1 || parse_rc=2
  unset _TIRITH_CAPTURE_LINE _TIRITH_PARSED_RECEIPT
  case "$parse_rc" in
    0) ;;
    1) return 1 ;;
    *)
      _tirith_receipt_discard bash-preexec "$token"
      return 1
      ;;
  esac
  if ! _tirith_receipt_consume bash-preexec "$token" "$scan_target"; then
    _tirith_receipt_reconcile bash-preexec "$token" || return 1
  fi
  return 0
}


# Return 1 only when Bash is actually in extdebug skip mode. A non-empty reason
# means the current line also ends enforcement after being skipped. When Bash
# cannot enter skip mode, return 0 and say explicitly that the command could not
# be blocked; never print a BLOCKED verdict and silently execute it.
_tirith_preexec_block_current_line() {
  local reason="${1:-}" extdebug_state
  _tirith_prepare_extdebug_block
  extdebug_state=$?
  if [[ $extdebug_state -eq 1 ]]; then
    _TIRITH_PREEXEC_BLOCK_ACTIVE=0
    _TIRITH_PREEXEC_ACTIVE_DECISION="allow"
    _tirith_session_degrade_to_warn_only \
      "tirith: bash could not enable extdebug for the blocking decision; this command was NOT blocked and enforcement is disabled for this shell"
    return 0
  fi
  if [[ $extdebug_state -eq 2 ]]; then
    _tirith_session_degrade_to_warn_only \
      "tirith: extdebug became enabled outside Tirith; the current command was blocked, but Tirith cannot safely own or restore debugger state, so enforcement is disabled for this shell"
  elif [[ -n "$reason" ]]; then
    _tirith_session_degrade_to_warn_only "$reason"
  fi
  _TIRITH_PREEXEC_BLOCK_ACTIVE=1
  _TIRITH_PREEXEC_ACTIVE_DECISION="block"
  return 1
}


_tirith_preexec() {
  [[ "${_TIRITH_BASH_INTERNAL:-0}" == "1" ]] && return 0
  local bash_cmd="${3:-$BASH_COMMAND}"
  local entry history_index="" history_line=""
  if entry="$(_tirith_read_history_entry)"; then
    history_index="${entry%%|*}"
    history_line="${entry#*|}"
  fi

  # Exact prompt sentinels are internal only when Bash reached them through the
  # installed prompt bracket. A user who types the private function name gets a
  # normal history match and therefore a normal full-line scan; this is not a
  # function-name allowlist.
  if [[ "${_TIRITH_PREEXEC_PROMPT_GUARDS:-0}" == "1" ]] \
     && [[ "$bash_cmd" == "_tirith_preexec_prompt_begin" ]]; then
    local automatic_prompt_begin=0
    if [[ "${_TIRITH_PREEXEC_PHASE:-startup}" != "user" ]] \
       || [[ -n "${_TIRITH_PREEXEC_ACTIVE_DECISION:-}" ]]; then
      automatic_prompt_begin=1
    elif ! _tirith_cmd_is_in_line "$bash_cmd" "$history_line"; then
      automatic_prompt_begin=1
    fi
    if [[ $automatic_prompt_begin -eq 1 ]]; then
      _TIRITH_PREEXEC_PHASE="prompt"
      _TIRITH_PREEXEC_AWAITING_USER=0
      _TIRITH_PREEXEC_BLOCK_ACTIVE=0
      _TIRITH_PREEXEC_ACTIVE_DECISION=""
      unset _tirith_last_key _tirith_last_rc _tirith_last_cmd
      if ! _tirith_disable_owned_extdebug; then
        _tirith_session_degrade_to_warn_only \
          "tirith: could not restore Tirith-owned extdebug state at the prompt boundary; enforcement is disabled for this shell"
      elif [[ "${_TIRITH_PREEXEC_ENFORCE:-0}" == "1" ]] \
           && shopt -q extdebug; then
        _tirith_session_degrade_to_warn_only \
          "tirith: extdebug became enabled outside Tirith; enforcement is disabled because user debugger state cannot be safely restored"
      fi
      return 0
    fi
  fi
  if [[ "${_TIRITH_PREEXEC_PROMPT_GUARDS:-0}" == "1" ]] \
     && [[ "$bash_cmd" == "_tirith_preexec_prompt_end" ]] \
     && [[ "${_TIRITH_PREEXEC_PHASE:-}" == "prompt" ]]; then
    return 0
  fi

  # Nothing sourced after the hook and nothing run by PROMPT_COMMAND is a typed
  # user line. In particular, neither path may create an execution receipt.
  case "${_TIRITH_PREEXEC_PHASE:-startup}" in
    startup|prompt|off) return 0 ;;
  esac

  # Bash synthesizes `exit` when interactive stdin reaches EOF. Bash 3.2 can
  # instead expose the prompt-end function's final `return` as BASH_COMMAND
  # during that EOF handoff. No user line was accepted in either case, so the
  # previous history entry must not be treated as drift (or receipted). A typed
  # command with the same text remains a normal user line because history then
  # matches it and this narrow prompt-tail exception does not apply.
  if [[ "${_TIRITH_PREEXEC_AWAITING_USER:-0}" == "1" ]] \
     && { [[ "$bash_cmd" == "exit" ]] \
          || [[ "$bash_cmd" == 'return "$previous_status"' ]]; } \
     && ! _tirith_cmd_is_in_line "$bash_cmd" "$history_line"; then
    return 0
  fi

  # A lazy-block event inherits DEBUG into nested execution. Once the complete
  # top-level line has a decision, descendants reuse it without re-reading
  # history, re-scanning function bodies, or issuing duplicate receipts.
  local call_depth="${2:-1}"
  if [[ "$call_depth" -gt 1 ]]; then
    if [[ "${_TIRITH_PREEXEC_BLOCK_ACTIVE:-0}" == "1" ]] \
       && [[ "${_TIRITH_PREEXEC_ACTIVE_DECISION:-}" == "block" ]]; then
      return 1
    fi
    return 0
  fi
  if [[ "${_TIRITH_PREEXEC_BLOCK_ACTIVE:-0}" == "1" ]]; then
    return 1
  fi
  _TIRITH_PREEXEC_AWAITING_USER=0

  if [[ "${_TIRITH_PREEXEC_PHASE:-}" == "unbracketed" ]] \
     && ! _tirith_cmd_is_in_line "$bash_cmd" "$history_line"; then
    return 0
  fi

  # Guard removal destroys the only reliable prompt/user origin boundary.
  # Continue in visibly degraded fragment warn-only mode; never claim blocking
  # or typed-line receipt evidence after that boundary is lost.
  if [[ "${_TIRITH_PREEXEC_PROMPT_GUARDS:-0}" == "1" ]] \
     && ! _tirith_preexec_prompt_guards_attached; then
    _TIRITH_PREEXEC_PROMPT_GUARDS=0
    _TIRITH_PREEXEC_PHASE="unbracketed"
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    _TIRITH_WARN_ONLY_USE_BASH_COMMAND=1
    if [[ "${_TIRITH_PREEXEC_ENFORCE:-0}" == "1" ]]; then
      _tirith_session_degrade_to_warn_only \
        "tirith: PROMPT_COMMAND no longer contains Tirith's prompt-boundary guards; enforcement is disabled for this shell"
    fi
    # If a prompt framework removed the guards, this fire may itself be one of
    # its automatic commands. Do not scan it as user input; a real typed line
    # still matches history and continues below in fragment warn-only mode.
    if ! _tirith_cmd_is_in_line "$bash_cmd" "$history_line"; then
      return 0
    fi
  fi

  # Once-per-shell warn-only banner, emitted only for a typed user line (never
  # while .bashrc or PROMPT_COMMAND is running).
  if [[ -z "${_TIRITH_PREEXEC_WARNED:-}" ]] \
     && [[ $- == *i* ]] \
     && [[ "${_TIRITH_PREEXEC_ENFORCE:-0}" != "1" ]]; then
    _TIRITH_PREEXEC_WARNED=1
    _tirith_output "tirith: bash is in preexec mode (warn-only, does not block)"
    _tirith_output "  Run 'tirith doctor' to test enter mode (blocking) for this shell"
  fi

  # Per-typed-line cache key. The trampoline captures the caller's line
  # number (BASH_LINENO[0] from its own frame) and passes it as $1; that
  # value advances on each prompt-boundary even when the user's
  # HISTCONTROL/HISTIGNORE settings make `history 1` skip entries, so it
  # identifies "same typed line" reliably even in filtered shells. All
  # simple commands of one typed line (`a; b`, `a | b`, `a && b`) share
  # the same value. Fall back to the topmost BASH_LINENO frame for the
  # rare case preexec is invoked directly without going through the
  # trampoline.
  local line_id="${1:-${BASH_LINENO[${#BASH_LINENO[@]}-1]:-0}}"

  local _tirith_prev_internal="${_TIRITH_BASH_INTERNAL:-0}"
  local rc

  if [[ "${_TIRITH_PREEXEC_ENFORCE:-0}" == "1" ]]; then
    # Helper failed (no history entry available): cannot enforce whole-line
    # semantics, so block the current DEBUG fire and downgrade the session.
    if [[ -z "$history_index" ]]; then
      _tirith_last_key="$line_id"
      _tirith_last_rc=1
      _tirith_preexec_block_current_line \
        "tirith: bash history is unavailable in this shell (history disabled or buffer empty), cannot enforce whole-line semantics; falling back to warn-only. For guaranteed blocking, use enter mode (export TIRITH_BASH_MODE=enter)."
      return $?
    fi

    # Drift check FIRST. Critical: a stale history index (e.g. when a
    # filtered command leaves history_index unchanged from a prior allow)
    # MUST NOT short-circuit to the cache before we re-validate that the
    # current BASH_COMMAND still belongs to the typed line. Otherwise an
    # attacker can flip on `HISTCONTROL=ignorespace` mid-session and reuse
    # an earlier allow verdict for a brand-new blocked command.
    if ! _tirith_cmd_is_in_line "$bash_cmd" "$history_line"; then
      _tirith_last_key="$line_id"
      _tirith_last_rc=1
      _tirith_preexec_block_current_line \
        "tirith: bash history no longer matches BASH_COMMAND (likely HISTCONTROL/HISTIGNORE filtering, an alias, or a shell transformation outside the whole-line drift check); cannot enforce whole-line semantics; falling back to warn-only. For guaranteed blocking, use enter mode (export TIRITH_BASH_MODE=enter)."
      return $?
    fi

    # Modern Bash can expose the same blocked function invocation once more
    # while handing an interactive pipe to EOF, after PROMPT_COMMAND has already
    # run. `history` does not advance for that synthetic retry. Carry only a
    # prior BLOCK across the prompt and key it to both index and complete line:
    # this suppresses duplicate decisions/receipts without ever reusing an
    # allow verdict. A real re-submission gets a new history index (enforcement
    # already rejects ignoredups/ignoreboth), so it is checked afresh.
    local history_key="${history_index}|${history_line}"
    if [[ -n "${_TIRITH_PREEXEC_BLOCK_HISTORY_KEY:-}" ]]; then
      if [[ "$_TIRITH_PREEXEC_BLOCK_HISTORY_KEY" == "$history_key" ]]; then
        _tirith_last_key="$line_id"
        _tirith_last_rc=1
        _tirith_preexec_block_current_line
        return $?
      fi
      unset _TIRITH_PREEXEC_BLOCK_HISTORY_KEY
    fi

    # Cache hit on the current typed line (drift just validated).
    if [[ "${_tirith_last_key:-}" == "$line_id" ]]; then
      return "${_tirith_last_rc:-0}"
    fi

    # Cache miss: fresh whole-line scan.
    _TIRITH_BASH_INTERNAL=1
    if [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 \
          && "${_TIRITH_PREEXEC_RECEIPTS_TRUSTED:-0}" == "1" ]]; then
      _tirith_preexec_receipt_check "$history_line" no
      rc=$?
    else
      _TIRITH_HOOK=1 builtin command "$_TIRITH_BIN" check --shell posix -- "$history_line"
      rc=$?
    fi
    _TIRITH_BASH_INTERNAL="$_tirith_prev_internal"

    case "$rc" in
      0|2)
        _tirith_last_key="$line_id"
        _tirith_last_rc=0
        _TIRITH_PREEXEC_ACTIVE_DECISION="allow"
        return 0
        ;;
      1)
        _tirith_last_key="$line_id"
        _tirith_last_rc=1
        _TIRITH_PREEXEC_BLOCK_HISTORY_KEY="$history_key"
        _tirith_preexec_block_current_line
        return $?
        ;;
      *)
        _tirith_last_key="$line_id"
        _tirith_last_rc=1
        _TIRITH_PREEXEC_BLOCK_HISTORY_KEY="$history_key"
        _tirith_preexec_block_current_line \
          "tirith: preexec enforcement failed unexpectedly (exit $rc), blocking this command and disabling enforcement for this shell"
        return $?
        ;;
    esac
  fi

  # Cross-path pinned-block carryover: a prior degrade may have written
  # (_tirith_last_key=$line_id, _tirith_last_rc=1) so the rest of the same
  # typed line continues to be skipped by extdebug. Keying on LINENO means
  # a later prompt cannot inherit the block — even in shells where history
  # filtering keeps history_index pinned across prompts.
  if [[ "${_tirith_last_key:-}" == "$line_id" ]] \
     && [[ "${_tirith_last_rc:-}" == "1" ]]; then
    return 1
  fi

  # When the session has been degraded (install-time hostile-config or
  # runtime drift), history_line can no longer be trusted to correspond to
  # the current simple command, so scan BASH_COMMAND instead. Otherwise
  # prefer history_line so composite rules (pipe-to-interpreter, etc.) fire
  # on the full typed line.
  local scan_target
  if [[ "${_TIRITH_WARN_ONLY_USE_BASH_COMMAND:-0}" == "1" ]]; then
    scan_target="$bash_cmd"
  elif [[ -n "$history_line" ]]; then
    scan_target="$history_line"
  else
    scan_target="$bash_cmd"
  fi

  # Within-line dedupe: skip when this exact scan target was already sent
  # to tirith on the SAME typed line (DEBUG can fire multiple times for one
  # simple command via subshell expansion). Combine the per-line id with
  # the scan target so identical commands on separate prompts each get a
  # fresh DETECTED banner — the prompt boundary advances line_id and
  # naturally invalidates the dedupe.
  local dedupe_key="${line_id}|${scan_target}"
  if [[ "${_tirith_last_cmd:-}" == "$dedupe_key" ]]; then
    _TIRITH_PREEXEC_ACTIVE_DECISION="allow"
    return 0
  fi
  _tirith_last_cmd="$dedupe_key"

  _TIRITH_BASH_INTERNAL=1
  if [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 \
        && "${_TIRITH_PREEXEC_RECEIPTS_TRUSTED:-0}" == "1" ]]; then
    if _tirith_receipt_parent_context_is_valid; then
      if ! _tirith_preexec_receipt_check "$scan_target" yes; then
        # The receipt path failed before the user saw anything: its stdout goes
        # to a capture file, so a capture, parse, or consume failure swallows
        # the scan output along with the receipt. The command runs regardless
        # in warn-only mode, which makes the scan the only thing this mode
        # offers. Run it plainly, and say once that execution evidence for this
        # shell is no longer strict.
        _TIRITH_HOOK=1 builtin command "$_TIRITH_BIN" check --shell posix --warn-only -- "$scan_target" || true
        if [[ -z "${_TIRITH_RECEIPT_DEGRADE_WARNED:-}" ]]; then
          _TIRITH_RECEIPT_DEGRADE_WARNED=1
          _tirith_output "tirith: execution receipts unavailable; legacy checks remain active but session execution evidence is degraded"
          [[ -n "${_TIRITH_RECEIPT_REGISTER_ERROR:-}" ]] \
            && _tirith_output "$_TIRITH_RECEIPT_REGISTER_ERROR"
        fi
      fi
    else
      # A functrace-inherited DEBUG trap may run in a Bash subshell where `$$`
      # still names the registered top-level shell. Do not make a false strict
      # receipt claim there; retain the mode's honest warn-only scan instead.
      _TIRITH_HOOK=1 builtin command "$_TIRITH_BIN" check --shell posix --warn-only -- "$scan_target" || true
    fi
  else
    _TIRITH_HOOK=1 builtin command "$_TIRITH_BIN" check --shell posix --warn-only -- "$scan_target" || true
  fi
  _TIRITH_BASH_INTERNAL="$_tirith_prev_internal"
  _TIRITH_PREEXEC_ACTIVE_DECISION="allow"
  return 0
}


# Enter mode has to cover every primary Readline keymap a session can switch
# to after the hook is loaded. Preserve Ctrl-O separately for each map because
# it is an accept-line equivalent that must be disabled only while enter mode
# owns command delivery.
_TIRITH_PROTECTED_KEYMAPS=(emacs-standard vi-insert vi-command)
_TIRITH_SAVED_CTRL_O_KINDS=()
_TIRITH_SAVED_CTRL_O_BINDINGS=()

_tirith_bind_x_record_is_ctrl_o() {
  local key="${1%%[[:space:]]*}"
  # Bash releases have emitted both `"\C-o" command` and
  # `"\C-o": command` forms from `bind -X`.
  key="${key%:}"
  [[ "$key" == '"\C-o"' ]]
}

_tirith_bind_output_has_ctrl_o() {
  local output="$1" line
  while IFS= read -r line; do
    _tirith_bind_x_record_is_ctrl_o "$line" && return 0
  done <<< "$output"
  return 1
}

_tirith_bind_x_has_exact_binding() {
  local output="$1"
  local key="$2"
  local command="$3"
  local line
  # Bash 5.2 prints inputrc-style `"key": "command"` records, while 5.3
  # omits the colon. Match complete records in either reusable format so a
  # substring or a similarly named callback cannot satisfy the health gate.
  while IFS= read -r line; do
    if [[ "$line" == "\"${key}\" \"${command}\"" \
       || "$line" == "\"${key}\": \"${command}\"" ]]; then
      return 0
    fi
  done <<< "$output"
  return 1
}

_tirith_capture_ctrl_o_bindings() {
  local map output line index
  # Bash versions that cannot enumerate bind-x entries cannot safely preserve
  # an existing shell-command binding. They already fail the enter-mode health
  # gate, so refuse before changing any bindings and use preexec instead.
  builtin bind -X >/dev/null 2>&1 || return 1
  _TIRITH_SAVED_CTRL_O_KINDS=()
  _TIRITH_SAVED_CTRL_O_BINDINGS=()

  for ((index = 0; index < ${#_TIRITH_PROTECTED_KEYMAPS[@]}; index++)); do
    map="${_TIRITH_PROTECTED_KEYMAPS[index]}"
    _TIRITH_SAVED_CTRL_O_KINDS[index]="unbound"
    _TIRITH_SAVED_CTRL_O_BINDINGS[index]=""

    output="$(builtin bind -m "$map" -X 2>/dev/null)" || return 1
    while IFS= read -r line; do
      if _tirith_bind_x_record_is_ctrl_o "$line"; then
        _TIRITH_SAVED_CTRL_O_KINDS[index]="bind-x"
        _TIRITH_SAVED_CTRL_O_BINDINGS[index]="$line"
        break
      fi
    done <<< "$output"
    [[ "${_TIRITH_SAVED_CTRL_O_KINDS[index]}" == "bind-x" ]] && continue

    output="$(builtin bind -m "$map" -s 2>/dev/null)" || return 1
    while IFS= read -r line; do
      if [[ "${line%%:*}" == '"\C-o"' ]]; then
        _TIRITH_SAVED_CTRL_O_KINDS[index]="binding"
        _TIRITH_SAVED_CTRL_O_BINDINGS[index]="$line"
        break
      fi
    done <<< "$output"
    [[ "${_TIRITH_SAVED_CTRL_O_KINDS[index]}" == "binding" ]] && continue

    output="$(builtin bind -m "$map" -p 2>/dev/null)" || return 1
    while IFS= read -r line; do
      if [[ "${line%%:*}" == '"\C-o"' ]]; then
        _TIRITH_SAVED_CTRL_O_KINDS[index]="binding"
        _TIRITH_SAVED_CTRL_O_BINDINGS[index]="$line"
        break
      fi
    done <<< "$output"
  done
  return 0
}

_tirith_restore_ctrl_o_bindings() {
  local map kind binding index restore_rc=0
  for ((index = 0; index < ${#_TIRITH_PROTECTED_KEYMAPS[@]}; index++)); do
    map="${_TIRITH_PROTECTED_KEYMAPS[index]}"
    kind="${_TIRITH_SAVED_CTRL_O_KINDS[index]:-unbound}"
    binding="${_TIRITH_SAVED_CTRL_O_BINDINGS[index]:-}"
    case "$kind" in
      bind-x)
        builtin bind -m "$map" -x "$binding" 2>/dev/null || restore_rc=1
        ;;
      binding)
        builtin bind -m "$map" "$binding" 2>/dev/null || restore_rc=1
        ;;
      *)
        builtin bind -m "$map" -r '\C-o' 2>/dev/null || restore_rc=1
        ;;
    esac
  done
  unset _TIRITH_SAVED_CTRL_O_KINDS _TIRITH_SAVED_CTRL_O_BINDINGS
  return "$restore_rc"
}


_tirith_degrade_to_preexec() {
  local reason="${1:-unknown}"

  # Safe deterministic degrade: set known-safe defaults for current session.
  # Custom bindings from .inputrc/.bashrc return on next shell (safe mode persisted,
  # so tirith won't install bind-x on restart).
  if [[ "${_TIRITH_BINDS_INSTALLED:-0}" == "1" ]]; then
    local _tirith_keymap
    for _tirith_keymap in "${_TIRITH_PROTECTED_KEYMAPS[@]}"; do
      builtin bind -m "$_tirith_keymap" '"\C-m": accept-line' 2>/dev/null || true
      builtin bind -m "$_tirith_keymap" '"\C-j": accept-line' 2>/dev/null || true
      # Unbind the macro-dispatch helper sequences (checker + guarded accept)
      # so no stale binding survives the degrade in any switchable keymap.
      builtin bind -m "$_tirith_keymap" -r "$_TIRITH_ENTER_CHECK_KEYS" 2>/dev/null || true
      builtin bind -m "$_tirith_keymap" -r "$_TIRITH_ENTER_ACCEPT_KEYS" 2>/dev/null || true
      # Restore bracketed paste to the Readline default if available.
      builtin bind -m "$_tirith_keymap" '"\e[200~": bracketed-paste-begin' \
        2>/dev/null || builtin bind -m "$_tirith_keymap" -r '\e[200~' 2>/dev/null || true
    done
    _tirith_restore_ctrl_o_bindings || true
    _TIRITH_BINDS_INSTALLED=0
  fi

  _TIRITH_PREEXEC_PHASE="startup"
  _TIRITH_PREEXEC_ACTIVE_DECISION=""
  _TIRITH_PREEXEC_BLOCK_ACTIVE=0
  _TIRITH_PREEXEC_ENFORCE_PENDING=0
  if shopt -q extdebug; then
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    _TIRITH_BASH_MODE="preexec"
    _tirith_persist_safe_mode
    export TIRITH_BASH_EFFECTIVE_MODE="preexec"
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: enter mode failed ($reason), and the preexec fallback cannot own a user-enabled extdebug setting; interception is off for this shell"
    return 1
  elif ! _tirith_prepare_debug_trap_capture; then
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    _TIRITH_BASH_MODE="preexec"
    _tirith_persist_safe_mode
    export TIRITH_BASH_EFFECTIVE_MODE="preexec"
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: enter mode failed ($reason), and the preexec fallback could not preserve the existing DEBUG trap; interception is off for this shell"
    return 1
  elif _tirith_install_preexec_prompt_guards; then
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=1
    # Capture/chaining completes in the first prompt before Bash accepts input.
    # Until then, advertise no interception rather than a premature guarantee.
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "off"
  else
    if [[ -n "${_TIRITH_DEBUG_CAPTURE_FILE:-}" ]]; then
      _tirith_remove_capture_file "$_TIRITH_DEBUG_CAPTURE_FILE" >/dev/null 2>&1 || true
    fi
    _TIRITH_DEBUG_CAPTURE_FILE=""
    _TIRITH_DEBUG_TRAP_CAPTURE_READY=2
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_PROMPT_GUARDS=0
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    _TIRITH_BASH_MODE="preexec"
    _tirith_persist_safe_mode
    export TIRITH_BASH_EFFECTIVE_MODE="preexec"
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: enter mode failed ($reason), and the preexec fallback could not safely bracket PROMPT_COMMAND; interception is off for this shell"
    return 1
  fi
  _TIRITH_BASH_MODE="preexec"
  _tirith_persist_safe_mode
  if [[ $- == *i* ]]; then
    # Re-export the effective-state contract so a child `tirith doctor` sees the
    # post-degrade truth, not the stale enter/blocks values exported at startup.
    # Hardcoded warn-only: a shell that degrades out of enter mode never had
    # preexec enforcement enabled (enforcement is evaluated only at startup for
    # shells that START in preexec).
    export TIRITH_BASH_EFFECTIVE_MODE="preexec"
    export TIRITH_BASH_EFFECTIVE_PROTECTION="warn-only"
    _tirith_set_status "degraded"
  fi
  # One consolidated, one-shot degraded-protection banner — same wording as
  # every other degrade path. The enter-mode specifics (what failed, how to
  # re-enable) go on the detail line so the message stays a single clear shape.
  _tirith_warn_degraded_once \
    "enter mode failed ($reason); now warn-only. Persistent — restart your shell, or re-enable with TIRITH_BASH_MODE=enter."
}


_tirith_prompt_hook() {
  # Re-disarm the guarded accept-line every prompt. Arming leaves it bound to
  # accept-line until this runs, so disarming here closes the window in which
  # an injected accept sequence could accept a line the checker never approved.
  if declare -F _tirith_enter_disarm_accept >/dev/null 2>&1; then
    if ! _tirith_enter_disarm_accept; then
      local failed_pending_receipt="${_TIRITH_PENDING_RECEIPT:-}"
      unset _TIRITH_PENDING_EVAL
      unset _TIRITH_PENDING_RECEIPT _TIRITH_PENDING_COMMAND
      if [[ -n "$failed_pending_receipt" ]]; then
        _tirith_receipt_discard bash-enter "$failed_pending_receipt" || true
      fi
      _tirith_degrade_to_preexec "could not disarm guarded accept-line" || true
      return
    fi
  fi
  local pending_eval="${_TIRITH_PENDING_EVAL:-}"
  local pending_receipt="${_TIRITH_PENDING_RECEIPT:-}"
  local pending_command="${_TIRITH_PENDING_COMMAND:-}"
  unset _TIRITH_PENDING_EVAL
  unset _TIRITH_PENDING_RECEIPT _TIRITH_PENDING_COMMAND

  if [[ -n "$pending_receipt" ]]; then
    if [[ $_TIRITH_RECEIPT_PROTOCOL -ne 3 \
          || -z "$pending_eval" \
          || -z "$pending_command" \
          || "$pending_eval" != "$pending_command" ]]; then
      _tirith_receipt_discard bash-enter "$pending_receipt" || true
      _tirith_degrade_to_preexec "deferred command state did not match its receipt"
      return 1
    fi
    if ! _tirith_receipt_consume bash-enter "$pending_receipt" "$pending_command"; then
      if ! _tirith_receipt_reconcile bash-enter "$pending_receipt"; then
        _tirith_degrade_to_preexec "execution receipt could not be committed before delivery"
        return 1
      fi
    fi
  elif [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 \
          && ( -n "$pending_eval" || -n "$pending_command" ) ]]; then
    _tirith_degrade_to_preexec "deferred command state lacks its receipt commit marker"
    return 1
  fi

  if [[ -n "$pending_eval" ]]; then
    builtin eval -- "$pending_eval"
  fi
}

_tirith_is_prompt_hook_attached() {
  local pc_decl
  pc_decl="$(declare -p PROMPT_COMMAND 2>/dev/null)" || return 1

  if [[ "$pc_decl" == "declare -a"* ]]; then
    local entry
    for entry in "${PROMPT_COMMAND[@]}"; do
      [[ "$entry" == "_tirith_prompt_hook" ]] && return 0
    done
    return 1
  else
    # String form: use regex to match _tirith_prompt_hook as a semicolon-delimited
    # token with optional surrounding whitespace.
    [[ "$PROMPT_COMMAND" =~ (^|;)[[:space:]]*_tirith_prompt_hook[[:space:]]*(;|$) ]] && return 0
    return 1
  fi
}

_tirith_ensure_prompt_hook() {
  _tirith_is_prompt_hook_attached && return 0

  local pc_decl pc_attrs
  pc_decl="$(declare -p PROMPT_COMMAND 2>/dev/null)" || pc_decl=""
  pc_attrs="${pc_decl#declare }"
  pc_attrs="${pc_attrs%% *}"
  # Never attempt the assignment when PROMPT_COMMAND is readonly (or otherwise
  # unwrappable): assigning to a readonly variable is a FATAL error that aborts
  # this whole function before it can report failure, so the caller would never
  # see a return value and never degrade. Refuse cleanly instead, and let the
  # caller degrade (the preexec-guard install refuses the same attributes).
  if [[ -n "$pc_decl" ]]; then
    _tirith_prompt_command_attrs_safe "$pc_attrs" || return 1
  fi

  if [[ "$pc_decl" == "declare -a"* ]]; then
    PROMPT_COMMAND=(_tirith_prompt_hook "${PROMPT_COMMAND[@]}") 2>/dev/null || return 1
  elif [[ -n "${PROMPT_COMMAND:-}" ]]; then
    PROMPT_COMMAND="_tirith_prompt_hook;${PROMPT_COMMAND}" 2>/dev/null || return 1
  else
    PROMPT_COMMAND="_tirith_prompt_hook" 2>/dev/null || return 1
  fi
  # Confirm the reattachment actually took effect.
  _tirith_is_prompt_hook_attached
}


# A sourced file cannot see its caller's DEBUG trap: `trap -p DEBUG` reports an
# empty handler inside the file even though returning to the interactive shell
# restores one. Defer capture to a direct PROMPT_COMMAND element, which Bash
# evaluates in the caller's top-level context before the next user command.
_TIRITH_DEBUG_TRAP_CAPTURE_READY=0
_TIRITH_CAPTURED_DEBUG_TRAP_SPEC=""
_TIRITH_DEBUG_TRAP_INSTALLED=0
_TIRITH_DEBUG_CAPTURE_FILE=""
_TIRITH_DEBUG_OWNERSHIP_FILE=""
_TIRITH_DEBUG_TRAP_OWNERSHIP_OK=0
_TIRITH_PREEXEC_ENFORCE_PENDING=0
_TIRITH_PREEXEC_BOOTSTRAP_COMMAND='if [[ "${_TIRITH_DEBUG_TRAP_CAPTURE_READY:-0}" == "0" ]]; then builtin trap -p DEBUG >|"$_TIRITH_DEBUG_CAPTURE_FILE" 2>/dev/null; _tirith_finalize_debug_trap_capture; fi; if [[ "${_TIRITH_DEBUG_TRAP_INSTALLED:-0}" == "1" ]]; then builtin trap -p DEBUG >|"$_TIRITH_DEBUG_OWNERSHIP_FILE" 2>/dev/null; _tirith_verify_debug_trap_ownership; fi; _tirith_restore_prompt_status'


if [[ -n "${TIRITH_BASH_MODE:-}" ]]; then
  # Explicit user override always wins. A user who exports TIRITH_BASH_MODE has
  # made a deliberate choice; if they force `enter` in an environment where
  # delivery is broken, the startup health gate and the pending-not-consumed
  # detection still degrade visibly (contract invariant f) — never silently.
  case "$TIRITH_BASH_MODE" in
    enter|preexec) _TIRITH_BASH_MODE="$TIRITH_BASH_MODE" ;;
    *)
      # An arbitrary value previously selected neither installer branch while
      # still exporting a plausible warn-only status. Refuse that silent
      # no-hook state: fall back to the conservative preexec path and identify
      # the invalid configuration at startup.
      _TIRITH_BASH_MODE="preexec"
      [[ $- == *i* ]] && _tirith_output "tirith: invalid TIRITH_BASH_MODE (expected enter or preexec); using preexec"
      ;;
  esac
elif _tirith_check_safe_mode; then
  _TIRITH_BASH_MODE="preexec"
  # Only print warning in interactive shells (avoid polluting scripted output)
  [[ $- == *i* ]] && _tirith_output "tirith: safe mode active (preexec) — previous enter-mode failure detected"
  [[ $- == *i* ]] && _tirith_output "  Re-enable: TIRITH_BASH_MODE=enter or tirith doctor --reset-bash-safe-mode"
elif [[ -n "${SSH_CONNECTION:-}" || -n "${SSH_TTY:-}" || -n "${SSH_CLIENT:-}" ]]; then
  # SSH PTY environments are more reliable with DEBUG-trap preexec mode.
  _TIRITH_BASH_MODE="preexec"
elif _tirith_enter_capability_proven; then
  # Default path: enter mode is used only when the capability self-test (run by
  # `tirith setup` / `tirith doctor`) has PROVEN, for this exact bash, that
  # enter-mode delivery works and blocking works. See issue #111.
  _TIRITH_BASH_MODE="enter"
else
  # No proof that enter mode works here (cache missing, stale, or recorded a
  # failure). Fall back to the safe default rather than risk silently eating a
  # command. `tirith doctor` (or `tirith doctor --simulate-enter`) runs the
  # self-test and, when enter mode works, enables it for subsequent shells.
  _TIRITH_BASH_MODE="preexec"
fi

#
# Doctor is a child process and cannot read shell-local `_TIRITH_*` variables,
# so the hook exports a small public contract: `TIRITH_BASH_EFFECTIVE_MODE` and
# `TIRITH_BASH_EFFECTIVE_PROTECTION`. These are re-exported on every state
# change (degrade, enforcement flip) so a subsequent `tirith doctor` invocation
# in the same shell sees truthful live state. Only exported in interactive
# shells where the hook actually installs interception; non-interactive
# sourcing is a no-op and must not leak status vars into child processes.
if [[ $- == *i* ]]; then
  export TIRITH_BASH_EFFECTIVE_MODE="$_TIRITH_BASH_MODE"
  if [[ "$_TIRITH_BASH_MODE" == "enter" ]]; then
    export TIRITH_BASH_EFFECTIVE_PROTECTION="blocks"
    # TIRITH_STATUS: opt-in prompt indicator (see docs/prompt-status.md), a
    # non-exported shell variable. enter mode blocks; preexec without
    # enforcement is warn-only. A later enforcement flip or a runtime degrade
    # updates this in place.
    _tirith_set_status "blocks"
  else
    export TIRITH_BASH_EFFECTIVE_PROTECTION="warn-only"
    _tirith_set_status "warn-only"
  fi
fi

#
# Users who set TIRITH_BASH_PREEXEC_ENFORCE to a truthy value get real
# blocking in preexec mode by enabling extdebug lazily after a whole-line block
# decision and returning 1 from the DEBUG trap. Prompt boundaries release that
# Tirith-owned state before user prompt functions run. Enforcement requires a
# trustworthy whole-line view and safe PROMPT_COMMAND bracketing; hostile
# history downgrades visibly, while unsafe debugger/prompt ownership leaves
# interception explicitly off.
_TIRITH_PREEXEC_ENFORCE=0
_TIRITH_OWNS_EXTDEBUG=0
_TIRITH_WARN_ONLY_USE_BASH_COMMAND=0
_TIRITH_PREEXEC_PROMPT_GUARDS=0
_TIRITH_PREEXEC_PHASE="off"
_TIRITH_PREEXEC_AWAITING_USER=0
_TIRITH_PREEXEC_BLOCK_ACTIVE=0
_TIRITH_PREEXEC_ACTIVE_DECISION=""
_TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
_TIRITH_PREEXEC_BLOCK_HISTORY_KEY=""

_tirith_env_is_truthy() {
  case "${1:-}" in
    1|true|TRUE|True|yes|YES|Yes|on|ON|On) return 0 ;;
  esac
  return 1
}

if [[ "$_TIRITH_BASH_MODE" == "preexec" ]] && [[ $- == *i* ]]; then
  _TIRITH_PREEXEC_PHASE="startup"
  if shopt -q extdebug; then
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_WARNED=1
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: bash preexec hook was not installed because extdebug is already user-enabled; existing debugger state was left unchanged"
  elif ! _tirith_prepare_debug_trap_capture; then
    # Do not mutate PROMPT_COMMAND unless the top-level DEBUG capture has a
    # private destination. With no future Tirith trap, warn-only is false too.
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_WARNED=1
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: bash preexec hook was not installed because the existing DEBUG trap could not be preserved safely; existing debugger state was left unchanged"
  elif _tirith_install_preexec_prompt_guards; then
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=1
    # Capture/chaining completes in the first prompt before Bash accepts input.
    # Until then, advertise no interception rather than a premature guarantee.
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "off"
  else
    # The direct prompt bootstrap is the only context where Bash exposes a
    # caller-owned DEBUG trap. If PROMPT_COMMAND cannot be bracketed, preserve
    # both user-owned states and make the lack of interception explicit.
    if [[ -n "${_TIRITH_DEBUG_CAPTURE_FILE:-}" ]]; then
      _tirith_remove_capture_file "$_TIRITH_DEBUG_CAPTURE_FILE" >/dev/null 2>&1 || true
    fi
    _TIRITH_DEBUG_CAPTURE_FILE=""
    _TIRITH_DEBUG_TRAP_CAPTURE_READY=2
    _TIRITH_PREEXEC_PHASE="off"
    _TIRITH_PREEXEC_PROMPT_GUARDS=0
    _TIRITH_PREEXEC_WARNED=1
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    export TIRITH_BASH_EFFECTIVE_PROTECTION="off"
    _tirith_set_status "degraded"
    _tirith_output "tirith: bash preexec hook was not installed because PROMPT_COMMAND is readonly, associative, coercing, unsupported, or otherwise cannot be safely bracketed; existing prompt and DEBUG state was left unchanged"
  fi
fi

if [[ "$_TIRITH_BASH_MODE" == "preexec" ]] \
   && [[ $- == *i* ]] \
   && _tirith_env_is_truthy "${TIRITH_BASH_PREEXEC_ENFORCE:-}"; then
  if [[ "${_TIRITH_PREEXEC_PHASE:-}" == "off" ]]; then
    _TIRITH_PREEXEC_WARNED=1
    _tirith_set_status "degraded"
  elif [[ "${_TIRITH_PREEXEC_PROMPT_GUARDS:-0}" != "1" ]]; then
    _TIRITH_PREEXEC_WARNED=1
    _tirith_set_status "degraded"
    _tirith_warn_degraded_once \
      "preexec enforcement could not engage because PROMPT_COMMAND is readonly, associative, or otherwise cannot be safely bracketed. For guaranteed blocking, use enter mode (export TIRITH_BASH_MODE=enter)."
  elif shopt -q extdebug; then
    # Preserve user debugger state exactly. Always-on user extdebug inherits
    # DEBUG into function bodies, so claiming a whole-line blocking boundary
    # would be unsafe even though warn-only top-level scans remain available.
    _TIRITH_PREEXEC_WARNED=1
    _tirith_set_status "degraded"
    _tirith_warn_degraded_once \
      "preexec enforcement could not engage because extdebug was already enabled outside Tirith; user debugger state was preserved. Disable extdebug or use enter mode for blocking."
  elif _tirith_history_is_trustworthy_for_enforcement; then
    # The caller's DEBUG trap is only visible at the first top-level prompt.
    # Arm enforcement there, immediately after that trap is captured/chained
    # and before Bash can accept another user command.
    _TIRITH_PREEXEC_ENFORCE_PENDING=1
  else
    # Same hostile-history check that triggers a runtime drift downgrade —
    # so the warn-only scan target must also flip to BASH_COMMAND, not the
    # untrustworthy history_line. Without this the warn-only path would
    # produce stale DETECTED banners scanned against whatever entry
    # `history 1` happens to surface.
    _TIRITH_WARN_ONLY_USE_BASH_COMMAND=1
    _TIRITH_PREEXEC_RECEIPTS_TRUSTED=0
    # The user asked for blocking (TIRITH_BASH_PREEXEC_ENFORCE) but a hostile
    # history config prevents it — that is a downgrade from the requested
    # protection level, so the prompt indicator is `degraded`. Routed through
    # the one-shot banner so the headline matches every other degrade path.
    _tirith_set_status "degraded"
    _TIRITH_PREEXEC_WARNED=1
    _tirith_warn_degraded_once \
      "preexec enforcement could not engage (HISTCONTROL/HISTIGNORE or disabled history prevents a trustworthy whole-line view). For guaranteed blocking, use enter mode (export TIRITH_BASH_MODE=enter)."
  fi
fi

# New hooks can keep running their legacy decision checks against an older
# binary, but without the one-shot receipt protocol they cannot prove that a
# permitted command reached the shell boundary. Surface that evidence loss
# explicitly without overwriting the live interception contract above:
# blocking/warn-only protection and durable execution evidence are separate
# claims.
if [[ $- == *i* ]] && [[ $_TIRITH_RECEIPT_PROTOCOL -ne 3 ]]; then
  if [[ -z "${_TIRITH_RECEIPT_DEGRADE_WARNED:-}" ]]; then
    _TIRITH_RECEIPT_DEGRADE_WARNED=1
    _tirith_output "tirith: execution receipts unavailable; legacy checks remain active but session execution evidence is degraded"
    [[ -n "${_TIRITH_RECEIPT_REGISTER_ERROR:-}" ]] \
      && _tirith_output "$_TIRITH_RECEIPT_REGISTER_ERROR"
  fi
fi


# Check if a command is unsafe to eval (heredocs, multiline, etc.)
_tirith_unsafe_to_eval() {
  local cmd="$1"

  # Contains literal newline
  if [[ "$cmd" == *$'\n'* ]]; then
    return 0
  fi

  # Ends with backslash (line continuation)
  if [[ "$cmd" == *'\' ]]; then
    return 0
  fi

  # Contains heredoc
  if [[ "$cmd" == *'<<'* ]]; then
    return 0
  fi

  # Contains compound command keywords that suggest multi-line constructs
  local keywords='(^|[;&| ])(\{|\}|function |case |select |for |while |until |coproc )'
  if [[ "$cmd" =~ $keywords ]]; then
    return 0
  fi

  # Contains '; do' or '; then' patterns (inline loops/conditionals)
  if [[ "$cmd" == *'; do'* ]] || [[ "$cmd" == *'; then'* ]]; then
    return 0
  fi

  # Contains command group parentheses
  if [[ "$cmd" == *'( '* ]] || [[ "$cmd" == *' )'* ]]; then
    return 0
  fi

  return 1
}


_tirith_queue_enter_delivery() {
  local cmd="$1" receipt_token="$2"
  _TIRITH_PENDING_EVAL="$cmd"
  _TIRITH_PENDING_COMMAND="$cmd"
  # Commit marker: publish only after both command copies are complete.
  if [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 ]]; then
    _TIRITH_PENDING_RECEIPT="$receipt_token"
  fi

  # The accept sub-sequence is processed only after this bind-x callback
  # returns. If any keymap cannot be armed, roll the delivery back while the
  # command can still be put visibly into Readline for a safe retry.
  if ! _tirith_enter_arm_accept; then
    unset _TIRITH_PENDING_EVAL _TIRITH_PENDING_COMMAND _TIRITH_PENDING_RECEIPT
    _tirith_receipt_discard bash-enter "$receipt_token" || true
    READLINE_LINE="$cmd"
    READLINE_POINT=${#cmd}
    _tirith_degrade_to_preexec "could not arm guarded accept-line" || true
    return 1
  fi

  history -s -- "$cmd"
  return 0
}


_tirith_startup_health_check() {
  # Test-only override: bypass startup gate to reach runtime failure paths in PTY tests.
  [[ "${_TIRITH_TEST_SKIP_HEALTH:-}" == "1" ]] && return 0
  # Test-only override for CI (avoids needing PTY)
  [[ "${_TIRITH_TEST_FAIL_HEALTH:-}" == "1" ]] && return 1
  # The checker must be installed as a bind -x function.
  local map xbinds sbinds pbinds
  # Both \C-m and \C-j must map to the checker+accept Enter macro in every
  # primary keymap. A later `set -o vi` must not expose an unguarded accept-line.
  local macro="$_TIRITH_ENTER_CHECK_KEYS$_TIRITH_ENTER_ACCEPT_KEYS"
  local cm_needle="\"\\C-m\": \"$macro\""
  local cj_needle="\"\\C-j\": \"$macro\""
  for map in "${_TIRITH_PROTECTED_KEYMAPS[@]}"; do
    xbinds="$(builtin bind -m "$map" -X 2>/dev/null)" || return 1
    _tirith_bind_x_has_exact_binding \
      "$xbinds" "$_TIRITH_ENTER_CHECK_KEYS" "_tirith_enter" || return 1
    _tirith_bind_x_has_exact_binding \
      "$xbinds" "$_TIRITH_ENTER_ACCEPT_KEYS" "_tirith_enter_accept_noop" || return 1
    _tirith_bind_output_has_ctrl_o "$xbinds" && return 1
    sbinds="$(builtin bind -m "$map" -s 2>/dev/null)" || return 1
    [[ "$sbinds" == *"$cm_needle"* ]] || return 1
    [[ "$sbinds" == *"$cj_needle"* ]] || return 1
    _tirith_bind_output_has_ctrl_o "$sbinds" && return 1
    pbinds="$(builtin bind -m "$map" -p 2>/dev/null)" || return 1
    _tirith_bind_output_has_ctrl_o "$pbinds" && return 1
  done
  # Verify prompt hook is still attached
  _tirith_is_prompt_hook_attached || return 1
  return 0
}


if [[ "$_TIRITH_BASH_MODE" == "enter" ]] && [[ $- == *i* ]]; then
  # Enter mode: interactive shell only (bind-x requires readline).
  # Non-interactive sourcing (bash -c, scripts, BASH_ENV) skips this entire block.
  # Mode variable stays "enter" but nothing is installed — effectively a no-op.
  # No traps, no bindings, no state writes in non-interactive context.
  _TIRITH_BINDS_INSTALLED=0

  # Attach prompt hook (gates further setup)
  if ! _tirith_ensure_prompt_hook; then
    _tirith_degrade_to_preexec "PROMPT_COMMAND is readonly or unattachable"
  else
    _tirith_enter() {
      # Save terminal state — bind -x can corrupt echo in some PTY environments (gcloud ssh, etc.)
      local _saved_stty
      if [[ -n "$_TIRITH_STTY_BIN" ]]; then
        _saved_stty="$(builtin command "$_TIRITH_STTY_BIN" -g 2>/dev/null)" || _saved_stty=""
      fi

      # Ensure terminal state is restored on exit
      builtin trap '_tirith_restore_terminal_state "$_saved_stty"' RETURN

      # Self-heal: verify prompt hook is still attached
      if ! _tirith_ensure_prompt_hook; then
        _tirith_degrade_to_preexec "PROMPT_COMMAND reattachment failed"
        return  # READLINE_LINE stays intact
      fi

      # Detect broken delivery: if previous pending was never consumed
      if [[ -n "${_TIRITH_PENDING_EVAL:-}" \
            || -n "${_TIRITH_PENDING_COMMAND:-}" \
            || -n "${_TIRITH_PENDING_RECEIPT:-}" ]]; then
        _tirith_receipt_discard bash-enter "${_TIRITH_PENDING_RECEIPT:-}"
        unset _TIRITH_PENDING_EVAL
        unset _TIRITH_PENDING_RECEIPT _TIRITH_PENDING_COMMAND
        _tirith_degrade_to_preexec "previous command not delivered (check shell history)"
        return  # READLINE_LINE stays intact
      fi

      # Empty input: accept the empty line so a fresh prompt is shown.
      if [[ -z "$READLINE_LINE" ]]; then
        READLINE_LINE=""
        READLINE_POINT=0
        if ! _tirith_enter_arm_accept; then
          _tirith_degrade_to_preexec "could not arm guarded accept-line" || true
        fi
        return
      fi

      # Check for incomplete input (open quotes, unclosed blocks)
      local syntax_err syntax_rc
      _tirith_check_command_syntax "$READLINE_LINE"
      syntax_err="$_TIRITH_SYNTAX_ERROR"
      syntax_rc="$_TIRITH_SYNTAX_RC"
      unset _TIRITH_SYNTAX_ERROR _TIRITH_SYNTAX_RC
      if [[ $syntax_rc -ne 0 ]] && [[ "$syntax_err" == *"unexpected EOF"* || "$syntax_err" == *"unexpected end of file"* ]]; then
        # Incomplete input: insert newline for continued editing
        READLINE_LINE+=$'\n'
        READLINE_POINT=${#READLINE_LINE}
        return
      fi

      # Run Tirith directly from this long-lived shell. Capturing the receipt in
      # `$(...)` would make Tirith a child of a Bash 3.2 helper subshell and break
      # protocol-v3 parent-PID validation.
      local errfile stdout_file rc
      errfile="$(_tirith_new_capture_file 2>/dev/null)" || errfile=""
      stdout_file="$(_tirith_new_capture_file 2>/dev/null)" || stdout_file=""
      if [[ -z "$errfile" || -z "$stdout_file" ]]; then
        [[ -n "$errfile" ]] && _tirith_remove_capture_file "$errfile" >/dev/null 2>&1
        [[ -n "$stdout_file" ]] && _tirith_remove_capture_file "$stdout_file" >/dev/null 2>&1
        _tirith_degrade_to_preexec "could not create private receipt capture files"
        return
      fi
      local approval_path="" warn_ack_path="" receipt_token=""
      local _tirith_prev_internal="${_TIRITH_BASH_INTERNAL:-0}"
      _TIRITH_BASH_INTERNAL=1
      local -a receipt_args
      receipt_args=()
      [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 ]] && receipt_args=(--execution-receipt bash-enter)
      _TIRITH_HOOK=1 _TIRITH_RECEIPT_INSTANCE="$_TIRITH_RECEIPT_INSTANCE" \
        _TIRITH_RECEIPT_SHELL_PID="$_TIRITH_RECEIPT_SHELL_PID" \
        _TIRITH_RECEIPT_FAMILY="$_TIRITH_RECEIPT_FAMILY" \
        builtin command "$_TIRITH_BIN" check --approval-check --non-interactive --interactive --shell posix \
        "${receipt_args[@]}" -- "$READLINE_LINE" >|"$stdout_file" 2>|"$errfile"
      rc=$?
      _TIRITH_BASH_INTERNAL="$_tirith_prev_internal"
      local output
      output=$(<"$errfile")
      _tirith_remove_capture_file "$errfile" >/dev/null 2>&1

      local receipt_lines=0 path_lines=0 malformed_stdout=0 line
      if [[ $_TIRITH_RECEIPT_PROTOCOL -eq 3 ]]; then
        local protocol_parse_rc
        _tirith_parse_v3_receipt_response "$stdout_file" "$rc"
        protocol_parse_rc=$?
        receipt_token="$_TIRITH_PARSED_RECEIPT"
        _tirith_remove_capture_file "$stdout_file" >/dev/null 2>&1 || protocol_parse_rc=2
        unset _TIRITH_CAPTURE_LINE _TIRITH_PARSED_RECEIPT
        case "$protocol_parse_rc" in
          0)
            if [[ $rc -eq 2 ]]; then
              local escaped_line
              escaped_line=$(_tirith_escape_preview "$READLINE_LINE")
              _tirith_output ""
              _tirith_output "command> $escaped_line"
              [[ -n "$output" ]] && _tirith_output "$output"
            fi
            ;;
          1)
            local escaped_line
            escaped_line=$(_tirith_escape_preview "$READLINE_LINE")
            _tirith_output ""
            _tirith_output "command> $escaped_line"
            [[ -n "$output" ]] && _tirith_output "$output"
            READLINE_LINE=""
            READLINE_POINT=0
            return
            ;;
          *)
            local escaped_line
            escaped_line=$(_tirith_escape_preview "$READLINE_LINE")
            _tirith_output ""
            _tirith_output "command> $escaped_line"
            [[ -n "$output" ]] && _tirith_output "$output"
            _tirith_receipt_discard bash-enter "$receipt_token"
            _tirith_degrade_to_preexec "invalid protocol-v3 execution-receipt response (exit $rc)"
            return
            ;;
        esac
      else
        while IFS= read -r line || [[ -n "$line" ]]; do
          if [[ "$line" == TIRITH_EXECUTION_RECEIPT=* ]]; then
            receipt_lines=$((receipt_lines + 1))
            receipt_token="${line#TIRITH_EXECUTION_RECEIPT=}"
          elif [[ -n "$line" ]]; then
            path_lines=$((path_lines + 1))
            if [[ $path_lines -eq 1 ]]; then
              approval_path="$line"
            elif [[ $path_lines -eq 2 && $rc -eq 3 ]]; then
              warn_ack_path="$line"
            else
              malformed_stdout=1
            fi
          fi
        done < "$stdout_file"
        _tirith_remove_capture_file "$stdout_file" >/dev/null 2>&1 || malformed_stdout=1
        if [[ $malformed_stdout -ne 0 ]]; then
          [[ -n "$approval_path" ]] && _tirith_remove_capture_file "$approval_path" >/dev/null 2>&1
          [[ -n "$warn_ack_path" ]] && _tirith_remove_capture_file "$warn_ack_path" >/dev/null 2>&1
          _tirith_degrade_to_preexec "invalid legacy check response"
          return
        fi
      fi
      local approval_outcome="" warn_acknowledged="no"

      # Protocol v3 has already finalized approvals/warn acknowledgement and
      # returned an armed token. Only an unnegotiated legacy binary may enter
      # the temp-path parsing and prompt workflow below.
      if [[ $_TIRITH_RECEIPT_PROTOCOL -ne 3 ]]; then
        if [[ $rc -eq 0 ]]; then
          :  # Allow: no output
        elif [[ $rc -eq 2 || $rc -eq 3 ]]; then
          local escaped_line
          escaped_line=$(_tirith_escape_preview "$READLINE_LINE")
          _tirith_output ""
          _tirith_output "command> $escaped_line"
          [[ -n "$output" ]] && _tirith_output "$output"
        elif [[ $rc -eq 1 ]]; then
          local escaped_line
          escaped_line=$(_tirith_escape_preview "$READLINE_LINE")
          _tirith_output ""
          _tirith_output "command> $escaped_line"
          [[ -n "$output" ]] && _tirith_output "$output"
        else
          # Unexpected exit code: degrade to preexec
          local escaped_line
          escaped_line=$(_tirith_escape_preview "$READLINE_LINE")
          _tirith_output ""
          _tirith_output "command> $escaped_line"
          [[ -n "$output" ]] && _tirith_output "$output"
          [[ -n "$approval_path" ]] && _tirith_remove_capture_file "$approval_path" >/dev/null 2>&1
          [[ -n "$warn_ack_path" ]] && _tirith_remove_capture_file "$warn_ack_path" >/dev/null 2>&1
          _tirith_receipt_discard bash-enter "$receipt_token"
          _tirith_degrade_to_preexec "tirith returned unexpected exit code $rc"
          return  # READLINE_LINE preserved for re-execution via preexec
        fi

        # Approval workflow: runs for ALL exit codes (0, 1, 2, 3).
        # For rc=1 (block), approval gives user a chance to override.
        if [[ -n "$approval_path" ]]; then
          _tirith_parse_approval "$approval_path"
          if [[ "$_tirith_ap_required" == "yes" ]]; then
            _tirith_output "tirith: approval required for $_tirith_ap_rule"
            [[ -n "$_tirith_ap_desc" ]] && _tirith_output "  $_tirith_ap_desc"
            local response=""
            local approval_read_rc=0
            if [[ "$_tirith_ap_timeout" -gt 0 ]]; then
              read -t "$_tirith_ap_timeout" -p "Approve? (${_tirith_ap_timeout}s timeout) [y/N] " response </dev/tty 2>/dev/null || approval_read_rc=$?
            else
              read -p "Approve? [y/N] " response </dev/tty 2>/dev/null || approval_read_rc=$?
            fi
            if [[ "$response" == [yY]* ]]; then
              approval_outcome="granted"
            else
              if [[ "$_tirith_ap_timeout" -gt 0 && $approval_read_rc -ne 0 ]]; then
                approval_outcome="timed-out"
              else
                approval_outcome="rejected"
              fi
              case "$_tirith_ap_fallback" in
                allow)
                  _tirith_output "tirith: approval not granted — fallback: allow"
                  ;;
                warn)
                  _tirith_output "tirith: approval not granted — fallback: warn"
                  ;;
                *)
                  _tirith_output "tirith: approval not granted — fallback: block"
                  [[ -n "$warn_ack_path" ]] && _tirith_remove_capture_file "$warn_ack_path" >/dev/null 2>&1
                  _tirith_receipt_discard bash-enter "$receipt_token"
                  READLINE_LINE=""
                  READLINE_POINT=0
                  return
                  ;;
              esac
            fi
          elif [[ $rc -eq 1 ]]; then
            # Approval not required but command was blocked: honor block
            [[ -n "$warn_ack_path" ]] && _tirith_remove_capture_file "$warn_ack_path" >/dev/null 2>&1
            _tirith_receipt_discard bash-enter "$receipt_token"
            READLINE_LINE=""
            READLINE_POINT=0
            return
          fi
        elif [[ $rc -eq 1 ]]; then
          # No approval file: honor block
          _tirith_receipt_discard bash-enter "$receipt_token"
          READLINE_LINE=""
          READLINE_POINT=0
          return
        fi

        # Warn-ack workflow (exit code 3): strict_warn requires explicit acknowledgement
        if [[ $rc -eq 3 && -n "$warn_ack_path" ]]; then
          if ! _tirith_parse_warn_ack "$warn_ack_path"; then
            _tirith_receipt_discard bash-enter "$receipt_token"
            _tirith_output "tirith: warning acknowledgement metadata is invalid; command blocked"
            READLINE_LINE=""
            READLINE_POINT=0
            return
          fi
          local response=""
          read -p "tirith: proceed with ${_tirith_wa_findings} warning(s)? [y/N] " response </dev/tty 2>/dev/null
          if [[ "$response" == [yY]* ]]; then
            warn_acknowledged="yes"
          else
            _tirith_output "tirith: warnings not acknowledged — command blocked"
            _tirith_receipt_discard bash-enter "$receipt_token"
            READLINE_LINE=""
            READLINE_POINT=0
            return
          fi
        elif [[ -n "$warn_ack_path" ]]; then
          _tirith_remove_capture_file "$warn_ack_path" >/dev/null 2>&1
        fi
      fi

      # Execute the command (approval workflow above handled block cases)
      local cmd="$READLINE_LINE"
      READLINE_LINE=""
      READLINE_POINT=0
      # The full buffer already passed Bash's syntax check above. Passing it as
      # one quoted argument to the builtin preserves multiline/heredoc/compound
      # syntax without a source file, process-substitution race, or disk copy.
      if _tirith_unsafe_to_eval "$cmd"; then
        _tirith_queue_enter_delivery "$cmd" "$receipt_token"
        return $?
      fi

      _tirith_queue_enter_delivery "$cmd" "$receipt_token"
      return $?
    }

    # Bracketed paste interception
    _tirith_paste() {
      # Save terminal state — bind -x can corrupt echo in some PTY environments (gcloud ssh, etc.)
      local _saved_stty
      if [[ -n "$_TIRITH_STTY_BIN" ]]; then
        _saved_stty="$(builtin command "$_TIRITH_STTY_BIN" -g 2>/dev/null)" || _saved_stty=""
      fi
      builtin trap '_tirith_restore_terminal_state "$_saved_stty"' RETURN

      # Read pasted content until bracketed paste end sequence (\e[201~)
      local pasted=""
      local char
      while IFS= read -r -n 1 -d '' -t 1 char; do
        pasted+="$char"
        # Check for end of bracketed paste
        if [[ "$pasted" == *$'\e[201~' ]]; then
          # Strip the end sequence
          pasted="${pasted%$'\e[201~'}"
          break
        fi
      done

      if [[ -n "$pasted" ]]; then
        # Check with tirith paste, use temp file to prevent tty leakage
        local tmpfile
        tmpfile="$(_tirith_new_capture_file 2>/dev/null)" || {
          _tirith_output "tirith: paste check failed (could not create private output capture)"
          return
        }
        local _tirith_prev_internal="${_TIRITH_BASH_INTERNAL:-0}"
        _TIRITH_BASH_INTERNAL=1
        printf '%s' "$pasted" | builtin command "$_TIRITH_BIN" paste --shell posix --interactive >|"$tmpfile" 2>&1
        local rc=$?
        _TIRITH_BASH_INTERNAL="$_tirith_prev_internal"
        local output=$(<"$tmpfile")
        _tirith_remove_capture_file "$tmpfile" >/dev/null 2>&1

        if [[ $rc -eq 0 ]]; then
          # Allow: fall through to insert
          :
        elif [[ $rc -eq 2 ]]; then
          # Warn: show warning, fall through to insert
          [[ -n "$output" ]] && { _tirith_output ""; _tirith_output "$output"; }
        else
          # Block (rc=1) or unexpected: discard paste (safe — user can re-paste)
          local escaped_paste
          escaped_paste=$(_tirith_escape_preview "$pasted")
          _tirith_output ""
          _tirith_output "paste> $escaped_paste"
          [[ -n "$output" ]] && _tirith_output "$output"
          [[ $rc -ne 1 ]] && _tirith_output "tirith: paste check failed (exit code $rc)"
          return
        fi
      fi

      # Allow: insert into readline buffer
      READLINE_LINE="${READLINE_LINE:0:$READLINE_POINT}${pasted}${READLINE_LINE:$READLINE_POINT}"
      READLINE_POINT=$((READLINE_POINT + ${#pasted}))
    }

    # Macro-dispatch delivery (issues #111, #224). A bare `bind -x` on Enter
    # runs the checker but does NOT then accept the line on stock bash, so the
    # stashed command was silently eaten and the hook degraded to preexec. Bind
    # Enter to a MACRO that runs the checker and then a GUARDED accept-line: the
    # accept sub-sequence is a no-op until `_tirith_enter` arms it, so a line is
    # only accepted once the checker has decided to deliver it (the prompt hook
    # then evaluates the stashed command, exactly as before). A raw injection of
    # the accept bytes hits the disarmed no-op, and every prompt re-disarms it,
    # so possession of the accept sequence alone can never accept a line.
    _TIRITH_ENTER_CHECK_KEYS='\C-x\C-t7'
    _TIRITH_ENTER_ACCEPT_KEYS='\C-x\C-r7'
    _tirith_enter_accept_noop() { :; }
    _tirith_enter_arm_accept() {
      local _tirith_keymap _tirith_bind_rc=0
      for _tirith_keymap in "${_TIRITH_PROTECTED_KEYMAPS[@]}"; do
        builtin bind -m "$_tirith_keymap" \
          "\"$_TIRITH_ENTER_ACCEPT_KEYS\": accept-line" 2>/dev/null \
          || _tirith_bind_rc=1
      done
      return "$_tirith_bind_rc"
    }
    _tirith_enter_disarm_accept() {
      local _tirith_keymap _tirith_bind_rc=0
      for _tirith_keymap in "${_TIRITH_PROTECTED_KEYMAPS[@]}"; do
        builtin bind -m "$_tirith_keymap" -x \
          "\"$_TIRITH_ENTER_ACCEPT_KEYS\": _tirith_enter_accept_noop" 2>/dev/null \
          || _tirith_bind_rc=1
      done
      return "$_tirith_bind_rc"
    }

    if ! _tirith_capture_ctrl_o_bindings; then
      _tirith_degrade_to_preexec "could not preserve existing Ctrl-O bindings"
    else
      # Install checker, guarded accept, Enter macros, paste interception, and
      # Ctrl-O closure in every keymap a live session can switch to.
      _tirith_bind_install_ok=1
      for _tirith_keymap in "${_TIRITH_PROTECTED_KEYMAPS[@]}"; do
        builtin bind -m "$_tirith_keymap" -x \
          "\"$_TIRITH_ENTER_CHECK_KEYS\": _tirith_enter" || _tirith_bind_install_ok=0
        builtin bind -m "$_tirith_keymap" \
          "\"\C-m\": \"$_TIRITH_ENTER_CHECK_KEYS$_TIRITH_ENTER_ACCEPT_KEYS\"" \
          || _tirith_bind_install_ok=0
        builtin bind -m "$_tirith_keymap" \
          "\"\C-j\": \"$_TIRITH_ENTER_CHECK_KEYS$_TIRITH_ENTER_ACCEPT_KEYS\"" \
          || _tirith_bind_install_ok=0
        builtin bind -m "$_tirith_keymap" -x '"\e[200~": _tirith_paste' \
          || _tirith_bind_install_ok=0
        # operate-and-get-next accepts the current line without the checker.
        builtin bind -m "$_tirith_keymap" -r '\C-o' 2>/dev/null \
          || _tirith_bind_install_ok=0
      done
      _tirith_enter_disarm_accept || _tirith_bind_install_ok=0
      _TIRITH_BINDS_INSTALLED=1

      # Startup health gate: verify every protected keymap took effect.
      if [[ "$_tirith_bind_install_ok" != "1" ]] || ! _tirith_startup_health_check; then
        _tirith_degrade_to_preexec "startup health check failed (enter macro or PROMPT_COMMAND)"
      fi
      unset _tirith_keymap _tirith_bind_install_ok
    fi
  fi

fi

# Exit summary: show session warnings on shell exit
_tirith_exit_summary() {
  _tirith_discard_pending_debug_trap_capture
  if _tirith_capture_file_is_private "${_TIRITH_DEBUG_OWNERSHIP_FILE:-}"; then
    _tirith_remove_capture_file "$_TIRITH_DEBUG_OWNERSHIP_FILE" >/dev/null 2>&1 || true
  fi
  _TIRITH_DEBUG_OWNERSHIP_FILE=""
  local pending_receipt="${_TIRITH_PENDING_RECEIPT:-}"
  unset _TIRITH_PENDING_EVAL
  unset _TIRITH_PENDING_RECEIPT _TIRITH_PENDING_COMMAND
  [[ -n "$pending_receipt" ]] && _tirith_receipt_discard bash-enter "$pending_receipt"
  [[ -n "${TIRITH_SESSION_ID:-}" ]] || return
  local _sd="${XDG_STATE_HOME:-$HOME/.local/state}/tirith"
  [[ -f "$_sd/sessions/$TIRITH_SESSION_ID.json" ]] || return
  builtin command "$_TIRITH_BIN" warnings --summary
}

_tirith_exit_trampoline() {
  if [[ -n "${_TIRITH_PREV_EXIT_TRAP:-}" ]]; then
    builtin eval -- "$_TIRITH_PREV_EXIT_TRAP" || true
  fi
  _tirith_exit_summary
}

_tirith_prev_exit_spec="$(builtin trap -p EXIT 2>/dev/null)"
_TIRITH_PREV_EXIT_TRAP=""
if _tirith_extract_trap_body "$_tirith_prev_exit_spec" EXIT; then
  _TIRITH_PREV_EXIT_TRAP="$_TIRITH_EXTRACTED_TRAP"
fi
if [[ -n "$_TIRITH_PREV_EXIT_TRAP" ]]; then
  builtin trap '_tirith_exit_trampoline' EXIT
else
  builtin trap '_tirith_exit_summary' EXIT
fi
unset _tirith_prev_exit_spec _TIRITH_EXTRACTED_TRAP

# Preexec's first prompt captures and chains the caller's DEBUG trap before the
# shell can accept another user command. Enter mode leaves DEBUG untouched;
# its runtime fallback installs the same prompt bootstrap on demand.

# ── tirith output wrap (M7 ch1) ─────────────────────────────────────────────
# Opt-in output-direction wrapper. Commented out by default in this embedded
# hook copy; `tirith output wrap on` writes an active copy of the function
# into the user's shell-profile separately. This block is kept here as the
# canonical source so a user reading the hook understands the surface area.
#
# Scope honesty: this wraps INDIVIDUAL commands invoked via `tirith-out
# <cmd>`. It does NOT intercept output from anything run outside the wrapper.
#
# tirith-output-guard-wrap() {
#   if [[ "$#" -eq 0 ]]; then
#     printf 'tirith-output-guard-wrap: usage: tirith-out <cmd> [args...]\n' >&2
#     return 2
#   fi
#   "$@" 2>&1 | command tirith view --max-bytes 16777216 -
# }
# alias tirith-out='tirith-output-guard-wrap'
else
  # A readonly or otherwise hostile POSIXLY_CORRECT can deny the only
  # grammar-level path to trusted builtin lookup. Skip the entire hook body and
  # publish no protection claim; an absolute executable is immune to function
  # and alias shadowing, so the interactive failure remains visible.
  TIRITH_STATUS=off
  # Do not invoke `export` here: this branch exists because builtin identity is
  # untrusted, and an imported `export` function could run attacker code. An
  # inherited exported effective-state variable retains its export attribute
  # when assigned, so child processes cannot keep a stale active value.
  TIRITH_BASH_EFFECTIVE_MODE=off
  TIRITH_BASH_EFFECTIVE_PROTECTION=off
  if [[ $- == *i* ]]; then
    if [[ -x /usr/bin/printf ]]; then
      /usr/bin/printf '%s\n' 'tirith: bash hooks disabled because trusted builtin lookup could not be established' >&2
    elif [[ -x /bin/printf ]]; then
      /bin/printf '%s\n' 'tirith: bash hooks disabled because trusted builtin lookup could not be established' >&2
    fi
  fi
fi