cflx 0.6.327

Conflux – a spec-driven parallel coding orchestrator that runs AI agents on git worktrees
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
use crate::dependency_targets::DependencyTargetClass;
use crate::openspec::{VerificationCompletionRole, VerificationDeclaration, VerificationRoleIssue};
use crate::openspec_cmd::dependency_status::classify_proposal_dependency_targets;
use crate::openspec_cmd::promotion::merge_spec_delta;
use crate::openspec_cmd::rendering::truncate_for_display;
use regex::Regex;
use std::collections::HashSet;
use std::fs;
use std::path::{Component, Path};
use std::process::Command;
use std::sync::OnceLock;

pub(super) struct ValidationEngine<'a> {
    pub(super) manager: &'a super::OpenSpecManager,
}

impl<'a> ValidationEngine<'a> {
    pub(super) fn validate_change(
        &self,
        change_id: Option<&str>,
        strict: bool,
        evidence_mode: &str,
    ) -> (bool, Vec<String>, Vec<String>) {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        if let Some(id) = change_id {
            let change_dir = match self.manager.find_change_dir(id) {
                Ok(Some(d)) => d,
                Ok(None) => {
                    errors.push(format!("Change '{}' not found", id));
                    return (false, errors, warnings);
                }
                Err(error) => {
                    errors.push(error);
                    return (false, errors, warnings);
                }
            };
            let (e, w) = self.validate_change_dir(&change_dir, strict, evidence_mode);
            errors.extend(e);
            warnings.extend(w);
        } else {
            // Validate all changes
            if self.manager.changes_dir.exists() {
                if let Ok(entries) = fs::read_dir(&self.manager.changes_dir) {
                    for entry in entries.filter_map(|e| e.ok()) {
                        let path = entry.path();
                        if path.is_dir() {
                            let name = path
                                .file_name()
                                .unwrap_or_default()
                                .to_string_lossy()
                                .to_string();
                            if name == "archive" || name.starts_with('.') {
                                continue;
                            }
                            let (e, w) = self.validate_change_dir(&path, strict, evidence_mode);
                            errors.extend(e);
                            warnings.extend(w);
                        }
                    }
                }
            }
        }

        (errors.is_empty(), errors, warnings)
    }

    fn validate_change_dir(
        &self,
        change_dir: &Path,
        strict: bool,
        evidence_mode: &str,
    ) -> (Vec<String>, Vec<String>) {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();
        let change_id = change_dir
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
            .to_string();

        let proposal_file = change_dir.join("proposal.md");
        // The change entry owns exactly one task artifact; ambiguity is an error
        // rather than a precedence decision.
        let tasks_file = match crate::task_file::find_in_entry(change_dir) {
            Ok(file) => file,
            Err(error) => {
                errors.push(format!("{}: {}", change_id, error));
                None
            }
        };

        // Check required files
        if !proposal_file.exists() {
            errors.push(format!("{}: Missing proposal.md", change_id));
        }
        if tasks_file.is_none() && errors.iter().all(|error| !error.contains("Ambiguous")) {
            errors.push(format!(
                "{}: Missing {} or {}",
                change_id,
                crate::task_file::MARKDOWN_FILE_NAME,
                crate::task_file::JSON_FILE_NAME
            ));
        }

        // Validate proposal structure
        if proposal_file.exists() {
            if let Ok(content) = fs::read_to_string(&proposal_file) {
                static HEADING_RE: OnceLock<Regex> = OnceLock::new();
                let re = HEADING_RE.get_or_init(|| Regex::new(r"(?m)^#\s+.+$").unwrap());
                if !re.is_match(&content) {
                    errors.push(format!("{}: proposal.md missing title heading", change_id));
                }

                // Validate Change Type field in strict mode
                if strict {
                    let change_type = extract_change_type(&content);
                    match change_type.as_deref() {
                        None => errors.push(format!(
                            "{}: proposal.md missing 'Change Type' field (must be one of: hybrid, implementation, spec-only)",
                            change_id
                        )),
                        Some(ct) if !matches!(ct, "spec-only" | "implementation" | "hybrid") => {
                            errors.push(format!(
                                "{}: proposal.md has invalid Change Type '{}' (must be one of: hybrid, implementation, spec-only)",
                                change_id, ct
                            ));
                        }
                        _ => {}
                    }
                    let (verification_errors, verification_warnings) =
                        validate_verification_declarations(
                            &content,
                            &proposal_file,
                            &self.manager.root_dir,
                            &change_id,
                            change_type.as_deref(),
                        );
                    errors.extend(verification_errors);
                    warnings.extend(verification_warnings);

                    let (gate_errors, gate_warnings) = validate_release_gate_dependencies(
                        &self.manager.root_dir,
                        &change_id,
                        &content,
                        &proposal_file,
                    );
                    errors.extend(gate_errors);
                    warnings.extend(gate_warnings);
                }

                let dependency_diagnostics =
                    classify_proposal_dependency_targets(&change_id, &proposal_file);
                for diagnostic in dependency_diagnostics {
                    match diagnostic.classification {
                        DependencyTargetClass::Missing | DependencyTargetClass::Rejected => {
                            errors.push(diagnostic.message)
                        }
                        DependencyTargetClass::Archived => warnings.push(diagnostic.message),
                        DependencyTargetClass::Queued
                        | DependencyTargetClass::InFlight
                        | DependencyTargetClass::Resolving
                        | DependencyTargetClass::ActiveButNotQueued => {}
                        DependencyTargetClass::Error => unreachable!(
                            "proposal dependency classification cannot produce terminal-error state"
                        ),
                    }
                }
            }
        }

        // Validate tasks format in whichever representation the entry declares
        if let Some(tasks_file) = tasks_file.as_ref() {
            if let Ok(content) = fs::read_to_string(&tasks_file.path) {
                let proposal_content = fs::read_to_string(&proposal_file).ok();
                let change_type = proposal_content
                    .as_deref()
                    .and_then(extract_change_type)
                    .as_deref()
                    .map(str::to_string);
                let (te, tw) = validate_task_artifact(
                    tasks_file.format,
                    &content,
                    &change_id,
                    strict,
                    evidence_mode,
                    change_type.as_deref(),
                    proposal_content.as_deref(),
                );
                errors.extend(te);
                warnings.extend(tw);
            }
        }

        // Validate spec deltas (strict mode)
        if strict {
            let specs_dir = change_dir.join("specs");
            let no_delta_marker = specs_dir.join(".no-delta");

            if !specs_dir.exists() || !specs_dir.is_dir() {
                errors.push(format!(
                    "{}: No spec deltas found (required in strict mode)",
                    change_id
                ));
                return (errors, warnings);
            }

            let has_no_delta_marker = no_delta_marker.exists() && no_delta_marker.is_file();
            let spec_delta_dirs: Vec<_> = fs::read_dir(&specs_dir)
                .into_iter()
                .flatten()
                .filter_map(|e| e.ok())
                .filter(|e| e.path().is_dir())
                .collect();

            if has_no_delta_marker && !spec_delta_dirs.is_empty() {
                errors.push(format!(
                    "{}: specs/.no-delta conflicts with existing spec delta directories",
                    change_id
                ));
                return (errors, warnings);
            }

            if has_no_delta_marker {
                // Intentional no-delta change
                return (errors, warnings);
            }

            if !spec_delta_dirs.is_empty() {
                let se = self.validate_specs_dir(&specs_dir, &change_id);
                errors.extend(se);

                // Archive-risk warning for spec-only proposals
                if proposal_file.exists() {
                    if let Ok(content) = fs::read_to_string(&proposal_file) {
                        if extract_change_type(&content).as_deref() == Some("spec-only") {
                            let rw = check_archive_risk(&specs_dir, &change_id);
                            warnings.extend(rw);
                        }
                    }
                }
            } else {
                errors.push(format!(
                    "{}: No spec deltas found (required in strict mode)",
                    change_id
                ));
            }
        }

        (errors, warnings)
    }

    fn validate_specs_dir(&self, specs_dir: &Path, change_id: &str) -> Vec<String> {
        let mut errors = Vec::new();

        static REQ_RE: OnceLock<Regex> = OnceLock::new();
        static SCENARIO_RE: OnceLock<Regex> = OnceLock::new();
        let req_re = REQ_RE.get_or_init(|| Regex::new(r"(?m)^### Requirement:").unwrap());
        let scenario_re = SCENARIO_RE.get_or_init(|| Regex::new(r"(?m)^#### Scenario:").unwrap());

        if let Ok(entries) = fs::read_dir(specs_dir) {
            for entry in entries.filter_map(|e| e.ok()) {
                let path = entry.path();
                if !path.is_dir() {
                    continue;
                }

                let spec_name = path
                    .file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string();
                let spec_file = path.join("spec.md");

                if !spec_file.exists() {
                    errors.push(format!("{}: Missing spec.md in {}", change_id, spec_name));
                    continue;
                }

                if let Ok(content) = fs::read_to_string(&spec_file) {
                    // Check for delta markers
                    let has_delta = content.contains("## ADDED Requirements")
                        || content.contains("## MODIFIED Requirements")
                        || content.contains("## REMOVED Requirements");

                    if !has_delta {
                        errors.push(format!(
                            "{}: {}/spec.md missing delta markers (ADDED/MODIFIED/REMOVED)",
                            change_id, spec_name
                        ));
                    }

                    // Check for scenarios
                    let has_reqs = req_re.is_match(&content);
                    let has_scenarios = scenario_re.is_match(&content);

                    if has_reqs && !has_scenarios {
                        errors.push(format!(
                            "{}: {}/spec.md has requirements but no scenarios",
                            change_id, spec_name
                        ));
                    }

                    errors.extend(
                        self.validate_delta_targets_against_canonical(
                            &spec_name, &content, change_id,
                        ),
                    );
                }
            }
        }

        errors
    }

    fn validate_delta_targets_against_canonical(
        &self,
        spec_name: &str,
        delta_content: &str,
        change_id: &str,
    ) -> Vec<String> {
        let canonical_spec = self.manager.specs_dir.join(spec_name).join("spec.md");
        let canonical_content = if canonical_spec.exists() {
            fs::read_to_string(&canonical_spec).unwrap_or_default()
        } else {
            String::new()
        };

        let (_, promotion_errors) = merge_spec_delta(&canonical_content, delta_content);
        promotion_errors
            .into_iter()
            .filter(|err| {
                err.contains("MODIFIED target not found in canonical spec")
                    || err.contains("REMOVED target not found in canonical spec")
            })
            .map(|err| format!("{}: {}: {}", change_id, spec_name, err))
            .collect()
    }
}

pub(super) fn count_requirements_in_spec(spec_path: &Path) -> usize {
    static REQUIREMENT_RE: OnceLock<Regex> = OnceLock::new();
    let requirement_re =
        REQUIREMENT_RE.get_or_init(|| Regex::new(r"(?m)^### Requirement:").unwrap());

    match fs::read_to_string(spec_path) {
        Ok(content) => requirement_re.find_iter(&content).count(),
        Err(_) => 0,
    }
}

/// Classification of a top-level `tasks.md` section.
///
/// Task counting and task validation share this contract so a section can never
/// be counted as active work by one and narrative metadata by the other.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TaskSectionKind {
    /// Implementation work. Task-like bullets MUST use checkboxes.
    Active,
    /// Human-facing metadata (Final Validation, Implementation Blocker, Future
    /// Work, Out of Scope, Notes, Acceptance Notes). Ordinary prose and list
    /// metadata are permitted; checkboxes are not.
    Narrative,
    /// Runtime-owned acceptance follow-up. The runtime writes and clears these
    /// sections, so they keep their own parsing and validation behavior.
    RuntimeAcceptanceFollowUp,
}

impl TaskSectionKind {
    /// Whether checkbox tasks in this section participate in progress totals.
    fn counts_tasks(self) -> bool {
        !matches!(self, TaskSectionKind::Narrative)
    }
}

/// Narrative section markers matched as substrings of a lowercased heading.
///
/// `Recovered Acceptance Notes` and `Acceptance Notes` both match `notes`, and
/// `Implementation Blocker #3` matches `implementation blocker`.
const NARRATIVE_SECTION_MARKERS: &[&str] = &[
    "future work",
    "out of scope",
    "notes",
    "final validation",
    "implementation blocker",
];

/// Classify a top-level `tasks.md` heading line (`## ...`).
///
/// Runtime ownership wins over narrative matching so runtime-owned sections keep
/// their dedicated behavior regardless of wording overlap.
pub(crate) fn classify_task_section(heading_line: &str) -> TaskSectionKind {
    let section_name = heading_line.trim_start_matches('#').trim().to_lowercase();

    if section_name == "current acceptance follow-up"
        || (section_name.starts_with("acceptance #")
            && section_name.ends_with(" failure follow-up"))
    {
        return TaskSectionKind::RuntimeAcceptanceFollowUp;
    }

    if NARRATIVE_SECTION_MARKERS
        .iter()
        .any(|marker| section_name.contains(marker))
    {
        return TaskSectionKind::Narrative;
    }

    TaskSectionKind::Active
}

pub(super) fn count_tasks(content: &str) -> (u32, u32) {
    static CHECKBOX_RE: OnceLock<Regex> = OnceLock::new();
    static CHECKED_RE: OnceLock<Regex> = OnceLock::new();
    let checkbox_re = CHECKBOX_RE.get_or_init(|| Regex::new(r"^\s*[-*]\s*\[[ x]\]").unwrap());
    let checked_re = CHECKED_RE.get_or_init(|| Regex::new(r"^\s*[-*]\s*\[x\]").unwrap());

    let mut section = TaskSectionKind::Active;
    let mut completed = 0u32;
    let mut total = 0u32;
    let mut fences = crate::task_parser::FenceTracker::default();

    for line in content.lines() {
        // Fenced literals (e.g. recovered acceptance notes) are inert content.
        if fences.observe(line) {
            continue;
        }
        if line.starts_with("##") {
            // Runtime-owned follow-up subsections stay runtime-owned until the
            // next top-level section, mirroring task validation.
            if line.starts_with("###") && section == TaskSectionKind::RuntimeAcceptanceFollowUp {
                continue;
            }
            section = classify_task_section(line);
            continue;
        }
        if !section.counts_tasks() {
            continue;
        }
        if checkbox_re.is_match(line) {
            total += 1;
            if checked_re.is_match(line) {
                completed += 1;
            }
        }
    }

    (completed, total)
}

/// Read one change entry's task counts and body through the shared contract.
///
/// Returns `None` when the entry declares no readable task artifact — a missing
/// file, two competing filenames, or a JSON body that fails validation. This is
/// the read-only list/show projection; it never authorizes a workflow decision.
pub(super) fn count_entry_tasks(entry_dir: &Path) -> Option<(u32, u32, String)> {
    let file = crate::task_file::find_in_entry(entry_dir).ok().flatten()?;
    let content = fs::read_to_string(&file.path).ok()?;
    let (completed, total) = match file.format {
        crate::task_file::TaskFileFormat::Markdown => count_tasks(&content),
        crate::task_file::TaskFileFormat::Json => {
            let progress = crate::task_file::parse_json_document(&content)
                .ok()?
                .progress();
            (progress.completed, progress.total)
        }
    };
    Some((completed, total, content))
}

pub(super) fn extract_change_type(proposal_content: &str) -> Option<String> {
    static CT_RE: OnceLock<Regex> = OnceLock::new();
    let re = CT_RE.get_or_init(|| {
        Regex::new(r"(?mi)^\*\*Change Type\*\*\s*:\s*(.+)$|^Change Type\s*:\s*(.+)$").unwrap()
    });

    re.captures(proposal_content).map(|caps| {
        let value = caps
            .get(1)
            .or_else(|| caps.get(2))
            .unwrap()
            .as_str()
            .trim()
            .trim_matches('`')
            .to_lowercase();
        value
    })
}

fn validate_verification_declarations(
    proposal_content: &str,
    proposal_file: &Path,
    root_dir: &Path,
    change_id: &str,
    change_type: Option<&str>,
) -> (Vec<String>, Vec<String>) {
    let parsed =
        crate::openspec::parse_proposal_frontmatter_strict(proposal_content, proposal_file);
    let mut errors = parsed
        .diagnostics
        .into_iter()
        .map(|diagnostic| {
            format!(
                "{}: proposal.md verification metadata: {}",
                change_id, diagnostic
            )
        })
        .collect::<Vec<_>>();
    let mut warnings = Vec::new();
    let verifications = parsed
        .metadata
        .map(|metadata| metadata.verifications)
        .unwrap_or_default();
    let mut ids = HashSet::new();
    let mut has_pre_integration = false;

    for verification in &verifications {
        let label = verification.id.as_deref().unwrap_or("<missing id>");
        for (field, value) in [
            ("id", verification.id.as_deref()),
            ("requirement", verification.requirement.as_deref()),
            ("phase", verification.phase.as_deref()),
            ("owner", verification.owner.as_deref()),
            ("trigger", verification.trigger.as_deref()),
            ("automation", verification.automation.as_deref()),
            ("evidence", verification.evidence.as_deref()),
            ("rerun", verification.rerun.as_deref()),
        ] {
            if value.is_none_or(|value| value.trim().is_empty()) {
                errors.push(format!(
                    "{}: verification '{}': missing non-empty {}",
                    change_id, label, field
                ));
            }
        }
        match verification.prerequisites.as_deref() {
            None => errors.push(format!(
                "{}: verification '{}': missing prerequisites list",
                change_id, label
            )),
            Some(prerequisites) if prerequisites.iter().any(|item| item.trim().is_empty()) => {
                errors.push(format!(
                    "{}: verification '{}': prerequisites must not contain empty values",
                    change_id, label
                ));
            }
            Some(_) => {}
        }
        if let Some(id) = verification
            .id
            .as_deref()
            .filter(|id| !id.trim().is_empty())
        {
            if !ids.insert(id) {
                errors.push(format!("{}: duplicate verification id '{}'", change_id, id));
            }
        }
        match verification.phase.as_deref() {
            Some("pre-integration") => {
                has_pre_integration = true;
                if verification.owner.as_deref() != Some("conflux-acceptance") {
                    errors.push(format!(
                        "{}: verification '{}': pre-integration requires owner: conflux-acceptance",
                        change_id, label
                    ));
                }
            }
            Some("post-integration") => {
                if verification.owner.as_deref() != Some("repository-automation") {
                    errors.push(format!("{}: verification '{}': post-integration requires owner: repository-automation", change_id, label));
                }
            }
            Some(phase) => errors.push(format!(
                "{}: verification '{}': invalid phase '{}'",
                change_id, label, phase
            )),
            None => {}
        }
        if let Some(automation) = verification.automation.as_deref() {
            errors.extend(validate_automation_path(
                root_dir, change_id, label, automation,
            ));
        }
        warnings.extend(heavy_declaration_warnings(change_id, verification));
        for issue in crate::openspec::evaluate_verification_role(verification) {
            let message = verification_role_issue_message(change_id, label, verification, &issue);
            if issue.is_warning() {
                warnings.push(message);
            } else {
                errors.push(message);
            }
        }
    }

    if matches!(change_type, Some("implementation" | "hybrid")) && !has_pre_integration {
        errors.push(format!("{}: implementation and hybrid proposals require at least one pre-integration verification with repository-verifiable evidence", change_id));
    }
    (errors, warnings)
}

/// Render a role-metadata issue as an owning-proposal diagnostic.
///
/// Migration guidance is derived from the structured `phase` field rather than
/// prose so natural-language content never controls the classification.
fn verification_role_issue_message(
    change_id: &str,
    label: &str,
    verification: &VerificationDeclaration,
    issue: &VerificationRoleIssue,
) -> String {
    match issue {
        VerificationRoleIssue::UnknownExecutionClass(value) => format!(
            "{}: verification '{}': invalid execution_class '{}' (must be one of: {})",
            change_id, label, value, EXECUTION_CLASS_VALUES
        ),
        VerificationRoleIssue::UnknownCompletionRole(value) => format!(
            "{}: verification '{}': invalid completion_role '{}' (must be one of: change-blocking, operational-observation)",
            change_id, label, value
        ),
        VerificationRoleIssue::IncompleteRoleMetadata => format!(
            "{}: verification '{}': execution_class and completion_role must be declared together",
            change_id, label
        ),
        VerificationRoleIssue::PostIntegrationChangeBlocking(phase) => format!(
            "{}: verification '{}': completion_role: change-blocking requires phase: pre-integration (found '{}'); declare completion_role: {} instead",
            change_id,
            label,
            phase,
            VerificationCompletionRole::OperationalObservation.as_str()
        ),
        VerificationRoleIssue::NonLocalChangeBlocking(class) => format!(
            "{}: verification '{}': completion_role: change-blocking requires execution_class: repository-local (found '{}'); non-local outcomes must be completion_role: {} and must not block acceptance, archive, or merge",
            change_id,
            label,
            class.as_str(),
            VerificationCompletionRole::OperationalObservation.as_str()
        ),
        VerificationRoleIssue::LegacyRoleMetadataMissing => {
            let suggestion = match verification.phase.as_deref() {
                Some("post-integration") => {
                    "add execution_class: repository-automation (or another non-local class) and completion_role: operational-observation"
                }
                Some("pre-integration") => {
                    "add execution_class: repository-local and completion_role: change-blocking"
                }
                _ => "add execution_class and completion_role",
            };
            format!(
                "{}: verification '{}': legacy declaration without execution_class/completion_role; {} during migration",
                change_id, label, suggestion
            )
        }
    }
}

const EXECUTION_CLASS_VALUES: &str = "repository-local, repository-automation, deployed-service, physical-device, external-approval, credentialed-external";

/// Structured release-gate facts about one dependency target proposal.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct ReleaseGateTarget {
    /// The target's own frontmatter could not be decoded.
    pub(super) metadata_unreadable: bool,
    /// `(verification id, human-readable non-local reason)` pairs.
    pub(super) non_local_blockers: Vec<(String, String)>,
}

/// Extract release-gate facts from already-parsed declarations.
pub(super) fn release_gate_target_facts(
    verifications: &[VerificationDeclaration],
) -> ReleaseGateTarget {
    ReleaseGateTarget {
        metadata_unreadable: false,
        non_local_blockers: verifications
            .iter()
            .filter(|declaration| declaration.is_non_local_change_blocker())
            .map(|declaration| {
                let reason = match (declaration.execution_class(), declaration.phase.as_deref()) {
                    (Some(class), _) if !class.is_repository_local() => {
                        format!("execution class '{}'", class.as_str())
                    }
                    (_, Some(phase)) if phase != "pre-integration" => {
                        format!("phase '{}'", phase)
                    }
                    _ => "missing repository-local pre-integration metadata".to_string(),
                };
                (verification_label(declaration), reason)
            })
            .collect(),
    }
}

fn verification_label(declaration: &VerificationDeclaration) -> String {
    declaration
        .id
        .as_deref()
        .map(str::trim)
        .filter(|id| !id.is_empty())
        .unwrap_or("<missing id>")
        .to_string()
}

/// Classify one dependency edge from already-collected structured facts.
///
/// Pure decision logic: no filesystem, process, or network access, so the
/// release-gate rule can be verified in isolation from repository layout.
pub(super) fn classify_release_gate_edge(
    dependent: &str,
    dependent_is_observational: bool,
    dependent_in_flight: bool,
    target_id: &str,
    target: &ReleaseGateTarget,
) -> (Vec<String>, Vec<String>) {
    if target.metadata_unreadable {
        return (
            Vec::new(),
            vec![format!(
                "{}: proposal dependency '{}' has unreadable verification metadata; resolve the verification metadata errors reported on '{}' before this dependency edge can be classified",
                dependent, target_id, target_id
            )],
        );
    }

    // Release observations never block Conflux completion, so an observational
    // dependent cannot be stalled by the target's observational outcomes.
    if dependent_is_observational {
        return (Vec::new(), Vec::new());
    }

    let mut errors = Vec::new();
    let mut warnings = Vec::new();
    for (verification_id, reason) in &target.non_local_blockers {
        let message = format!(
            "{}: proposal dependency '{}' declares non-local change-blocking verification '{}' ({}); a repository-local implementation change must not depend on non-local release acceptance. Remedy: split '{}' into a repository-local implementation change plus a separate operational-observation release change, or remove this hard dependency",
            dependent, target_id, verification_id, reason, target_id
        );
        if dependent_in_flight {
            warnings.push(format!(
                "{} (in-flight operation is not interrupted; enforcement applies at the next dispatch eligibility decision)",
                message
            ));
        } else {
            errors.push(message);
        }
    }
    (errors, warnings)
}

/// Render reverse-dependency impact warnings for a target that declares a
/// non-local change blocker.
pub(super) fn reverse_impact_warnings(
    target_id: &str,
    blocker_ids: &[String],
    queued_dependents: &[String],
    in_flight_dependents: &[String],
) -> Vec<String> {
    if blocker_ids.is_empty() {
        return Vec::new();
    }

    let mut warnings = Vec::new();
    if !queued_dependents.is_empty() {
        warnings.push(format!(
            "{}: non-local change-blocking verification(s) [{}] affect queued dependents: {}. Those dependents become ineligible at their next dispatch eligibility decision",
            target_id,
            blocker_ids.join(", "),
            queued_dependents.join(", ")
        ));
    }
    if !in_flight_dependents.is_empty() {
        warnings.push(format!(
            "{}: in-flight dependents are not interrupted by this verification metadata change: {}",
            target_id,
            in_flight_dependents.join(", ")
        ));
    }
    warnings
}

/// Read a dependency target's structured release-gate facts.
///
/// Only valid structured declarations participate; prose is never consulted.
fn read_release_gate_target(root_dir: &Path, target_id: &str) -> Option<ReleaseGateTarget> {
    let target_proposal = root_dir
        .join("openspec/changes")
        .join(target_id)
        .join("proposal.md");
    let content = fs::read_to_string(&target_proposal).ok()?;
    let parsed = crate::openspec::parse_proposal_frontmatter_strict(&content, &target_proposal);
    if !parsed.diagnostics.is_empty() {
        return Some(ReleaseGateTarget {
            metadata_unreadable: true,
            non_local_blockers: Vec::new(),
        });
    }

    let verifications = parsed.metadata.map(|m| m.verifications).unwrap_or_default();
    Some(release_gate_target_facts(&verifications))
}

/// Whether a change is a correctly modeled release-observation change.
///
/// Such changes never block Conflux completion, so they may legitimately form
/// ordered chains among themselves and behind implementation changes.
pub(super) fn is_observational_release_change(verifications: &[VerificationDeclaration]) -> bool {
    let declared: Vec<_> = verifications
        .iter()
        .filter(|declaration| declaration.declares_role_metadata())
        .collect();
    !declared.is_empty()
        && declared.iter().all(|declaration| {
            declaration.completion_role()
                == Some(crate::openspec::VerificationCompletionRole::OperationalObservation)
        })
}

/// Reject hard dependency edges that turn non-local release acceptance into an
/// implementation-graph bottleneck, and report reverse-dependency impact.
///
/// Both directions are derived only from valid structured verification
/// declarations; the classification never reads natural-language content and
/// never contacts an external system.
fn validate_release_gate_dependencies(
    root_dir: &Path,
    change_id: &str,
    proposal_content: &str,
    proposal_file: &Path,
) -> (Vec<String>, Vec<String>) {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    let parsed =
        crate::openspec::parse_proposal_frontmatter_strict(proposal_content, proposal_file);
    let own_verifications = parsed.metadata.map(|m| m.verifications).unwrap_or_default();
    let dependent_is_observational = is_observational_release_change(&own_verifications);

    let dependencies =
        crate::openspec::parse_proposal_metadata_from_file(proposal_file).dependencies;
    let archived_ids = crate::dependency_targets::collect_archived_change_ids(root_dir);
    let active_ids = super::dependency_status::collect_active_change_ids_from_root(root_dir);
    let in_flight_ids = super::dependency_status::collect_in_flight_change_ids_from_root(root_dir);
    // An in-flight dependent keeps running; the new classification only takes
    // effect at its next dispatch eligibility decision.
    let dependent_in_flight = in_flight_ids.contains(change_id);

    for dependency in &dependencies {
        if dependency == change_id || archived_ids.contains(dependency) {
            continue;
        }
        if !active_ids.contains(dependency) && !in_flight_ids.contains(dependency) {
            // Missing/rejected targets already have dedicated diagnostics.
            continue;
        }
        let Some(target) = read_release_gate_target(root_dir, dependency) else {
            continue;
        };

        let (edge_errors, edge_warnings) = classify_release_gate_edge(
            change_id,
            dependent_is_observational,
            dependent_in_flight,
            dependency,
            &target,
        );
        errors.extend(edge_errors);
        warnings.extend(edge_warnings);
    }

    // Reverse-dependency impact: this change is the target that gained a blocker.
    let own_blockers: Vec<String> = own_verifications
        .iter()
        .filter(|declaration| declaration.is_non_local_change_blocker())
        .map(verification_label)
        .collect();
    if !own_blockers.is_empty() {
        let (queued, in_flight) =
            collect_dependents(root_dir, change_id, &active_ids, &in_flight_ids);
        warnings.extend(reverse_impact_warnings(
            change_id,
            &own_blockers,
            &queued,
            &in_flight,
        ));
    }

    (errors, warnings)
}

/// Collect active dependents of `target_id`, split into queued and in-flight.
fn collect_dependents(
    root_dir: &Path,
    target_id: &str,
    active_ids: &HashSet<String>,
    in_flight_ids: &HashSet<String>,
) -> (Vec<String>, Vec<String>) {
    let mut queued = Vec::new();
    let mut in_flight = Vec::new();

    for candidate in active_ids.iter().chain(in_flight_ids.iter()) {
        if candidate == target_id || queued.contains(candidate) || in_flight.contains(candidate) {
            continue;
        }
        let proposal = root_dir
            .join("openspec/changes")
            .join(candidate)
            .join("proposal.md");
        if !proposal.exists() {
            continue;
        }
        if !crate::openspec::parse_proposal_metadata_from_file(&proposal)
            .dependencies
            .iter()
            .any(|dependency| dependency == target_id)
        {
            continue;
        }
        if in_flight_ids.contains(candidate) {
            in_flight.push(candidate.clone());
        } else {
            queued.push(candidate.clone());
        }
    }

    queued.sort();
    in_flight.sort();
    (queued, in_flight)
}

fn validate_automation_path(
    root_dir: &Path,
    change_id: &str,
    id: &str,
    automation: &str,
) -> Vec<String> {
    let path = Path::new(automation);
    if automation.trim().is_empty()
        || path.is_absolute()
        || path
            .components()
            .any(|component| matches!(component, Component::ParentDir))
    {
        return vec![format!(
            "{}: verification '{}': unsafe automation path '{}'",
            change_id, id, automation
        )];
    }
    let candidate = root_dir.join(path);
    let canonical_root = match root_dir.canonicalize() {
        Ok(path) => path,
        Err(_) => {
            return vec![format!(
                "{}: verification '{}': cannot resolve repository root",
                change_id, id
            )]
        }
    };
    let canonical_candidate = match candidate.canonicalize() {
        Ok(path) => path,
        Err(_) => {
            return vec![format!(
                "{}: verification '{}': automation path '{}' does not exist",
                change_id, id, automation
            )]
        }
    };
    if !canonical_candidate.starts_with(&canonical_root) {
        return vec![format!(
            "{}: verification '{}': automation path '{}' escapes repository",
            change_id, id, automation
        )];
    }
    if !canonical_candidate.is_file() {
        return vec![format!(
            "{}: verification '{}': automation path '{}' is not a regular file",
            change_id, id, automation
        )];
    }
    match Command::new("git")
        .args(["ls-files", "--error-unmatch", "--", automation])
        .current_dir(root_dir)
        .output()
    {
        Ok(output) if output.status.success() => Vec::new(),
        Ok(_) => vec![format!(
            "{}: verification '{}': automation path '{}' is not tracked by git",
            change_id, id, automation
        )],
        Err(error) => vec![format!(
            "{}: verification '{}': cannot verify tracked automation path '{}': {}",
            change_id, id, automation, error
        )],
    }
}

/// Evidence hint patterns
const EVIDENCE_HINTS: &[&str] = &[
    "src/",
    "tests/",
    "test/",
    "source path",
    "source paths",
    "test file",
    "test files",
    "runnable command",
    "runnable commands",
    "uv run ",
    "pytest",
    "make ",
    "python ",
    "python3 ",
    "cflx validate",
    ".py",
    ".ts",
    ".js",
    ".rs",
    ".go",
    ".toml",
    ".spec",
    ".test",
    "dockerfile",
    " --once",
    "npm test",
    "npm run ",
    "npx ",
    "yarn ",
    "pnpm ",
    "cargo test",
    "cargo build",
    "docker build",
    "go test",
];

const VERIFICATION_OWNERSHIP_MARKERS: &[&str] = &[
    "unit",
    "integration",
    "e2e",
    "manual",
    "benchmark",
    "not-testable",
];

pub(super) fn has_repository_evidence_hint(verification_text: &str) -> bool {
    let normalized = verification_text.trim().to_lowercase();
    EVIDENCE_HINTS.iter().any(|hint| normalized.contains(hint))
}

pub(super) fn has_verification_ownership_marker(verification_text: &str) -> bool {
    let normalized = verification_text.trim().to_lowercase();
    VERIFICATION_OWNERSHIP_MARKERS
        .iter()
        .any(|marker| normalized.contains(marker))
}

// ---------------------------------------------------------------------------
// Change-blocking heavyweight-command migration warnings
// ---------------------------------------------------------------------------
//
// Structured frontmatter is the single command authority. Only
// `verifications[].evidence` and `verifications[].rerun` are inspected; task
// prose is never a command-authority source, and no cohesion rule is derived
// from task-note ownership markers or task-local commands.

/// Structural class of a declared command form that is known to be unbounded.
///
/// Every class is decided from command syntax alone. Prose is never consulted,
/// so narrative words such as "heavy" or "full" cannot create a classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum HeavyCommandCategory {
    ContainerOrchestration,
    ArchitectureEmulation,
    Benchmark,
    BroadSelector,
    StructuralRepetition,
}

impl HeavyCommandCategory {
    pub(super) fn as_str(self) -> &'static str {
        match self {
            Self::ContainerOrchestration => "container orchestration",
            Self::ArchitectureEmulation => "architecture emulation",
            Self::Benchmark => "benchmark",
            Self::BroadSelector => "broad selector",
            Self::StructuralRepetition => "structural repetition",
        }
    }
}

/// How one denylist entry matches an already-tokenized command.
///
/// Every variant compares whole tokens. Substring containment is deliberately
/// absent: it is what made `cargo test full_pipeline_smoke` look heavy and what
/// made a bounded `docker build` inseparable from `docker compose`.
enum HeavyPattern {
    /// Whole-token equality.
    Token(&'static str),
    /// Two adjacent whole tokens, e.g. `docker compose`.
    TokenPair(&'static str, &'static str),
    /// Whole-token prefix, used only for the `qemu-system-*` executable family.
    TokenPrefix(&'static str),
}

/// The migration denylist of structurally unbounded execution forms.
///
/// Entries are deterministic syntax, not semantics: each one names a command,
/// subcommand, or flag whose presence alone proves the execution cannot be a
/// bounded repository-local proof. `docker build` is deliberately absent — a
/// bounded image build is valid change-blocking evidence. Extend the list only
/// from observed false negatives that have equally deterministic syntax.
const HEAVY_COMMAND_RULES: &[(HeavyCommandCategory, HeavyPattern)] = &[
    // Container orchestration. `docker build` stays valid, so the `docker`
    // executable is matched only together with an orchestration subcommand.
    (
        HeavyCommandCategory::ContainerOrchestration,
        HeavyPattern::TokenPair("docker", "compose"),
    ),
    (
        HeavyCommandCategory::ContainerOrchestration,
        HeavyPattern::TokenPair("docker", "run"),
    ),
    (
        HeavyCommandCategory::ContainerOrchestration,
        HeavyPattern::TokenPair("docker", "swarm"),
    ),
    (
        HeavyCommandCategory::ContainerOrchestration,
        HeavyPattern::Token("docker-compose"),
    ),
    (
        HeavyCommandCategory::ContainerOrchestration,
        HeavyPattern::Token("podman"),
    ),
    (
        HeavyCommandCategory::ContainerOrchestration,
        HeavyPattern::Token("kubectl"),
    ),
    // Architecture emulation.
    (
        HeavyCommandCategory::ArchitectureEmulation,
        HeavyPattern::TokenPrefix("qemu-system"),
    ),
    (
        HeavyCommandCategory::ArchitectureEmulation,
        HeavyPattern::Token("cross"),
    ),
    // Benchmarks.
    (
        HeavyCommandCategory::Benchmark,
        HeavyPattern::TokenPair("cargo", "bench"),
    ),
    // Broad selectors.
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::Token("--workspace"),
    ),
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::Token("--all-features"),
    ),
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::Token("--ignored"),
    ),
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::Token("--include-ignored"),
    ),
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::Token("--exhaustive"),
    ),
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::TokenPair("--features", "heavy"),
    ),
    (
        HeavyCommandCategory::BroadSelector,
        HeavyPattern::Token("--features=heavy"),
    ),
    // Structural repetition.
    (
        HeavyCommandCategory::StructuralRepetition,
        HeavyPattern::Token("seq"),
    ),
    (
        HeavyCommandCategory::StructuralRepetition,
        HeavyPattern::Token("xargs"),
    ),
];

/// Shell punctuation trimmed from a token before whole-token comparison.
///
/// `$(seq 3)` and `| xargs` are structural repetition regardless of the shell
/// syntax carrying them, and a trailing `;` never changes what a token names.
const SHELL_PUNCTUATION: &[char] = &[
    '$', '(', ')', '{', '}', '[', ']', ';', '|', '&', '<', '>', '"', '\'', ',',
];

/// Normalize a declared command form for structural comparison.
///
/// Markdown backticks are removed, internal whitespace folds to one ASCII
/// space, the result is trimmed, and comparison is case-insensitive.
pub(super) fn normalize_command(command: &str) -> String {
    command
        .replace('`', "")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
        .to_lowercase()
}

/// Split an already-normalized command into comparable whole tokens.
pub(super) fn command_tokens(normalized: &str) -> Vec<&str> {
    normalized
        .split(' ')
        .map(|token| token.trim_matches(|c: char| SHELL_PUNCTUATION.contains(&c)))
        .filter(|token| !token.is_empty())
        .collect()
}

/// Classify a declared command form against the structural denylist.
///
/// Returns the first matching category and the exact matched form, or `None`
/// for a command whose tokens carry no known unbounded form.
pub(super) fn heavy_command_match(command: &str) -> Option<(HeavyCommandCategory, String)> {
    let normalized = normalize_command(command);
    if normalized.is_empty() {
        return None;
    }
    let tokens = command_tokens(&normalized);
    HEAVY_COMMAND_RULES
        .iter()
        .find_map(|(category, pattern)| match pattern {
            HeavyPattern::Token(value) => tokens
                .contains(value)
                .then(|| (*category, (*value).to_string())),
            HeavyPattern::TokenPair(first, second) => tokens
                .windows(2)
                .any(|pair| pair[0] == *first && pair[1] == *second)
                .then(|| (*category, format!("{} {}", first, second))),
            HeavyPattern::TokenPrefix(value) => tokens
                .iter()
                .find(|token| token.starts_with(value))
                .map(|token| (*category, (*token).to_string())),
        })
}

const BOUNDED_PROOF_REMEDY: &str = "prove the requirement with a bounded repository-local command, and give the broad execution its own operational-observation verification or repository automation";

/// Warn about heavyweight command forms declared on a change-blocking gate.
///
/// Pure decision logic over one already-parsed declaration. Findings are
/// migration warnings: they are actionable, they name the verification ID and
/// the matched form, and they never fail strict or archive-gate validation.
/// A legacy declaration without `completion_role` is not change-blocking, so
/// the policy stays inert for it.
pub(super) fn heavy_declaration_warnings(
    change_id: &str,
    verification: &VerificationDeclaration,
) -> Vec<String> {
    if !verification.is_change_blocking() {
        return Vec::new();
    }
    let label = verification_label(verification);
    declared_command_forms(verification)
        .into_iter()
        .filter_map(|(field, value)| {
            heavy_command_match(value).map(|(category, matched)| {
                format!(
                    "{}: verification '{}': change-blocking {} declares a heavyweight command form ({}: '{}'): '{}'; {}; this is a migration warning and does not fail archive-gate validation",
                    change_id,
                    label,
                    field,
                    category.as_str(),
                    matched,
                    normalize_command(value),
                    BOUNDED_PROOF_REMEDY
                )
            })
        })
        .collect()
}

/// Every declared command form carried by one verification declaration.
///
/// The declaration schema carries `evidence` and `rerun` today; a structured
/// argv field joins this list unchanged if the schema ever gains one.
fn declared_command_forms(verification: &VerificationDeclaration) -> Vec<(&'static str, &str)> {
    [
        ("evidence", verification.evidence.as_deref()),
        ("rerun", verification.rerun.as_deref()),
    ]
    .into_iter()
    .filter_map(|(field, value)| value.map(|value| (field, value)))
    .collect()
}

pub(super) fn find_case_insensitive(haystack: &str, needle: &str) -> Option<usize> {
    let needle_lower = needle.to_lowercase();
    haystack
        .char_indices()
        .map(|(idx, _)| idx)
        .find(|&idx| haystack[idx..].to_lowercase().starts_with(&needle_lower))
}

pub(super) fn extract_inline_verification(task_text: &str) -> Option<String> {
    let marker = "(verification:";
    let start = find_case_insensitive(task_text, marker)?;
    let mut depth = 1usize;
    let mut in_backticks = false;
    let content_start = start + marker.len();
    let mut content_end = None;

    for (relative_idx, ch) in task_text[content_start..].char_indices() {
        match ch {
            '`' => in_backticks = !in_backticks,
            '(' if !in_backticks => depth += 1,
            ')' if !in_backticks => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    content_end = Some(content_start + relative_idx);
                    break;
                }
            }
            _ => {}
        }
    }

    let end = content_end.unwrap_or(task_text.len());
    Some(task_text[content_start..end].trim().to_string())
}

pub(super) fn is_self_referential_final_validation_task(task_text: &str, change_id: &str) -> bool {
    let normalized = task_text.to_lowercase();
    let change_id = change_id.to_lowercase();

    let mentions_same_change_validation = normalized.contains("cflx openspec validate")
        && normalized.contains(&change_id)
        && (normalized.contains("--strict")
            || normalized.contains("--evidence")
            || normalized.contains("final")
            || normalized.contains("archive"));

    let asks_for_final_validation = normalized.contains("final openspec validation")
        || normalized.contains("final validation")
        || normalized.contains("archive validation")
        || normalized.contains("archive gate")
        || normalized.contains("archive readiness");

    mentions_same_change_validation && asks_for_final_validation
}

pub(super) fn self_referential_final_validation_message(
    change_id: &str,
    line_num: usize,
) -> String {
    format!(
        "{}: tasks.md:{}: self-referential final OpenSpec validation checkbox detected. \
         Final OpenSpec validation must not be a checkbox task; move final validation to a \
         non-checkbox `## Final Validation` section because archive validation is the authoritative gate.",
        change_id, line_num
    )
}

/// Deterministic task-format validation for a task artifact body.
///
/// This is the format-only subset of [`validate_task_artifact`]: for Markdown it
/// reports active-section bullets that look like tasks but lack checkboxes,
/// checkboxes inside narrative non-task sections, and self-referential
/// final-validation checkboxes; for JSON it reports the typed schema and
/// semantic failures plus the same final-validation rule. Evidence/verification
/// ownership policy is intentionally excluded so the runtime pre-accept gate
/// stays independent of proposal metadata and evidence mode.
pub(crate) fn validate_task_format(
    format: crate::task_file::TaskFileFormat,
    content: &str,
    change_id: &str,
) -> Vec<String> {
    let (errors, _) = validate_task_artifact(format, content, change_id, false, "off", None, None);
    errors
}

/// Validate one task artifact body in its declared representation.
///
/// Both representations answer the same questions — active versus narrative
/// classification, the Final Validation non-task rule, and verification
/// linkage — so a JSON-only change is held to exactly the Markdown contract.
#[allow(clippy::too_many_arguments)]
pub(super) fn validate_task_artifact(
    format: crate::task_file::TaskFileFormat,
    content: &str,
    change_id: &str,
    strict: bool,
    evidence_mode: &str,
    change_type: Option<&str>,
    proposal_content: Option<&str>,
) -> (Vec<String>, Vec<String>) {
    match format {
        crate::task_file::TaskFileFormat::Markdown => validate_tasks_content(
            content,
            change_id,
            strict,
            evidence_mode,
            change_type,
            proposal_content,
        ),
        crate::task_file::TaskFileFormat::Json => validate_json_tasks_content(
            content,
            change_id,
            strict,
            evidence_mode,
            change_type,
            proposal_content,
        ),
    }
}

/// Strict and format validation for a `tasks.json` body.
///
/// Schema and semantic failures fail closed as errors; nothing here can project
/// a valid-but-empty document out of an artifact the runtime cannot read.
pub(super) fn validate_json_tasks_content(
    content: &str,
    change_id: &str,
    strict: bool,
    evidence_mode: &str,
    change_type: Option<&str>,
    proposal_content: Option<&str>,
) -> (Vec<String>, Vec<String>) {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    let document = match crate::task_file::parse_json_document(content) {
        Ok(document) => document,
        Err(error) => return (vec![format!("{}: {}", change_id, error)], warnings),
    };

    let is_behavior_change = matches!(change_type, Some("implementation" | "hybrid"));
    let linkage = (strict && is_behavior_change)
        .then(|| VerificationLinkage::from_proposal(proposal_content))
        .flatten();

    for task in &document.tasks {
        let location = format!("{}:{}", crate::task_file::JSON_FILE_NAME, task.pointer);

        // Narrative final validation is prose; representing it as an ordinary
        // task is the same self-completion the Markdown rule refuses.
        if strict && is_self_referential_final_validation_task(&task.title, change_id) {
            errors.push(format!(
                "{}: {}/title: self-referential final OpenSpec validation checkbox detected. \
                 Final OpenSpec validation must not be a task; move final validation to the \
                 narrative `final_validation` field because archive validation is the authoritative gate.",
                change_id, location
            ));
            continue;
        }

        if let Some(linkage) = linkage.as_ref() {
            match task.verification_id.as_deref() {
                Some(reference) => {
                    if let Some(message) = linkage.evaluate_reference(reference) {
                        errors.push(format!("{}: {}/verification_id: {}", change_id, location, message));
                    }
                }
                None => errors.push(format!(
                    "{}: {}/verification_id: active implementation task must reference a change-blocking verification",
                    change_id, location
                )),
            }
        }

        if strict && evidence_mode != "off" && is_behavior_change {
            if task.verification_kind.is_none() {
                let message = format!(
                    "{}: {}/verification/kind: Verification ownership missing for behavior-changing task (expected one of: unit, integration, e2e, manual, benchmark, not-testable)",
                    change_id, location
                );
                push_by_evidence_mode(evidence_mode, message, &mut errors, &mut warnings);
            }
            let cites_evidence = task
                .verification_command
                .as_deref()
                .is_some_and(has_repository_evidence_hint);
            if !cites_evidence {
                let message = format!(
                    "{}: {}/verification/command: Verification note should cite repository-verifiable evidence such as source paths, tests, or runnable commands",
                    change_id, location
                );
                push_by_evidence_mode(evidence_mode, message, &mut errors, &mut warnings);
            }
        }
    }

    (errors, warnings)
}

fn push_by_evidence_mode(
    evidence_mode: &str,
    message: String,
    errors: &mut Vec<String>,
    warnings: &mut Vec<String>,
) {
    match evidence_mode {
        "error" => errors.push(message),
        "warn" => warnings.push(message),
        _ => {}
    }
}

/// Extract a `verification-id: <id>` reference from a task or continuation line.
pub(super) fn extract_verification_id_reference(text: &str) -> Option<String> {
    static VERIFICATION_ID_RE: OnceLock<Regex> = OnceLock::new();
    let re = VERIFICATION_ID_RE
        .get_or_init(|| Regex::new(r"(?i)verification-id\s*:\s*([A-Za-z0-9._-]+)").unwrap());
    re.captures(text)
        .and_then(|caps| caps.get(1))
        .map(|m| m.as_str().to_string())
}

/// Structured verification linkage requirements for one proposal's task list.
///
/// The requirement only activates once the proposal has migrated to the role
/// model; legacy declarations stay compatible and are handled by migration
/// warnings on the proposal itself.
struct VerificationLinkage {
    declared_ids: HashSet<String>,
    change_blocking_ids: HashSet<String>,
}

impl VerificationLinkage {
    fn from_proposal(proposal_content: Option<&str>) -> Option<Self> {
        let parsed = crate::openspec::parse_proposal_frontmatter_strict(
            proposal_content?,
            Path::new("proposal.md"),
        );
        let verifications = parsed.metadata.map(|m| m.verifications).unwrap_or_default();
        if !verifications
            .iter()
            .any(VerificationDeclaration::declares_role_metadata)
        {
            return None;
        }
        Some(Self {
            declared_ids: verifications
                .iter()
                .filter_map(|declaration| declaration.id.clone())
                .map(|id| id.trim().to_string())
                .filter(|id| !id.is_empty())
                .collect(),
            change_blocking_ids: crate::openspec::change_blocking_verification_ids(&verifications)
                .into_iter()
                .collect(),
        })
    }

    /// Location-independent verdict for one `verification-id` reference.
    ///
    /// `None` means the reference names a change-blocking verification. The
    /// message is shared by both representations so a JSON-only change and a
    /// Markdown change are refused for the same reason.
    fn evaluate_reference(&self, reference: &str) -> Option<String> {
        if self.change_blocking_ids.contains(reference) {
            return None;
        }
        if !self.declared_ids.contains(reference) {
            return Some(format!(
                "verification-id '{}' is not declared in proposal.md verifications",
                reference
            ));
        }
        Some(format!(
            "verification-id '{}' is not a change-blocking verification; move the non-local outcome to Future Work or a separate release-observation change",
            reference
        ))
    }

    fn evaluate(&self, change_id: &str, line_num: usize, reference: &str) -> Option<String> {
        if self.change_blocking_ids.contains(reference) {
            return None;
        }
        if !self.declared_ids.contains(reference) {
            return Some(format!(
                "{}: tasks.md:{}: verification-id '{}' is not declared in proposal.md verifications",
                change_id, line_num, reference
            ));
        }
        Some(format!(
            "{}: tasks.md:{}: verification-id '{}' is not a change-blocking verification; move the non-local outcome to Future Work or a separate release-observation change",
            change_id, line_num, reference
        ))
    }

    fn missing_reference_message(change_id: &str, line_num: usize) -> String {
        format!(
            "{}: tasks.md:{}: active implementation checkbox must reference a change-blocking verification via 'verification-id: <id>'",
            change_id, line_num
        )
    }
}

pub(super) fn validate_tasks_content(
    content: &str,
    change_id: &str,
    strict: bool,
    evidence_mode: &str,
    change_type: Option<&str>,
    proposal_content: Option<&str>,
) -> (Vec<String>, Vec<String>) {
    let mut errors = Vec::new();
    let mut warnings = Vec::new();

    static CHECKBOX_RE: OnceLock<Regex> = OnceLock::new();
    static CHECKBOX_DETAIL_RE: OnceLock<Regex> = OnceLock::new();
    static BARE_TASK_RE: OnceLock<Regex> = OnceLock::new();
    static VERIFICATION_CONTINUATION_RE: OnceLock<Regex> = OnceLock::new();

    let checkbox_re = CHECKBOX_RE.get_or_init(|| Regex::new(r"^\s*[-*]\s*\[[ x]\]").unwrap());
    let checkbox_detail_re =
        CHECKBOX_DETAIL_RE.get_or_init(|| Regex::new(r"^\s*[-*]\s*\[([ x])\]\s+(.*)$").unwrap());
    let bare_task_re = BARE_TASK_RE.get_or_init(|| Regex::new(r"^\s*[-*]\s+[^\[]").unwrap());
    let verification_continuation_re = VERIFICATION_CONTINUATION_RE
        .get_or_init(|| Regex::new(r"^\s{2,}(?i:verification:)\s*(.+)$").unwrap());

    let mut section = TaskSectionKind::Active;

    let is_behavior_change = matches!(change_type, Some("implementation" | "hybrid"));

    let mut last_checkbox_line_num: Option<usize> = None;
    let mut pending_behavior_task_without_verification: Option<usize> = None;
    let mut fences = crate::task_parser::FenceTracker::default();

    // Linkage is enforced only for behavior-changing proposals that already
    // declare structured verification roles.
    let linkage = (strict && is_behavior_change)
        .then(|| VerificationLinkage::from_proposal(proposal_content))
        .flatten();
    let mut pending_verification_id_line: Option<usize> = None;

    for (i, line) in content.lines().enumerate() {
        let line_num = i + 1;

        // Fenced literals (e.g. recovered acceptance notes) are untrusted historical
        // content, never headings, tasks, or verification declarations.
        if fences.observe(line) {
            continue;
        }

        if line.starts_with("##") {
            // Runtime-owned follow-up subsections (e.g. `### External blockers`)
            // stay excluded until the next top-level section.
            if line.starts_with("###") && section == TaskSectionKind::RuntimeAcceptanceFollowUp {
                continue;
            }
            section = classify_task_section(line);
            continue;
        }

        // Runtime-owned acceptance findings are not implementation tasks and have no
        // implementation verification contract. The runtime removes them after PASS.
        if section == TaskSectionKind::RuntimeAcceptanceFollowUp {
            continue;
        }

        let in_excluded = section == TaskSectionKind::Narrative;

        // Check for checkboxes in narrative (non-task) sections
        if in_excluded && checkbox_re.is_match(line) {
            errors.push(format!(
                "{}: tasks.md:{}: Checkbox found in excluded section (should be removed)",
                change_id, line_num
            ));
            continue;
        }

        if let Some(caps) = checkbox_detail_re.captures(line) {
            // A new checkbox ends the previous checkbox's continuation window.
            if let Some(unresolved) = pending_verification_id_line.take() {
                errors.push(VerificationLinkage::missing_reference_message(
                    change_id, unresolved,
                ));
            }
            last_checkbox_line_num = Some(line_num);
            if !in_excluded {
                let task_text = caps.get(2).map_or("", |m| m.as_str()).trim();

                let inline_verification = extract_inline_verification(task_text);
                let continuation_verification = verification_continuation_re
                    .captures(line)
                    .and_then(|vcaps| vcaps.get(1).map(|m| m.as_str().trim().to_string()));
                let verification_text = inline_verification
                    .or(continuation_verification)
                    .filter(|v| !v.is_empty());

                if strict && is_self_referential_final_validation_task(task_text, change_id) {
                    errors.push(self_referential_final_validation_message(
                        change_id, line_num,
                    ));
                    pending_behavior_task_without_verification = None;
                    continue;
                }

                if let Some(linkage) = linkage.as_ref() {
                    let inline_reference = extract_verification_id_reference(task_text);
                    match inline_reference.as_deref() {
                        Some(reference) => {
                            errors.extend(linkage.evaluate(change_id, line_num, reference))
                        }
                        // The reference may still arrive on a continuation line.
                        None => pending_verification_id_line = Some(line_num),
                    }
                }

                if strict && evidence_mode != "off" && is_behavior_change {
                    if let Some(vtext) = verification_text {
                        if !has_repository_evidence_hint(&vtext) {
                            let msg = format!(
                                "{}: tasks.md:{}: Verification note should cite repository-verifiable evidence such as source paths, tests, or runnable commands",
                                change_id, line_num
                            );
                            if evidence_mode == "error" {
                                errors.push(msg);
                            } else if evidence_mode == "warn" {
                                warnings.push(msg);
                            }
                        }
                        if !has_verification_ownership_marker(&vtext) {
                            let msg = format!(
                                "{}: tasks.md:{}: Verification ownership missing for behavior-changing task (expected one of: unit, integration, e2e, manual, benchmark, not-testable)",
                                change_id, line_num
                            );
                            if evidence_mode == "error" {
                                errors.push(msg);
                            } else if evidence_mode == "warn" {
                                warnings.push(msg);
                            }
                        }
                        pending_behavior_task_without_verification = None;
                    } else {
                        pending_behavior_task_without_verification = Some(line_num);
                    }
                }
            }
            continue;
        }

        if let Some(caps) = verification_continuation_re.captures(line) {
            if !in_excluded {
                if let Some(prev_line_num) = last_checkbox_line_num {
                    let vtext = caps.get(1).map_or("", |m| m.as_str()).trim();
                    if let (Some(linkage), Some(unresolved)) =
                        (linkage.as_ref(), pending_verification_id_line)
                    {
                        if unresolved == prev_line_num {
                            if let Some(reference) = extract_verification_id_reference(vtext) {
                                errors.extend(linkage.evaluate(
                                    change_id,
                                    prev_line_num,
                                    &reference,
                                ));
                                pending_verification_id_line = None;
                            }
                        }
                    }
                    if strict && evidence_mode != "off" && !vtext.is_empty() {
                        if !has_repository_evidence_hint(vtext) {
                            let msg = format!(
                                "{}: tasks.md:{}: Verification note should cite repository-verifiable evidence such as source paths, tests, or runnable commands",
                                change_id, prev_line_num
                            );
                            if evidence_mode == "error" {
                                errors.push(msg);
                            } else if evidence_mode == "warn" {
                                warnings.push(msg);
                            }
                        }
                        if !has_verification_ownership_marker(vtext) {
                            let msg = format!(
                                "{}: tasks.md:{}: Verification ownership missing for behavior-changing task (expected one of: unit, integration, e2e, manual, benchmark, not-testable)",
                                change_id, prev_line_num
                            );
                            if evidence_mode == "error" {
                                errors.push(msg);
                            } else if evidence_mode == "warn" {
                                warnings.push(msg);
                            }
                        }
                    }
                    if pending_behavior_task_without_verification == Some(prev_line_num) {
                        pending_behavior_task_without_verification = None;
                    }
                }
            }
            continue;
        }

        // Check for tasks without checkboxes in active sections
        if !in_excluded && bare_task_re.is_match(line) && !line.trim().is_empty() {
            let trimmed = line.trim();
            if !trimmed.starts_with("##")
                && !trimmed.starts_with('#')
                && !trimmed.starts_with("---")
                && !trimmed.starts_with("```")
            {
                errors.push(format!(
                    "{}: tasks.md:{}: Possible task without checkbox: {}",
                    change_id,
                    line_num,
                    truncate_for_display(trimmed, 50)
                ));
            }
        }
    }

    if let Some(unresolved) = pending_verification_id_line {
        errors.push(VerificationLinkage::missing_reference_message(
            change_id, unresolved,
        ));
    }

    if strict && evidence_mode != "off" {
        if let Some(line_num) = pending_behavior_task_without_verification {
            let msg = format!(
                "{}: tasks.md:{}: Behavior-bearing task missing '(verification: ...)' note",
                change_id, line_num
            );
            if evidence_mode == "error" {
                errors.push(msg);
            } else if evidence_mode == "warn" {
                warnings.push(msg);
            }
        }
    }

    (errors, warnings)
}

pub(super) fn check_archive_risk(specs_dir: &Path, change_id: &str) -> Vec<String> {
    let mut warnings = Vec::new();
    let mut has_added = false;
    let mut has_risky = false;

    if let Ok(entries) = fs::read_dir(specs_dir) {
        for entry in entries.filter_map(|e| e.ok()) {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let spec_file = path.join("spec.md");
            if !spec_file.exists() {
                continue;
            }
            if let Ok(content) = fs::read_to_string(&spec_file) {
                if content.contains("## ADDED Requirements") {
                    has_added = true;
                }
                if content.contains("## MODIFIED Requirements")
                    || content.contains("## REMOVED Requirements")
                {
                    has_risky = true;
                }
            }
        }
    }

    if has_risky && !has_added {
        warnings.push(format!(
            "{}: ARCHIVE-RISK WARNING — spec-only proposal relies solely on \
             MODIFIED/REMOVED deltas. These require successful canonical promotion rather \
             than simple append behavior. Verify canonical promotion behavior before acceptance.",
            change_id
        ));
    }

    warnings
}