cflx 0.6.189

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
use crate::dependency_targets::DependencyTargetClass;
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");
        let tasks_file = change_dir.join("tasks.md");

        // Check required files
        if !proposal_file.exists() {
            errors.push(format!("{}: Missing proposal.md", change_id));
        }
        if !tasks_file.exists() {
            errors.push(format!("{}: Missing tasks.md", change_id));
        }

        // 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
                            ));
                        }
                        _ => {}
                    }
                    errors.extend(validate_verification_declarations(
                        &content,
                        &proposal_file,
                        &self.manager.root_dir,
                        &change_id,
                        change_type.as_deref(),
                    ));
                }

                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
        if tasks_file.exists() {
            if let Ok(content) = fs::read_to_string(&tasks_file) {
                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_tasks_content(
                    &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,
    }
}

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 excluded_sections = ["future work", "out of scope", "notes"];
    let mut in_excluded = false;
    let mut completed = 0u32;
    let mut total = 0u32;

    for line in content.lines() {
        if line.starts_with("##") {
            let section_name = line.trim_start_matches('#').trim().to_lowercase();
            in_excluded = excluded_sections.iter().any(|&s| section_name.contains(s));
            continue;
        }
        if in_excluded {
            continue;
        }
        if checkbox_re.is_match(line) {
            total += 1;
            if checked_re.is_match(line) {
                completed += 1;
            }
        }
    }

    (completed, total)
}

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> {
    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 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,
            ));
        }
    }

    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
}

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))
}

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
    )
}

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 excluded_sections = ["future work", "out of scope", "notes"];
    let mut in_excluded = false;
    let mut in_runtime_acceptance_follow_up = false;

    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;

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

        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("###") && in_runtime_acceptance_follow_up {
                continue;
            }
            let section_name = line.trim_start_matches('#').trim().to_lowercase();
            in_excluded = excluded_sections.iter().any(|&s| section_name.contains(s));
            in_runtime_acceptance_follow_up = section_name == "current acceptance follow-up"
                || (section_name.starts_with("acceptance #")
                    && section_name.ends_with(" failure follow-up"));
            continue;
        }

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

        // Check for checkboxes in excluded 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) {
            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;
                } else 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 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 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
}