devflow 2.4.0

DevFlow CLI — an opinionated take on AI-driven development automation
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
//! Build staleness/provenance (17d/18c, shaped by 18-06): deciding whether
//! the running `devflow` binary is stale relative to the tree under test
//! (the ancestry half of D-19's composite check plus the live dirty-tree
//! arm, CR-02/17-11), and enforcing that decision as a hard self-dogfood
//! block or a soft warning (D-17/D-18, 18c worktree-aware execution root).
//! Extracted mechanically (19-07, D-09 pure move) out of `main.rs` — every
//! function below is byte-identical to its pre-move body modulo an added
//! `pub(crate)` and adjusted `use` paths.

use devflow_core::events;
use devflow_core::gates;
use devflow_core::git::git_command;
use devflow_core::state::State;
use std::path::Path;

use crate::CliError;

/// Whether the build embedded in `embedded_commit` is stale relative to
/// `execution_root`'s current `HEAD` — the tree where the code under test
/// actually lives (18c: the phase's worktree when one is set, else
/// `project_root` — see `enforce_build_staleness`) — the ancestry half of
/// D-19's composite definition. Per git's documented exit-code contract for
/// `merge-base --is-ancestor` (exit 0 = ancestor, exit 1 = not, other =
/// error/unknown commit — Pitfall 4), exit 1 is treated as definitively
/// Stale; any other outcome (including an empty `embedded_commit` — D-20:
/// absence of provenance is not staleness) is Indeterminate, never a false
/// block. WR-01 (17-06 gap closure): exit 0 alone is NOT sufficient for
/// Fresh — `merge-base --is-ancestor` also exits 0 when `embedded_commit` is
/// a STRICT ancestor of HEAD (HEAD moved forward since the build), which is
/// exactly the "committed new commits, forgot to rebuild" incident class
/// this fix closes. An EXACT match to the current HEAD commit is genuinely
/// Fresh; so, per 23g, is a strict-ancestor OR a genuinely divergent
/// (mutually non-ancestor) range whose committed diff touches no
/// build-affecting file (`ancestry_range_affects_build`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Staleness {
    Fresh,
    Stale,
    /// The embedded commit is a strict DESCENDANT of `execution_root`'s
    /// HEAD: the binary is newer than the source it drives. Not the
    /// "committed, forgot to rebuild" incident this gate exists to catch,
    /// so it never blocks — but it is still a build/source mismatch worth
    /// surfacing.
    Ahead,
    Indeterminate,
}

fn embedded_commit_is_stale(execution_root: &Path, embedded_commit: &str) -> Staleness {
    if embedded_commit.is_empty() {
        return Staleness::Indeterminate;
    }
    let output = git_command(execution_root)
        .args(["merge-base", "--is-ancestor", embedded_commit, "HEAD"])
        .output();
    match output.map(|o| o.status.code()) {
        Ok(Some(0)) => match run_git_stdout(execution_root, &["rev-parse", "HEAD"]) {
            Some(head) if head.trim() == embedded_commit.trim() => Staleness::Fresh,
            Some(_) => {
                if ancestry_range_affects_build(execution_root, embedded_commit) {
                    Staleness::Stale
                } else {
                    Staleness::Fresh
                }
            }
            None => Staleness::Indeterminate,
        },
        // Exit 1 only says "not an ancestor" — which is true both for a
        // genuinely older/divergent commit AND for a descendant. Probe the
        // reverse direction to tell them apart, or an ahead build gets
        // reported as stale and hard-blocked.
        Ok(Some(1)) => {
            let reverse = git_command(execution_root)
                .args(["merge-base", "--is-ancestor", "HEAD", embedded_commit])
                .output();
            match reverse.map(|o| o.status.code()) {
                Ok(Some(0)) => Staleness::Ahead,
                // 23g (2026-07-26 acceptance-run false block): genuine
                // divergence — neither commit is an ancestor of the other —
                // is content-checked exactly like the strict-ancestor arm
                // above, reusing `ancestry_range_affects_build` verbatim. A
                // divergent range that touches nothing build-affecting
                // (e.g. only `.planning/` docs) must not hard-block.
                Ok(Some(1)) => {
                    if ancestry_range_affects_build(execution_root, embedded_commit) {
                        Staleness::Stale
                    } else {
                        Staleness::Fresh
                    }
                }
                _ => Staleness::Indeterminate,
            }
        }
        _ => Staleness::Indeterminate,
    }
}

/// 21d/D-07 (999.29), extended by 23g: whether the committed range between
/// `embedded_commit` and `execution_root`'s current `HEAD` touches at least
/// one build-affecting file — the content-aware narrowing of
/// `embedded_commit_is_stale`'s strict-ancestor arm AND (23g) its
/// divergent-lineage arm. DevFlow's own primary workflow commits docs
/// (`.planning/`) constantly; a docs-only commit must not re-arm a hard
/// block after every build, whether the resulting relationship is linear
/// staleness or genuine divergence. Reuses `affects_compiled_binary`
/// verbatim (D-07 — not forked or reimplemented). On any git failure,
/// returns `true` (fail toward Stale) so a git error is never a false Fresh
/// — mirrors `tree_has_modified_build_inputs`'s `None => Indeterminate`
/// posture, adapted here to "assume the worse outcome" since this helper
/// only returns a `bool`, not a tri-state.
fn ancestry_range_affects_build(execution_root: &Path, embedded_commit: &str) -> bool {
    run_git_stdout(
        execution_root,
        &["diff", "--name-only", embedded_commit, "HEAD"],
    )
    .map(|out| out.lines().any(affects_compiled_binary))
    .unwrap_or(true)
}

/// Shell `git` in `project_root`, returning `None` on any failure (missing
/// binary, non-git directory, non-zero exit) — same argv-array idiom as
/// `build.rs`'s `run_git`.
pub(crate) fn run_git_stdout(project_root: &Path, args: &[&str]) -> Option<String> {
    let output = git_command(project_root).args(args).output().ok()?;
    output
        .status
        .success()
        .then(|| String::from_utf8_lossy(&output.stdout).to_string())
}

/// The live half of D-19's composite staleness (CR-02, 17-11): whether
/// `execution_root`'s working tree — the tree where the code under test
/// actually lives (18c) — CURRENTLY has any tracked, modified file that can
/// change the compiled binary (`affects_compiled_binary`, reused from
/// 17-10 — not duplicated). No timestamp is available any more (`build.rs`
/// no longer embeds one — CR-02), so this cannot itself distinguish
/// "modified after the build" from "modified before the build, still
/// uncommitted"; combined with the build's own `build_dirty` flag in
/// `combined_staleness`, it distinguishes "built clean, source changed
/// since" (definitely Stale) from "built dirty, source still dirty"
/// (Indeterminate — cannot tell "same dirt" from "more dirt" without a
/// timestamp, Pitfall 4). Returns `None` when git itself is unavailable, so
/// the composite check falls back to the ancestry arm alone.
fn tree_has_modified_build_inputs(execution_root: &Path) -> Option<bool> {
    let status = run_git_stdout(execution_root, &["status", "--porcelain"])?;
    if status.trim().is_empty() {
        return Some(false);
    }
    // WR-03: enumerate from `--porcelain` itself rather than `git ls-files -m`.
    // `ls-files -m` compares worktree-vs-INDEX, so a *staged* source edit
    // (`git add src/lib.rs`) reports nothing while porcelain reports `M `.
    // That fell through to the ancestry arm as Fresh, letting a stale binary
    // drive its own workspace — the exact false-evidence class this gate exists
    // to catch. Untracked files stay excluded, as under `ls-files -m`.
    Some(
        status
            .lines()
            .any(|line| porcelain_tracked_path(line).is_some_and(affects_compiled_binary)),
    )
}

/// The repo-relative path a `git status --porcelain` line refers to, or `None`
/// for untracked (`??`) entries. Porcelain v1 lines are `XY<space>PATH`, with
/// renames/copies rendered as `ORIG -> PATH`; the destination is the path that
/// exists in the worktree. Paths containing special characters are quoted by
/// git, so surrounding quotes are stripped.
fn porcelain_tracked_path(line: &str) -> Option<&str> {
    if line.len() < 4 || line.starts_with("??") {
        return None;
    }
    let path = &line[3..];
    let path = path.rsplit(" -> ").next().unwrap_or(path);
    Some(path.trim_matches('"'))
}

/// Whether a repo-relative path can change the compiled binary. The live
/// dirty-tree arm of the staleness check must consider ONLY these: a dirty
/// `CHANGELOG.md` or `.planning/` file says nothing about whether the
/// binary matches its source.
///
/// Found live — DevFlow's own `ChangelogAppend` hook dirtied `CHANGELOG.md`
/// during the Validate→Ship transition, which an unfiltered check read as
/// a stale build, hard-blocking Ship on a file the pipeline had just written.
fn affects_compiled_binary(rel_path: &str) -> bool {
    const BUILD_AFFECTING_FILES: [&str; 4] = [
        "Cargo.toml",
        "Cargo.lock",
        "build.rs",
        "rust-toolchain.toml",
    ];
    rel_path.ends_with(".rs")
        || BUILD_AFFECTING_FILES
            .iter()
            .any(|name| rel_path == *name || rel_path.ends_with(&format!("/{name}")))
}

/// D-19: composite staleness (CR-02, 17-11: the dirty-flag arm replaces the
/// old mtime arm; the ancestry arm below is unchanged). Evaluates
/// `execution_root` — the tree where the code under test actually lives
/// (18c). Decision table for the second signal, evaluated only once
/// ancestry alone hasn't already settled Stale:
///
/// | build was dirty | tree has modified build inputs now | result |
/// |---|---|---|
/// | `false` | yes | **Stale** — built clean, source changed since (CR-02) |
/// | `true` | yes | **Indeterminate** — can't distinguish "same dirt" from |
/// |         |     | "more dirt" without a timestamp; warn, never block |
/// |         |     | (Pitfall 4) |
/// | either | no | fall through to the ancestry result unchanged |
fn combined_staleness(
    execution_root: &Path,
    embedded_commit: &str,
    build_dirty: bool,
) -> Staleness {
    let ancestry = embedded_commit_is_stale(execution_root, embedded_commit);
    if ancestry == Staleness::Stale {
        return Staleness::Stale;
    }
    match tree_has_modified_build_inputs(execution_root) {
        Some(true) if build_dirty => Staleness::Indeterminate,
        Some(true) => Staleness::Stale,
        _ => ancestry,
    }
}

/// D-17: whether `project_root` IS the DevFlow workspace itself (as opposed
/// to some other project being driven by a devflow binary) — deterministic,
/// offline, no config. Scans the `members = [...]` array of the root
/// `Cargo.toml` for BOTH exact member-path strings, never a package `name`
/// (the CLI crate's package is named `devflow`, not `devflow-cli` — a name
/// match would never fire on the incident workspace; review consensus #2 +
/// Plan 05 MEDIUM OpenCode). No TOML parser is used here: locating the
/// `members` array's bounds first, then scanning within it, is the
/// sanctioned middle ground and is unlikely to false-positive on an
/// unrelated project.
fn is_self_dogfood_workspace(project_root: &Path) -> bool {
    let Ok(contents) = std::fs::read_to_string(project_root.join("Cargo.toml")) else {
        return false;
    };
    // WR-05: anchor on the `members` KEY, not the first substring hit.
    // `default-members` contains `members`, so a bare `find` would scan that
    // array instead and silently degrade the self-dogfood hard block to a
    // warning the moment the root manifest gains a `default-members` key
    // above `members`.
    let Some(members_start) = contents.match_indices("members").find_map(|(idx, _)| {
        let preceded_by_ident = contents[..idx]
            .chars()
            .next_back()
            .is_some_and(|ch| ch.is_alphanumeric() || ch == '_' || ch == '-');
        (!preceded_by_ident).then_some(idx)
    }) else {
        return false;
    };
    let rest = &contents[members_start..];
    let Some(open_rel) = rest.find('[') else {
        return false;
    };
    let after_open = &rest[open_rel + 1..];
    let Some(close_rel) = after_open.find(']') else {
        return false;
    };
    let members = &after_open[..close_rel];
    // WR-02: compare each array element for exact equality rather than
    // substring-matching the whole array. `str::contains` would classify a
    // workspace whose members are `crates/devflow-core-extras` /
    // `crates/devflow-cli-plugin` as self-dogfood, and self-dogfood + Stale
    // hard-blocks the pipeline — the one outcome this must never inflict on
    // an unrelated project.
    let has_member = |wanted: &str| {
        members
            .split(',')
            .any(|entry| entry.trim().trim_matches(['"', '\'']).trim() == wanted)
    };
    has_member("crates/devflow-core") && has_member("crates/devflow-cli")
}

/// The outcome of the self-dogfood staleness gate (D-18): `Block` only when
/// the project IS DevFlow's own workspace AND its build is confirmed Stale —
/// everything else (an ordinary project, or an Indeterminate result on any
/// project, Pitfall 4) only warns or is silent. Kept pure so the
/// self-dogfood-blocks vs. ordinary-warns split is directly unit-testable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StalenessOutcome {
    Block,
    Warn,
    Ok,
}

fn staleness_outcome(is_self_dogfood: bool, staleness: Staleness) -> StalenessOutcome {
    match (is_self_dogfood, staleness) {
        (true, Staleness::Stale) => StalenessOutcome::Block,
        (false, Staleness::Stale) => StalenessOutcome::Warn,
        (_, Staleness::Ahead) => StalenessOutcome::Warn,
        (_, Staleness::Indeterminate) => StalenessOutcome::Warn,
        (_, Staleness::Fresh) => StalenessOutcome::Ok,
    }
}

/// D-17/D-18/D-19 (17d), execution_root (18c): the self-dogfood
/// build-staleness gate, called from `launch_stage` before
/// `monitor::spawn_monitor`. A Stale build against DevFlow's OWN workspace
/// is a hard block — deliberately NOT an approvable gate, because approving
/// it would reintroduce the exact Phase 16 false-evidence incident — but it
/// is never SILENT: notify + an event fire before the blocking error is
/// returned, so an unattended cron run still sees it (reconciling D-15's
/// never-silent idiom with D-18's hard block). An ordinary project (or an
/// Indeterminate result) only warns and proceeds.
///
/// 18c: ancestry/dirty-tree checks run against `execution_root` — the
/// phase's worktree when `state.worktree_path` is set, else `project_root`
/// — because that is the tree where the code under test actually lives.
/// Evaluating a worktree-based phase against `project_root` alone is Round
/// 4 CR-01's root cause: a binary behind the worktree branch can still be a
/// descendant of `project_root`'s HEAD and misclassify `Ahead` (warn only).
///
/// `is_self_dogfood_workspace` deliberately stays anchored on `project_root`
/// (Assumption A3, 18-RESEARCH.md Pitfall 4): it answers "is this workspace
/// DevFlow's own repo at all", not "is the binary stale relative to tree X"
/// — DevFlow's bookkeeping (`.planning/`, `.devflow/`) always lives in the
/// main checkout even when execution does not, and `events::emit` keeps
/// writing there too. A git worktree shares the same tracked files as the
/// commit it is checked out to, so in practice both roots agree; the
/// residual risk is a PLAN that modified the root `Cargo.toml`'s `members`
/// array on the feature branch mid-flight, making the two roots disagree.
pub(crate) fn enforce_build_staleness(
    project_root: &Path,
    state: &State,
    embedded_commit: &str,
    build_dirty: bool,
) -> Result<(), CliError> {
    let execution_root = state.worktree_path.as_deref().unwrap_or(project_root);
    let staleness = combined_staleness(execution_root, embedded_commit, build_dirty);
    let self_dogfood = is_self_dogfood_workspace(project_root);
    match staleness_outcome(self_dogfood, staleness) {
        StalenessOutcome::Block => {
            let message = format!(
                "self-dogfood stale build blocked for stage {}: a build-relevant file \
                 (.rs/Cargo.toml/Cargo.lock/build.rs/rust-toolchain.toml) changed in {}'s \
                 tracked source since this devflow binary was built, or its embedded commit \
                 is not an ancestor of current HEAD at all — rebuild devflow before driving \
                 its own workspace (D-18; the Phase 16 false-evidence incident){}",
                state.stage,
                execution_root.display(),
                if state.worktree_path.is_some() {
                    " — evaluated against this phase's WORKTREE HEAD, not the main checkout; \
                     rebuild and reinstall the binary before resuming"
                } else {
                    ""
                }
            );
            gates::fire_gate_notify(state.phase, state.stage, &message, true);
            // WR-02 (18-fix): `message` embeds `execution_root.display()` —
            // an absolute filesystem path (and, on a typical Linux/macOS
            // path, the operator's OS username). `fire_gate_notify` and the
            // returned `Err` below are the only places that path-bearing
            // string is allowed to reach — `events::emit` persists to
            // `.devflow/events.jsonl`, which `OPERATIONS.md` advertises as
            // safe to "tail from any tool", so it must never carry a path.
            // A bare, path-free label plus the two structured facts an
            // operator actually needs (which stage, and whether a worktree
            // was involved) are enough to explain the event without leaking
            // anything.
            events::emit(
                project_root,
                state.phase,
                "self_dogfood_stale_blocked",
                serde_json::json!({
                    "stage": state.stage.to_string(),
                    "reason": "stale_build_blocked",
                    "worktree": state.worktree_path.is_some(),
                }),
            );
            Err(CliError::Message(message))
        }
        StalenessOutcome::Warn => {
            println!(
                "warning: build provenance staleness check did not confirm a fresh build for \
                 stage {} — proceeding (only DevFlow's own workspace is ever hard-blocked, D-18)",
                state.stage
            );
            Ok(())
        }
        StalenessOutcome::Ok => Ok(()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pipeline_launch::launch_stage_inner;
    use crate::test_support::*;
    use devflow_core::mode::Mode;
    use devflow_core::stage::Stage;
    use devflow_core::state::AgentKind;
    use devflow_core::workflow;
    use std::path::PathBuf;

    // -----------------------------------------------------------------
    // 27-01 (D-03): run_git_stdout holds under a hostile GIT_DIR
    // -----------------------------------------------------------------

    /// D-03: `run_git_stdout` produces correct answers under a hostile
    /// `GIT_DIR` where it previously did not. Proven the same way
    /// `devflow_core::git`'s own hostile-`GIT_DIR` tests prove it (no
    /// process-global env mutation, Rust 2024 `unsafe`/unsound — Phase 25
    /// D-14): (a) a real spawn of the exact argv `run_git_stdout` issues,
    /// through the scrubbed `devflow_core::git::git_command`, with a
    /// foreign `GIT_DIR` chained on top of the scrub (hostile injection
    /// applied on top, the strongest form of the claim — `--show-toplevel`
    /// is immune via its own `GIT_WORK_TREE`-absent fallback to cwd), still
    /// resolves `root`; (b) the actual production function, called
    /// normally with nothing re-adding `GIT_DIR` afterward, returns the
    /// same answer.
    #[test]
    fn run_git_stdout_ignores_a_hostile_git_dir() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        let foreign = tempfile::tempdir().unwrap();
        let foreign_root = foreign.path();
        assert!(
            devflow_core::test_support::git_command(foreign_root)
                .args(["init", "-q"])
                .output()
                .unwrap()
                .status
                .success(),
            "git init failed in foreign repo"
        );

        // (a) the exact argv run_git_stdout issues, spawned through the
        // scrubbed constructor with a hostile GIT_DIR chained on top.
        let output = git_command(root)
            .args(["rev-parse", "--show-toplevel"])
            .env("GIT_DIR", foreign_root.join(".git"))
            .output()
            .expect("spawn git");
        let resolved = std::fs::canonicalize(String::from_utf8_lossy(&output.stdout).trim())
            .expect("canonicalize resolved toplevel");
        let expected = std::fs::canonicalize(root).expect("canonicalize root");
        assert_eq!(
            resolved, expected,
            "the argv run_git_stdout issues must resolve root even with a foreign GIT_DIR set"
        );

        // (b) the actual production function returns the same answer.
        let via_run_git_stdout = run_git_stdout(root, &["rev-parse", "--show-toplevel"])
            .expect("run_git_stdout must succeed");
        let resolved_prod = std::fs::canonicalize(via_run_git_stdout.trim())
            .expect("canonicalize run_git_stdout's result");
        assert_eq!(resolved_prod, expected);
    }

    /// D-17: matches only when BOTH exact member paths appear inside the
    /// `members = [...]` array — never a package `name` match.
    #[test]
    fn is_self_dogfood_workspace_matches_both_member_paths_only() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\n    \"crates/devflow-core\",\n    \"crates/devflow-cli\",\n]\n",
        )
        .unwrap();
        assert!(is_self_dogfood_workspace(root));

        let name_only = tempfile::tempdir().unwrap();
        std::fs::write(
            name_only.path().join("Cargo.toml"),
            "[package]\nname = \"devflow-cli\"\n",
        )
        .unwrap();
        assert!(
            !is_self_dogfood_workspace(name_only.path()),
            "a package NAME match must never fire — the CLI package is named `devflow`"
        );

        let partial = tempfile::tempdir().unwrap();
        std::fs::write(
            partial.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\"]\n",
        )
        .unwrap();
        assert!(!is_self_dogfood_workspace(partial.path()));

        let missing = tempfile::tempdir().unwrap();
        assert!(!is_self_dogfood_workspace(missing.path()));
    }

    /// WR-02: member paths that merely *contain* the real member names must
    /// not classify an unrelated workspace as self-dogfood — that combination
    /// hard-blocks the project's entire pipeline when its build reads Stale.
    #[test]
    fn is_self_dogfood_workspace_requires_exact_member_paths_not_substrings() {
        let lookalike = tempfile::tempdir().unwrap();
        std::fs::write(
            lookalike.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\n    \"crates/devflow-core-extras\",\n    \"crates/devflow-cli-plugin\",\n]\n",
        )
        .unwrap();
        assert!(
            !is_self_dogfood_workspace(lookalike.path()),
            "`devflow-core-extras`/`devflow-cli-plugin` are not the real members — \
             a substring match here would hard-block an unrelated project"
        );

        let prefixed = tempfile::tempdir().unwrap();
        std::fs::write(
            prefixed.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\n    \"vendor/crates/devflow-core\",\n    \"vendor/crates/devflow-cli\",\n]\n",
        )
        .unwrap();
        assert!(
            !is_self_dogfood_workspace(prefixed.path()),
            "vendored copies at a different path are not DevFlow's own workspace"
        );
    }

    /// WR-05: `"default-members"` contains `"members"`. A bare
    /// `contents.find("members")` locks onto that key's array instead, so the
    /// real member list is never scanned and the self-dogfood hard block
    /// silently degrades to a warning — with every existing test still green,
    /// because their fixtures all put `members = [...]` first.
    #[test]
    fn is_self_dogfood_workspace_anchors_on_members_not_default_members() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace]\n\
             default-members = [\"crates/devflow-cli\"]\n\
             members = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        assert!(
            is_self_dogfood_workspace(dir.path()),
            "a `default-members` key ahead of `members` must not hide the real \
             member list — that turns the D-18 hard block into a warning"
        );
    }

    /// Build a real `git worktree add` fixture for the 18c wrong-tree defect
    /// (Round 4 CR-01): a `develop` branch with one commit (the "embedded"
    /// commit, recorded before the worktree diverges) at
    /// `<tempdir>/project`, and a feature-branch worktree checked out from
    /// it as a SIBLING directory at `<tempdir>/worktree` — deliberately NOT
    /// nested under `project`, so a test can assert unambiguously on which
    /// of the two paths a message names (a nested worktree path would
    /// contain `project_root`'s path as a string prefix, making "worktree
    /// path present" and "project_root path absent" mutually exclusive
    /// assertions). Two further commits are made INSIDE the worktree, each
    /// touching a `.rs` file (build-affecting), so `project_root`'s HEAD
    /// never moves and the worktree's HEAD advances two commits past the
    /// recorded hash. Mirrors
    /// `worktree::tests::add_creates_worktree_on_new_branch`'s construction
    /// (`git worktree add -b <branch> <path> <start_point>`) — the closest
    /// existing precedent for a real worktree fixture.
    ///
    /// Returns `(tempdir_guard, worktree_path, embedded_commit)`.
    /// `project_root` is `tempdir_guard.path().join("project")`. The guard
    /// must be kept alive for the duration of the test.
    fn worktree_staleness_fixture() -> (tempfile::TempDir, PathBuf, String) {
        let outer = tempfile::tempdir().unwrap();
        let project_root = outer.path().join("project");
        std::fs::create_dir_all(&project_root).unwrap();
        let worktree_path = outer.path().join("worktree");

        let git = |args: &[&str], cwd: &Path| {
            assert!(
                devflow_core::test_support::git_command(cwd)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} in {cwd:?} failed"
            );
        };

        git(&["init", "-q", "-b", "develop"], &project_root);
        git(&["config", "user.email", "t@e.st"], &project_root);
        git(&["config", "user.name", "t"], &project_root);
        git(&["config", "commit.gpgsign", "false"], &project_root);
        git(&["config", "core.hooksPath", "/dev/null"], &project_root);
        std::fs::create_dir_all(project_root.join("src")).unwrap();
        std::fs::write(project_root.join("src/lib.rs"), "// base\n").unwrap();
        git(&["add", "."], &project_root);
        git(&["commit", "-q", "-m", "base"], &project_root);
        let embedded_commit = run_git_stdout(&project_root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        git(
            &[
                "worktree",
                "add",
                "-b",
                "feature/phase-90",
                worktree_path.to_str().unwrap(),
                "develop",
            ],
            &project_root,
        );

        // Two build-affecting commits, made ONLY inside the worktree —
        // project_root's HEAD (develop) never moves. This asymmetry (Fresh
        // against project_root, Stale against the worktree) is exactly the
        // Round 4 CR-01 mechanism.
        std::fs::write(worktree_path.join("src/lib.rs"), "// wt commit 1\n").unwrap();
        git(&["add", "."], &worktree_path);
        git(&["commit", "-q", "-m", "wt commit 1"], &worktree_path);
        std::fs::write(worktree_path.join("src/lib.rs"), "// wt commit 2\n").unwrap();
        git(&["add", "."], &worktree_path);
        git(&["commit", "-q", "-m", "wt commit 2"], &worktree_path);

        (outer, worktree_path, embedded_commit)
    }

    /// 18c (Round 4 CR-01 root cause): the SAME embedded commit is
    /// simultaneously `Fresh` against `project_root` and `Stale` against the
    /// worktree HEAD. Evaluating a worktree-based phase against
    /// `project_root` alone is exactly the bug — a binary two commits behind
    /// the worktree branch reads as if it were built from the current
    /// source. Both halves are asserted in one test: a single assertion
    /// would pass for the wrong reason if the fixture were built
    /// incorrectly.
    ///
    /// This test is already GREEN pre-fix — both calls are already
    /// parameterized by a root, so this proves the fixture is correct, not
    /// that the defect is fixed. The RED proof of the actual defect (the
    /// real entry point, `enforce_build_staleness`, evaluated against the
    /// wrong root) lives in
    /// `enforce_build_staleness_blocks_self_dogfood_behind_worktree_head`.
    ///
    /// (18-fix) `worktree_staleness_fixture` spawns real `git` subprocesses
    /// unguarded — under concurrent load this raced this file's
    /// PATH-mutating tests (the same `ENV_MUTEX`/19i flake class as
    /// `transition_resets_infra_failures`), reproduced at roughly 1-in-8 to
    /// 1-in-10. Guarded under `ENV_MUTEX` so it never runs concurrently with
    /// a PATH mutator, mirroring the established pattern rather than
    /// inventing a new one.
    #[test]
    fn embedded_commit_is_stale_uses_worktree_head() {
        let _guard = env_lock();

        let (outer, worktree_path, embedded_commit) = worktree_staleness_fixture();
        let project_root = outer.path().join("project");

        assert_eq!(
            embedded_commit_is_stale(&project_root, &embedded_commit),
            Staleness::Fresh,
            "project_root's HEAD never moved, so the embedded commit is still an exact match"
        );
        assert_eq!(
            embedded_commit_is_stale(&worktree_path, &embedded_commit),
            Staleness::Stale,
            "the worktree branch advanced two commits past the embedded commit — Round 4 \
             CR-01's mechanism: evaluated against the wrong tree, this same commit reads Fresh"
        );
    }

    /// 18c GREEN: `enforce_build_staleness` now evaluates ancestry against
    /// the worktree HEAD (via `execution_root`) rather than `project_root`,
    /// so a self-dogfood binary behind the worktree branch is a hard
    /// BLOCK — closing Round 4 CR-01, where the identical scenario
    /// evaluated against `project_root` alone classified `Ahead` (warn
    /// only) because the embedded commit was still a descendant of
    /// `develop`.
    ///
    /// (18-fix) Guarded under `ENV_MUTEX`, same rationale as
    /// `embedded_commit_is_stale_uses_worktree_head` — this test also drives
    /// `worktree_staleness_fixture`'s unguarded real `git` subprocesses.
    #[test]
    fn enforce_build_staleness_blocks_self_dogfood_behind_worktree_head() {
        let _guard = env_lock();

        let (outer, worktree_path, embedded_commit) = worktree_staleness_fixture();
        let project_root = outer.path().join("project");
        std::fs::write(
            project_root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        assert!(is_self_dogfood_workspace(&project_root));

        let phase = 90;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, project_root.clone());
        state.stage = Stage::Code;
        state.worktree_path = Some(worktree_path.clone());

        let err =
            enforce_build_staleness(&project_root, &state, &embedded_commit, false).unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains(&worktree_path.display().to_string()),
            "block message must name the worktree that was actually evaluated: {message}"
        );
        assert!(
            !message.contains(&project_root.display().to_string()),
            "block message must not name project_root when a worktree was evaluated: {message}"
        );

        // WR-02 (18-fix): the persisted event's `worktree` flag mirrors
        // `state.worktree_path.is_some()`, path-free.
        let last = devflow_core::events::last_event_for_phase(&project_root, phase)
            .expect("staleness block must record an event before returning the error");
        assert_eq!(last["reason"], "stale_build_blocked");
        assert_eq!(last["worktree"], true);
    }

    /// 25-03 (Task 2, D-03/D-04/D-05 regression): the staleness adjudication
    /// now happens exactly once, in `commands::start` — a mid-run stage
    /// transition (`pipeline_launch::launch_stage_inner`, the exact function
    /// 25b's Task 1 deleted the `enforce_build_staleness` call from) must not
    /// re-invoke it.
    ///
    /// Proven behaviourally, not structurally — a test that merely grepped
    /// `pipeline_launch.rs` for the absent call would pass against a
    /// re-introduction anywhere else in the launch path. Instead the SAME
    /// fixture, whose worktree HEAD is build-affecting-ahead of the embedded
    /// commit, is adjudicated twice: once the way `start` adjudicates it (a
    /// direct `enforce_build_staleness` call, which still refuses — the
    /// Phase 16 protection is intact, D-05), and once the way a mid-run
    /// stage transition adjudicates it (`launch_stage_inner`, driven with a
    /// stubbed `claude` binary so it can actually complete rather than fail
    /// for the unrelated reason of a missing agent binary). If the check
    /// were re-invoked anywhere in `launch_stage_inner`'s path, this second
    /// call would fail with the identical block error the first call just
    /// produced — instead it must succeed, and exactly one
    /// `self_dogfood_stale_blocked` event (the first call's) must exist for
    /// this phase afterward.
    ///
    /// Also re-asserts WR-02 on the first call's persisted event: the
    /// `reason` field stays a bare, path-free label even though the
    /// returned `CliError` (terminal-only) still names the worktree path.
    ///
    /// Guarded under `ENV_MUTEX` (999.38-class flake): drives
    /// `worktree_staleness_fixture`'s unguarded real `git` subprocesses AND
    /// mutates `PATH` for the stubbed `claude` binary.
    #[test]
    fn mid_run_stage_transition_does_not_readjudicate_staleness() {
        let _guard = env_lock();

        let (outer, worktree_path, embedded_commit) = worktree_staleness_fixture();
        let project_root = outer.path().join("project");
        std::fs::write(
            project_root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        assert!(is_self_dogfood_workspace(&project_root));

        // On top of the fixture's two committed "ahead" commits, leave an
        // UNCOMMITTED build-affecting edit in the worktree too. This makes
        // `combined_staleness`'s dirty-flag arm independently reach `Stale`
        // (`tree_has_modified_build_inputs` sees a modified `.rs` file) even
        // when a call site's `embedded_commit` is unrelated to this
        // fixture's own throwaway history — which is exactly what the REAL
        // production call sites use (`env!("DEVFLOW_BUILD_COMMIT")`, this
        // binary's own build commit, not this fixture's). Without this, the
        // RED discrimination check below (reverting Task 1's deletion)
        // would silently classify `Indeterminate` via a foreign-SHA
        // ancestry lookup and never actually reproduce the pre-fix block.
        std::fs::write(
            worktree_path.join("src/lib.rs"),
            "// wt uncommitted dirty change (not committed)\n",
        )
        .unwrap();

        let phase = 94;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, project_root.clone());
        state.stage = Stage::Code;
        state.worktree_path = Some(worktree_path.clone());
        // 31-03: Code is the stage widened to the `stream-json` transport, so
        // the `launch_stage_inner` call in part 2 below passes the D-15
        // delivery-canary gate. Recording an already-`Confirmed` outcome keeps
        // this test measuring what it was written to measure — that the
        // STALENESS check is not re-adjudicated mid-run — instead of failing on
        // an unrelated guard. The canary's own refusal path is covered by
        // `pipeline_launch::tests::launch_stage_inner_refuses_at_code_when_the_canary_cannot_confirm`.
        state.canary = Some(devflow_core::canary::CanaryOutcome::Confirmed);

        // 1. The `start`-shaped adjudication: called directly, exactly the
        // way `commands::start` now calls it — once, before any stage is
        // launched. The Phase 16 protection must still fire on a fresh
        // start.
        let err =
            enforce_build_staleness(&project_root, &state, &embedded_commit, false).unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains(&worktree_path.display().to_string()),
            "block message must name the worktree that was actually evaluated: {message}"
        );
        assert!(
            !message.contains(&project_root.display().to_string()),
            "block message must not name project_root when a worktree was evaluated: {message}"
        );
        let blocked_event = devflow_core::events::last_event_for_phase(&project_root, phase)
            .expect(
                "the start-shaped adjudication must record an event before returning the error",
            );
        assert_eq!(blocked_event["event"], "self_dogfood_stale_blocked");
        assert_eq!(blocked_event["reason"], "stale_build_blocked");
        assert_eq!(blocked_event["worktree"], true);
        let reason_str = blocked_event["reason"].as_str().unwrap();
        assert!(
            !reason_str.contains(&worktree_path.display().to_string())
                && !reason_str.contains(&project_root.display().to_string()),
            "persisted reason must never carry an absolute filesystem path (WR-02): {reason_str}"
        );

        // 2. The SAME fixture, driven through a mid-run stage transition.
        // `launch_stage_inner` is the exact function 25b's Task 1 deleted
        // the `enforce_build_staleness` call from — if the check were
        // re-invoked anywhere in this path, this call would fail with the
        // identical "self-dogfood stale build blocked" error produced
        // above; instead it must complete.
        workflow::save_state(&state).unwrap();
        let stub_dir = stub_agent_binary("claude");
        let original_path = std::env::var_os("PATH");
        let stubbed_path = prepend_path(&stub_dir, &original_path);
        // SAFETY: serialized under ENV_MUTEX.
        unsafe {
            std::env::set_var("PATH", &stubbed_path);
        }

        let result = launch_stage_inner(&mut state, None, None);

        // WR-03 / 999.46: the launch_stage_inner call above spawned a real
        // detached monitor wrapper. Bound here — this test's LAST `&mut
        // state` use — the guard reaps it, verified, before `outer` drops
        // below and unlinks the project root out from under it (999.44's
        // reproduction shape), and it outranks both panicking checkpoints
        // that follow: `result.expect(...)` and the `assert_eq!` on
        // `blocked_count` (G-25-2, 25-17).
        let _reap_guard = ReapMonitorOnDrop::after_launch(&state);

        // SAFETY: still serialized under ENV_MUTEX from above.
        unsafe {
            match &original_path {
                Some(path) => std::env::set_var("PATH", path),
                None => std::env::remove_var("PATH"),
            }
        }

        result.expect(
            "a mid-run stage transition must not re-invoke the staleness adjudication — this \
             same fixture just refused via the direct start-shaped call above",
        );

        // Exactly one self_dogfood_stale_blocked event must exist for this
        // phase — the direct start-shaped call's, not a second one fired by
        // launch_stage_inner.
        let all_events =
            std::fs::read_to_string(devflow_core::events::events_path(&project_root)).unwrap();
        let blocked_count = all_events
            .lines()
            .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
            .filter(|e| e["phase"] == phase && e["event"] == "self_dogfood_stale_blocked")
            .count();
        assert_eq!(
            blocked_count, 1,
            "exactly one self_dogfood_stale_blocked event must exist — the direct \
             start-shaped call's, not a second one from the mid-run stage transition"
        );
    }

    /// 18c (T-18-26): the SAME fixture with `worktree_path: None` must fall
    /// back to `project_root` and produce `Ok` — proving the
    /// `unwrap_or(project_root)` fallback preserves existing behavior for
    /// non-worktree phases and that this fix cannot start blocking them.
    ///
    /// (18-fix) Guarded under `ENV_MUTEX`, same rationale as
    /// `embedded_commit_is_stale_uses_worktree_head` — this test also drives
    /// `worktree_staleness_fixture`'s unguarded real `git` subprocesses.
    #[test]
    fn staleness_without_worktree_is_unchanged() {
        let _guard = env_lock();

        let (outer, _worktree_path, embedded_commit) = worktree_staleness_fixture();
        let project_root = outer.path().join("project");
        std::fs::write(
            project_root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();

        let phase = 91;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, project_root.clone());
        state.stage = Stage::Code;
        assert!(
            state.worktree_path.is_none(),
            "fixture precondition: no worktree recorded on this state"
        );

        assert!(
            enforce_build_staleness(&project_root, &state, &embedded_commit, false).is_ok(),
            "no worktree recorded must fall back to project_root, which the fixture never \
             advances past embedded_commit"
        );
    }

    /// Build a repo with a `base` commit, a diverged `side`-branch commit
    /// that is NOT an ancestor of the final `trunk` HEAD, then return to
    /// `trunk` — exercises all three `embedded_commit_is_stale` outcomes
    /// against a real git history.
    fn init_repo_with_diverged_commit(root: &Path) -> (String, String) {
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        let rev_parse = || {
            let out = devflow_core::test_support::git_command(root)
                .args(["rev-parse", "HEAD"])
                .output()
                .unwrap();
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        };

        git(&["init", "-q", "-b", "trunk"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);
        std::fs::write(root.join("a.txt"), "one").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);
        let base = rev_parse();

        git(&["checkout", "-q", "-b", "side"]);
        std::fs::write(root.join("side.txt"), "s").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "side"]);
        let side = rev_parse();

        git(&["checkout", "-q", "trunk"]);
        // 21d/D-07: a build-affecting `.rs` file, not a bare `.txt` — `base`
        // must stay a build-affecting strict ancestor of the final HEAD, or
        // the content-aware ancestry arm would (correctly) reclassify
        // `base -> Stale` as Fresh, breaking
        // `embedded_commit_is_stale_maps_ancestry_exit_codes`'s assertion.
        std::fs::write(root.join("trunk2.rs"), "// t2\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "trunk2"]);

        (base, side)
    }

    /// Pitfall 4 / WR-01: exit 1 -> Stale, and anything else (unknown
    /// commit, empty embedded commit) -> Indeterminate, never a false block.
    /// Exit 0 (merge-base --is-ancestor) splits further: a strict ancestor
    /// of HEAD -> Stale (WR-01 fix — `base` here is an ancestor of the
    /// fixture's final `trunk2` HEAD but is NOT HEAD itself, which is
    /// exactly the "committed, forgot to rebuild" incident class), and only
    /// an EXACT match to HEAD -> Fresh.
    #[test]
    fn embedded_commit_is_stale_maps_ancestry_exit_codes() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let (base, side) = init_repo_with_diverged_commit(root);
        let head = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        // `base` is a strict ancestor of the fixture's final `trunk2` HEAD —
        // this previously asserted Fresh, which encoded the WR-01 bug (a
        // clean-tree binary built from `base` would have been misclassified
        // Fresh even though two commits landed on top of it since).
        assert_eq!(embedded_commit_is_stale(root, &base), Staleness::Stale);
        // The genuine Fresh case: an exact match to the current HEAD.
        assert_eq!(embedded_commit_is_stale(root, &head), Staleness::Fresh);
        assert_eq!(embedded_commit_is_stale(root, &side), Staleness::Stale);
        assert_eq!(embedded_commit_is_stale(root, ""), Staleness::Indeterminate);
        assert_eq!(
            embedded_commit_is_stale(root, "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"),
            Staleness::Indeterminate
        );
    }

    // -----------------------------------------------------------------
    // 27-04 (D-01/D-03): embedded_commit_is_stale's two remaining direct
    // sites (base-commit lines 51, 72) now scrubbed via the git_command
    // constructor, called with execution_root
    // -----------------------------------------------------------------

    /// D-01/D-03: `embedded_commit_is_stale` produces the correct staleness
    /// verdict for `execution_root` even when a hostile `GIT_DIR` points at
    /// an unrelated repository. `GIT_DIR` is genuinely present in a
    /// process's environment for this proof — never via
    /// `std::env::set_var` on THIS test's own process (Rust 2024 `unsafe`,
    /// unsound under threaded tests — Phase 25 D-14, and the plan's own
    /// instruction). Instead it is set only on a freshly spawned CHILD
    /// process: this same test binary, re-invoked filtered to just this one
    /// test, with the hostile variable scoped to that one child's
    /// `Command::env()` call and nothing else — the literal "spawned child
    /// only" shape 27-01 established for its own hostile-`GIT_DIR` proofs
    /// (`git.rs`, `run_git_stdout_ignores_a_hostile_git_dir` above),
    /// extended here from "one child git process" to "one child test
    /// process" because `embedded_commit_is_stale` is a private function
    /// with no injection point of its own to chain `.env()` onto directly —
    /// and because (27-01-SUMMARY.md Deviation 1, empirically verified,
    /// git 2.55.0) chaining `.env("GIT_DIR", foreign)` directly onto a
    /// `git_command`-built Command genuinely redirects `merge-base
    /// --is-ancestor`'s ref resolution, so a literal reproduction of that
    /// shape would prove nothing about this function specifically.
    #[test]
    fn embedded_commit_is_stale_resolves_execution_root_under_a_hostile_git_dir() {
        const INNER_ROOT: &str = "DEVFLOW_27_04_STALE_INNER_ROOT";
        const INNER_COMMIT: &str = "DEVFLOW_27_04_STALE_INNER_COMMIT";

        if let Ok(root) = std::env::var(INNER_ROOT) {
            // Inner mode: this process was spawned by the outer half below
            // with GIT_DIR pointed at an unrelated foreign repository —
            // scoped to this child process only.
            let commit = std::env::var(INNER_COMMIT).expect("inner commit env set by parent");
            assert_eq!(
                embedded_commit_is_stale(Path::new(&root), &commit),
                Staleness::Stale,
                "a hostile GIT_DIR pointed at an unrelated repository must not \
                 change embedded_commit_is_stale's verdict for execution_root"
            );
            return;
        }

        // Outer mode: build the real repository (reusing
        // init_repo_with_diverged_commit's `base` — a build-affecting
        // strict ancestor of HEAD, a definite Stale verdict, same fixture
        // as embedded_commit_is_stale_maps_ancestry_exit_codes above) and a
        // second, unrelated foreign repository whose history does NOT
        // contain `base` at all.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let (base, _side) = init_repo_with_diverged_commit(root);

        let foreign = tempfile::tempdir().unwrap();
        let foreign_root = foreign.path();
        assert!(
            devflow_core::test_support::git_command(foreign_root)
                .args(["init", "-q"])
                .output()
                .unwrap()
                .status
                .success(),
            "git init failed in foreign repo"
        );

        let exe = std::env::current_exe().expect("current_exe for child re-invocation");
        let status = std::process::Command::new(&exe)
            .arg("embedded_commit_is_stale_resolves_execution_root_under_a_hostile_git_dir")
            .arg("--test-threads=1")
            .env(INNER_ROOT, root.to_str().unwrap())
            .env(INNER_COMMIT, &base)
            .env("GIT_DIR", foreign_root.join(".git"))
            .status()
            .expect("spawn hostile child test process");
        assert!(
            status.success(),
            "child test process (hostile GIT_DIR pointed at an unrelated \
             foreign repository) must still report embedded_commit_is_stale \
             == Stale for execution_root's own history; child exit status {status:?}"
        );
    }

    /// WR-01 regression (17-06 gap closure): reproduces the verifier's exact
    /// live-reproduction narrative (17-VERIFICATION.md Gap 2 / Truth 10) — a
    /// LINEAR, clean-tree, two-commit fixture where the embedded commit
    /// legitimately IS an ancestor of the new HEAD, so `merge-base
    /// --is-ancestor` exits 0 and the mtime arm never runs on a clean tree.
    /// Before the WR-01 fix, this was misclassified Fresh; it must now be
    /// Stale, and `enforce_build_staleness` must hard-block a self-dogfood
    /// workspace in exactly this scenario — the Phase 16 "committed,
    /// forgot to rebuild" incident class this gate exists to catch.
    #[test]
    fn wr01_clean_tree_strict_ancestor_build_is_stale_and_hard_blocks() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        // First commit: a workspace Cargo.toml (both crate member paths) plus
        // one other tracked file.
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        std::fs::write(root.join("a.txt"), "one").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "workspace init"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        // Second commit on top: a NEW build-affecting `.rs` file — no
        // modifications to already-committed files, so the tree stays clean.
        // 21d/D-07: this must stay a genuine code change after the build, or
        // the content-aware ancestry arm would (correctly) reclassify this
        // fixture Fresh, breaking this test's Stale/hard-block intent.
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/main.rs"), "fn main() {}\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "unrelated follow-up"]);

        // Clean-tree property: this is what makes the mtime arm never run,
        // leaving the ancestry arm as the sole signal — exactly the gap the
        // WR-01 fix closes.
        let status = run_git_stdout(root, &["status", "--porcelain"]).unwrap();
        assert!(
            status.trim().is_empty(),
            "fixture must have a clean working tree"
        );

        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Stale
        );
        assert_eq!(
            combined_staleness(root, &embedded_commit, false),
            Staleness::Stale
        );
        assert!(is_self_dogfood_workspace(root));

        let phase = 66;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Code;

        let err = enforce_build_staleness(root, &state, &embedded_commit, false).unwrap_err();
        assert!(
            err.to_string().contains("self-dogfood stale build blocked"),
            "{err}"
        );

        let last = devflow_core::events::last_event_for_phase(root, phase)
            .expect("staleness block must record an event before returning the error");
        assert_eq!(last["event"], "self_dogfood_stale_blocked");
    }

    /// A binary built from a branch AHEAD of `project_root`'s HEAD is newer
    /// than the source it drives — the inverse of the "committed, forgot to
    /// rebuild" incident. `merge-base --is-ancestor <embedded> HEAD` exits 1
    /// for BOTH a descendant and a genuinely divergent/older commit, so the
    /// bare `Ok(Some(1)) => Stale` mapping hard-blocked a fresher build. Found
    /// live: this phase's own Validate stage was blocked by a binary built
    /// from `feature/phase-17` while the checkout sat on `develop`.
    ///
    /// (999.38 / D-14, 25-03 Task 3) This test previously drove its fixture
    /// reads through the production helper `run_git_stdout`, which resolves
    /// `git` through the ambient PATH — unguarded, this raced this file's
    /// PATH-mutating tests under concurrent `cargo test --workspace`
    /// (the same `ENV_MUTEX`/19i flake class three sibling tests in this
    /// module already guard against, e.g. `embedded_commit_is_stale_uses_
    /// worktree_head`). Fixed the same way as those siblings: guarded under
    /// `ENV_MUTEX` so it never runs concurrently with a PATH mutator (this
    /// is serialization against PATH mutators, not process-global mutation —
    /// this test never calls `set_var` itself), and every fixture read now
    /// goes through `devflow_core::test_support::git_command`'s hermetic
    /// builder (matching the `git(&[...])` closure this test already uses
    /// for its other fixture calls) instead of the production
    /// `run_git_stdout` helper.
    ///
    /// **Deliberate residual, recorded rather than silently narrowed:**
    /// 999.38's broader ambition — converting the five PATH-mutating call
    /// sites in `pipeline_launch.rs`/`pipeline_outcomes.rs`/`preflight.rs`
    /// from process-global `std::env::set_var` to per-`Command` `env`,
    /// which would let `ENV_MUTEX` shrink or disappear — is explicitly out
    /// of this fold-in's scope (D-14: "one pass over one module"). Per
    /// 25-RESEARCH.md Pitfall 3, the idiom does NOT transfer cleanly to
    /// `ensure_agent_binary`/`agent_binary_available`, which read
    /// `std::env::var_os("PATH")` directly with no `Command` to attach to
    /// and would need a signature change to accept an injected search path.
    /// That remainder is scoped out on purpose, not missed — see
    /// `25-03-SUMMARY.md` for re-filing.
    #[test]
    fn ahead_build_from_descendant_commit_warns_instead_of_blocking() {
        let _guard = env_lock();

        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        // 999.38 (D-14): fixture stdout reads, hermetic like `git` above —
        // never the production `run_git_stdout` helper, which resolves
        // `git` through the ambient PATH.
        let git_stdout = |args: &[&str]| -> String {
            let output = devflow_core::test_support::git_command(root)
                .args(args)
                .output()
                .unwrap();
            assert!(output.status.success(), "git {args:?} failed");
            String::from_utf8_lossy(&output.stdout).trim().to_string()
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        std::fs::write(root.join("a.txt"), "one").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "workspace init"]);
        let base_commit = git_stdout(&["rev-parse", "HEAD"]);

        // The build is made from the LATER commit...
        std::fs::write(root.join("b.txt"), "two").unwrap();
        git(&["add", "."]);
        git(&[
            "commit",
            "-q",
            "-m",
            "newer work the checkout does not have",
        ]);
        let embedded_commit = git_stdout(&["rev-parse", "HEAD"]);

        // ...while the checkout is moved BACK, leaving the embedded commit a
        // strict descendant of HEAD on a clean tree (so the mtime arm stays
        // out of it and ancestry is the sole signal).
        git(&["reset", "--hard", "-q", &base_commit]);
        let status = git_stdout(&["status", "--porcelain"]);
        assert!(
            status.trim().is_empty(),
            "fixture must have a clean working tree"
        );

        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Ahead,
            "a descendant embedded commit is newer than HEAD, not stale"
        );
        assert_eq!(
            staleness_outcome(true, Staleness::Ahead),
            StalenessOutcome::Warn,
            "an ahead build must warn, never hard-block, even for self-dogfood"
        );

        let phase = 67;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Validate;
        assert!(
            enforce_build_staleness(root, &state, &embedded_commit, false).is_ok(),
            "ahead build must not block a self-dogfood workspace"
        );
    }

    /// The live dirty-tree arm must only consider files that can change the
    /// compiled binary. Found live: DevFlow's own `ChangelogAppend` hook
    /// dirtied `CHANGELOG.md` during the Validate->Ship transition, an
    /// unfiltered check read that as a stale build, and the self-dogfood
    /// gate hard-blocked Ship — the pipeline blocking itself on a markdown
    /// file it had just written. A modified `.rs` file must still flag
    /// Stale (when the build was clean), or the gate stops catching the
    /// real "committed, forgot to rebuild" case (CR-02, 17-11: rewritten
    /// against the dirty-flag rule — the fixture's guarantees are
    /// unchanged, only the timestamp mechanism is gone).
    #[test]
    fn dirty_flag_arm_ignores_non_build_files_but_still_flags_sources() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        std::fs::write(root.join("CHANGELOG.md"), "# Changelog\n").unwrap();
        std::fs::create_dir_all(root.join("crates/devflow-cli/src")).unwrap();
        std::fs::write(
            root.join("crates/devflow-cli/src/main.rs"),
            "fn main() {}\n",
        )
        .unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "workspace init"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        // This binary was built from a CLEAN tree (the CR-02 incident
        // scenario): `build_dirty` is false throughout.
        let build_dirty = false;

        // Only a doc is dirty — exactly the live Ship-block condition.
        std::fs::write(root.join("CHANGELOG.md"), "# Changelog\n\n## 1.4.26\n").unwrap();
        assert_eq!(
            run_git_stdout(root, &["ls-files", "-m"]).unwrap().trim(),
            "CHANGELOG.md",
            "fixture must have exactly one dirty tracked file"
        );
        assert_eq!(
            tree_has_modified_build_inputs(root),
            Some(false),
            "a dirty CHANGELOG.md cannot change the compiled binary"
        );
        assert_eq!(
            combined_staleness(root, &embedded_commit, build_dirty),
            Staleness::Fresh,
            "a doc-only dirty tree must not be Stale"
        );

        let phase = 68;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Ship;
        assert!(
            enforce_build_staleness(root, &state, &embedded_commit, build_dirty).is_ok(),
            "a doc-only dirty tree must not block Ship"
        );

        // Converse: a dirty source file, on a build that was clean, IS
        // stale — the CR-02 case this whole plan exists to fix.
        std::fs::write(
            root.join("crates/devflow-cli/src/main.rs"),
            "fn main() { /* edited after build */ }\n",
        )
        .unwrap();
        assert_eq!(
            tree_has_modified_build_inputs(root),
            Some(true),
            "a modified .rs file is genuine staleness input"
        );

        // WR-03: the same edit, STAGED, must read identically. `git ls-files -m`
        // compares worktree-vs-index and goes silent once the edit is staged,
        // which let a stale binary certify itself as Fresh.
        git(&["add", "crates/devflow-cli/src/main.rs"]);
        assert!(
            !run_git_stdout(root, &["ls-files", "-m"])
                .unwrap()
                .lines()
                .any(|line| line.ends_with(".rs")),
            "fixture precondition: `ls-files -m` is blind to the staged .rs edit"
        );
        assert_eq!(
            tree_has_modified_build_inputs(root),
            Some(true),
            "a STAGED source edit is just as much a staleness input as an unstaged one"
        );
        assert_eq!(
            combined_staleness(root, &embedded_commit, build_dirty),
            Staleness::Stale,
            "a staged, uncommitted source edit on a clean build is Stale"
        );
        git(&["reset", "-q"]);
        assert_eq!(
            combined_staleness(root, &embedded_commit, build_dirty),
            Staleness::Stale
        );
        assert!(
            enforce_build_staleness(root, &state, &embedded_commit, build_dirty).is_err(),
            "a stale source build must still hard-block a self-dogfood workspace"
        );
    }

    /// D-19 composite/OR: a clean tree whose embedded commit IS an ancestor
    /// (HEAD itself) is Fresh regardless of `build_dirty`; but once a
    /// TRACKED, build-affecting file is modified (dirty tree) on a build
    /// that was made from a CLEAN tree, the dirty-flag arm flips the
    /// composite result to Stale even though ancestry alone says Fresh —
    /// this is the CR-02 case itself. CR-02 (17-11): renamed and rewritten
    /// against the dirty-flag rule (no more timestamp/mtime comparison);
    /// the test's *intent* — a second signal can flip an ancestry-Fresh
    /// result to Stale — survives unchanged.
    #[test]
    fn combined_staleness_dirty_flag_arm_flags_modified_tree_when_build_was_clean() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);
        // 17-10: the dirty file must be a BUILD-AFFECTING one. This fixture
        // used `a.txt`, which encoded the over-broad mtime arm that hard-blocked
        // Ship on a dirty CHANGELOG.md. The test's intent — a second signal
        // flips an ancestry-Fresh result to Stale — is unchanged; only the
        // fixture is corrected to a file that can actually change the binary.
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// one\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "init"]);
        let head = {
            let out = devflow_core::test_support::git_command(root)
                .args(["rev-parse", "HEAD"])
                .output()
                .unwrap();
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        };

        assert_eq!(embedded_commit_is_stale(root, &head), Staleness::Fresh);
        assert_eq!(combined_staleness(root, &head, false), Staleness::Fresh);

        std::fs::write(root.join("src/lib.rs"), "// modified after build\n").unwrap();
        assert_eq!(combined_staleness(root, &head, false), Staleness::Stale);
    }

    /// 21d/D-07 (999.29): a strict-ancestor range whose ONLY intervening
    /// commit touches a non-build file (here, `.planning/x.md`) must read
    /// `Fresh`, not `Stale` — the false-positive hard-block observed live
    /// during this very phase's launch (binary embedded commit a strict
    /// ancestor of HEAD, delta `.planning/*` only, yet hard-blocked).
    /// Written RED first against the unmodified `Some(_) =>
    /// Staleness::Stale` arm to confirm it fails Stale, then GREEN once
    /// `ancestry_range_affects_build` narrows that arm.
    #[test]
    fn docs_only_range_is_fresh() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// base\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        // The only intervening commit touches a doc, never a build input.
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/x.md"), "docs only\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "docs only"]);

        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Fresh,
            "a docs-only strict-ancestor range must not hard-block (999.29)"
        );
        assert_eq!(
            combined_staleness(root, &embedded_commit, false),
            Staleness::Fresh
        );
    }

    /// 21d/D-07: real-change protection preserved — a mixed range that
    /// touches BOTH a doc (`.planning/x.md`) AND a NESTED `.rs` file
    /// (`crates/devflow-cli/src/main.rs`, proving nested-path routing
    /// through `affects_compiled_binary`, not just a top-level `.rs`) must
    /// still read `Stale` (Phase 16 false-evidence protection preserved).
    #[test]
    fn mixed_range_docs_and_source_is_stale() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        std::fs::create_dir_all(root.join("crates/devflow-cli/src")).unwrap();
        std::fs::write(
            root.join("crates/devflow-cli/src/main.rs"),
            "fn main() {}\n",
        )
        .unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        // One intervening commit touches BOTH a doc and a nested .rs file.
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/x.md"), "docs\n").unwrap();
        std::fs::write(
            root.join("crates/devflow-cli/src/main.rs"),
            "fn main() { /* changed */ }\n",
        )
        .unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "docs + nested source"]);

        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Stale,
            "a mixed docs+source range must still hard-block (real-change protection preserved)"
        );
        assert_eq!(
            combined_staleness(root, &embedded_commit, false),
            Staleness::Stale
        );
    }

    /// 21d/D-07 (Codex + OpenCode LOW): the stated-but-previously-untested
    /// fail-toward-Stale safety posture. Forces `git diff --name-only` to
    /// fail over the ancestry range while leaving `git merge-base
    /// --is-ancestor` (pure commit-graph traversal, no tree access) able to
    /// succeed: the embedded commit's root TREE object is deleted from the
    /// local object store while its COMMIT object stays intact. A git
    /// failure in the ancestry arm must never read as a false `Fresh`.
    #[test]
    fn git_error_range_fails_toward_stale() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// base\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();
        let embedded_tree =
            run_git_stdout(root, &["rev-parse", &format!("{embedded_commit}^{{tree}}")])
                .expect("rev-parse tree")
                .trim()
                .to_string();

        // Advance HEAD so the embedded commit is a strict ancestor.
        std::fs::write(root.join("src/lib.rs"), "// second\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "second"]);

        assert!(
            devflow_core::test_support::git_command(root)
                .args(["merge-base", "--is-ancestor", &embedded_commit, "HEAD"])
                .status()
                .unwrap()
                .success(),
            "fixture precondition: embedded commit must be a strict ancestor of HEAD"
        );

        // Delete the embedded commit's root tree object — its commit object
        // stays intact (merge-base keeps working, needing only commit
        // objects) but `git diff --name-only` can no longer read the tree it
        // needs to enumerate changed paths.
        let object_path = root
            .join(".git/objects")
            .join(&embedded_tree[..2])
            .join(&embedded_tree[2..]);
        assert!(
            object_path.exists(),
            "fixture precondition: tree object must exist as a loose object at {object_path:?}"
        );
        std::fs::remove_file(&object_path).unwrap();

        assert!(
            run_git_stdout(root, &["diff", "--name-only", &embedded_commit, "HEAD"]).is_none(),
            "fixture precondition: git diff must fail once the embedded commit's tree object is gone"
        );

        assert!(
            ancestry_range_affects_build(root, &embedded_commit),
            "a git failure in the ancestry arm must fail toward Stale (true), never a false Fresh"
        );
        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Stale,
            "a git diff failure over the ancestry range must never yield a false Fresh"
        );
    }

    /// The Indeterminate branch of the decision table (must_haves truth 5,
    /// 17-11): a build made from an ALREADY-dirty tree, run against a tree
    /// that STILL has modified build inputs, cannot tell "same dirt" from
    /// "more dirt" without a timestamp — so it must be Indeterminate, never
    /// Stale, even though ancestry alone says Fresh. Pitfall 4: Indeterminate
    /// must never hard-block, even for a self-dogfood workspace.
    #[test]
    fn combined_staleness_dirty_flag_arm_is_indeterminate_when_build_was_already_dirty() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// one\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "init"]);
        let head = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();
        assert!(is_self_dogfood_workspace(root));

        // The tree is dirty NOW (a build-affecting file is modified) — but
        // the embedded build's own dirty flag says it was ALSO built from a
        // dirty tree. Ancestry alone says Fresh (embedded_commit == HEAD).
        std::fs::write(root.join("src/lib.rs"), "// modified\n").unwrap();
        assert_eq!(embedded_commit_is_stale(root, &head), Staleness::Fresh);
        assert_eq!(
            tree_has_modified_build_inputs(root),
            Some(true),
            "fixture must have a dirty, build-affecting tree"
        );

        let build_was_dirty = true;
        assert_eq!(
            combined_staleness(root, &head, build_was_dirty),
            Staleness::Indeterminate,
            "cannot distinguish \"same dirt\" from \"more dirt\" without a timestamp"
        );

        let phase = 71;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Code;
        assert!(
            enforce_build_staleness(root, &state, &head, build_was_dirty).is_ok(),
            "Indeterminate must never hard-block, even for a self-dogfood workspace (Pitfall 4)"
        );
    }

    /// D-18: a self-dogfood workspace (matching `members = [...]`) with a
    /// confirmed-Stale embedded commit is a HARD block — but never silent:
    /// notify fires (best-effort; no `DEVFLOW_GATE_NOTIFY_CMD` is set here so
    /// it's a no-op) and an event is recorded BEFORE the blocking error is
    /// returned.
    #[test]
    fn enforce_build_staleness_blocks_self_dogfood_and_records_event_before_erroring() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let (_base, side) = init_repo_with_diverged_commit(root);
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "add workspace cargo toml"]);
        assert!(is_self_dogfood_workspace(root));

        let phase = 63;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Code;

        let err = enforce_build_staleness(root, &state, &side, false).unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains("self-dogfood stale build blocked"),
            "{message}"
        );
        assert!(
            message.contains(&root.display().to_string()),
            "the returned CliError (terminal-only) must still name the path: {message}"
        );

        let last = devflow_core::events::last_event_for_phase(root, phase)
            .expect("staleness block must record an event before returning the error");
        assert_eq!(last["event"], "self_dogfood_stale_blocked");
        // WR-02 (18-fix): the persisted event's reason must be a bare,
        // path-free label — the full path-bearing message is for
        // fire_gate_notify/the returned Err only, never events.jsonl.
        assert_eq!(last["reason"], "stale_build_blocked");
        assert_eq!(last["worktree"], false);
        let reason_str = last["reason"].as_str().unwrap();
        assert!(
            !reason_str.contains(&root.display().to_string()),
            "persisted reason must never carry the project root path: {reason_str}"
        );
    }

    /// D-18: an ordinary (non-self-dogfood) project with the same confirmed-
    /// Stale embedded commit only warns and proceeds — no event, no error.
    #[test]
    fn enforce_build_staleness_warns_for_ordinary_project_with_stale_commit() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let (_base, side) = init_repo_with_diverged_commit(root);
        assert!(!is_self_dogfood_workspace(root));

        let phase = 64;
        let state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());

        let result = enforce_build_staleness(root, &state, &side, false);
        assert!(
            result.is_ok(),
            "an ordinary project's stale build must only warn, never block"
        );
        assert!(
            devflow_core::events::last_event_for_phase(root, phase).is_none(),
            "a warn-only path must not fire the self_dogfood_stale_blocked event"
        );
    }

    /// Pitfall 4 / D-18: an Indeterminate result (unknown embedded commit)
    /// never hard-blocks, even for a self-dogfood workspace.
    #[test]
    fn enforce_build_staleness_never_blocks_on_indeterminate() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "init"]);
        assert!(is_self_dogfood_workspace(root));

        let phase = 65;
        let state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());

        let result = enforce_build_staleness(
            root,
            &state,
            "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef",
            false,
        );
        assert!(
            result.is_ok(),
            "an Indeterminate result must never hard-block"
        );
    }

    /// 23g (2026-07-26 acceptance-run regression, 23-16): a genuinely
    /// divergent range — neither commit an ancestor of the other, unlike
    /// `docs_only_range_is_fresh`'s strict-ancestor shape — whose only
    /// difference is a `.planning/` doc must classify `Fresh`, not `Stale`.
    /// This is the exact shape that blocked the 23-15 acceptance run: the
    /// running binary's embedded commit (`0c9dcfe`) and the target worktree's
    /// HEAD (`0dad20d`) were mutually non-ancestors, differing only by a
    /// `.planning/` doc, yet the unmodified bare-`Stale` reverse-probe arm
    /// hard-blocked unconditionally with no content check at all.
    /// Written RED first against that unmodified arm to confirm it fails on
    /// the `Fresh` assertion (not a fixture-precondition assertion, not a
    /// compile error), then GREEN once the divergent arm calls
    /// `ancestry_range_affects_build` exactly like the strict-ancestor arm
    /// above it already does.
    #[test]
    fn divergent_lineage_docs_only_range_is_fresh() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q", "-b", "trunk"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        // `base`: a build-affecting file both branches inherit unchanged, so
        // it never appears in the eventual diff between them.
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// base\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);

        // `embedded-side`'s tip becomes the embedded_commit under test —
        // adds only a doc.
        git(&["checkout", "-q", "-b", "embedded-side"]);
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/a.md"), "embedded side doc\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "embedded side: docs only"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        // Back to `trunk`, which advances independently — this becomes the
        // repo's current HEAD at assertion time. Neither branch's later
        // commit is an ancestor of the other.
        git(&["checkout", "-q", "trunk"]);
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/b.md"), "trunk doc\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "trunk: docs only"]);

        // Fixture precondition: confirm genuine divergence — neither commit
        // is an ancestor of the other — before trusting the assertion below,
        // so a broken fixture fails loudly rather than silently validating
        // the wrong shape.
        let forward = devflow_core::test_support::git_command(root)
            .args(["merge-base", "--is-ancestor", &embedded_commit, "HEAD"])
            .status()
            .unwrap();
        assert_eq!(
            forward.code(),
            Some(1),
            "fixture precondition: embedded commit must NOT be an ancestor of HEAD"
        );
        let reverse = devflow_core::test_support::git_command(root)
            .args(["merge-base", "--is-ancestor", "HEAD", &embedded_commit])
            .status()
            .unwrap();
        assert_eq!(
            reverse.code(),
            Some(1),
            "fixture precondition: HEAD must NOT be an ancestor of the embedded commit \
             either — this must be genuine divergence, not a strict-ancestor shape"
        );

        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Fresh,
            "23g / 2026-07-26 acceptance-run regression shape: a docs-only divergent \
             range must not hard-block"
        );
    }

    /// 23g: real-change protection preserved on the divergent path — the
    /// same mutually-non-ancestor construction as
    /// `divergent_lineage_docs_only_range_is_fresh`, but the range also
    /// touches a real `.rs` (build-affecting) file. Must still classify
    /// `Stale` — guards against the fix over-permitting a genuinely stale
    /// divergent build.
    #[test]
    fn divergent_lineage_with_source_change_is_stale() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q", "-b", "trunk"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// base\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);

        // `embedded-side`'s tip becomes the embedded_commit under test —
        // this time it modifies a real build-affecting file.
        git(&["checkout", "-q", "-b", "embedded-side"]);
        std::fs::write(root.join("src/lib.rs"), "// embedded side change\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "embedded side: source change"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        git(&["checkout", "-q", "trunk"]);
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/b.md"), "trunk doc\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "trunk: docs only"]);

        let forward = devflow_core::test_support::git_command(root)
            .args(["merge-base", "--is-ancestor", &embedded_commit, "HEAD"])
            .status()
            .unwrap();
        assert_eq!(
            forward.code(),
            Some(1),
            "fixture precondition: embedded commit must NOT be an ancestor of HEAD"
        );
        let reverse = devflow_core::test_support::git_command(root)
            .args(["merge-base", "--is-ancestor", "HEAD", &embedded_commit])
            .status()
            .unwrap();
        assert_eq!(
            reverse.code(),
            Some(1),
            "fixture precondition: HEAD must NOT be an ancestor of the embedded commit \
             either — this must be genuine divergence, not a strict-ancestor shape"
        );

        assert_eq!(
            embedded_commit_is_stale(root, &embedded_commit),
            Staleness::Stale,
            "a divergent range touching a real source file must still hard-block, \
             even after the 23g content-check fix"
        );
    }

    /// 23g end-to-end proof (test-signal-rejection pattern 4): the
    /// `divergent_lineage_docs_only_range_is_fresh` fixture, but driven
    /// through the real `enforce_build_staleness` entry point against a
    /// self-dogfood workspace, not only the pure `embedded_commit_is_stale`
    /// predicate. Proves the fix reaches the actual call path
    /// `devflow start` uses (the 23-15 acceptance run's real failure mode),
    /// not merely a source-level assertion one layer removed from it.
    #[test]
    fn enforce_build_staleness_does_not_block_self_dogfood_on_divergent_docs_only_lineage() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let git = |args: &[&str]| {
            assert!(
                devflow_core::test_support::git_command(root)
                    .args(args)
                    .output()
                    .unwrap()
                    .status
                    .success(),
                "git {args:?} failed"
            );
        };
        git(&["init", "-q", "-b", "trunk"]);
        git(&["config", "user.email", "t@e.st"]);
        git(&["config", "user.name", "t"]);
        git(&["config", "commit.gpgsign", "false"]);
        git(&["config", "core.hooksPath", "/dev/null"]);

        // `base`: a build-affecting file both branches inherit unchanged,
        // plus a workspace `Cargo.toml` so `is_self_dogfood_workspace` is
        // true for this fixture root.
        std::fs::create_dir_all(root.join("src")).unwrap();
        std::fs::write(root.join("src/lib.rs"), "// base\n").unwrap();
        std::fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"crates/devflow-core\", \"crates/devflow-cli\"]\n",
        )
        .unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "base"]);

        git(&["checkout", "-q", "-b", "embedded-side"]);
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/a.md"), "embedded side doc\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "embedded side: docs only"]);
        let embedded_commit = run_git_stdout(root, &["rev-parse", "HEAD"])
            .expect("rev-parse HEAD")
            .trim()
            .to_string();

        git(&["checkout", "-q", "trunk"]);
        std::fs::create_dir_all(root.join(".planning")).unwrap();
        std::fs::write(root.join(".planning/b.md"), "trunk doc\n").unwrap();
        git(&["add", "."]);
        git(&["commit", "-q", "-m", "trunk: docs only"]);

        let forward = devflow_core::test_support::git_command(root)
            .args(["merge-base", "--is-ancestor", &embedded_commit, "HEAD"])
            .status()
            .unwrap();
        assert_eq!(
            forward.code(),
            Some(1),
            "fixture precondition: embedded commit must NOT be an ancestor of HEAD"
        );
        let reverse = devflow_core::test_support::git_command(root)
            .args(["merge-base", "--is-ancestor", "HEAD", &embedded_commit])
            .status()
            .unwrap();
        assert_eq!(
            reverse.code(),
            Some(1),
            "fixture precondition: HEAD must NOT be an ancestor of the embedded commit \
             either — this must be genuine divergence, not a strict-ancestor shape"
        );

        assert!(
            is_self_dogfood_workspace(root),
            "fixture precondition: this workspace must be classified self-dogfood"
        );

        let phase = 66;
        let mut state = State::new(phase, AgentKind::Claude, Mode::Auto, root.to_path_buf());
        state.stage = Stage::Code;

        let result = enforce_build_staleness(root, &state, &embedded_commit, false);
        assert!(
            result.is_ok(),
            "23g: enforce_build_staleness must not hard-block the self-dogfood \
             divergent-docs-only-lineage shape that blocked the 23-15 acceptance run: \
             {result:?}"
        );
    }
}