devflow-core 1.4.0

Agent-agnostic development workflow state machine
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
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
//! Agent completion detection — parses DEVFLOW_RESULT markers and evaluates
//! exit codes to determine whether a coding agent succeeded or failed.
//!
//! Four-layer decision engine:
//! 0. Run operator-authored external post-condition probes (authoritative failure)
//! 1. Parse DEVFLOW_RESULT from agent stdout (authoritative for ordinary plans)
//! 2. Exit code + commit count gate (reliable fallback)
//! 3. Process gone + commits exist (last resort warning)

use crate::config::GitFlowConfig;
use crate::stage::Stage;
use crate::state::State;
use std::path::{Path, PathBuf};

/// Parsed agent completion result.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AgentResult {
    pub status: AgentStatus,
    pub exit_code: Option<i32>,
    pub reason: Option<String>,
    pub commits: Option<u32>,
    pub summary: Option<String>,
    /// The Validate stage's self-reported verdict — distinct from `status`.
    /// `status` reports whether the stage's task (running `/gsd-validate-phase`)
    /// completed; `verdict` reports whether validation ITSELF passed. Only
    /// `Some(Verdict::Pass)` should advance Validate to Ship; `Some(Verdict::Gaps)`
    /// and `None` both gate/loop back to Code (see `advance()`'s Validate arm).
    /// Ignored entirely for non-Validate stages.
    ///
    /// Deserialized leniently via [`deserialize_verdict_lenient`]: an absent,
    /// unknown, or mis-cased value becomes `None` rather than failing the
    /// whole `AgentResult` parse (T-13-14) — a malformed verdict must never
    /// silently drop a valid `status` to Layer 2.
    #[serde(default, deserialize_with = "deserialize_verdict_lenient")]
    pub verdict: Option<Verdict>,
    /// Which evaluation layer (0-3) produced this result (D-10, 17-01). Set by
    /// every constructor in this module; `None` is reserved for test-only
    /// fixture literals that don't route through the real cascade.
    #[serde(default)]
    pub decided_by_layer: Option<u8>,
}

/// Agent completion status determined by DevFlow.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AgentStatus {
    /// Agent self-reported success via DEVFLOW_RESULT.
    Success,
    /// Agent self-reported failure, or exit code + commit gate indicated failure.
    Failed,
    /// Agent stopped because an upstream API or usage quota rate-limited it.
    RateLimited,
    /// No signal received — fallback to exit code / commit heuristic.
    Unknown,
    /// Layer 2 classified the process as killed for resource exhaustion
    /// (exit code 137, typically SIGKILL from an OOM killer) (D-07, 17b).
    #[serde(rename = "resource_killed")]
    ResourceKilled,
    /// Layer 2 classified the process as unable to start (exit code 127,
    /// typically "command not found") (D-07, 17b).
    #[serde(rename = "agent_unavailable")]
    AgentUnavailable,
}

impl AgentStatus {
    /// The wire-format name for this variant, pinned equal to
    /// `serde_json::to_string(&self)` with the surrounding quotes stripped
    /// (see the `as_wire_str_matches_serde_form` test). Exhaustive match with
    /// NO wildcard arm — adding a variant without updating this is a compile
    /// error. This is the sanctioned replacement for
    /// `format!("{:?}", status).to_ascii_lowercase()`, which collapses word
    /// boundaries on multi-word variants (review consensus #1).
    pub fn as_wire_str(&self) -> &'static str {
        match self {
            AgentStatus::Success => "success",
            AgentStatus::Failed => "failed",
            AgentStatus::RateLimited => "ratelimited",
            AgentStatus::Unknown => "unknown",
            AgentStatus::ResourceKilled => "resource_killed",
            AgentStatus::AgentUnavailable => "agent_unavailable",
        }
    }
}

/// The Validate stage's self-reported verdict (13b verdict-vs-ran split).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
    /// Validation found no gaps — ready to advance to Ship.
    Pass,
    /// Validation found gaps that still need fixing — must loop back to Code
    /// (or gate, depending on the consecutive-failure threshold).
    Gaps,
}

/// Deserialize `verdict` leniently: an absent, unknown, or mis-cased value
/// (e.g. `"wat"`, `"Pass"`) becomes `Ok(None)` rather than an error, so a
/// malformed verdict never fails the whole `from_str::<AgentResult>` parse
/// and silently drops a valid `status` to Layer 2 (T-13-14, consensus #5).
///
/// Matching is intentionally exact-case (only the wire-format lowercase
/// strings `"pass"`/`"gaps"` are accepted) — a mis-cased value like `"Pass"`
/// is NOT case-folded into a match; it is treated the same as an unknown
/// value and maps to `None`, so a subtly wrong-case verdict fails safe
/// (gate/loop) instead of silently passing.
///
/// WR-09 (13-REVIEW.md): decodes as `serde_json::Value` first, then only
/// pattern-matches the string case — a non-string JSON type (`true`, `123`,
/// an object) is a wrong *type*, not a malformed string value, and must
/// still fall through to `None` rather than erroring out the entire
/// `AgentResult` parse (the same guarantee this deserializer already gives
/// mis-cased/unknown string values).
fn deserialize_verdict_lenient<'de, D>(deserializer: D) -> Result<Option<Verdict>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let raw = <Option<serde_json::Value> as serde::Deserialize>::deserialize(deserializer)?;
    Ok(raw.and_then(|v| {
        v.as_str().and_then(|s| match s {
            "pass" => Some(Verdict::Pass),
            "gaps" => Some(Verdict::Gaps),
            _ => None,
        })
    }))
}

/// Errors produced by agent result evaluation.
#[derive(Debug, thiserror::Error)]
pub enum ResultError {
    #[error("I/O error reading agent output: {0}")]
    Io(#[from] std::io::Error),
    #[error("phase directory not found")]
    NoPhaseDir,
}

/// Search stdout for a DEVFLOW_RESULT marker.
///
/// The marker is a single line starting with `DEVFLOW_RESULT:` followed by
/// a JSON object with at minimum a `status` field. Matching is case-insensitive.
///
/// When an agent is run with `--output-format json` (e.g. Claude), its final
/// message is wrapped in a JSON result envelope with the text — and its
/// embedded newlines — escaped inside a `result` field. In that case the
/// marker never appears at the start of a line, so we first unwrap the
/// envelope and search the inner text.
pub fn parse_devflow_result(stdout: &str) -> Option<AgentResult> {
    if let Some(inner) = extract_json_result_text(stdout)
        && let Some(result) = parse_marker_lines(&inner)
    {
        return Some(result);
    }
    parse_marker_lines(stdout)
}

/// Detect agent-specific rate-limit output and return the retry description.
///
/// Claude can emit a JSON result envelope when run with `--output-format json`;
/// Codex commonly emits plain text such as "Try again at ...". This function is
/// intentionally conservative so ordinary progress text does not become a
/// false positive.
pub fn detect_rate_limit(stdout: &str) -> Option<String> {
    detect_claude_rate_limit(stdout).or_else(|| detect_codex_rate_limit(stdout))
}

fn detect_claude_rate_limit(stdout: &str) -> Option<String> {
    let value: serde_json::Value = serde_json::from_str(stdout.trim()).ok()?;
    let rate_limited = json_has_str(&value, "subtype", "error_rate_limit")
        || json_has_i64(&value, "api_error_status", 429)
        || json_has_i64(&value, "status", 429)
        || json_has_i64(&value, "status_code", 429);
    if !rate_limited {
        return None;
    }
    json_find_key(&value, "retry_after")
        .and_then(json_scalar_to_string)
        .or_else(|| json_find_key(&value, "message").and_then(json_scalar_to_string))
        .or_else(|| json_find_key(&value, "error").and_then(json_scalar_to_string))
        .or_else(|| Some("usage limit".to_string()))
}

fn detect_codex_rate_limit(stdout: &str) -> Option<String> {
    // This heuristic exists for Codex's PLAIN-TEXT output. JSONL event lines
    // are authoritative and handled by parse_codex_event_result — scanning
    // them here false-positives on document content echoed into events
    // (13-06 dogfood finding: GSD reference tables mentioning "rate limiting"
    // were read by the agent, echoed into an `item.completed` payload, and
    // this scan returned that entire multi-KB line as the "retry time").
    let stdout: String = stdout
        .lines()
        .filter(|line| {
            serde_json::from_str::<serde_json::Value>(line)
                .map(|v| !v.is_object())
                .unwrap_or(true)
        })
        .collect::<Vec<_>>()
        .join("\n");
    let stdout = stdout.as_str();
    let lower = stdout.to_ascii_lowercase();
    if let Some(idx) = lower.find("try again at ") {
        let start = idx + "try again at ".len();
        let retry = stdout[start..]
            .lines()
            .next()
            .unwrap_or_default()
            .trim()
            .trim_end_matches(['.', ',', ';'])
            .trim();
        if !retry.is_empty() {
            return Some(retry.to_string());
        }
    }

    if lower.contains("usage limit") || lower.contains("rate limit") || lower.contains("429") {
        stdout
            .lines()
            .find(|line| {
                let line = line.to_ascii_lowercase();
                line.contains("usage limit") || line.contains("rate limit") || line.contains("429")
            })
            .map(str::trim)
            .filter(|line| !line.is_empty())
            .map(str::to_string)
            .or_else(|| Some("usage limit".to_string()))
    } else {
        None
    }
}

/// If `stdout` is a JSON result envelope, return the decoded `result` text
/// field (with escapes such as `\n` resolved). Returns `None` for plain text.
fn extract_json_result_text(stdout: &str) -> Option<String> {
    let trimmed = stdout.trim();
    if !trimmed.starts_with('{') {
        return None;
    }
    let value: serde_json::Value = serde_json::from_str(trimmed).ok()?;
    value.get("result")?.as_str().map(str::to_string)
}

// WR-12 (13-REVIEW.md), revised: these traversal helpers run on the coding
// agent's raw stdout (via detect_claude_rate_limit, which every `devflow
// advance` invocation runs through evaluate_layer1), so deeply nested JSON —
// accidental or adversarial — must not stack-overflow the process. The
// traversal is iterative (an explicit worklist), so nesting depth never
// consumes call stack and no depth cap is needed. The first WR-12 fix capped
// recursion at 64, which silently missed keys at depths 64–128 — nesting
// serde_json's default 128-level parse recursion limit (the only producer of
// these `Value`s) accepts just fine.

/// Depth-first pre-order scan over every JSON object in `value`, returning
/// the first `Some` produced by `visit` on an object's map.
fn json_scan<'a, T>(
    value: &'a serde_json::Value,
    visit: impl Fn(&'a serde_json::Map<String, serde_json::Value>) -> Option<T>,
) -> Option<T> {
    let mut stack = vec![value];
    while let Some(current) = stack.pop() {
        match current {
            serde_json::Value::Object(map) => {
                if let Some(found) = visit(map) {
                    return Some(found);
                }
                // Push in reverse so pop order preserves document order.
                for child in map.values().rev() {
                    stack.push(child);
                }
            }
            serde_json::Value::Array(values) => {
                for child in values.iter().rev() {
                    stack.push(child);
                }
            }
            _ => {}
        }
    }
    None
}

fn json_has_str(value: &serde_json::Value, key: &str, expected: &str) -> bool {
    json_scan(value, |map| {
        (map.get(key)?.as_str()? == expected).then_some(())
    })
    .is_some()
}

fn json_has_i64(value: &serde_json::Value, key: &str, expected: i64) -> bool {
    json_scan(value, |map| {
        (map.get(key)?.as_i64()? == expected).then_some(())
    })
    .is_some()
}

fn json_find_key<'a>(value: &'a serde_json::Value, key: &str) -> Option<&'a serde_json::Value> {
    json_scan(value, |map| map.get(key))
}

fn json_scalar_to_string(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Number(n) => Some(n.to_string()),
        _ => None,
    }
}

/// Read the top-level `is_error` boolean (and, if present, `num_turns`) from
/// a Claude JSON result envelope (`--output-format json`) and treat
/// `is_error: true` as an authoritative Layer-1 failure.
///
/// This is checked BEFORE the `DEVFLOW_RESULT` marker path in
/// [`evaluate_layer1`], so `is_error: true` OVERRIDES a stale/echoed success
/// marker embedded in the same envelope's `result` text — the envelope is
/// authoritative for errors. `is_error` absent or `false` returns `None`,
/// deferring to the marker path and, ultimately, Layer 2. It runs AFTER
/// `detect_claude_rate_limit`, though: rate-limit envelopes also carry
/// `is_error: true`, and the specific `RateLimited` classification (which
/// drives sequentagent's handoff and the resume cron) must win over this
/// generic `Failed`.
///
/// Per RESEARCH Pitfall 5, `is_error` (not specific `subtype` strings) is
/// the documented, stable signal — this does not special-case non-success
/// subtype values beyond what already exists in `detect_claude_rate_limit`.
fn detect_claude_envelope_failure(stdout: &str) -> Option<AgentResult> {
    let trimmed = stdout.trim();
    if !trimmed.starts_with('{') {
        return None;
    }
    let value: serde_json::Value = serde_json::from_str(trimmed).ok()?;
    let is_error = value.get("is_error")?.as_bool()?;
    if !is_error {
        return None;
    }

    let num_turns = value.get("num_turns").and_then(serde_json::Value::as_u64);
    let base_reason = value
        .get("result")
        .and_then(serde_json::Value::as_str)
        .map(str::to_string)
        .or_else(|| {
            value
                .get("subtype")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
        })
        .unwrap_or_else(|| "agent reported is_error".to_string());
    let reason = match num_turns {
        Some(n) => format!("{base_reason} (num_turns: {n})"),
        None => base_reason,
    };

    Some(AgentResult {
        status: AgentStatus::Failed,
        exit_code: None,
        reason: Some(reason),
        commits: None,
        summary: None,
        verdict: None,
        decided_by_layer: Some(1),
    })
}

/// Determine whether a set of parsed JSONL lines look like a Codex `--json`
/// event stream (as opposed to a single-document Claude envelope or plain
/// text) — i.e. at least one line is a `thread.started` or `turn.*` event.
fn is_codex_event_stream(events: &[serde_json::Value]) -> bool {
    events.iter().any(|v| {
        v.get("type")
            .and_then(serde_json::Value::as_str)
            .is_some_and(|t| t == "thread.started" || t.starts_with("turn."))
    })
}

/// Parse a Codex `--json` JSONL event stream (one JSON object per line) and
/// look at the LAST terminal event (`turn.completed` / `turn.failed`).
///
/// Only decisive when the captured stdout is actually a Codex event stream
/// (per [`is_codex_event_stream`]) — a single-document Claude envelope
/// (`type: "result"`, no `turn.*` lines) is not consumed here and returns
/// `None`, so the Claude envelope/marker paths handle it instead.
///
/// `turn.failed` is decisive: returns `AgentStatus::Failed` with `reason`
/// from `error.message`. A final `turn.completed` with no `DEVFLOW_RESULT`
/// marker returns `None` (defers to Layer 2) rather than an unconditional
/// Success — a marker-less turn must not silently advance a stage (this is
/// the composition fix that keeps a marker-less Validate run from
/// false-passing to Ship).
///
/// NOTE: written against the documented `--json` event schema (thread.started
/// / turn.started / item.* / turn.completed with usage / turn.failed with
/// error.message) but not yet verified against the installed Codex CLI
/// version — the 13-06 dogfood run captures real output and reconciles any
/// delta, the same empirical practice 12-12-SUMMARY.md used for Claude.
fn parse_codex_event_result(stdout: &str) -> Option<AgentResult> {
    let events: Vec<serde_json::Value> = stdout
        .lines()
        .filter(|line| !line.trim().is_empty())
        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
        .collect();

    if !is_codex_event_stream(&events) {
        return None;
    }

    // Codex delivers the agent's DEVFLOW_RESULT self-report inside an
    // `agent_message` item's `text` — never as a raw stdout line — so the
    // top-level marker scan cannot see it (13-06 dogfood finding: a Codex
    // `DEVFLOW_RESULT: failed` was invisible and the run fell through to
    // heuristics). The decoded `text` is a plain marker line; reuse the
    // marker parser on it. Last marker wins, matching parse_marker_lines.
    let marker = events.iter().rev().find_map(|v| {
        if v.get("type").and_then(serde_json::Value::as_str) != Some("item.completed") {
            return None;
        }
        let item = v.get("item")?;
        if item.get("type").and_then(serde_json::Value::as_str) != Some("agent_message") {
            return None;
        }
        let text = item.get("text").and_then(serde_json::Value::as_str)?;
        parse_marker_lines(text)
    });
    if marker.is_some() {
        return marker;
    }

    let terminal = events.iter().rev().find(|v| {
        matches!(
            v.get("type").and_then(serde_json::Value::as_str),
            Some("turn.completed") | Some("turn.failed")
        )
    })?;

    if terminal.get("type").and_then(serde_json::Value::as_str) != Some("turn.failed") {
        // turn.completed (or any other terminal we don't recognize) defers
        // to Layer 2 rather than an unconditional Success.
        return None;
    }

    let reason = terminal
        .get("error")
        .and_then(|e| e.get("message"))
        .and_then(serde_json::Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| "codex turn failed".to_string());

    Some(AgentResult {
        status: AgentStatus::Failed,
        exit_code: None,
        reason: Some(reason),
        commits: None,
        summary: None,
        verdict: None,
        decided_by_layer: Some(1),
    })
}

/// Scan the last ~4000 characters of `stdout` in reverse line order.
///
/// `DEVFLOW_RESULT` markers are ASCII. Searching the bounded tail and returning
/// the last valid marker ensures the agent's final status wins over an earlier
/// prompt echo without requiring the surrounding output to be ASCII.
fn parse_marker_lines(stdout: &str) -> Option<AgentResult> {
    // Only search the tail — agents may echo the marker in their prompt
    // and we want the LAST occurrence (which is their actual final status).
    let tail: String = stdout
        .chars()
        .rev()
        .take(4000)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();

    for line in tail.lines().rev() {
        let Some(json_str) = line
            .strip_prefix("DEVFLOW_RESULT: ")
            .or_else(|| line.strip_prefix("devflow_result: "))
            .or_else(|| line.strip_prefix("DEVFLOW_RESULT:"))
            .or_else(|| line.strip_prefix("devflow_result:"))
        else {
            continue;
        };

        let json_str = json_str.trim();
        if let Ok(result) = serde_json::from_str::<AgentResult>(json_str) {
            return Some(result);
        }
    }
    None
}

/// Layer 1: Try to detect agent result from the native per-adapter envelope
/// or the DEVFLOW_RESULT marker in stdout.
///
/// Precedence: Claude rate-limit envelope (a SPECIFIC failure that must
/// outrank the generic `is_error` check — rate-limit envelopes carry
/// `is_error: true`, and classifying them `Failed` would kill sequentagent's
/// handoff/cron path) → Claude envelope `is_error: true` (authoritative,
/// overrides a success marker) → DEVFLOW_RESULT marker (portable; works for
/// plain text and a Claude envelope's unwrapped `result` text) → Codex JSONL
/// event stream (`turn.failed` decisive; `turn.completed` defers) → Codex
/// plain-text rate-limit heuristic (least authoritative, stays last).
pub fn evaluate_layer1(project_root: &Path, phase: u32) -> Option<AgentResult> {
    let stdout_path = devflow_dir(project_root).join(format!("phase-{:02}-stdout", phase));
    // Read lossily: in monitor mode the agent's stdout reaches this file via
    // raw sh redirection, so one invalid UTF-8 byte in a strict
    // read_to_string would silently disable ALL Layer-1 detection (marker,
    // envelope, rate limit) — the same failure class CR-01 (13-REVIEW.md)
    // fixed in the blocking-mode capture.
    let bytes = std::fs::read(&stdout_path).ok()?;
    let stdout = String::from_utf8_lossy(&bytes);
    detect_claude_rate_limit(&stdout)
        .map(rate_limited_result)
        .or_else(|| detect_claude_envelope_failure(&stdout))
        .or_else(|| parse_devflow_result(&stdout))
        .or_else(|| parse_codex_event_result(&stdout))
        .or_else(|| detect_codex_rate_limit(&stdout).map(rate_limited_result))
}

/// Build the `RateLimited` result Layer 1 reports for a detected retry hint.
fn rate_limited_result(retry: String) -> AgentResult {
    AgentResult {
        status: AgentStatus::RateLimited,
        exit_code: None,
        reason: Some(format!("rate limited until {retry}")),
        commits: None,
        summary: None,
        verdict: None,
        decided_by_layer: Some(1),
    }
}

/// Layer 2: Use exit code + commit count to determine result.
///
/// Reads exit code from `.devflow/phase-NN-exit` file.
/// Counts commits in `feature/phase-NN` branch (if it exists).
///
/// The commit-count gate ("no commits → failed") is scoped to `stage` — it
/// only applies to `Stage::Plan`/`Stage::Code` (checked via an explicit
/// `matches!`, NOT `Stage::is_agent_stage()`, since that also includes
/// `Define`, which legitimately produces zero commits). `exit≠0` is ALWAYS
/// `Failed`, for every stage — only the `exit=0`/zero-commits branch is
/// stage-scoped.
///
/// Decision matrix:
///   exit=137                                             → ResourceKilled (ALL stages, D-07)
///   exit=127                                             → AgentUnavailable (ALL stages, D-07)
///   exit≠0 (excluding 137/127)                           → Failed (ALL stages)
///   exit=0, stage in {Plan, Code}, commits=0             → Failed ("no work done")
///   exit=0, stage in {Plan, Code}, commits>0             → Success
///   exit=0, stage NOT in {Plan, Code} (Define/Validate/Ship), commits=0 → Success
///           (not commit-gated; Validate's real pass signal is its verdict,
///           not a bare zero-commit — see Task 2's turn.completed deferral)
///   exit unknown                                         → fall to Layer 3 (return None)
///
/// WR-06 (13-REVIEW.md): takes only the explicit `project_root` parameter
/// for both the `.devflow/` file paths and the git subprocess `current_dir`
/// — previously it also accepted `state: &State` and used `state.project_root`
/// for the git calls, which every caller happened to pass consistently with
/// `project_root` but which the function itself had no way to enforce.
pub fn evaluate_layer2(
    project_root: &Path,
    phase: u32,
    git_flow: &GitFlowConfig,
    stage: Stage,
) -> Result<Option<AgentResult>, ResultError> {
    let exit_path = devflow_dir(project_root).join(format!("phase-{:02}-exit", phase));
    let exit_code: i32 = match std::fs::read_to_string(&exit_path) {
        Ok(s) => s.trim().parse().unwrap_or(-1),
        Err(_) => return Ok(None), // fall to Layer 3
    };

    let branch = format!("{}phase-{:02}", git_flow.feature_prefix, phase);

    // Verify branch exists before counting commits.
    let branch_exists = std::process::Command::new("git")
        .args(["rev-parse", "--verify", &branch])
        .current_dir(project_root)
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    let commits: u32 = if branch_exists {
        let range = format!("{}..{branch}", git_flow.develop);
        std::process::Command::new("git")
            .args(["rev-list", "--count", &range])
            .current_dir(project_root)
            .output()
            .ok()
            .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok())
            .unwrap_or(0)
    } else {
        0
    };

    let commit_gated = matches!(stage, Stage::Plan | Stage::Code);
    let no_work_done = commit_gated && commits == 0;

    // 137 (SIGKILL, typically OOM) and 127 (command not found) are classified
    // BEFORE the generic `exit_code != 0 -> Failed` catch-all, using the same
    // trusted plain-i32 already parsed above from the monitor-written exit
    // file (D-07, 17b — no ExitStatusExt/signal API per Pitfall 1a).
    let status = if exit_code == 137 {
        AgentStatus::ResourceKilled
    } else if exit_code == 127 {
        AgentStatus::AgentUnavailable
    } else if exit_code != 0 || no_work_done {
        AgentStatus::Failed
    } else {
        AgentStatus::Success
    };

    Ok(Some(AgentResult {
        status,
        exit_code: Some(exit_code),
        reason: if exit_code == 137 {
            Some(format!(
                "agent process was killed (exit code 137, likely OOM) ({} commits on {})",
                commits, branch
            ))
        } else if exit_code == 127 {
            Some(format!(
                "agent command was unavailable (exit code 127, command not found) ({} commits on {})",
                commits, branch
            ))
        } else if exit_code != 0 {
            Some(format!(
                "agent exited with code {} ({} commits on {})",
                exit_code, commits, branch
            ))
        } else if no_work_done {
            Some(format!(
                "no commits found on {} (agent exit code was {})",
                branch, exit_code
            ))
        } else {
            Some(format!(
                "{} commits on {} (agent exit code was {})",
                commits, branch, exit_code
            ))
        },
        commits: Some(commits),
        summary: None,
        verdict: None,
        decided_by_layer: Some(2),
    }))
}

/// Layer 3: Last resort — agent process is gone.
///
/// Split per D-02/D-03 case 3 (17-03): "process gone, commits exist" stays
/// `Unknown` — unverified but there is SOMETHING to account for, and Plan
/// 04's never-advance dispatch gates it downstream (D-04) rather than
/// reclassifying it here. "Process gone, zero commits, nothing declared" is
/// no longer a blanket advanceable `Unknown` — it is reclassified to
/// `Failed` so a vanished agent that produced and declared nothing cannot
/// masquerade as ambiguous-but-fine; the reason flags that human review is
/// needed. This only fires when neither Layer 1 nor Layer 2 produced a
/// definitive result.
pub fn evaluate_layer3(
    project_root: &Path,
    phase: u32,
    git_flow: &GitFlowConfig,
) -> Result<AgentResult, ResultError> {
    let branch = format!("{}phase-{:02}", git_flow.feature_prefix, phase);
    let commits = std::process::Command::new("git")
        .args([
            "rev-list",
            "--count",
            &format!("{}..{branch}", git_flow.develop),
        ])
        .current_dir(project_root)
        .output()
        .ok()
        .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok())
        .unwrap_or(0);

    let (status, reason) = if commits > 0 {
        (
            AgentStatus::Unknown,
            format!(
                "unverified — agent process is gone but {} commits exist on {}",
                commits, branch
            ),
        )
    } else {
        (
            AgentStatus::Failed,
            "no work accounted for — agent process is gone with no commits and no declared \
             external post-condition; human review needed"
                .to_string(),
        )
    };

    Ok(AgentResult {
        status,
        exit_code: None,
        reason: Some(reason),
        commits: Some(commits),
        summary: None,
        verdict: None,
        decided_by_layer: Some(3),
    })
}

/// Layer 0: run explicitly operator-approved external post-condition probes.
///
/// A failed probe outranks every agent-controlled signal. An approved,
/// all-passing set of declared probes is itself affirmative completion
/// evidence — `Success` — so a legitimately external-only stage with zero
/// commits can still complete cleanly (D-05 gap 2). Evaluated for EVERY
/// stage, not only Code (D-05 gap 1 / D-06). With no declarations (or when
/// disabled), behavior is byte-for-byte the pre-Phase-16 cascade.
///
/// Two roots are intentionally kept distinct (review Plan 03 MEDIUM,
/// OpenCode): `project_root` is used to DISCOVER the PLAN's declared
/// commands (`.planning/phases/` lives there, not in a worktree checkout),
/// while `execution_root` — the worktree, when one is set — is where probes
/// actually RUN. Conflating the two previously meant a worktree-based phase
/// could not find its own declaration and silently mis-hit the
/// "PLAN removed" veto below.
fn evaluate_layer0(
    project_root: &Path,
    state: &State,
    approved_commands: Option<&[String]>,
) -> Option<AgentResult> {
    if !crate::config::external_verify_enabled(project_root) {
        return None;
    }

    let execution_root = state.worktree_path.as_deref().unwrap_or(project_root);
    let commands = crate::verify::external_verify_commands(project_root, state.phase);
    if commands.is_empty() {
        return approved_commands.map(|_| AgentResult {
            status: AgentStatus::Failed,
            exit_code: None,
            reason: Some(
                "external verification approval mismatch; PLAN declaration was removed".into(),
            ),
            commits: None,
            summary: None,
            verdict: None,
            decided_by_layer: Some(0),
        });
    }
    let Some(approved_commands) = approved_commands else {
        return Some(AgentResult {
            status: AgentStatus::Failed,
            exit_code: None,
            reason: Some(format!(
                "external verification is not approved; set {} to the reviewed JSON command array",
                crate::verify::TRUST_EXTERNAL_VERIFY_ENV
            )),
            commits: None,
            summary: None,
            verdict: None,
            decided_by_layer: Some(0),
        });
    };
    if commands != approved_commands {
        return Some(AgentResult {
            status: AgentStatus::Failed,
            exit_code: None,
            reason: Some("external verification approval mismatch; PLAN commands changed".into()),
            commits: None,
            summary: None,
            verdict: None,
            decided_by_layer: Some(0),
        });
    }
    match commands
        .into_iter()
        .find(|command| !crate::verify::run_external_verification(command, execution_root))
    {
        Some(command) => Some(AgentResult {
            status: AgentStatus::Failed,
            exit_code: None,
            reason: Some(format!("external verification failed: {command}")),
            commits: None,
            summary: None,
            verdict: None,
            decided_by_layer: Some(0),
        }),
        // Every declared, approved probe passed — affirmative completion
        // evidence on its own (D-05 gap 2), even with zero commits.
        None => Some(AgentResult {
            status: AgentStatus::Success,
            exit_code: None,
            reason: Some(
                "external verification passed — all declared, approved probes succeeded".into(),
            ),
            commits: None,
            summary: None,
            verdict: None,
            decided_by_layer: Some(0),
        }),
    }
}

/// Full four-layer evaluation: returns the best available AgentResult.
pub fn evaluate_agent_result(
    project_root: &Path,
    state: &State,
    git_flow: &GitFlowConfig,
) -> Result<AgentResult, ResultError> {
    let approval = crate::verify::external_verification_approval();
    evaluate_agent_result_inner(project_root, state, git_flow, approval.as_deref())
}

fn evaluate_agent_result_inner(
    project_root: &Path,
    state: &State,
    git_flow: &GitFlowConfig,
    approved_commands: Option<&[String]>,
) -> Result<AgentResult, ResultError> {
    // Layer 0: operator-authored external post-condition (authoritative failure)
    if let Some(result) = evaluate_layer0(project_root, state, approved_commands) {
        return Ok(result);
    }

    // Layer 1: DEVFLOW_RESULT marker (authoritative)
    if let Some(result) = evaluate_layer1(project_root, state.phase) {
        return Ok(result);
    }

    // Layer 2: Exit code + commit gate
    if let Some(result) = evaluate_layer2(project_root, state.phase, git_flow, state.stage)? {
        return Ok(result);
    }

    // Layer 3: Process existence + commits
    evaluate_layer3(project_root, state.phase, git_flow)
}

/// Path to the .devflow directory for a project root.
fn devflow_dir(project_root: &Path) -> PathBuf {
    project_root.join(".devflow")
}

/// Path to the stdout file for a given phase.
pub fn stdout_path(project_root: &Path, phase: u32) -> PathBuf {
    devflow_dir(project_root).join(format!("phase-{:02}-stdout", phase))
}

/// Path where the agent's stderr is captured for a given phase.
/// Lives alongside `stdout_path` under `.devflow/`.
pub fn stderr_path(project_root: &Path, phase: u32) -> PathBuf {
    devflow_dir(project_root).join(format!("phase-{phase:02}-stderr.log"))
}

/// Path to the exit code file for a given phase.
pub fn exit_code_path(project_root: &Path, phase: u32) -> PathBuf {
    devflow_dir(project_root).join(format!("phase-{:02}-exit", phase))
}

/// Path to the file where the monitor records the launched agent's PID.
pub fn agent_pid_path(project_root: &Path, phase: u32) -> PathBuf {
    devflow_dir(project_root).join(format!("phase-{:02}-agent-pid", phase))
}

/// Path to the archived-capture-history directory for a phase (16b).
///
/// `.devflow/history/phase-NN/` holds retained per-stage capture generations
/// so a false-positive self-report can be diagnosed after the fact. Exposed
/// as a constructor (rather than inlined at each call site) so downstream
/// tooling (16h in 16-07's correlation, 16i in 16-05's enumeration) always
/// derives the path from here instead of hardcoding it.
pub fn history_dir(project_root: &Path, phase: u32) -> PathBuf {
    devflow_dir(project_root)
        .join("history")
        .join(format!("phase-{:02}", phase))
}

/// Monotonically increasing tie-breaker appended to the nanosecond timestamp
/// used to stamp archived generations, so two archives issued within the
/// same nanosecond (possible in a tight test loop) never collide.
static ARCHIVE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// A stamp unique within this process, used to name an archived generation.
/// The outgoing stage's name is not available at the `archive_phase_files`
/// call site (see `launch_stage` in main.rs), so a monotonic timestamp is
/// used instead — sufficient to order and identify generations.
fn archive_stamp() -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let seq = ARCHIVE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    format!("{nanos}-{seq}")
}

/// Archive the prior stage's stdout/exit captures into bounded per-phase
/// history instead of wiping them outright, so a false-positive self-report
/// can be diagnosed after the fact (16b). Replaces the old
/// `cleanup_phase_files`, which deleted these files unconditionally.
///
/// At most `retain` capture generations are kept per phase; older ones are
/// pruned (see [`prune_history`]). The agent-pid file is still removed
/// outright — it is process bookkeeping, not diagnostic output. When there
/// is nothing to archive (first launch), this is a no-op success.
pub fn archive_phase_files(
    project_root: &Path,
    evidence_root: &Path,
    phase: u32,
    retain: usize,
) -> Result<Option<String>, std::io::Error> {
    archive_phase_files_with_stamp(project_root, evidence_root, phase, retain, &archive_stamp())
}

fn archive_phase_files_with_stamp(
    project_root: &Path,
    evidence_root: &Path,
    phase: u32,
    retain: usize,
    stamp: &str,
) -> Result<Option<String>, std::io::Error> {
    let _ = std::fs::remove_file(agent_pid_path(project_root, phase));

    let stdout_src = stdout_path(project_root, phase);
    let exit_src = exit_code_path(project_root, phase);
    let stdout_exists = stdout_src.exists();
    let exit_exists = exit_src.exists();
    if !stdout_exists && !exit_exists {
        return Ok(None); // Nothing to archive — first launch.
    }

    let history_dir = history_dir(project_root, phase);
    std::fs::create_dir_all(&history_dir)?;

    let staging_dir = history_dir.join(format!(".pending-{stamp}"));
    std::fs::create_dir(&staging_dir)?;
    let stdout_stage = staging_dir.join("stdout");
    let exit_stage = staging_dir.join("exit");
    let review_stage = staging_dir.join("REVIEW.md");
    let stdout_dest = history_dir.join(format!("{stamp}-stdout"));
    let exit_dest = history_dir.join(format!("{stamp}-exit"));
    let review_dest = history_dir.join(format!("{stamp}-REVIEW.md"));
    let review_src = phase_review_path(evidence_root, phase);

    let mut stdout_staged = false;
    let mut exit_staged = false;
    let mut stdout_published = false;
    let mut exit_published = false;
    let mut review_published = false;

    let archive_result = (|| -> Result<(), std::io::Error> {
        if stdout_exists {
            std::fs::rename(&stdout_src, &stdout_stage)?;
            stdout_staged = true;
        }
        if exit_exists {
            std::fs::rename(&exit_src, &exit_stage)?;
            exit_staged = true;
        }
        if let Some(review) = &review_src {
            std::fs::copy(review, &review_stage)?;
        }

        if stdout_exists {
            std::fs::rename(&stdout_stage, &stdout_dest)?;
            stdout_staged = false;
            stdout_published = true;
        }
        if exit_exists {
            std::fs::rename(&exit_stage, &exit_dest)?;
            exit_staged = false;
            exit_published = true;
        }
        if review_src.is_some() {
            std::fs::rename(&review_stage, &review_dest)?;
            review_published = true;
        }
        Ok(())
    })();

    if let Err(error) = archive_result {
        let mut rollback_error = None;
        let mut restore = |from: &Path, to: &Path| {
            if let Err(error) = std::fs::rename(from, to)
                && rollback_error.is_none()
            {
                rollback_error = Some(error);
            }
        };
        if stdout_published {
            restore(&stdout_dest, &stdout_src);
        } else if stdout_staged {
            restore(&stdout_stage, &stdout_src);
        }
        if exit_published {
            restore(&exit_dest, &exit_src);
        } else if exit_staged {
            restore(&exit_stage, &exit_src);
        }
        if review_published {
            let _ = std::fs::remove_file(&review_dest);
        }
        let _ = std::fs::remove_dir_all(&staging_dir);

        if let Some(rollback_error) = rollback_error {
            return Err(std::io::Error::new(
                error.kind(),
                format!("{error}; archive rollback failed: {rollback_error}"),
            ));
        }
        return Err(error);
    }

    let _ = std::fs::remove_dir(&staging_dir);

    prune_history(&history_dir, retain);
    Ok(Some(stamp.to_string()))
}

fn phase_review_path(project_root: &Path, phase: u32) -> Option<PathBuf> {
    let phases = std::fs::read_dir(project_root.join(".planning/phases")).ok()?;
    let prefix = format!("{phase:02}-");
    for entry in phases.flatten() {
        if entry
            .file_name()
            .to_str()
            .is_some_and(|name| name.starts_with(&prefix))
        {
            let review = entry.path().join(format!("{phase:02}-REVIEW.md"));
            if review.exists() {
                return Some(review);
            }
        }
    }
    None
}

/// Keep only the newest `retain` capture generations under `history_dir`,
/// deleting older ones. Generations are grouped by their stamp (the shared
/// prefix of a `{stamp}-stdout`/`{stamp}-exit` pair, split off the trailing
/// `-stdout`/`-exit` suffix via `rsplit_once`) and ordered lexicographically,
/// which matches numeric/chronological order for the fixed-width nanosecond
/// stamps `archive_stamp` produces. Ordering parses both numeric components;
/// the process-local sequence is intentionally not fixed-width.
fn prune_history(history_dir: &Path, retain: usize) {
    let Ok(entries) = std::fs::read_dir(history_dir) else {
        return;
    };

    let mut stamps: Vec<String> = entries
        .flatten()
        .filter_map(|entry| {
            let name = entry.file_name().to_str()?.to_string();
            name.rsplit_once('-')
                .map(|(stamp, _suffix)| stamp.to_string())
        })
        .collect();
    stamps.sort_by_key(|stamp| {
        let mut parts = stamp.split('-');
        let nanos = parts
            .next()
            .and_then(|part| part.parse::<u128>().ok())
            .unwrap_or(0);
        let sequence = parts
            .next()
            .and_then(|part| part.parse::<u64>().ok())
            .unwrap_or(0);
        (nanos, sequence)
    });
    stamps.dedup();

    if stamps.len() <= retain {
        return;
    }

    let to_remove = stamps.len() - retain;
    for stamp in &stamps[..to_remove] {
        let _ = std::fs::remove_file(history_dir.join(format!("{stamp}-stdout")));
        let _ = std::fs::remove_file(history_dir.join(format!("{stamp}-exit")));
        let _ = std::fs::remove_file(history_dir.join(format!("{stamp}-REVIEW.md")));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::GitFlowConfig;
    use crate::mode::Mode;
    use crate::stage::Stage;
    use crate::state::{AgentKind, State};
    use std::process::Command;

    fn state_in(root: &Path, phase: u32) -> State {
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Code;
        state
    }

    fn git(root: &Path, args: &[&str]) {
        let output = Command::new("git")
            .args(args)
            .current_dir(root)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "git {:?} failed\nstdout: {}\nstderr: {}",
            args,
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }

    fn init_repo_with_feature_commit(root: &Path, phase: u32) {
        git(root, &["init"]);
        git(root, &["config", "user.email", "devflow@example.com"]);
        git(root, &["config", "user.name", "DevFlow Tests"]);
        git(root, &["config", "commit.gpgsign", "false"]);
        git(root, &["config", "tag.gpgsign", "false"]);
        git(root, &["checkout", "-b", "develop"]);
        std::fs::write(root.join("README.md"), "base\n").unwrap();
        git(root, &["add", "README.md"]);
        git(root, &["commit", "-m", "base"]);

        let branch = format!("feature/phase-{phase:02}");
        git(root, &["checkout", "-b", &branch]);
        std::fs::write(root.join("phase.txt"), "feature work\n").unwrap();
        git(root, &["add", "phase.txt"]);
        git(root, &["commit", "-m", "feature work"]);
    }

    /// Like `init_repo_with_feature_commit`, but the feature branch sits at
    /// develop's tip with **no** extra commit (0 commits ahead).
    fn init_repo_with_feature_no_commit(root: &Path, phase: u32) {
        git(root, &["init"]);
        git(root, &["config", "user.email", "devflow@example.com"]);
        git(root, &["config", "user.name", "DevFlow Tests"]);
        git(root, &["config", "commit.gpgsign", "false"]);
        git(root, &["config", "tag.gpgsign", "false"]);
        git(root, &["checkout", "-b", "develop"]);
        std::fs::write(root.join("README.md"), "base\n").unwrap();
        git(root, &["add", "README.md"]);
        git(root, &["commit", "-m", "base"]);

        let branch = format!("feature/phase-{phase:02}");
        git(root, &["checkout", "-b", &branch]);
    }

    #[test]
    fn parse_success_marker() {
        let stdout = "some output\nDEVFLOW_RESULT: {\"status\":\"success\"}\n";
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
    }

    #[test]
    fn parse_failed_marker_with_reason() {
        let stdout =
            "work done\nDEVFLOW_RESULT: {\"status\":\"failed\",\"reason\":\"clippy errors\"}\n";
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.reason.unwrap(), "clippy errors");
    }

    #[test]
    fn parse_missing_marker_returns_none() {
        let stdout = "just some output\nno marker here\n";
        assert!(parse_devflow_result(stdout).is_none());
    }

    #[test]
    fn parse_malformed_json_returns_none() {
        let stdout = "DEVFLOW_RESULT: {not valid json}\n";
        assert!(parse_devflow_result(stdout).is_none());
    }

    #[test]
    fn parse_lowercase_marker() {
        let stdout = "devflow_result: {\"status\":\"success\"}\n";
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
    }

    #[test]
    fn parse_marker_without_space_after_colon() {
        let stdout = "DEVFLOW_RESULT:{\"status\":\"success\"}\n";
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
    }

    #[test]
    fn parse_lowercase_no_space_marker() {
        // Lowercase prefix AND no space after the colon — the combination that
        // the Phase 6 review flagged as uncovered.
        let stdout = "devflow_result:{\"status\":\"success\"}\n";
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
    }

    #[test]
    fn parse_finds_last_marker_in_tail() {
        // Multiple markers — should find the last one.
        let stdout = "DEVFLOW_RESULT: {\"status\":\"failed\"}\nsome more output\nDEVFLOW_RESULT: {\"status\":\"success\"}\n";
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
    }

    #[test]
    fn parse_marker_lines_returns_last_marker_in_long_output() {
        let stdout = format!(
            "{}\nDEVFLOW_RESULT: {{\"status\":\"failed\"}}\n{}\n\
             DEVFLOW_RESULT: {{\"status\":\"success\"}}\n",
            "prefix".repeat(900),
            "tail output".repeat(100)
        );

        let result = parse_marker_lines(&stdout).unwrap();

        assert_eq!(result.status, AgentStatus::Success);
    }

    #[test]
    fn parse_marker_only_in_last_4000_chars() {
        // Marker beyond 4000 chars from end should not be found.
        let prefix = "a".repeat(5000);
        let stdout = format!("DEVFLOW_RESULT: {{\"status\":\"success\"}}\n{prefix}");
        assert!(parse_devflow_result(&stdout).is_none());
    }

    #[test]
    fn parse_marker_with_commits_and_summary() {
        let stdout = r#"DEVFLOW_RESULT: {"status":"success","commits":3,"summary":"added tests"}"#;
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.commits, Some(3));
        assert_eq!(result.summary.unwrap(), "added tests");
    }

    #[test]
    fn parse_marker_inside_json_result_envelope() {
        // Claude --output-format json wraps the final text in a `result` field
        // with embedded newlines escaped.
        let stdout = r#"{"type":"result","subtype":"success","result":"All done.\nDEVFLOW_RESULT: {\"status\": \"success\", \"commits\": 2}","session_id":"abc"}"#;
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.commits, Some(2));
    }

    #[test]
    fn parse_failed_marker_inside_json_envelope() {
        let stdout = r#"{"result":"work\nDEVFLOW_RESULT: {\"status\": \"failed\", \"reason\": \"tests failed\"}"}"#;
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.reason.unwrap(), "tests failed");
    }

    #[test]
    fn parse_json_envelope_without_marker_returns_none() {
        let stdout = r#"{"result":"did some work but forgot the marker","session_id":"x"}"#;
        assert!(parse_devflow_result(stdout).is_none());
    }

    #[test]
    fn detect_claude_json_rate_limit_by_subtype() {
        let stdout = r#"{"type":"result","subtype":"error_rate_limit","retry_after":"2026-06-18T15:45:30Z","result":"rate limited"}"#;
        assert_eq!(
            detect_rate_limit(stdout).as_deref(),
            Some("2026-06-18T15:45:30Z")
        );
    }

    #[test]
    fn detect_claude_json_rate_limit_by_429() {
        let stdout = r#"{"type":"result","api_error_status":429,"error":{"message":"Too many requests. Try later."}}"#;
        assert_eq!(
            detect_rate_limit(stdout).as_deref(),
            Some("Too many requests. Try later.")
        );
    }

    #[test]
    fn detect_codex_try_again_rate_limit() {
        let stdout = "Usage limit reached. Try again at 3:45 PM.\n";
        assert_eq!(detect_rate_limit(stdout).as_deref(), Some("3:45 PM"));
    }

    /// WR-12 (13-REVIEW.md), revised: `json_has_str`/`json_has_i64`/
    /// `json_find_key` run on the coding agent's raw stdout via
    /// `detect_claude_rate_limit`, which every `devflow advance` invocation
    /// goes through. Deeply nested JSON — accidental or adversarial — must
    /// not stack-overflow the process, and a real marker at any depth
    /// serde_json will parse (its default recursion limit is exactly 128)
    /// must still be FOUND — the first WR-12 fix capped traversal at 64 and
    /// silently misclassified rate-limit markers at depths 64–128.
    #[test]
    fn detect_rate_limit_finds_marker_in_deeply_nested_json_without_overflow() {
        // 100 levels: parseable by serde_json (limit 128), deeper than the
        // removed 64-level traversal cap that used to hide the marker.
        const DEPTH: usize = 100;
        let mut stdout = String::new();
        for _ in 0..DEPTH {
            stdout.push_str(r#"{"nested":"#);
        }
        stdout.push_str(r#"{"type":"result","subtype":"error_rate_limit","retry_after":"deep"}"#);
        for _ in 0..DEPTH {
            stdout.push('}');
        }

        // Must return promptly without crashing AND find the buried marker —
        // the iterative worklist traversal has no silent-miss window.
        assert_eq!(detect_rate_limit(&stdout).as_deref(), Some("deep"));
    }

    #[test]
    fn detect_rate_limit_ignores_normal_stdout() {
        let stdout = "implemented feature\nDEVFLOW_RESULT: {\"status\":\"success\"}\n";
        assert!(detect_rate_limit(stdout).is_none());
    }

    #[test]
    fn claude_envelope_is_error_detected() {
        let stdout = r#"{"type":"result","subtype":"error","is_error":true,"num_turns":2,"result":"tool call failed","session_id":"abc"}"#;
        let result = detect_claude_envelope_failure(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
    }

    #[test]
    fn claude_is_error_overrides_success_marker() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 9),
            r#"{"type":"result","is_error":true,"num_turns":3,"result":"oops\nDEVFLOW_RESULT: {\"status\":\"success\"}","session_id":"abc"}"#,
        )
        .unwrap();

        let result = evaluate_layer1(dir.path(), 9).unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
    }

    #[test]
    fn claude_envelope_is_error_false_defers() {
        let stdout = r#"{"type":"result","is_error":false,"num_turns":1,"result":"did some work","session_id":"abc"}"#;
        assert!(detect_claude_envelope_failure(stdout).is_none());
    }

    #[test]
    fn claude_envelope_marker_still_wins() {
        let stdout = r#"{"type":"result","is_error":false,"result":"done\nDEVFLOW_RESULT: {\"status\":\"success\",\"commits\":2}","session_id":"abc"}"#;
        assert!(detect_claude_envelope_failure(stdout).is_none());
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.commits, Some(2));
    }

    #[test]
    fn codex_event_stream_parses_turn_failed() {
        let stdout = concat!(
            "{\"type\":\"thread.started\",\"thread_id\":\"t1\"}\n",
            "{\"type\":\"turn.started\"}\n",
            "{\"type\":\"item.started\",\"item\":{}}\n",
            "{\"type\":\"turn.failed\",\"error\":{\"message\":\"sandbox denied write\"}}\n",
        );
        let result = parse_codex_event_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.reason.as_deref(), Some("sandbox denied write"));
    }

    #[test]
    fn codex_turn_completed_no_marker_defers() {
        let stdout = concat!(
            "{\"type\":\"thread.started\",\"thread_id\":\"t1\"}\n",
            "{\"type\":\"turn.started\"}\n",
            "{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":5}}\n",
        );
        assert!(parse_codex_event_result(stdout).is_none());
    }

    /// 13-06 dogfood regression: Codex delivers the DEVFLOW_RESULT marker
    /// inside an `agent_message` item's text, never as a raw stdout line. A
    /// self-reported failure followed by a bare `turn.completed` must parse
    /// as Failed with the agent's reason — not defer to Layer 2 (which would
    /// see exit 0 and call it a success).
    #[test]
    fn codex_agent_message_marker_failed_wins_over_bare_turn_completed() {
        let stdout = concat!(
            "{\"type\":\"thread.started\",\"thread_id\":\"t1\"}\n",
            "{\"type\":\"item.completed\",\"item\":{\"id\":\"item_7\",\"type\":\"agent_message\",\"text\":\"DEVFLOW_RESULT: {\\\"status\\\": \\\"failed\\\", \\\"reason\\\": \\\"interactive input unavailable\\\"}\"}}\n",
            "{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":5}}\n",
        );
        let result = parse_codex_event_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(
            result.reason.as_deref(),
            Some("interactive input unavailable")
        );
    }

    #[test]
    fn codex_agent_message_marker_success_short_circuits() {
        let stdout = concat!(
            "{\"type\":\"thread.started\",\"thread_id\":\"t1\"}\n",
            "{\"type\":\"item.completed\",\"item\":{\"id\":\"item_2\",\"type\":\"agent_message\",\"text\":\"DEVFLOW_RESULT: {\\\"status\\\": \\\"success\\\"}\"}}\n",
            "{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":5}}\n",
        );
        let result = parse_codex_event_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
    }

    /// 13-06 dogfood regression: document content echoed into a JSONL event
    /// (GSD reference tables mentioning "rate limiting") must not trip the
    /// plain-text rate-limit heuristic — it returned the entire multi-KB
    /// event line as the "retry time" and that reached the desktop
    /// notification verbatim.
    #[test]
    fn detect_rate_limit_ignores_json_event_lines() {
        let stdout = concat!(
            "{\"type\":\"thread.started\",\"thread_id\":\"t1\"}\n",
            "{\"type\":\"item.completed\",\"item\":{\"id\":\"item_4\",\"type\":\"command_execution\",\"aggregated_output\":\"| API keys | Rate limiting per key? |\"}}\n",
            "{\"type\":\"turn.completed\",\"usage\":{\"input_tokens\":10,\"output_tokens\":5}}\n",
        );
        assert_eq!(detect_rate_limit(stdout), None);
    }

    #[test]
    fn detect_rate_limit_still_reads_codex_plain_text() {
        let stdout = "Rate limit reached.\nTry again at 3:45 PM.\n";
        assert_eq!(detect_rate_limit(stdout).as_deref(), Some("3:45 PM"));
    }

    #[test]
    fn codex_event_stream_ignores_progress_and_unparseable_lines() {
        let stdout = concat!(
            "{\"type\":\"thread.started\",\"thread_id\":\"t1\"}\n",
            "not json at all\n",
            "{\"type\":\"item.started\",\"item\":{}}\n",
            "{\"type\":\"item.updated\",\"item\":{}}\n",
            "{\"type\":\"turn.failed\",\"error\":{\"message\":\"boom\"}}\n",
        );
        let result = parse_codex_event_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.reason.as_deref(), Some("boom"));
    }

    #[test]
    fn claude_envelope_not_consumed_by_codex_parser() {
        let stdout = r#"{"type":"result","subtype":"success","is_error":false,"num_turns":4,"result":"All done.","session_id":"abc"}"#;
        assert!(parse_codex_event_result(stdout).is_none());
    }

    #[test]
    fn evaluate_layer1_reports_rate_limited_without_marker() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 7),
            r#"{"type":"result","subtype":"error_rate_limit","retry_after":"2026-06-18T15:45:30Z"}"#,
        )
        .unwrap();

        let result = evaluate_layer1(dir.path(), 7).unwrap();

        assert_eq!(result.status, AgentStatus::RateLimited);
        assert_eq!(
            result.reason.as_deref(),
            Some("rate limited until 2026-06-18T15:45:30Z")
        );
    }

    /// A real Claude rate-limit envelope carries `is_error: true` alongside
    /// `subtype: "error_rate_limit"`. The specific RateLimited classification
    /// must outrank the generic is_error → Failed path, or sequentagent's
    /// handoff/cron machinery never triggers for the exact case it exists for.
    #[test]
    fn evaluate_layer1_rate_limit_envelope_with_is_error_is_rate_limited() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 7),
            r#"{"type":"result","subtype":"error_rate_limit","is_error":true,"retry_after":"2026-06-18T15:45:30Z"}"#,
        )
        .unwrap();

        let result = evaluate_layer1(dir.path(), 7).unwrap();

        assert_eq!(result.status, AgentStatus::RateLimited);
        assert_eq!(
            result.reason.as_deref(),
            Some("rate limited until 2026-06-18T15:45:30Z")
        );
    }

    /// CR-01 (13-REVIEW.md) completion: the monitor path writes raw agent
    /// bytes to the stdout file via sh redirection, so evaluate_layer1 must
    /// tolerate invalid UTF-8 rather than silently disabling all Layer-1
    /// detection (the blocking-mode capture was fixed; the file read here is
    /// the other half of the same bug).
    #[test]
    fn evaluate_layer1_finds_marker_despite_invalid_utf8_bytes() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        let mut bytes = b"progress \xff\xfe garbage\n".to_vec();
        bytes.extend_from_slice(
            b"DEVFLOW_RESULT: {\"status\":\"failed\",\"reason\":\"review: bad\"}\n",
        );
        std::fs::write(stdout_path(dir.path(), 5), bytes).unwrap();

        let result = evaluate_layer1(dir.path(), 5).unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.reason.as_deref(), Some("review: bad"));
    }

    #[test]
    fn failing_external_probe_outranks_success_marker() {
        let dir = tempfile::tempdir().unwrap();
        let phase_dir = dir
            .path()
            .join(".planning/phases/16-pipeline-reliability-hardening");
        std::fs::create_dir_all(&phase_dir).unwrap();
        std::fs::write(
            phase_dir.join("16-03-PLAN.md"),
            "---\nphase: 16\nexternal_verify: \"test -f externally-shipped\"\n---\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 16),
            "DEVFLOW_RESULT: {\"status\":\"success\"}\n",
        )
        .unwrap();
        let state = state_in(dir.path(), 16);

        let approval = vec!["test -f externally-shipped".to_string()];
        let result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert!(
            result
                .reason
                .as_deref()
                .is_some_and(|reason| reason.contains("external verification failed"))
        );
    }

    /// D-05 gap 1 / D-06 (17-03): Layer 0 now evaluates on every stage, not
    /// only Code. Also covers the review-flagged worktree bug (Plan 03
    /// MEDIUM, OpenCode): PLAN discovery must read `project_root` (where
    /// `.planning/phases/` actually lives), while probe execution still
    /// reads `execution_root` (the worktree) — using the worktree for
    /// discovery would find zero commands and mis-fire the "PLAN removed"
    /// veto.
    #[test]
    fn external_probe_discovers_from_project_root_across_every_stage_and_executes_in_worktree() {
        let dir = tempfile::tempdir().unwrap();
        let worktree = dir.path().join("phase-worktree");
        std::fs::create_dir_all(&worktree).unwrap();
        let phase_dir = dir.path().join(".planning/phases/16-reliability");
        std::fs::create_dir_all(&phase_dir).unwrap();
        std::fs::write(
            phase_dir.join("16-01-PLAN.md"),
            "---\nexternal_verify: \"test -f implemented\"\n---\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 16),
            "DEVFLOW_RESULT: {\"status\":\"success\"}\n",
        )
        .unwrap();
        let mut state = state_in(dir.path(), 16);
        state.worktree_path = Some(worktree.clone());
        state.stage = Stage::Plan;

        let approval = vec!["test -f implemented".to_string()];

        // Layer 0 now fires on Plan too — the probe file does not yet exist
        // in the worktree, so this must fail on the probe itself (NOT a
        // false PLAN-removed veto, which would mean discovery silently
        // returned zero commands).
        let plan_result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();
        assert_eq!(plan_result.status, AgentStatus::Failed);
        assert!(
            plan_result
                .reason
                .as_deref()
                .is_some_and(|reason| reason.contains("external verification failed")),
            "expected a failing-probe reason, not a false PLAN-removed veto: {:?}",
            plan_result.reason
        );

        state.stage = Stage::Code;
        let code_result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();
        assert_eq!(code_result.status, AgentStatus::Failed);

        // The probe still executes against execution_root (the worktree) —
        // only PLAN discovery moved to project_root.
        std::fs::write(worktree.join("implemented"), "done").unwrap();
        let passing = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();
        assert_eq!(passing.status, AgentStatus::Success);
        assert_eq!(passing.decided_by_layer, Some(0));
    }

    #[test]
    fn changed_external_probe_never_inherits_prior_approval() {
        let dir = tempfile::tempdir().unwrap();
        let phase_dir = dir.path().join(".planning/phases/16-reliability");
        std::fs::create_dir_all(&phase_dir).unwrap();
        std::fs::write(
            phase_dir.join("16-01-PLAN.md"),
            "---\nexternal_verify: \"touch escaped\"\n---\n",
        )
        .unwrap();
        let state = state_in(dir.path(), 16);
        let approved = vec!["test -f reviewed-artifact".to_string()];

        let result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approved),
        )
        .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert!(result.reason.unwrap().contains("approval mismatch"));
        assert!(!dir.path().join("escaped").exists());
    }

    #[test]
    fn removed_external_probe_fails_closed_against_prior_approval() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 16),
            "DEVFLOW_RESULT: {\"status\":\"success\"}\n",
        )
        .unwrap();
        let state = state_in(dir.path(), 16);
        let approved = vec!["test -f shipped".to_string()];

        let result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approved),
        )
        .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert!(result.reason.unwrap().contains("declaration was removed"));
    }

    #[test]
    fn no_external_declaration_preserves_layer1_result() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 16),
            "DEVFLOW_RESULT: {\"status\":\"success\",\"commits\":2,\"summary\":\"done\"}\n",
        )
        .unwrap();
        let state = state_in(dir.path(), 16);
        let layer1 = evaluate_layer1(dir.path(), 16).unwrap();

        let full = evaluate_agent_result(dir.path(), &state, &GitFlowConfig::default()).unwrap();

        assert_eq!(
            serde_json::to_value(full).unwrap(),
            serde_json::to_value(layer1).unwrap()
        );
    }

    /// D-05 gap 2 (17-03): a declared, operator-approved external
    /// post-condition whose probe passes is affirmative Success evidence on
    /// its own — even with zero commits and on a non-Code stage (Define
    /// here). No agent stdout is written at all, so if Layer 0 did not
    /// short-circuit, there would be nothing for Layer 1 to find and Layer 2
    /// would fall through for lack of an exit-code file.
    #[test]
    fn layer0_affirmative_success_on_non_code_stage_with_zero_commits() {
        let dir = tempfile::tempdir().unwrap();
        let phase_dir = dir.path().join(".planning/phases/16-reliability");
        std::fs::create_dir_all(&phase_dir).unwrap();
        std::fs::write(
            phase_dir.join("16-01-PLAN.md"),
            "---\nexternal_verify: \"test -f shipped\"\n---\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("shipped"), "done").unwrap();
        let mut state = state_in(dir.path(), 16);
        state.stage = Stage::Define;

        let approval = vec!["test -f shipped".to_string()];
        let result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();

        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.decided_by_layer, Some(0));
        assert_eq!(result.commits, None);
    }

    /// Review Plan 03 LOW (Codex+OpenCode), 16a: an approved all-passing
    /// Layer 0 probe intentionally outranks a Layer 1 self-reported failure
    /// marker — proven here at the cascade level (`evaluate_agent_result_inner`),
    /// not merely in isolation on `evaluate_layer0`.
    #[test]
    fn layer0_affirmative_success_outranks_layer1_failure_marker() {
        let dir = tempfile::tempdir().unwrap();
        let phase_dir = dir
            .path()
            .join(".planning/phases/16-pipeline-reliability-hardening");
        std::fs::create_dir_all(&phase_dir).unwrap();
        std::fs::write(
            phase_dir.join("16-03-PLAN.md"),
            "---\nphase: 16\nexternal_verify: \"test -f externally-shipped\"\n---\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("externally-shipped"), "done").unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 16),
            "DEVFLOW_RESULT: {\"status\":\"failed\",\"reason\":\"agent self-reported failure\"}\n",
        )
        .unwrap();
        let state = state_in(dir.path(), 16);

        let approval = vec!["test -f externally-shipped".to_string()];
        let result = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();

        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.decided_by_layer, Some(0));
    }

    /// Ordering edge (17a): with multiple declared probes, ALL must pass for
    /// affirmative Success — the first failing probe vetoes the outcome
    /// regardless of which position it occupies among the declarations.
    #[test]
    fn multiple_declared_probes_first_failure_vetoes_regardless_of_order() {
        let dir = tempfile::tempdir().unwrap();
        let phase_dir = dir.path().join(".planning/phases/16-reliability");
        std::fs::create_dir_all(&phase_dir).unwrap();
        // 16-01 comes first alphabetically and passes; 16-02 comes second and fails.
        std::fs::write(
            phase_dir.join("16-01-PLAN.md"),
            "---\nexternal_verify: \"test -f passing-artifact\"\n---\n",
        )
        .unwrap();
        std::fs::write(
            phase_dir.join("16-02-PLAN.md"),
            "---\nexternal_verify: \"test -f never-created\"\n---\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("passing-artifact"), "done").unwrap();
        let mut state = state_in(dir.path(), 16);
        state.stage = Stage::Define;

        let approval = vec![
            "test -f passing-artifact".to_string(),
            "test -f never-created".to_string(),
        ];
        let result_a = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval),
        )
        .unwrap();
        assert_eq!(result_a.status, AgentStatus::Failed);
        assert!(
            result_a
                .reason
                .as_deref()
                .is_some_and(|reason| reason.contains("never-created")),
            "unexpected reason: {:?}",
            result_a.reason
        );

        // Swap which position fails: 16-01 now fails, 16-02 passes. The
        // overall outcome must still veto — order of declaration must not
        // matter.
        std::fs::write(
            phase_dir.join("16-01-PLAN.md"),
            "---\nexternal_verify: \"test -f still-missing\"\n---\n",
        )
        .unwrap();
        std::fs::write(
            phase_dir.join("16-02-PLAN.md"),
            "---\nexternal_verify: \"test -f passing-artifact\"\n---\n",
        )
        .unwrap();
        let approval_swapped = vec![
            "test -f still-missing".to_string(),
            "test -f passing-artifact".to_string(),
        ];
        let result_b = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval_swapped),
        )
        .unwrap();
        assert_eq!(result_b.status, AgentStatus::Failed);

        // Now make BOTH pass: only then is the outcome Success.
        std::fs::write(dir.path().join("still-missing"), "done").unwrap();
        let result_c = evaluate_agent_result_inner(
            dir.path(),
            &state,
            &GitFlowConfig::default(),
            Some(&approval_swapped),
        )
        .unwrap();
        assert_eq!(result_c.status, AgentStatus::Success);
        assert_eq!(result_c.decided_by_layer, Some(0));
    }

    #[test]
    fn archive_moves_captures_into_history_and_removes_pid_file() {
        // 16b: prior-stage captures must survive a simulated next-launch by
        // appearing under .devflow/history/phase-NN/, not be wiped outright.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join(".devflow")).unwrap();
        std::fs::write(root.join(".devflow/phase-01-stdout"), "prior stdout").unwrap();
        std::fs::write(root.join(".devflow/phase-01-exit"), "0").unwrap();
        std::fs::write(root.join(".devflow/phase-01-agent-pid"), "1234").unwrap();

        archive_phase_files(root, root, 1, 5).unwrap();

        // The live capture paths are gone (moved, not merely deleted).
        assert!(!root.join(".devflow/phase-01-stdout").exists());
        assert!(!root.join(".devflow/phase-01-exit").exists());
        // Agent-pid is bookkeeping, not diagnostic — still removed outright.
        assert!(!root.join(".devflow/phase-01-agent-pid").exists());

        let history = history_dir(root, 1);
        let archived: Vec<_> = std::fs::read_dir(&history)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        let archived_stdout = archived
            .iter()
            .find(|name| name.ends_with("-stdout"))
            .expect("stdout capture should be archived into history");
        assert!(archived.iter().any(|name| name.ends_with("-exit")));
        let contents = std::fs::read_to_string(history.join(archived_stdout)).unwrap();
        assert_eq!(contents, "prior stdout");
    }

    #[test]
    fn archive_is_noop_when_nothing_to_archive() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // Should not panic when there is nothing to archive (first launch).
        archive_phase_files(root, root, 1, 5).unwrap();
        assert!(!history_dir(root, 1).exists());
    }

    #[test]
    fn archive_handles_missing_devflow_dir() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // No .devflow dir at all — should not panic.
        archive_phase_files(root, root, 1, 5).unwrap();
    }

    #[test]
    fn archive_failure_preserves_live_capture_for_retry() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join(".devflow")).unwrap();
        std::fs::write(stdout_path(root, 1), "evidence").unwrap();
        // A file where the history directory must be forces create_dir_all
        // to fail before the live capture is moved or a monitor can truncate it.
        std::fs::write(root.join(".devflow/history"), "blocked").unwrap();

        assert!(archive_phase_files(root, root, 1, 5).is_err());
        assert_eq!(
            std::fs::read_to_string(stdout_path(root, 1)).unwrap(),
            "evidence"
        );
    }

    #[test]
    fn archive_second_publish_failure_rolls_back_complete_live_pair() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join(".devflow")).unwrap();
        std::fs::write(stdout_path(root, 1), "stdout evidence").unwrap();
        std::fs::write(exit_code_path(root, 1), "17").unwrap();
        let history = history_dir(root, 1);
        std::fs::create_dir_all(history.join("fixed-exit/blocker")).unwrap();

        assert!(archive_phase_files_with_stamp(root, root, 1, 5, "fixed").is_err());

        assert_eq!(
            std::fs::read_to_string(stdout_path(root, 1)).unwrap(),
            "stdout evidence"
        );
        assert_eq!(
            std::fs::read_to_string(exit_code_path(root, 1)).unwrap(),
            "17"
        );
        assert!(!history.join("fixed-stdout").exists());
        assert!(!history.join(".pending-fixed").exists());
    }

    #[test]
    fn archive_review_copy_failure_rolls_back_complete_live_pair() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let evidence_root = root.join("phase-worktree");
        std::fs::create_dir_all(root.join(".devflow")).unwrap();
        std::fs::write(stdout_path(root, 1), "stdout evidence").unwrap();
        std::fs::write(exit_code_path(root, 1), "23").unwrap();
        let review = evidence_root.join(".planning/phases/01-example/01-REVIEW.md");
        std::fs::create_dir_all(&review).unwrap();

        assert!(archive_phase_files_with_stamp(root, &evidence_root, 1, 5, "review-copy").is_err());

        assert_eq!(
            std::fs::read_to_string(stdout_path(root, 1)).unwrap(),
            "stdout evidence"
        );
        assert_eq!(
            std::fs::read_to_string(exit_code_path(root, 1)).unwrap(),
            "23"
        );
        let history = history_dir(root, 1);
        assert!(!history.join("review-copy-stdout").exists());
        assert!(!history.join("review-copy-exit").exists());
        assert!(!history.join(".pending-review-copy").exists());
    }

    #[test]
    fn archive_snapshots_current_review_into_same_generation() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let evidence_root = root.join("phase-worktree");
        std::fs::create_dir_all(root.join(".devflow")).unwrap();
        std::fs::write(stdout_path(root, 1), "attempt").unwrap();
        let phase_dir = evidence_root.join(".planning/phases/01-example");
        std::fs::create_dir_all(&phase_dir).unwrap();
        std::fs::write(phase_dir.join("01-REVIEW.md"), "review one").unwrap();

        let stamp = archive_phase_files(root, &evidence_root, 1, 5)
            .unwrap()
            .unwrap();

        assert_eq!(
            std::fs::read_to_string(history_dir(root, 1).join(format!("{stamp}-REVIEW.md")))
                .unwrap(),
            "review one"
        );
    }

    #[test]
    fn archive_prunes_history_to_retain_count() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::create_dir_all(root.join(".devflow")).unwrap();

        for i in 0..7 {
            std::fs::write(root.join(".devflow/phase-01-stdout"), format!("gen {i}")).unwrap();
            std::fs::write(root.join(".devflow/phase-01-exit"), "0").unwrap();
            archive_phase_files(root, root, 1, 3).unwrap();
        }

        let history = history_dir(root, 1);
        let stdout_count = std::fs::read_dir(&history)
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().ends_with("-stdout"))
            .count();
        let exit_count = std::fs::read_dir(&history)
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().ends_with("-exit"))
            .count();
        assert_eq!(stdout_count, 3, "expected at most 3 retained generations");
        assert_eq!(exit_count, 3, "expected at most 3 retained generations");
    }

    #[test]
    fn evaluate_agent_result_reads_files_end_to_end() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 6),
            "done\nDEVFLOW_RESULT: {\"status\":\"success\",\"commits\":2,\"summary\":\"ok\"}\n",
        )
        .unwrap();
        std::fs::write(exit_code_path(dir.path(), 6), "0").unwrap();
        let state = state_in(dir.path(), 6);

        let result = evaluate_agent_result(dir.path(), &state, &GitFlowConfig::default()).unwrap();

        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.commits, Some(2));
        assert_eq!(result.summary.as_deref(), Some("ok"));
    }

    #[test]
    fn evaluate_layer1_finds_devflow_result_in_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(
            stdout_path(dir.path(), 3),
            "output\ndevflow_result: {\"status\":\"failed\",\"reason\":\"bad output\"}\n",
        )
        .unwrap();

        let result = evaluate_layer1(dir.path(), 3).unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.reason.as_deref(), Some("bad output"));
    }

    #[test]
    fn evaluate_layer2_falls_back_to_exit_code_and_commit_count() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_commit(dir.path(), 4);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 4), "0").unwrap();
        let state = state_in(dir.path(), 4);

        let result = evaluate_layer2(dir.path(), 4, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.exit_code, Some(0));
        assert_eq!(result.commits, Some(1));
        assert!(result.reason.unwrap().contains("1 commits"));
    }

    #[test]
    fn evaluate_layer2_exit_zero_no_commits_is_failed() {
        // exit=0 but the feature branch has 0 commits ahead of develop →
        // "no work done" failure (the Layer 2 middle branch).
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_no_commit(dir.path(), 4);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 4), "0").unwrap();
        let state = state_in(dir.path(), 4);

        let result = evaluate_layer2(dir.path(), 4, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.exit_code, Some(0));
        assert_eq!(result.commits, Some(0));
        assert!(result.reason.unwrap().contains("no commits"));
    }

    #[test]
    fn evaluate_layer2_nonzero_exit_is_failed() {
        // Non-zero exit code → failure regardless of commit count.
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_commit(dir.path(), 4);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 4), "1").unwrap();
        let state = state_in(dir.path(), 4);

        let result = evaluate_layer2(dir.path(), 4, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.exit_code, Some(1));
        assert!(result.reason.unwrap().contains("exited with code 1"));
    }

    #[test]
    fn layer2_nonzero_exit_is_failed_all_stages() {
        // Non-zero exit is Failed regardless of stage — including Define and
        // Validate, which are exempt from the zero-commit gate but NOT from
        // the exit-code check.
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_no_commit(dir.path(), 10);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 10), "1").unwrap();

        for stage in [
            Stage::Define,
            Stage::Plan,
            Stage::Code,
            Stage::Validate,
            Stage::Ship,
        ] {
            let result = evaluate_layer2(dir.path(), 10, &GitFlowConfig::default(), stage)
                .unwrap()
                .unwrap();
            assert_eq!(
                result.status,
                AgentStatus::Failed,
                "stage {stage:?} should be Failed on nonzero exit"
            );
        }
    }

    #[test]
    fn layer2_skips_commit_gate_for_define_and_validate() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_no_commit(dir.path(), 11);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 11), "0").unwrap();

        for stage in [Stage::Define, Stage::Validate] {
            let result = evaluate_layer2(dir.path(), 11, &GitFlowConfig::default(), stage)
                .unwrap()
                .unwrap();
            assert_ne!(
                result.status,
                AgentStatus::Failed,
                "stage {stage:?} should not be Failed for zero commits"
            );
        }

        // Code stage with the same zero-commit inputs is still Failed
        // (existing behavior preserved).
        let result = evaluate_layer2(dir.path(), 11, &GitFlowConfig::default(), Stage::Code)
            .unwrap()
            .unwrap();
        assert_eq!(result.status, AgentStatus::Failed);
    }

    #[test]
    fn evaluate_layer3_falls_back_to_commit_count() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_commit(dir.path(), 5);

        let result = evaluate_layer3(dir.path(), 5, &GitFlowConfig::default()).unwrap();

        assert_eq!(result.status, AgentStatus::Unknown);
        assert_eq!(result.exit_code, None);
        assert_eq!(result.commits, Some(1));
        assert!(result.reason.unwrap().contains("1 commits"));
        assert_eq!(result.decided_by_layer, Some(3));
    }

    /// D-02/D-03 case 3 (17-03): "process gone, nothing accounted for" — zero
    /// commits and no declared external post-condition — is a fail-closed
    /// `Failed` outcome that flags human review, not a blanket advanceable
    /// `Unknown`. The commits-present case above stays `Unknown` (gated
    /// downstream by Plan 04's never-advance dispatch, D-04) — only the
    /// zero-commit sub-case is reclassified here.
    #[test]
    fn evaluate_layer3_zero_commits_is_failed_and_flags_human_review() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_no_commit(dir.path(), 5);

        let result = evaluate_layer3(dir.path(), 5, &GitFlowConfig::default()).unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
        assert_eq!(result.exit_code, None);
        assert_eq!(result.commits, Some(0));
        assert_eq!(result.decided_by_layer, Some(3));
        let reason = result.reason.unwrap();
        assert!(reason.contains("no work"), "reason was: {reason}");
        assert!(
            reason.to_ascii_lowercase().contains("human review"),
            "reason was: {reason}"
        );
    }

    #[test]
    fn parse_devflow_result_reads_verdict() {
        let stdout = r#"DEVFLOW_RESULT: {"status":"success","verdict":"gaps"}"#;
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, Some(Verdict::Gaps));
    }

    #[test]
    fn parse_devflow_result_reads_verdict_pass() {
        let stdout = r#"DEVFLOW_RESULT: {"status":"success","verdict":"pass"}"#;
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, Some(Verdict::Pass));
    }

    #[test]
    fn parse_devflow_result_verdict_absent_is_none() {
        let stdout = r#"DEVFLOW_RESULT: {"status":"success"}"#;
        let result = parse_devflow_result(stdout).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, None);
    }

    #[test]
    fn parse_devflow_result_malformed_verdict_is_none_not_parse_error() {
        // An unknown verdict string must not fail the whole marker parse —
        // status must still come through as Success with verdict None (T-13-14).
        let unknown = r#"DEVFLOW_RESULT: {"status":"success","verdict":"wat"}"#;
        let result = parse_devflow_result(unknown).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, None);

        // Mis-cased ("Pass" instead of "pass") must also be lenient, not an error.
        let miscased = r#"DEVFLOW_RESULT: {"status":"success","verdict":"Pass"}"#;
        let result = parse_devflow_result(miscased).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, None);
    }

    /// WR-09 (13-REVIEW.md): a `verdict` field present with a non-string
    /// JSON *type* (bool, number, object) must be just as lenient as a
    /// malformed string value — before the fix, deserializing straight to
    /// `Option<String>` errored out the entire `AgentResult` parse for a
    /// type mismatch, defeating the doc comment's "a malformed verdict must
    /// never silently drop a valid status" guarantee for this specific case.
    #[test]
    fn parse_devflow_result_non_string_verdict_type_is_none_not_parse_error() {
        let bool_verdict = r#"DEVFLOW_RESULT: {"status":"success","verdict":true}"#;
        let result = parse_devflow_result(bool_verdict).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, None);

        let numeric_verdict = r#"DEVFLOW_RESULT: {"status":"success","verdict":123}"#;
        let result = parse_devflow_result(numeric_verdict).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, None);

        let object_verdict = r#"DEVFLOW_RESULT: {"status":"success","verdict":{"x":1}}"#;
        let result = parse_devflow_result(object_verdict).unwrap();
        assert_eq!(result.status, AgentStatus::Success);
        assert_eq!(result.verdict, None);
    }

    /// D-07 (17-01): the two new multi-word variants must serialize with
    /// their word boundary preserved — `#[serde(rename_all = "lowercase")]`
    /// alone would collapse `ResourceKilled` to `"resourcekilled"` (Pitfall 1).
    #[test]
    fn multi_word_variants_serialize_with_word_boundary() {
        assert_eq!(
            serde_json::to_string(&AgentStatus::ResourceKilled).unwrap(),
            "\"resource_killed\""
        );
        assert_eq!(
            serde_json::to_string(&AgentStatus::AgentUnavailable).unwrap(),
            "\"agent_unavailable\""
        );
        assert_eq!(
            serde_json::from_str::<AgentStatus>("\"resource_killed\"").unwrap(),
            AgentStatus::ResourceKilled
        );
        assert_eq!(
            serde_json::from_str::<AgentStatus>("\"agent_unavailable\"").unwrap(),
            AgentStatus::AgentUnavailable
        );
    }

    /// Existing variants must keep their pre-existing lowercase wire form
    /// unchanged by the two new variants' additions.
    #[test]
    fn existing_variants_keep_wire_form() {
        assert_eq!(
            serde_json::to_string(&AgentStatus::Success).unwrap(),
            "\"success\""
        );
        assert_eq!(
            serde_json::to_string(&AgentStatus::Failed).unwrap(),
            "\"failed\""
        );
        assert_eq!(
            serde_json::to_string(&AgentStatus::RateLimited).unwrap(),
            "\"ratelimited\""
        );
        assert_eq!(
            serde_json::to_string(&AgentStatus::Unknown).unwrap(),
            "\"unknown\""
        );
    }

    /// review consensus #1: `as_wire_str()` must never diverge from the serde
    /// form for ANY variant — pin it for all six via a single round-trip
    /// assertion (quotes stripped).
    #[test]
    fn as_wire_str_matches_serde_form_for_every_variant() {
        for variant in [
            AgentStatus::Success,
            AgentStatus::Failed,
            AgentStatus::RateLimited,
            AgentStatus::Unknown,
            AgentStatus::ResourceKilled,
            AgentStatus::AgentUnavailable,
        ] {
            let serde_form = serde_json::to_string(&variant).unwrap();
            let stripped = serde_form.trim_matches('"');
            assert_eq!(
                variant.as_wire_str(),
                stripped,
                "as_wire_str() diverged from serde form for {variant:?}"
            );
        }
    }

    #[test]
    fn evaluate_layer2_exit_137_is_resource_killed() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_commit(dir.path(), 20);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 20), "137").unwrap();
        let state = state_in(dir.path(), 20);

        let result = evaluate_layer2(dir.path(), 20, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::ResourceKilled);
        assert_eq!(result.exit_code, Some(137));
    }

    #[test]
    fn evaluate_layer2_exit_127_is_agent_unavailable() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_commit(dir.path(), 21);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 21), "127").unwrap();
        let state = state_in(dir.path(), 21);

        let result = evaluate_layer2(dir.path(), 21, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::AgentUnavailable);
        assert_eq!(result.exit_code, Some(127));
    }

    /// Unchanged-behavior guard: exit 0 with zero commits on a commit-gated
    /// stage is still Failed (the pre-existing "no work done" branch, not
    /// reclassified by the new 137/127 checks).
    #[test]
    fn evaluate_layer2_exit_0_zero_commits_still_failed() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_no_commit(dir.path(), 22);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 22), "0").unwrap();
        let state = state_in(dir.path(), 22);

        let result = evaluate_layer2(dir.path(), 22, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
    }

    /// Unchanged-behavior guard: exit 1 is still Failed (not misclassified
    /// as ResourceKilled/AgentUnavailable).
    #[test]
    fn evaluate_layer2_exit_1_still_failed() {
        let dir = tempfile::tempdir().unwrap();
        init_repo_with_feature_commit(dir.path(), 23);
        std::fs::create_dir_all(dir.path().join(".devflow")).unwrap();
        std::fs::write(exit_code_path(dir.path(), 23), "1").unwrap();
        let state = state_in(dir.path(), 23);

        let result = evaluate_layer2(dir.path(), 23, &GitFlowConfig::default(), state.stage)
            .unwrap()
            .unwrap();

        assert_eq!(result.status, AgentStatus::Failed);
    }
}