fno-agents 0.3.1

PTY supervisor substrate for persistent, attachable multi-CLI coding agents (codex, gemini, claude)
Documentation
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
//! Detection manifest engine (E6.2).
//!
//! E6.1 ([`crate::osc`], [`crate::screen`]) gave the read loop OSC title/progress
//! as detection regions on a [`ScreenView`]. This module is the engine that turns
//! a declarative TOML rule file into a state verdict over that view, so an agent's
//! readiness rules live in a `*.toml` (authored in E6.3) instead of hardcoded Rust
//! ([`crate::readiness`]).
//!
//! A manifest is a priority-ordered list of [`ManifestRule`]s. Each rule names a
//! text [`Region`] of the screen and a recursive boolean [`Gate`] over that
//! region's text, plus an optional context region/gate for surrounding evidence
//! that should not expand the answer fingerprint window. [`Manifest::evaluate`]
//! returns the highest-priority matching rule's `state` (and its
//! `skip_state_update` flag) - so a "yes" buried in scrollback never out-votes a
//! live-region rule that out-prioritizes it.
//!
//! Scope: E6.2 built the parser + region vocabulary + gate evaluator + priority
//! arbiter; E6.3 added the bundled `claude.toml`/`codex.toml`/`gemini.toml` rule
//! files and the [`load_manifest`] resolution chain (bundled + local override).
//! Still NOT wired into the runtime: the daemon state badge consumes
//! [`Manifest::evaluate`] only once E2 lands live claude panes to tune against.
//! Remote/cached/version-gated resolution is a logged fast-follow
//! (`min_engine_version` is parsed now so a later remote manifest can gate, but
//! is otherwise unused).
//!
//! ponytail: a rule's regexes recompile on each `evaluate` (regions are tiny,
//! evaluate runs at human-perception cadence on readiness polls); cache compiled
//! `Regex`es per rule if a profiler ever flags it. The `prompt_box_body` region
//! and `skip_state_update`/priority semantics are tuned against the reference design,
//! not yet against a live claude TUI (E6.3's job).

use crate::readiness::ScreenView;
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Max nesting depth for a [`Gate`] tree. A pathological manifest (deeply nested
/// `all`/`any`/`not`) is refused while building the [`Gate`] so `evaluate`'s
/// recursion is bounded. 16 is far past any real rule (the reference's deepest is ~3).
///
/// Note: this caps OUR tree-walk, not `toml::from_str`, which builds the nested
/// `toml::Value` first. For locally-authored (trusted) manifests that is fine;
/// when remote/cached resolution lands (the logged fast-follow) the input must be
/// nesting-bounded BEFORE `toml::from_str`. Tracked as a carveout.
const MAX_GATE_DEPTH: usize = 16;

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ManifestError {
    #[error("manifest is not valid TOML: {0}")]
    Toml(String),
    #[error("manifest io error for {path}: {detail}")]
    Io { path: String, detail: String },
    #[error("rule {rule}: missing or wrong-typed field '{field}'")]
    Field { rule: String, field: String },
    #[error("rule {rule}: unknown region selector '{region}'")]
    UnknownRegion { rule: String, region: String },
    #[error("rule {rule}: bad regex '{pattern}': {detail}")]
    BadRegex {
        rule: String,
        pattern: String,
        detail: String,
    },
    #[error("rule {rule}: gate nested deeper than {max}", max = MAX_GATE_DEPTH)]
    GateTooDeep { rule: String },
    #[error(
        "rule {rule}: gate table must have exactly one of contains/regex/line_regex/all/any/not"
    )]
    BadGate { rule: String },
}

/// A text region of the screen a rule's gate is matched against. `osc_title` /
/// `osc_progress` read the OSC-captured strings (which survive scrollback/wrap/
/// resize); the rest read the grid text. The v1 set is the design's recommended
/// minimum; `after_last_horizontal_rule` / `after_last_prompt_marker` are
/// deferred until a rule needs them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Region {
    /// The whole visible screen (scrollback already trimmed by the snapshot).
    WholeRecent,
    /// The last `N` non-empty lines, joined by `\n`. Where a CLI draws its
    /// composer + status bar; scopes a match away from scrollback.
    BottomNonEmptyLines(usize),
    /// The body of the last box-drawn input box (claude's composer). Empty when
    /// no box is on screen.
    PromptBoxBody,
    /// The latest OSC window title (OSC 0/2). Empty when none captured.
    OscTitle,
    /// The latest OSC 9;4 progress payload. Empty when none captured.
    OscProgress,
}

impl Region {
    /// Parse a region selector string. `rule` only seasons the error.
    fn parse(s: &str, rule: &str) -> Result<Region, ManifestError> {
        if let Some(arg) = s
            .strip_prefix("bottom_non_empty_lines(")
            .and_then(|r| r.strip_suffix(')'))
        {
            let n = arg
                .trim()
                .parse::<usize>()
                .map_err(|_| ManifestError::Field {
                    rule: rule.to_string(),
                    field: "region (bottom_non_empty_lines arg)".to_string(),
                })?;
            if n == 0 {
                // bottom(0) is an empty region: a degenerate rule that never
                // fires. Reject it rather than silently never-match (fail closed).
                return Err(ManifestError::Field {
                    rule: rule.to_string(),
                    field: "region (bottom_non_empty_lines arg must be > 0)".to_string(),
                });
            }
            return Ok(Region::BottomNonEmptyLines(n));
        }
        match s {
            "whole_recent" => Ok(Region::WholeRecent),
            "prompt_box_body" => Ok(Region::PromptBoxBody),
            "osc_title" => Ok(Region::OscTitle),
            "osc_progress" => Ok(Region::OscProgress),
            _ => Err(ManifestError::UnknownRegion {
                rule: rule.to_string(),
                region: s.to_string(),
            }),
        }
    }

    /// Extract this region's text from a screen view. An absent OSC region is the
    /// empty string, so a `contains`/`regex` over it never matches (correct: no
    /// title means no spinner) while `not(...)` over it reads as "vacuously true".
    fn extract(&self, screen: &ScreenView) -> String {
        match self {
            Region::WholeRecent => screen.visible_text.to_string(),
            Region::BottomNonEmptyLines(n) => {
                let nonblank: Vec<&str> = screen
                    .visible_text
                    .lines()
                    .filter(|l| !l.trim().is_empty())
                    .collect();
                let start = nonblank.len().saturating_sub(*n);
                nonblank[start..].join("\n")
            }
            Region::PromptBoxBody => prompt_box_body(screen.visible_text),
            Region::OscTitle => screen.osc_title.unwrap_or("").to_string(),
            Region::OscProgress => screen.osc_progress.unwrap_or("").to_string(),
        }
    }
}

/// Pull the body out of the last box-drawn input box. claude's composer is a
/// `╭─╮ / │ … │ / ╰─╯` box; the body is the `│`-bordered lines between the last
/// bottom border (`╰`) and its nearest preceding top border (`╭`), with the
/// vertical borders stripped. Returns "" when no complete box is present.
///
/// ponytail: a single-heuristic box finder, tuned to claude's box-drawing glyphs;
/// it does not handle nested boxes or ASCII `+--+` frames, and it does NOT yet
/// distinguish the live composer from a box-drawn TABLE up in scrollback - it just
/// takes the bottommost `╰`/`╭` pair, so a scrollback table can be extracted as
/// stale "prompt body" and let a rule false-match (codex peer P2). Disambiguating
/// composer-vs-scrollback needs ground truth (the box near the status area / on the
/// cursor row) against a live claude TUI; deliberately not guessed here. E6.3's
/// `claude.toml` `live_prompt_box` rule consumes this region, so that
/// disambiguation is its load-bearing follow-up (carveout, pinned when E2 lands).
fn prompt_box_body(text: &str) -> String {
    let lines: Vec<&str> = text.lines().collect();
    let Some(bottom) = lines.iter().rposition(|l| l.contains('')) else {
        return String::new();
    };
    let Some(top) = lines[..bottom].iter().rposition(|l| l.contains('')) else {
        return String::new();
    };
    lines[top + 1..bottom]
        .iter()
        .map(|l| l.trim().trim_matches('').trim().to_string())
        .collect::<Vec<_>>()
        .join("\n")
}

/// A recursive boolean predicate over a region's text. Leaf predicates test the
/// region string; `all`/`any`/`not` compose them. Regexes are compiled at parse,
/// so a constructed `Gate` is always valid.
#[derive(Debug, Clone)]
pub enum Gate {
    /// Region contains this substring.
    Contains(String),
    /// Region matches this regex anywhere (use `^`/`$` to anchor).
    Regex(Regex),
    /// Any single line of the region matches this regex.
    LineRegex(Regex),
    /// Every sub-gate matches.
    All(Vec<Gate>),
    /// At least one sub-gate matches.
    Any(Vec<Gate>),
    /// The sub-gate does not match.
    Not(Box<Gate>),
}

impl Gate {
    /// Build a gate from a TOML value. The value must be a table with exactly one
    /// recognized key. `depth` guards against pathological nesting.
    fn parse(v: &toml::Value, rule: &str, depth: usize) -> Result<Gate, ManifestError> {
        if depth > MAX_GATE_DEPTH {
            return Err(ManifestError::GateTooDeep {
                rule: rule.to_string(),
            });
        }
        let table = v.as_table().ok_or_else(|| ManifestError::BadGate {
            rule: rule.to_string(),
        })?;
        if table.len() != 1 {
            return Err(ManifestError::BadGate {
                rule: rule.to_string(),
            });
        }
        let (key, val) = table.iter().next().expect("len checked == 1");
        let compile = |p: &str| {
            Regex::new(p).map_err(|e| ManifestError::BadRegex {
                rule: rule.to_string(),
                pattern: p.to_string(),
                detail: e.to_string(),
            })
        };
        let as_str = || {
            val.as_str().ok_or_else(|| ManifestError::Field {
                rule: rule.to_string(),
                field: format!("gate.{key}"),
            })
        };
        // An empty leaf pattern is fail-open the same way `all = []` is:
        // `"".contains("")` and `Regex::new("")` both match every region, pinning
        // the rule's state on every poll. Reject empty leaves at parse.
        let leaf_str = || {
            let s = as_str()?;
            if s.is_empty() {
                return Err(ManifestError::Field {
                    rule: rule.to_string(),
                    field: format!("gate.{key} (must be non-empty)"),
                });
            }
            Ok(s)
        };
        let as_array = || {
            val.as_array().ok_or_else(|| ManifestError::Field {
                rule: rule.to_string(),
                field: format!("gate.{key}"),
            })
        };
        match key.as_str() {
            "contains" => Ok(Gate::Contains(leaf_str()?.to_string())),
            "regex" => Ok(Gate::Regex(compile(leaf_str()?)?)),
            "line_regex" => Ok(Gate::LineRegex(compile(leaf_str()?)?)),
            "all" => Ok(Gate::All(Self::parse_children(as_array()?, rule, depth)?)),
            "any" => Ok(Gate::Any(Self::parse_children(as_array()?, rule, depth)?)),
            "not" => Ok(Gate::Not(Box::new(Gate::parse(val, rule, depth + 1)?))),
            _ => Err(ManifestError::BadGate {
                rule: rule.to_string(),
            }),
        }
    }

    fn parse_children(
        arr: &[toml::Value],
        rule: &str,
        depth: usize,
    ) -> Result<Vec<Gate>, ManifestError> {
        // An empty `all`/`any` is fail-open: `all([])` matches every screen
        // (vacuous truth), so a high-priority rule with `all = []` would pin its
        // state on every poll. Reject it at parse rather than mis-fire silently.
        if arr.is_empty() {
            return Err(ManifestError::BadGate {
                rule: rule.to_string(),
            });
        }
        arr.iter()
            .map(|child| Gate::parse(child, rule, depth + 1))
            .collect()
    }

    /// Evaluate against a region's text.
    fn matches(&self, text: &str) -> bool {
        match self {
            Gate::Contains(s) => text.contains(s.as_str()),
            Gate::Regex(re) => re.is_match(text),
            Gate::LineRegex(re) => text.lines().any(|l| re.is_match(l)),
            Gate::All(gs) => gs.iter().all(|g| g.matches(text)),
            Gate::Any(gs) => gs.iter().any(|g| g.matches(text)),
            Gate::Not(g) => !g.matches(text),
        }
    }
}

/// How a chosen option's captured index becomes PTY bytes. The entire v1
/// vocabulary (Locked 4): numbered permission prompts, no arrow-navigation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SendMapping {
    /// Send the captured `idx` as one ASCII byte.
    Digit,
    /// Send the captured `idx` then CR.
    DigitEnter,
}

/// The optional `[rule.answer]` grammar on a `blocked` rule: how to enumerate a
/// numbered prompt's options and how a picked option becomes a keystroke. Its
/// presence is what makes a blocked prompt *answerable* (its absence means
/// blocked-but-not-answerable, which the queue shows as focus-only).
#[derive(Debug, Clone)]
struct AnswerGrammar {
    /// One option per line the regex matches; must name `idx` + `label` captures.
    option: Regex,
    send: SendMapping,
}

/// One selectable option of an answerable prompt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnswerOption {
    /// The captured menu index the operator presses, e.g. "1".
    pub idx: String,
    /// The display label (untruncated; the client truncates for width).
    pub label: String,
    /// The exact PTY bytes to inject for this pick, pinned by the manifest's
    /// `send` mapping over `idx` - NEVER a runtime guess (Locked 2).
    pub keystroke: Vec<u8>,
}

/// A blocked prompt the operator can answer from the queue without focusing the
/// pane. Produced by [`ManifestRule::extract_answer`] and carried on the badge
/// to the sideline; the mux server re-verifies `fingerprint` against its live
/// grid before injecting a chosen option's `keystroke` (Locked 3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnswerablePrompt {
    /// The lines above the first option, display-only.
    pub prompt: String,
    pub options: Vec<AnswerOption>,
    /// blake3 of the region text the human reads - the server's freshness key.
    pub fingerprint: [u8; 32],
    /// The N of `bottom_non_empty_lines(N)`, so the server re-reads the same
    /// region window to re-hash.
    pub region_lines: usize,
}

impl AnswerGrammar {
    /// Parse a `[rule.answer]` table. Fails loud (like every manifest field): an
    /// answer grammar is meaningful ONLY on a `state = "blocked"` rule whose
    /// region is a `bottom_non_empty_lines(N)` window (so the server can re-read
    /// the same lines to re-hash). Either mismatch is a config bug, never ignored.
    fn parse(
        v: &toml::Value,
        rule: &str,
        state: &str,
        region: &Region,
    ) -> Result<AnswerGrammar, ManifestError> {
        if state != "blocked" {
            return Err(ManifestError::Field {
                rule: rule.to_string(),
                field: "answer (only allowed on a state = \"blocked\" rule)".to_string(),
            });
        }
        if !matches!(region, Region::BottomNonEmptyLines(_)) {
            return Err(ManifestError::Field {
                rule: rule.to_string(),
                field: "answer (region must be bottom_non_empty_lines(N))".to_string(),
            });
        }
        let table = v.as_table().ok_or_else(|| ManifestError::Field {
            rule: rule.to_string(),
            field: "answer (must be a table)".to_string(),
        })?;
        const ALLOWED: &[&str] = &["option", "send"];
        if let Some(unknown) = table.keys().find(|k| !ALLOWED.contains(&k.as_str())) {
            return Err(ManifestError::Field {
                rule: rule.to_string(),
                field: format!("answer unknown key '{unknown}'"),
            });
        }
        let option_pat = table
            .get("option")
            .and_then(|x| x.as_str())
            .ok_or_else(|| ManifestError::Field {
                rule: rule.to_string(),
                field: "answer.option".to_string(),
            })?;
        let option = Regex::new(option_pat).map_err(|e| ManifestError::BadRegex {
            rule: rule.to_string(),
            pattern: option_pat.to_string(),
            detail: e.to_string(),
        })?;
        // extract_answer reads the captures by name, so both must exist - a
        // missing `idx`/`label` group is a parse-time config error, not a
        // runtime None that would silently make every blocked prompt focus-only.
        let names: Vec<&str> = option.capture_names().flatten().collect();
        for need in ["idx", "label"] {
            if !names.contains(&need) {
                return Err(ManifestError::Field {
                    rule: rule.to_string(),
                    field: format!("answer.option (missing named capture '{need}')"),
                });
            }
        }
        let send = match table.get("send").and_then(|x| x.as_str()) {
            Some("digit") => SendMapping::Digit,
            Some("digit_enter") => SendMapping::DigitEnter,
            _ => {
                return Err(ManifestError::Field {
                    rule: rule.to_string(),
                    field: "answer.send (must be \"digit\" or \"digit_enter\")".to_string(),
                })
            }
        };
        Ok(AnswerGrammar { option, send })
    }
}

/// One detection rule: when `gate` matches `region` and the optional contextual
/// gate also matches, the agent is in `state`. `priority` arbitrates between
/// simultaneously-matching rules (highest wins). `skip_state_update` marks a
/// rule whose match means "hold the current state, don't update it" - e.g.
/// claude's ctrl+o transcript pager, which must not flip a working agent to idle.
/// `answer` (x-c929) makes a `blocked` prompt answerable from the queue.
#[derive(Debug, Clone)]
pub struct ManifestRule {
    pub id: String,
    pub state: String,
    pub priority: i32,
    pub region: Region,
    pub skip_state_update: bool,
    pub gate: Gate,
    context: Option<(Region, Gate)>,
    answer: Option<AnswerGrammar>,
}

impl ManifestRule {
    /// Match the rule's live answer region plus any wider contextual guard.
    /// The returned text is always the primary region: answer extraction and
    /// fingerprinting stay scoped to the small menu window even when detection
    /// needs context elsewhere on the visible screen.
    fn matched_region_text(&self, screen: &ScreenView) -> Option<String> {
        let text = self.region.extract(screen);
        if !self.gate.matches(&text) {
            return None;
        }
        if let Some((region, gate)) = &self.context {
            let context = region.extract(screen);
            if !gate.matches(&context) {
                return None;
            }
        }
        Some(text)
    }

    /// Enumerate this rule's answerable options from `region_text`, fail-closed.
    /// Returns `None` (blocked-but-not-answerable) unless the rule carries an
    /// `[answer]` grammar AND the region yields a clean numbered menu: >=1
    /// option, non-empty labels, and single-digit indices forming a contiguous
    /// `1..N` run. A lowest index != 1 means the menu top scrolled past the
    /// region window (truncated) and is not answerable (AC3-EDGE). Strictly
    /// additive to detection: any miss leaves the blocked badge untouched.
    pub fn extract_answer(&self, region_text: &str) -> Option<AnswerablePrompt> {
        let grammar = self.answer.as_ref()?;
        // Parse enforces a bottom-N region on any answer grammar; be defensive.
        let Region::BottomNonEmptyLines(n) = self.region else {
            return None;
        };
        let mut options: Vec<AnswerOption> = Vec::new();
        let mut first_option_line: Option<usize> = None;
        for (i, line) in region_text.lines().enumerate() {
            let Some(caps) = grammar.option.captures(line) else {
                continue;
            };
            let idx = caps.name("idx")?.as_str().to_string();
            let label = caps.name("label")?.as_str().trim().to_string();
            // One ASCII digit only (send maps one digit to one byte); a 2-digit
            // or non-digit index, or an empty label, is not answerable in v1.
            if idx.len() != 1 || !idx.as_bytes()[0].is_ascii_digit() || label.is_empty() {
                return None;
            }
            if first_option_line.is_none() {
                first_option_line = Some(i);
            }
            let mut keystroke = vec![idx.as_bytes()[0]];
            if matches!(grammar.send, SendMapping::DigitEnter) {
                keystroke.push(b'\r');
            }
            options.push(AnswerOption {
                idx,
                label,
                keystroke,
            });
        }
        if options.is_empty() {
            return None;
        }
        // The indices must be exactly {1, 2, ..., N}: unique, contiguous, and
        // starting at 1. This one check rejects duplicates (AC3-ERR), gaps, and
        // a truncated menu whose first captured option is `2.`/`3.` (AC3-EDGE).
        let mut idxs: Vec<u8> = options.iter().map(|o| o.idx.as_bytes()[0] - b'0').collect();
        idxs.sort_unstable();
        let expected: Vec<u8> = (1..=options.len() as u8).collect();
        if idxs != expected {
            return None;
        }
        let first = first_option_line.unwrap_or(0);
        let prompt = region_text
            .lines()
            .take(first)
            .collect::<Vec<_>>()
            .join("\n");
        let fingerprint = *blake3::hash(region_text.as_bytes()).as_bytes();
        Some(AnswerablePrompt {
            prompt,
            options,
            fingerprint,
            region_lines: n,
        })
    }
}

impl ManifestRule {
    fn parse(v: &toml::Value) -> Result<ManifestRule, ManifestError> {
        // id is read first so every later error can name the rule.
        let id = v
            .get("id")
            .and_then(|x| x.as_str())
            .ok_or_else(|| ManifestError::Field {
                rule: "<unnamed>".to_string(),
                field: "id".to_string(),
            })?
            .to_string();
        if id.trim().is_empty() {
            // The id seasons every error and rides in the Verdict; an empty one
            // makes both useless. Require it non-blank.
            return Err(ManifestError::Field {
                rule: "<unnamed>".to_string(),
                field: "id (must be non-empty)".to_string(),
            });
        }
        let str_field = |f: &str| {
            v.get(f)
                .and_then(|x| x.as_str())
                .ok_or_else(|| ManifestError::Field {
                    rule: id.clone(),
                    field: f.to_string(),
                })
        };
        let state = str_field("state")?.to_string();
        let priority_i64 = v
            .get("priority")
            .and_then(|x| x.as_integer())
            .ok_or_else(|| ManifestError::Field {
                rule: id.clone(),
                field: "priority".to_string(),
            })?;
        // TOML integers are i64; `as i32` would silently wrap a too-big priority
        // and corrupt arbitration. Reject out-of-range rather than truncate.
        let priority = i32::try_from(priority_i64).map_err(|_| ManifestError::Field {
            rule: id.clone(),
            field: "priority (out of i32 range)".to_string(),
        })?;
        let region = Region::parse(str_field("region")?, &id)?;
        // Present-but-wrong-type (e.g. `skip_state_update = "true"`) must error,
        // not silently read as false and swallow an authoring typo.
        let skip_state_update = match v.get("skip_state_update") {
            None => false,
            Some(x) => x.as_bool().ok_or_else(|| ManifestError::Field {
                rule: id.clone(),
                field: "skip_state_update (must be a boolean)".to_string(),
            })?,
        };
        let gate_val = v.get("gate").ok_or_else(|| ManifestError::Field {
            rule: id.clone(),
            field: "gate".to_string(),
        })?;
        let gate = Gate::parse(gate_val, &id, 0)?;
        let context = match (v.get("context_region"), v.get("context_gate")) {
            (None, None) => None,
            (Some(region), Some(gate)) => {
                let region = region.as_str().ok_or_else(|| ManifestError::Field {
                    rule: id.clone(),
                    field: "context_region".to_string(),
                })?;
                Some((Region::parse(region, &id)?, Gate::parse(gate, &id, 0)?))
            }
            _ => {
                return Err(ManifestError::Field {
                    rule: id.clone(),
                    field: "context_region and context_gate (must be provided together)"
                        .to_string(),
                })
            }
        };
        // Optional `[rule.answer]` (x-c929): parsed here so its blocked-only /
        // bottom-N-region constraints fail loud alongside every other field.
        let answer = match v.get("answer") {
            None => None,
            Some(a) => Some(AnswerGrammar::parse(a, &id, &state, &region)?),
        };
        // Reject unknown keys: a typo like `skip_state_updates = true` would
        // otherwise parse fine and silently drop the real flag, changing
        // arbitration. Fail closed instead (matches the gate's one-key rule).
        if let Some(table) = v.as_table() {
            const ALLOWED: &[&str] = &[
                "id",
                "state",
                "priority",
                "region",
                "skip_state_update",
                "gate",
                "context_region",
                "context_gate",
                "answer",
            ];
            if let Some(unknown) = table.keys().find(|k| !ALLOWED.contains(&k.as_str())) {
                return Err(ManifestError::Field {
                    rule: id.clone(),
                    field: format!("unknown key '{unknown}'"),
                });
            }
        }
        Ok(ManifestRule {
            id,
            state,
            priority,
            region,
            skip_state_update,
            gate,
            context,
            answer,
        })
    }
}

/// The verdict of evaluating a manifest against a screen: the matching rule's
/// id, the state it asserts, and whether the caller should hold the current
/// state instead of applying `state`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verdict<'a> {
    pub rule_id: &'a str,
    pub state: &'a str,
    pub skip_state_update: bool,
}

/// A parsed agent detection manifest: an engine-version floor plus the rules,
/// pre-sorted highest-priority-first so [`evaluate`](Manifest::evaluate) is a
/// linear scan that returns on the first match.
#[derive(Debug, Clone)]
pub struct Manifest {
    /// Minimum engine version a (future remote) manifest may demand. Parsed and
    /// stored now though unused in v1 (design: "Engine-version field now even if
    /// unused, so a later remote manifest can gate"). Defaults to 0.
    pub min_engine_version: u32,
    /// Rules sorted by `priority` descending; ties keep TOML order (stable sort).
    /// Private so the sort invariant `evaluate` relies on can only be established
    /// by [`parse`](Manifest::parse); read via [`rules`](Manifest::rules).
    rules: Vec<ManifestRule>,
}

impl Manifest {
    /// Parse a manifest TOML. Fails closed: a bad regex, unknown region, or
    /// over-deep gate is a parse error naming the offending rule, never a
    /// silently-dropped rule.
    pub fn parse(s: &str) -> Result<Manifest, ManifestError> {
        let root: toml::Value =
            toml::from_str(s).map_err(|e| ManifestError::Toml(e.to_string()))?;
        // Reject unknown root keys (typo like `min_engine_versions`). A later
        // format bump is gated by `min_engine_version`, not by tolerating
        // unknown keys, so fail closed in v1.
        if let Some(table) = root.as_table() {
            if let Some(unknown) = table
                .keys()
                .find(|k| !matches!(k.as_str(), "min_engine_version" | "rule"))
            {
                return Err(ManifestError::Field {
                    rule: "<root>".to_string(),
                    field: format!("unknown key '{unknown}'"),
                });
            }
        }
        // Absent -> 0. Present-but-wrong-type or negative is a malformed manifest,
        // not a silent default-to-0 (fail closed, matching the per-rule fields).
        let min_engine_version = match root.get("min_engine_version") {
            None => 0,
            Some(v) => v
                .as_integer()
                .and_then(|n| u32::try_from(n).ok())
                .ok_or_else(|| ManifestError::Field {
                    rule: "<root>".to_string(),
                    field: "min_engine_version (must be a non-negative integer)".to_string(),
                })?,
        };
        let mut rules = match root.get("rule") {
            Some(v) => v
                .as_array()
                .ok_or_else(|| ManifestError::Field {
                    rule: "<root>".to_string(),
                    field: "rule (must be an array of tables)".to_string(),
                })?
                .iter()
                .map(ManifestRule::parse)
                .collect::<Result<Vec<_>, _>>()?,
            None => Vec::new(),
        };
        // Highest priority first; stable so equal-priority rules keep file order.
        rules.sort_by(|a, b| b.priority.cmp(&a.priority));
        Ok(Manifest {
            min_engine_version,
            rules,
        })
    }

    /// The parsed rules, highest-priority-first. Read-only: the sort invariant is
    /// owned by [`parse`](Manifest::parse).
    pub fn rules(&self) -> &[ManifestRule] {
        &self.rules
    }

    /// Return the highest-priority rule whose gate matches the screen, or `None`
    /// when no rule matches (the caller decides what an undetected state means -
    /// the engine never guesses).
    pub fn evaluate(&self, screen: &ScreenView) -> Option<Verdict<'_>> {
        self.rules.iter().find_map(|rule| {
            rule.matched_region_text(screen).map(|_| Verdict {
                rule_id: &rule.id,
                state: &rule.state,
                skip_state_update: rule.skip_state_update,
            })
        })
    }

    /// Like [`evaluate`](Self::evaluate) but also returns the winning rule's
    /// [`AnswerablePrompt`] when it carries an `[answer]` grammar and the region
    /// yields a clean menu (`None` otherwise - blocked-but-not-answerable). The
    /// scrape sweep uses this so the answer payload rides the same badge; the
    /// cheap `evaluate` stays for callers that only need the state.
    pub fn evaluate_answerable(
        &self,
        screen: &ScreenView,
    ) -> Option<(Verdict<'_>, Option<AnswerablePrompt>)> {
        self.rules.iter().find_map(|rule| {
            let text = rule.matched_region_text(screen)?;
            let answerable = rule.extract_answer(&text);
            Some((
                Verdict {
                    rule_id: &rule.id,
                    state: &rule.state,
                    skip_state_update: rule.skip_state_update,
                },
                answerable,
            ))
        })
    }
}

/// The detection manifest compiled into the binary for a known agent (E6.3).
/// Returns `None` for an unknown agent - the caller fails loud rather than
/// guessing a manifest (mirrors `readiness.rs`'s Open Question #9: no
/// fail-open default).
pub fn bundled_manifest(agent: &str) -> Option<&'static str> {
    match agent {
        "claude" => Some(include_str!("manifests/claude.toml")),
        "codex" => Some(include_str!("manifests/codex.toml")),
        "gemini" => Some(include_str!("manifests/gemini.toml")),
        // x-8f7f: agy (hosted, US1) + opencode (staged/inert until x-51f6, US2).
        "agy" => Some(include_str!("manifests/agy.toml")),
        "opencode" => Some(include_str!("manifests/opencode.toml")),
        // x-83e7: full-roster roster. All staged/inert - none has a provider
        // host yet (no build_pane_argv arm), so each is bundled-but-dormant like
        // opencode. Adapted from the reference manifests per manifests/ADAPTING.md.
        // "copilot" resolves github-copilot.toml, mirroring the reference's own mapping.
        // antigravity is intentionally absent: the reference antigravity manifest is the
        // agy harness (id "agy"), already covered by agy.toml above.
        "amp" => Some(include_str!("manifests/amp.toml")),
        "cline" => Some(include_str!("manifests/cline.toml")),
        "cursor" => Some(include_str!("manifests/cursor.toml")),
        "devin" => Some(include_str!("manifests/devin.toml")),
        "droid" => Some(include_str!("manifests/droid.toml")),
        "copilot" => Some(include_str!("manifests/github-copilot.toml")),
        "grok" => Some(include_str!("manifests/grok.toml")),
        "hermes" => Some(include_str!("manifests/hermes.toml")),
        "kilo" => Some(include_str!("manifests/kilo.toml")),
        "kimi" => Some(include_str!("manifests/kimi.toml")),
        "kiro" => Some(include_str!("manifests/kiro.toml")),
        "pi" => Some(include_str!("manifests/pi.toml")),
        "qodercli" => Some(include_str!("manifests/qodercli.toml")),
        _ => None,
    }
}

/// Resolve and parse an agent's manifest. v1 resolution chain (design: bundled +
/// local override; remote/cached deferred): a readable `<agent>.toml` in
/// `override_dir` wins over the bundled copy, so an operator can hand-author a
/// rule file without a rebuild.
///
/// Returns `None` when no manifest exists for `agent` (unknown agent, no
/// override) - the caller decides what "no manifest" means and never guesses.
/// `Some(Err(..))` is a present-but-malformed manifest (the override or bundled
/// TOML failed to parse), surfaced verbatim so a bad hand edit fails loud
/// instead of silently falling back.
pub fn load_manifest(
    agent: &str,
    override_dir: Option<&Path>,
) -> Option<Result<Manifest, ManifestError>> {
    if let Some(dir) = override_dir {
        let path = dir.join(format!("{agent}.toml"));
        // A PRESENT override file is honoured as the operator's intent and fails
        // loud: a parse-bad TOML surfaces ManifestError::Toml, and a present file
        // that won't read (invalid UTF-8, permission-denied, lookup error)
        // surfaces ManifestError::Io. ONLY a genuinely absent override (a
        // NotFound read error) falls through to bundled. We match on the read
        // error kind rather than pre-checking is_file(), because is_file()
        // collapses every metadata error (permission, symlink loop) to false and
        // would silently fall back to bundled on a real error (codex peer P2).
        match std::fs::read_to_string(&path) {
            Ok(text) => return Some(Manifest::parse(&text)),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
            Err(e) => {
                return Some(Err(ManifestError::Io {
                    path: path.display().to_string(),
                    detail: e.to_string(),
                }))
            }
        }
    }
    bundled_manifest(agent).map(Manifest::parse)
}

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

    fn view(text: &str) -> ScreenView<'_> {
        ScreenView {
            visible_text: text,
            cursor_row: 0,
            cursor_col: 0,
            osc_title: None,
            osc_progress: None,
        }
    }

    fn view_title<'a>(text: &'a str, title: &'a str) -> ScreenView<'a> {
        ScreenView {
            visible_text: text,
            cursor_row: 0,
            cursor_col: 0,
            osc_title: Some(title),
            osc_progress: None,
        }
    }

    #[test]
    fn parses_fields_and_sorts_by_priority_desc() {
        let m = Manifest::parse(
            r#"
            min_engine_version = 2
            [[rule]]
            id = "low"
            state = "idle"
            priority = 10
            region = "whole_recent"
            gate = { contains = "x" }
            [[rule]]
            id = "high"
            state = "working"
            priority = 100
            region = "whole_recent"
            gate = { contains = "y" }
            "#,
        )
        .unwrap();
        assert_eq!(m.min_engine_version, 2);
        assert_eq!(m.rules().len(), 2);
        assert_eq!(m.rules()[0].id, "high", "highest priority sorts first");
        assert_eq!(m.rules()[1].id, "low");
    }

    #[test]
    fn min_engine_version_defaults_to_zero() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "idle"
            priority = 1
            region = "whole_recent"
            gate = { contains = "x" }
            "#,
        )
        .unwrap();
        assert_eq!(m.min_engine_version, 0);
    }

    // AC-E6-5: highest-priority match wins. A "yes" in scrollback must NOT fake a
    // permission prompt because the live-region rule out-prioritizes it.
    #[test]
    fn highest_priority_match_wins_over_scrollback() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "scrollback_yes"
            state = "blocked"
            priority = 100
            region = "whole_recent"
            gate = { contains = "yes" }
            [[rule]]
            id = "live_prompt"
            state = "idle"
            priority = 900
            region = "bottom_non_empty_lines(1)"
            gate = { line_regex = "^\\s*❯" }
            "#,
        )
        .unwrap();
        // "yes" is up in scrollback; the live composer shows the idle prompt.
        let screen = "I said yes earlier\nlots of reply text\n";
        let v = m.evaluate(&view(screen)).unwrap();
        assert_eq!(v.state, "idle", "live-region rule beats scrollback match");
        assert_eq!(v.rule_id, "live_prompt");
    }

    // AC-E6-2 (engine half): a braille-spinner title badges working from the
    // title alone, with the grid showing only scrollback (no glyph in the grid).
    #[test]
    fn osc_title_braille_spinner_badges_working_from_title_alone() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "osc_title_working"
            state = "working"
            priority = 1100
            region = "osc_title"
            gate = { regex = "^[\\x{2800}-\\x{28FF}]" }
            "#,
        )
        .unwrap();
        // Grid is pure scrollback (no spinner); the title carries U+280B.
        let screen = view_title("old output\nmore scrollback\n", "\u{280b} Compiling");
        let v = m.evaluate(&screen).unwrap();
        assert_eq!(v.state, "working");
        // No title -> the rule does not fire (engine never guesses).
        assert!(m.evaluate(&view("old output")).is_none());
    }

    // AC-E6-3: skip_state_update on a transcript-viewer rule keeps a working
    // agent from flipping to idle when the ctrl+o pager is open.
    #[test]
    fn skip_state_update_flag_is_carried_through() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "transcript_viewer"
            state = "idle"
            priority = 1000
            region = "bottom_non_empty_lines(3)"
            skip_state_update = true
            gate = { contains = "(END)" }
            "#,
        )
        .unwrap();
        let v = m.evaluate(&view("scrollback\nmore\n(END)")).unwrap();
        assert!(v.skip_state_update, "pager rule must not update state");
    }

    #[test]
    fn gate_all_any_not_compose() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "blocked_form"
            state = "blocked"
            priority = 980
            region = "whole_recent"
            gate = { all = [ { contains = "enter to select" }, { contains = "esc to cancel" }, { not = { contains = "esc to interrupt" } } ] }
            "#,
        )
        .unwrap();
        // all three sub-gates satisfied
        assert!(m
            .evaluate(&view("press enter to select, esc to cancel"))
            .is_some());
        // missing "esc to cancel" -> all() fails
        assert!(m.evaluate(&view("enter to select something")).is_none());
        // the not() clause: an interrupt hint present -> blocked rule must NOT fire
        assert!(m
            .evaluate(&view("enter to select, esc to cancel, esc to interrupt"))
            .is_none());
    }

    #[test]
    fn any_gate_matches_on_one() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "perm"
            state = "blocked"
            priority = 850
            region = "whole_recent"
            gate = { any = [ { contains = "do you want to proceed?" }, { contains = "1. Yes" } ] }
            "#,
        )
        .unwrap();
        assert!(m.evaluate(&view("1. Yes\n2. No")).is_some());
        assert!(m.evaluate(&view("nothing relevant")).is_none());
    }

    #[test]
    fn region_prompt_box_body_extracts_box_interior() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "live_prompt_box"
            state = "idle"
            priority = 950
            region = "prompt_box_body"
            gate = { regex = "❯" }
            "#,
        )
        .unwrap();
        // A "❯" in scrollback above the box must not count; only the box body does.
        let screen = "❯ earlier command in history\n\
                      ╭──────────────╮\n\
                      │ ❯ type here  │\n\
                      ╰──────────────╯";
        assert!(m.evaluate(&view(screen)).is_some());
        // No box on screen -> empty region -> no match.
        assert!(m.evaluate(&view("just text, no box")).is_none());
    }

    #[test]
    fn region_osc_progress_reads_progress_payload() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "progressing"
            state = "working"
            priority = 500
            region = "osc_progress"
            gate = { regex = "^4;" }
            "#,
        )
        .unwrap();
        let screen = ScreenView {
            visible_text: "anything",
            cursor_row: 0,
            cursor_col: 0,
            osc_title: None,
            osc_progress: Some("4;1;50"),
        };
        assert_eq!(m.evaluate(&screen).unwrap().state, "working");
    }

    #[test]
    fn no_rule_matches_returns_none() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "idle"
            priority = 1
            region = "whole_recent"
            gate = { contains = "zzz" }
            "#,
        )
        .unwrap();
        assert!(m.evaluate(&view("nothing here")).is_none());
    }

    #[test]
    fn empty_manifest_parses_to_no_rules() {
        let m = Manifest::parse("min_engine_version = 1").unwrap();
        assert!(m.rules().is_empty());
        assert!(m.evaluate(&view("anything")).is_none());
    }

    #[test]
    fn bad_regex_is_a_parse_error_not_a_silent_drop() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "broken"
            state = "x"
            priority = 1
            region = "whole_recent"
            gate = { regex = "(" }
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::BadRegex { rule, .. } if rule == "broken"));
    }

    #[test]
    fn unknown_region_is_a_parse_error() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "the_moon"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::UnknownRegion { region, .. } if region == "the_moon"));
    }

    #[test]
    fn missing_required_field_names_the_rule() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            priority = 1
            region = "whole_recent"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { rule, field } if rule == "r" && field == "state")
        );
    }

    #[test]
    fn multi_key_gate_table_is_rejected() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "whole_recent"
            gate = { contains = "a", regex = "b" }
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::BadGate { rule } if rule == "r"));
    }

    #[test]
    fn over_deep_gate_is_refused() {
        // Build a gate nested past MAX_GATE_DEPTH with chained `not`s.
        let mut gate = "{ contains = \"x\" }".to_string();
        for _ in 0..(MAX_GATE_DEPTH + 2) {
            gate = format!("{{ not = {gate} }}");
        }
        let toml = format!(
            "[[rule]]\nid = \"deep\"\nstate = \"x\"\npriority = 1\nregion = \"whole_recent\"\ngate = {gate}\n"
        );
        let err = Manifest::parse(&toml).unwrap_err();
        assert!(matches!(err, ManifestError::GateTooDeep { rule } if rule == "deep"));
    }

    #[test]
    fn bottom_non_empty_lines_scopes_to_tail() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "hit"
            priority = 1
            region = "bottom_non_empty_lines(2)"
            gate = { contains = "needle" }
            "#,
        )
        .unwrap();
        // needle is on line 1 of 4 non-empty lines; bottom(2) must not see it.
        let screen = "needle up here\n\nfiller\nmore filler\nlast line";
        assert!(m.evaluate(&view(screen)).is_none());
        // needle in the last two lines -> match.
        assert!(m.evaluate(&view("filler\nfiller\nneedle\nlast")).is_some());
    }

    #[test]
    fn empty_composite_gate_is_rejected_not_fail_open() {
        // `all = []` is vacuously true and would pin its state on every screen.
        // Both empty `all` and empty `any` must be parse errors.
        for body in ["all = []", "any = []"] {
            let err = Manifest::parse(&format!(
                "[[rule]]\nid = \"r\"\nstate = \"x\"\npriority = 1\nregion = \"whole_recent\"\ngate = {{ {body} }}\n"
            ))
            .unwrap_err();
            assert!(
                matches!(err, ManifestError::BadGate { rule } if rule == "r"),
                "{body} should be rejected"
            );
        }
    }

    #[test]
    fn bottom_non_empty_lines_zero_is_rejected() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "bottom_non_empty_lines(0)"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::Field { rule, .. } if rule == "r"));
    }

    #[test]
    fn malformed_scalar_fields_are_rejected_not_coerced() {
        // priority out of i32 range -> error (not a silent wrap).
        let big = i64::from(i32::MAX) + 1;
        let err = Manifest::parse(&format!(
            "[[rule]]\nid = \"r\"\nstate = \"x\"\npriority = {big}\nregion = \"whole_recent\"\ngate = {{ contains = \"x\" }}\n"
        ))
        .unwrap_err();
        assert!(matches!(err, ManifestError::Field { field, .. } if field.starts_with("priority")));

        // skip_state_update present but not a bool -> error (not silent false).
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "whole_recent"
            skip_state_update = "yes"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { field, .. } if field.starts_with("skip_state_update"))
        );

        // min_engine_version present but wrong type -> error (not silent 0).
        let err = Manifest::parse(
            r#"
            min_engine_version = "two"
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "whole_recent"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { field, .. } if field.starts_with("min_engine_version"))
        );
    }

    #[test]
    fn empty_leaf_gate_pattern_is_rejected_not_fail_open() {
        // `contains = ""` / `regex = ""` / `line_regex = ""` each match every
        // region; reject them like an empty `all = []` (codex peer P2).
        for leaf in [r#"contains = """#, r#"regex = """#, r#"line_regex = """#] {
            let err = Manifest::parse(&format!(
                "[[rule]]\nid = \"r\"\nstate = \"x\"\npriority = 1\nregion = \"whole_recent\"\ngate = {{ {leaf} }}\n"
            ))
            .unwrap_err();
            assert!(
                matches!(err, ManifestError::Field { rule, .. } if rule == "r"),
                "{leaf} should be rejected"
            );
        }
    }

    #[test]
    fn unknown_rule_and_root_keys_are_rejected() {
        // A typo'd rule key (`skip_state_updates`) would silently drop the real
        // flag; reject it (codex peer P2).
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "whole_recent"
            skip_state_updates = true
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { rule, field } if rule == "r" && field.contains("unknown key"))
        );

        // A typo'd root key is rejected too.
        let err = Manifest::parse(
            r#"
            min_engine_versions = 1
            [[rule]]
            id = "r"
            state = "x"
            priority = 1
            region = "whole_recent"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { rule, field } if rule == "<root>" && field.contains("unknown key"))
        );
    }

    #[test]
    fn empty_id_is_rejected() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = ""
            state = "x"
            priority = 1
            region = "whole_recent"
            gate = { contains = "x" }
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::Field { field, .. } if field.starts_with("id")));
    }

    // ---- E6.3: bundled rule files (claude/codex/gemini) ----

    use crate::readiness::{CodexReadinessDetector, GeminiReadinessDetector, ReadinessDetector};

    fn bundled(agent: &str) -> Manifest {
        Manifest::parse(bundled_manifest(agent).expect("bundled manifest exists"))
            .expect("bundled manifest parses")
    }

    /// Derive the old boolean readiness from a manifest verdict: ready only when
    /// the live state is `idle` and the rule did not ask us to hold state. This
    /// is the mapping the daemon badge will use when E2 wires evaluate() in.
    fn manifest_ready(m: &Manifest, screen: &ScreenView) -> bool {
        matches!(m.evaluate(screen), Some(v) if v.state == "idle" && !v.skip_state_update)
    }

    #[test]
    fn bundled_manifests_all_parse() {
        // Every bundled agent must parse, carry rules, and evaluate against a
        // synthetic view without panicking (x-83e7 AC-happy). This is the
        // parse-coverage guard the domain pitfall calls for: a leftover reference-
        // only key (unknown region/field/root key) fails loud here, NAMING the
        // file (x-83e7 AC-error) rather than silently shipping a dead manifest.
        // x-8f7f added agy + opencode; x-83e7 grew the roster to full-roster parity.
        let synthetic = view("some scrollback\nesc to interrupt\n\u{276f} ");
        for agent in [
            "claude", "codex", "gemini", "agy", "opencode", // pre-x-83e7
            "amp", "cline", "cursor", "devin", "droid", "copilot", "grok", "hermes", "kilo",
            "kimi", "kiro", "pi", "qodercli", // x-83e7
        ] {
            let src = bundled_manifest(agent).unwrap_or_else(|| panic!("{agent} is bundled"));
            let m = Manifest::parse(src)
                .unwrap_or_else(|e| panic!("{agent}.toml failed to parse: {e:?}"));
            assert!(!m.rules().is_empty(), "{agent}.toml has rules");
            // Must not panic (regexes compiled at parse; this exercises evaluate).
            let _ = m.evaluate(&synthetic);
        }
        // A genuinely-unhosted harness still resolves to None (the fail-loud
        // guard, mirrors readiness OQ#9: no fail-open default). aider is a real
        // coding CLI we deliberately do not bundle a manifest for.
        assert!(bundled_manifest("aider").is_none(), "unknown agent -> None");
    }

    // AC-E6-4: codex/gemini ported to TOML reproduce the hardcoded
    // CodexReadinessDetector/GeminiReadinessDetector decisions on the exact
    // readiness.rs test inputs, INCLUDING gemini's "Waiting for auth" false-ready.
    #[test]
    fn ac_e6_4_codex_gemini_toml_match_hardcoded_detectors() {
        let codex_m = bundled("codex");
        let gemini_m = bundled("gemini");
        // (input, expected ready) - mirrors readiness.rs's detector tests.
        let cases: &[(&str, bool)] = &[
            ("codex 0.130\n\n  build feature X\n\u{276f} ", true), // idle prompt
            ("running tool...\nEsc to interrupt\n\u{276f}", false), // busy beats glyph
            ("loading a 5000 byte banner of text", false),         // no glyph -> not ready
            ("Waiting for auth...\n\u{276f}", false),              // gemini false-ready trap
            ("Gemini ready\n\u{203a} ", true),                     // › idle glyph
            // "Working"/"Thinking" up in scrollback must NOT block (Codex P1).
            (
                "I am Working on the Thinking task you asked about.\n\
                 Here is a long reply that mentions Working again.\n\
                 filler line\nanother filler\n\u{276f} ",
                true,
            ),
        ];
        for (text, want) in cases {
            let trimmed = text.trim_end();
            let screen = view(trimmed);
            assert_eq!(
                manifest_ready(&codex_m, &screen),
                *want,
                "codex.toml readiness mismatch for {trimmed:?}"
            );
            // Cross-check against the real hardcoded detector: the TOML must
            // agree with the Rust it replaces, not just with `want`.
            assert_eq!(
                manifest_ready(&codex_m, &screen),
                CodexReadinessDetector.is_ready(&screen).unwrap(),
                "codex.toml diverges from CodexReadinessDetector for {trimmed:?}"
            );
            assert_eq!(
                manifest_ready(&gemini_m, &screen),
                GeminiReadinessDetector.is_ready(&screen).unwrap(),
                "gemini.toml diverges from GeminiReadinessDetector for {trimmed:?}"
            );
        }
    }

    // AC-E6-2: claude.toml's braille-spinner osc_title_working rule badges
    // `working` from the title alone, with the grid showing only scrollback.
    #[test]
    fn ac_e6_2_claude_osc_title_spinner_badges_working() {
        let m = bundled("claude");
        // Grid is pure scrollback (no spinner glyph); the title carries U+280B.
        let screen = view_title("old output\nmore scrollback\n", "\u{280b} Compiling");
        let v = m.evaluate(&screen).expect("spinner title matches");
        assert_eq!(v.state, "working");
        assert_eq!(v.rule_id, "osc_title_working");
        // No title at all -> the title rule cannot fire (engine never guesses).
        assert!(m
            .evaluate(&view("old output\nmore scrollback"))
            .is_none_or(|v| v.rule_id != "osc_title_working"));
    }

    // AC-E6-3: skip_state_update on claude.toml's transcript_viewer keeps a
    // ctrl+o transcript pager from flipping the badge to idle.
    #[test]
    fn ac_e6_3_claude_transcript_viewer_holds_state() {
        let m = bundled("claude");
        let v = m
            .evaluate(&view("scrollback line\nmore scrollback\n(END)"))
            .expect("transcript pager marker matches");
        assert_eq!(v.rule_id, "transcript_viewer");
        assert!(
            v.skip_state_update,
            "pager rule must hold state, not set idle"
        );
    }

    // AC-E6-5: highest-priority match wins. A claude whose grid shows an idle
    // composer box still badges `working` when the OSC title spinner is up,
    // because osc_title_working (1100) out-prioritizes live_prompt_box (950) -
    // the title is the authority a scraped grid cannot fake.
    #[test]
    fn ac_e6_5_claude_title_spinner_outranks_idle_grid_box() {
        let m = bundled("claude");
        let grid = "\u{256d}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256e}\n\
                    \u{2502} \u{276f} type here \u{2502}\n\
                    \u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}";
        // Sanity: with no title, the idle composer box wins -> idle.
        let v_idle = m.evaluate(&view(grid)).expect("idle box matches");
        assert_eq!(v_idle.state, "idle");
        assert_eq!(v_idle.rule_id, "live_prompt_box");
        // With the spinner title up, working out-prioritizes the same idle box.
        let v_working = m
            .evaluate(&view_title(grid, "\u{280b} Working"))
            .expect("spinner title matches");
        assert_eq!(v_working.state, "working");
        assert_eq!(v_working.rule_id, "osc_title_working");
    }

    // A live permission prompt outranks an idle composer box drawn beneath it:
    // badging `idle` while a prompt is up would be a false-ready (forbidden).
    #[test]
    fn ac_e6_5_claude_permission_prompt_outranks_idle_box() {
        let m = bundled("claude");
        // A permission prompt with the composer box still rendered below it.
        let screen = "do you want to proceed?\n\
                      1. Yes\n\
                      2. No\n\
                      \u{256d}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256e}\n\
                      \u{2502} \u{276f} type \u{2502}\n\
                      \u{2570}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256f}";
        let v = m.evaluate(&view(screen)).expect("a rule matches");
        assert_eq!(
            v.state, "blocked",
            "permission prompt must beat the idle box"
        );
        assert_eq!(v.rule_id, "permission_prompt");
    }

    #[test]
    fn load_manifest_prefers_override_then_bundled_then_none() {
        // No override dir -> bundled.
        let m = load_manifest("claude", None)
            .expect("known agent")
            .expect("parses");
        assert!(!m.rules().is_empty());
        // Unknown agent, no override -> None (caller fails loud). hermes is now
        // bundled (x-83e7 full-roster parity), so use aider (a real coding CLI we
        // deliberately do not bundle a manifest for).
        assert!(load_manifest("aider", None).is_none());

        // A readable <agent>.toml override wins over the bundled copy.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("codex.toml"),
            "[[rule]]\nid = \"override_only\"\nstate = \"idle\"\npriority = 1\nregion = \"whole_recent\"\ngate = { contains = \"OVR\" }\n",
        )
        .unwrap();
        let m = load_manifest("codex", Some(dir.path()))
            .expect("override present")
            .expect("override parses");
        assert_eq!(m.rules().len(), 1);
        assert_eq!(m.rules()[0].id, "override_only");
        // A missing override file for another agent falls through to bundled.
        let m = load_manifest("gemini", Some(dir.path()))
            .expect("falls back to bundled")
            .expect("parses");
        assert!(m.rules().iter().any(|r| r.id == "idle_prompt"));
        // A present-but-malformed override surfaces the parse error (no silent
        // fallback to bundled - a bad hand edit must fail loud).
        std::fs::write(dir.path().join("claude.toml"), "this = is = not = toml").unwrap();
        assert!(matches!(
            load_manifest("claude", Some(dir.path())),
            Some(Err(ManifestError::Toml(_)))
        ));
        // A present override that won't read (invalid UTF-8) also fails loud as
        // an Io error, NOT a silent fallback to bundled (gemini review).
        std::fs::write(dir.path().join("gemini.toml"), [0xff, 0xfe, 0x00]).unwrap();
        assert!(matches!(
            load_manifest("gemini", Some(dir.path())),
            Some(Err(ManifestError::Io { .. }))
        ));
    }

    // AC1-HP (x-8f7f): agy's manifest is authored from AgyReadinessDetector
    // (agy wraps Gemini, shares prompt_ready), so it badges idle/working/blocked
    // on the same conditions gemini does, with the never-false-ready bias
    // (auth_wall 980 > busy 900 > idle_prompt 100).
    #[test]
    fn x8f7f_agy_manifest_evaluates_idle_working_blocked() {
        let m = bundled("agy");
        assert_eq!(
            m.evaluate(&view("agy 1.0\n\u{276f} ")).unwrap().state,
            "idle"
        );
        assert_eq!(
            m.evaluate(&view("running tool...\nesc to interrupt\n\u{276f}"))
                .unwrap()
                .state,
            "working", // busy (900) beats the idle glyph (100)
        );
        assert_eq!(
            m.evaluate(&view("Waiting for auth...\n\u{276f}"))
                .unwrap()
                .state,
            "blocked", // auth_wall (980) is the never-false-ready guard
        );
    }

    // AC2-HP + AC2-EDGE (x-8f7f): opencode's reference manifest, translated per
    // ADAPTING.md, matches the same screens the reference's rules match - including the
    // multi-key AND permission rule whose nesting is preserved under one gate.
    #[test]
    fn x8f7f_opencode_manifest_matches_reference_screens() {
        let m = bundled("opencode");
        // Simple blocked marker.
        assert_eq!(
            m.evaluate(&view("△ Permission required")).unwrap().state,
            "blocked",
        );
        // Both working markers.
        assert_eq!(
            m.evaluate(&view("thinking\nesc to interrupt"))
                .unwrap()
                .state,
            "working",
        );
        assert_eq!(
            m.evaluate(&view("progress \u{25a0}\u{25a0}\u{25a0}\u{25a0}\u{25a0}"))
                .unwrap()
                .state,
            "working", // progress-bar regex (■|⬝){4,}
        );
        // AC2-EDGE: the nested any/all permission branch (esc dismiss AND a
        // confirm hint AND a select hint) still resolves to blocked.
        assert_eq!(
            m.evaluate(&view(
                "esc dismiss   enter confirm   \u{2191}\u{2193} select"
            ))
            .unwrap()
            .state,
            "blocked",
        );
        // A bare model reply that merely mentions none of the markers -> no rule
        // fires (the engine never guesses).
        assert!(m.evaluate(&view("here is your answer")).is_none());
    }

    // AC2-ERR (x-8f7f): an adaptation that leaves a unknown source key in the TOML
    // fails loud at parse (our fail-closed parser) - the bad port never ships.
    #[test]
    fn x8f7f_unknown_source_key_fails_loud() {
        let bad = "[[rule]]\nid = \"p\"\nstate = \"blocked\"\npriority = 1\n\
                   region = \"whole_recent\"\nvisible_blocker = true\n\
                   gate = { contains = \"x\" }\n";
        assert!(matches!(
            Manifest::parse(bad),
            Err(ManifestError::Field { .. })
        ));
    }

    // AC2-FR / AC3 (x-8f7f, flipped live at x-51f6): the hosting gate is
    // real. opencode's manifest was BUNDLED (staged) while opencode had no
    // provider impl; x-51f6 added OpencodeProvider, so opencode is now both
    // bundled AND hostable — like agy — and its manifest can fire. aider
    // remains the genuinely-unhosted example (bundled nothing, hosted
    // nothing).
    #[test]
    fn x8f7f_staged_manifest_fires_once_hosted() {
        for hosted in ["opencode", "agy"] {
            assert!(bundled_manifest(hosted).is_some(), "{hosted} bundled");
            assert!(
                crate::provider::for_name(hosted).is_some(),
                "{hosted} IS hostable -> manifest can fire",
            );
        }
        assert!(bundled_manifest("aider").is_none(), "aider not bundled");
        assert!(
            crate::provider::for_name("aider").is_none(),
            "aider not hosted"
        );
    }

    // ---- x-c929: answer grammar + fail-closed extractor ----

    fn blocked_answer_manifest() -> Manifest {
        Manifest::parse(
            r#"
            [[rule]]
            id = "perm"
            state = "blocked"
            priority = 900
            region = "bottom_non_empty_lines(8)"
            gate = { contains = "proceed?" }
            [rule.answer]
            option = '^\s*\x{276f}?\s*(?P<idx>[0-9])\.\s+(?P<label>.+?)\s*$'
            send = "digit"
            "#,
        )
        .unwrap()
    }

    // AC3-HP: a clean numbered menu yields one option per line with pinned digit
    // keystrokes, a display-only prompt, region_lines, and a blake3 fingerprint
    // over the exact region text the server will re-read.
    #[test]
    fn xc929_extract_answer_clean_numbered_menu() {
        let m = blocked_answer_manifest();
        // No blank lines, so the bottom_non_empty_lines(8) region == the screen.
        let screen = "Do you want to proceed?\n  ❯ 1. Yes\n  2. No";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(v.state, "blocked");
        let ans = ans.expect("a clean numbered menu is answerable");
        assert_eq!(ans.options.len(), 2);
        assert_eq!(ans.options[0].idx, "1");
        assert_eq!(ans.options[0].label, "Yes");
        assert_eq!(ans.options[0].keystroke, b"1");
        assert_eq!(ans.options[1].idx, "2");
        assert_eq!(ans.options[1].label, "No");
        assert_eq!(ans.options[1].keystroke, b"2");
        assert_eq!(ans.region_lines, 8);
        assert_eq!(ans.prompt, "Do you want to proceed?");
        // Fingerprint is blake3 over the region join (the server re-hashes this).
        assert_eq!(ans.fingerprint, *blake3::hash(screen.as_bytes()).as_bytes());
    }

    #[test]
    fn answer_rule_can_gate_context_outside_the_answer_region() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "approval"
            state = "blocked"
            priority = 10
            region = "bottom_non_empty_lines(4)"
            gate = { line_regex = '^\s*\x{203a}\s*[0-9]\.\s' }
            context_region = "whole_recent"
            context_gate = { contains = "Would you like to run the following command?" }
            [rule.answer]
            option = '^\s*\x{203a}?\s*(?P<idx>[0-9])\.\s+(?P<label>.+?)\s*$'
            send = "digit"
            "#,
        )
        .unwrap();
        let wrapped = (0..30)
            .map(|i| format!("wrapped command row {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let screen = format!(
            "Would you like to run the following command?\n{wrapped}\n\
             \u{203a} 1. Yes, proceed\n  2. Always allow\n  3. No, cancel\n  Press enter to confirm"
        );
        let (v, ans) = m.evaluate_answerable(&view(&screen)).unwrap();
        assert_eq!(v.rule_id, "approval");
        let ans = ans.expect("context gate detects the question; bottom region extracts the menu");
        assert_eq!(ans.options.len(), 3);
        assert_eq!(ans.region_lines, 4);

        let no_question = format!(
            "unrelated output\n{wrapped}\n\
             \u{203a} 1. Yes, proceed\n  2. Always allow\n  3. No, cancel\n  Press enter to confirm"
        );
        assert!(m.evaluate_answerable(&view(&no_question)).is_none());
    }

    // AC3-ERR: duplicated indices are not a clean 1..N run -> None (fail closed).
    #[test]
    fn xc929_extract_answer_rejects_duplicate_indices() {
        let m = blocked_answer_manifest();
        let screen = "proceed?\n1. Yes\n1. No";
        let (_, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert!(ans.is_none(), "duplicate index -> not answerable");
    }

    // AC3-EDGE: a menu whose top scrolled past the region window presents its
    // first captured option as "2." -> lowest index != 1 -> truncated -> None.
    #[test]
    fn xc929_extract_answer_rejects_truncated_menu() {
        let m = blocked_answer_manifest();
        let screen = "proceed?\n2. No\n3. Cancel";
        let (_, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert!(ans.is_none(), "menu not starting at 1 -> truncated -> None");
    }

    // AC3-FR: extraction is strictly additive - an unextractable blocked prompt
    // still badges `blocked`; only the answer payload degrades to None.
    #[test]
    fn xc929_extraction_failure_is_additive_badge_survives() {
        let m = blocked_answer_manifest();
        let screen = "proceed?\nuse arrows to select";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(
            v.state, "blocked",
            "detection unaffected by extraction miss"
        );
        assert!(ans.is_none(), "no numbered options -> focus-only");
    }

    // A long label is kept untruncated (the client truncates for display); the
    // fingerprint covers the full region text (AC3-UI is a client concern, but
    // the extractor must not pre-truncate).
    #[test]
    fn xc929_extract_answer_keeps_full_label() {
        let m = blocked_answer_manifest();
        let long = "No, and tell Claude what to do differently (esc)";
        let screen = format!("proceed?\n1. Yes\n2. {long}");
        let (_, ans) = m.evaluate_answerable(&view(&screen)).unwrap();
        assert_eq!(ans.unwrap().options[1].label, long);
    }

    // `send = "digit_enter"` appends CR to the pinned keystroke.
    #[test]
    fn xc929_send_digit_enter_appends_cr() {
        let m = Manifest::parse(
            r#"
            [[rule]]
            id = "perm"
            state = "blocked"
            priority = 900
            region = "bottom_non_empty_lines(8)"
            gate = { contains = "?" }
            [rule.answer]
            option = '^\s*(?P<idx>[0-9])\.\s+(?P<label>.+?)\s*$'
            send = "digit_enter"
            "#,
        )
        .unwrap();
        let (_, ans) = m.evaluate_answerable(&view("pick?\n1. A\n2. B")).unwrap();
        assert_eq!(ans.unwrap().options[0].keystroke, b"1\r");
    }

    // Parse-time fail-loud: an [answer] on a non-blocked rule is a config bug.
    #[test]
    fn xc929_answer_on_non_blocked_rule_fails_loud() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "idle"
            priority = 1
            region = "bottom_non_empty_lines(8)"
            gate = { contains = "x" }
            [rule.answer]
            option = '(?P<idx>[0-9])\.\s+(?P<label>.+)'
            send = "digit"
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { rule, field } if rule == "r" && field.starts_with("answer"))
        );
    }

    // Parse-time fail-loud: an [answer] needs a bottom_non_empty_lines(N) region
    // so the server can re-read the same window.
    #[test]
    fn xc929_answer_on_non_bottom_n_region_fails_loud() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "blocked"
            priority = 1
            region = "whole_recent"
            gate = { contains = "x" }
            [rule.answer]
            option = '(?P<idx>[0-9])\.\s+(?P<label>.+)'
            send = "digit"
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { field, .. } if field.contains("bottom_non_empty_lines"))
        );
    }

    // Parse-time fail-loud: the option regex must name both idx and label.
    #[test]
    fn xc929_answer_missing_named_capture_fails_loud() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "blocked"
            priority = 1
            region = "bottom_non_empty_lines(8)"
            gate = { contains = "x" }
            [rule.answer]
            option = '(?P<idx>[0-9])\.'
            send = "digit"
            "#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::Field { field, .. } if field.contains("label")));
    }

    // Parse-time fail-loud: an unknown send mapping is rejected (not v1 vocab).
    #[test]
    fn xc929_answer_bad_send_fails_loud() {
        let err = Manifest::parse(
            r#"
            [[rule]]
            id = "r"
            state = "blocked"
            priority = 1
            region = "bottom_non_empty_lines(8)"
            gate = { contains = "x" }
            [rule.answer]
            option = '(?P<idx>[0-9])\.\s+(?P<label>.+)'
            send = "arrows"
            "#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::Field { field, .. } if field.starts_with("answer.send"))
        );
    }

    // Integration: the bundled claude permission_prompt rule is answerable on a
    // real "Do you want to proceed? / 1. Yes / 2. No" screen.
    #[test]
    fn xc929_bundled_claude_permission_prompt_is_answerable() {
        let m = bundled("claude");
        let screen =
            "Do you want to proceed?\n  ❯ 1. Yes\n  2. No, and tell Claude what to do differently";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(v.rule_id, "permission_prompt");
        let ans = ans.expect("claude permission prompt is answerable");
        assert_eq!(ans.options.len(), 2);
        assert_eq!(ans.options[0].keystroke, b"1");
        assert_eq!(ans.options[1].idx, "2");
    }

    // x-5103: the bundled codex trust_prompt is answerable on a real (validated)
    // borderless "› 1. Yes, continue / 2. No, quit" menu; the "›" marker (U+203A)
    // and surrounding non-option lines don't break extraction, and send="digit".
    #[test]
    fn x5103_bundled_codex_trust_prompt_is_answerable() {
        let m = bundled("codex");
        let screen = "> You are in /tmp/foo\n  \
            Do you trust the contents of this directory? Trusting loads config.\n\
            \u{203a} 1. Yes, continue\n  2. No, quit\n\n  Press enter to continue";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(v.rule_id, "trust_prompt");
        assert_eq!(v.state, "blocked");
        let ans = ans.expect("codex numbered trust menu is answerable");
        assert_eq!(ans.options.len(), 2);
        assert_eq!(ans.options[0].idx, "1");
        assert_eq!(ans.options[0].label, "Yes, continue");
        assert_eq!(ans.options[0].keystroke, b"1");
        assert_eq!(ans.options[1].idx, "2");
        assert_eq!(ans.options[1].keystroke, b"2");
    }

    // x-5103 (codex review P2): a model reply that PRINTS "Do you trust …" plus a
    // plain numbered list while idle must NOT become answerable - only a live menu
    // draws the "›" selector before a digit. The gate's required marker is what
    // stops the response list from injecting "1"/"2" into the idle composer.
    #[test]
    fn x5103_codex_model_printed_list_is_not_a_false_trust_prompt() {
        let m = bundled("codex");
        let screen = "The permission flow. Do you trust the folder? Options:\n\
            1. Yes, it loads config\n  2. No, sandboxed\n\u{203a} ";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_ne!(
            v.rule_id, "trust_prompt",
            "a printed list without the › selector must not fire trust_prompt"
        );
        assert!(ans.is_none(), "no live menu -> not answerable");
    }

    // x-f498: Codex 0.144.1 renders command approval as a borderless numbered
    // menu and commits a bare digit. This screen was captured from the live TUI.
    #[test]
    fn xf498_bundled_codex_command_approval_is_answerable() {
        let m = bundled("codex");
        let screen = "Would you like to run the following command?\n\n\
            Environment: local\n\n\
            $ touch /tmp/fno-x-f498-approval-capture\n\n\
            \u{203a} 1. Yes, proceed (y)\n\
              2. Yes, and don't ask again for commands that start with `touch /tmp/fno-x-f498-approval-capture` (p)\n\
              3. No, and tell Codex what to do differently (esc)\n\n\
            Press enter to confirm or esc to cancel";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(v.rule_id, "approval_prompt");
        assert_eq!(v.state, "blocked");
        let ans = ans.expect("codex command approval is answerable");
        assert_eq!(ans.options.len(), 3);
        assert_eq!(ans.options[0].label, "Yes, proceed (y)");
        assert_eq!(ans.options[0].keystroke, b"1");
        assert_eq!(ans.options[2].idx, "3");
        assert_eq!(ans.options[2].keystroke, b"3");
    }

    #[test]
    fn xf498_codex_model_printed_list_is_not_a_false_command_approval() {
        let m = bundled("codex");
        let screen = "Here is an example. Would you like to run the following command?\n\
            1. Yes, proceed\n  2. No, cancel\n\u{203a} ";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_ne!(v.rule_id, "approval_prompt");
        assert!(ans.is_none(), "no marked live menu -> not answerable");
    }

    #[test]
    fn xf498_bundled_codex_edit_approval_is_answerable() {
        let m = bundled("codex");
        let screen = "Added .fno-x-f498-edit-capture (+1 -0)\n\
            1 +CAPTURE\n\n\
            Would you like to make the following edits?\n\n\
            \u{203a} 1. Yes, proceed (y)\n\
              2. Yes, and don't ask again for these files (a)\n\
              3. No, and tell Codex what to do differently (esc)\n\n\
            Press enter to confirm or esc to cancel";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(v.rule_id, "approval_prompt");
        let ans = ans.expect("codex edit approval is answerable");
        assert_eq!(ans.options.len(), 3);
        assert_eq!(
            ans.options[1].label,
            "Yes, and don't ask again for these files (a)"
        );
        assert_eq!(ans.options[2].keystroke, b"3");
    }

    #[test]
    fn xf498_codex_approval_survives_narrow_terminal_wrapping() {
        let m = bundled("codex");
        let wrapped = (0..40)
            .map(|i| format!("wrapped command row {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        let screen = format!(
            "Would you like to run the following command?\nEnvironment: local\n{wrapped}\n\
             \u{203a} 1. Yes, proceed (y)\n\
               2. Yes, and don't ask again (p)\n\
               3. No, and tell Codex what to do differently (esc)\n\
             Press enter to confirm or esc to cancel"
        );
        let (v, ans) = m.evaluate_answerable(&view(&screen)).unwrap();
        assert_eq!(v.rule_id, "approval_prompt");
        assert!(ans.is_some());
    }

    // x-5103: the bundled gemini trust_prompt is answerable on a real (validated)
    // BOXED radio ("│ ● 1. Trust folder … │"); the option regex consumes the box
    // border (│ U+2502) + radio marker (● U+25CF) and the trailing border.
    #[test]
    fn x5103_bundled_gemini_trust_prompt_is_answerable() {
        let m = bundled("gemini");
        let screen = "\u{256d}\u{2500}\u{2500}\u{2500}\u{256e}\n\
            \u{2502} Do you trust the files in this folder?        \u{2502}\n\
            \u{2502} Trusting a folder allows Gemini CLI to load.  \u{2502}\n\
            \u{2502}                                               \u{2502}\n\
            \u{2502} \u{25cf} 1. Trust folder (foo)                     \u{2502}\n\
            \u{2502}   2. Trust parent folder (tmp)                \u{2502}\n\
            \u{2502}   3. Don't trust                              \u{2502}\n\
            \u{2570}\u{2500}\u{2500}\u{2500}\u{256f}";
        let (v, ans) = m.evaluate_answerable(&view(screen)).unwrap();
        assert_eq!(v.rule_id, "trust_prompt");
        assert_eq!(v.state, "blocked");
        let ans = ans.expect("gemini boxed numbered menu is answerable");
        assert_eq!(ans.options.len(), 3);
        assert_eq!(ans.options[0].idx, "1");
        assert_eq!(ans.options[0].label, "Trust folder (foo)");
        assert_eq!(ans.options[0].keystroke, b"1");
        assert_eq!(ans.options[2].idx, "3");
        assert_eq!(ans.options[2].label, "Don't trust");
    }

    // x-5103: agy's trust prompt is ARROW-ONLY ("> Yes … / No, exit" +
    // "↑/↓ Navigate") - no numbered options. No agy rule matches it, so it stays
    // focus-only (the documented Open Q1 no-op), never a fabricated grammar.
    #[test]
    fn x5103_bundled_agy_arrow_menu_is_focus_only() {
        let m = bundled("agy");
        let screen = "Do you trust the contents of this project?\n\
            Antigravity CLI requires permission to read, edit, and execute files here.\n\
            > Yes, I trust this folder\n  No, exit\n  \u{2191}/\u{2193} Navigate \u{b7} enter Confirm";
        assert!(
            m.evaluate_answerable(&view(screen)).is_none(),
            "agy arrow-only menu must not be answerable (focus-only fallback)"
        );
    }
}