ito-core 0.1.29

Core functionality and business logic for Ito
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
//! Validate Ito repository artifacts.
//!
//! This module provides lightweight validation helpers for specs, changes, and
//! modules.
//!
//! The primary consumer is the CLI and any APIs that need a structured report
//! (`ValidationReport`) rather than a single error.

use std::path::{Path, PathBuf};

use crate::error_bridge::IntoCoreResult;
use crate::errors::{CoreError, CoreResult};
use serde::Serialize;

use ito_common::paths;

use crate::show::{parse_change_show_json, parse_spec_show_json, read_change_delta_spec_files};
use crate::templates::{
    ResolvedSchema, ValidationLevelYaml, ValidationYaml, ValidatorId, artifact_done,
    load_schema_validation, read_change_schema, resolve_schema,
};
use ito_config::ConfigContext;
use ito_domain::changes::ChangeRepository as DomainChangeRepository;
use ito_domain::modules::ModuleRepository as DomainModuleRepository;

mod delta_rules;
mod format_specs;
mod issue;
mod repo_integrity;
mod report;
mod rules_engine;
mod tracking_rules;

pub(crate) use issue::with_format_spec;
pub use issue::{error, info, issue, warning, with_line, with_loc, with_metadata, with_rule_id};
pub use repo_integrity::validate_change_dirs_repo_integrity;
pub use report::{ReportBuilder, report};

/// Severity level for a [`ValidationIssue`].
pub type ValidationLevel = &'static str;

/// Validation issue is an error (always fails validation).
pub const LEVEL_ERROR: ValidationLevel = "ERROR";
/// Validation issue is a warning (fails validation in strict mode).
pub const LEVEL_WARNING: ValidationLevel = "WARNING";
/// Validation issue is informational (never fails validation).
pub const LEVEL_INFO: ValidationLevel = "INFO";

// Thresholds: match TS defaults.
const MIN_PURPOSE_LENGTH: usize = 50;
const MIN_MODULE_PURPOSE_LENGTH: usize = 20;
const MAX_DELTAS_PER_CHANGE: usize = 10;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
/// One validation finding.
pub struct ValidationIssue {
    /// Issue severity.
    pub level: String,
    /// Logical path within the validated artifact (or a filename).
    pub path: String,
    /// Human-readable message.
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional 1-based line number.
    pub line: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional 1-based column number.
    pub column: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional rule id when the issue came from an opt-in rule.
    pub rule_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    /// Optional structured metadata for tooling.
    pub metadata: Option<serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
/// A validation report with a computed summary.
pub struct ValidationReport {
    /// Whether validation passed for the selected strictness.
    pub valid: bool,

    /// All issues found (errors + warnings + info).
    pub issues: Vec<ValidationIssue>,

    /// Counts grouped by severity.
    pub summary: ValidationSummary,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
/// Aggregated counts for a validation run.
pub struct ValidationSummary {
    /// Number of `ERROR` issues.
    pub errors: u32,
    /// Number of `WARNING` issues.
    pub warnings: u32,
    /// Number of `INFO` issues.
    pub info: u32,
}

impl ValidationReport {
    /// Construct a report and compute summary + `valid`.
    ///
    /// When `strict` is `true`, warnings are treated as failures.
    pub fn new(issues: Vec<ValidationIssue>, strict: bool) -> Self {
        let mut errors = 0u32;
        let mut warnings = 0u32;
        let mut info = 0u32;
        for i in &issues {
            match i.level.as_str() {
                LEVEL_ERROR => errors += 1,
                LEVEL_WARNING => warnings += 1,
                LEVEL_INFO => info += 1,
                _ => {}
            }
        }
        let valid = if strict {
            errors == 0 && warnings == 0
        } else {
            errors == 0
        };
        Self {
            valid,
            issues,
            summary: ValidationSummary {
                errors,
                warnings,
                info,
            },
        }
    }
}

/// Validate a spec markdown string and return a structured report.
pub fn validate_spec_markdown(markdown: &str, strict: bool) -> ValidationReport {
    let json = parse_spec_show_json("<spec>", markdown);

    let mut r = report(strict);

    if json.overview.trim().is_empty() {
        r.push(error("purpose", "Purpose section cannot be empty"));
    } else if json.overview.len() < MIN_PURPOSE_LENGTH {
        r.push(warning(
            "purpose",
            "Purpose section is too brief (less than 50 characters)",
        ));
    }

    if json.requirements.is_empty() {
        r.push(error(
            "requirements",
            "Spec must have at least one requirement",
        ));
    }

    for (idx, req) in json.requirements.iter().enumerate() {
        let path = format!("requirements[{idx}]");
        if req.text.trim().is_empty() {
            r.push(error(&path, "Requirement text cannot be empty"));
        }
        if req.scenarios.is_empty() {
            r.push(error(&path, "Requirement must have at least one scenario"));
        }
        for (sidx, sc) in req.scenarios.iter().enumerate() {
            let sp = format!("{path}.scenarios[{sidx}]");
            if sc.raw_text.trim().is_empty() {
                r.push(error(&sp, "Scenario text cannot be empty"));
            }
        }
    }

    r.finish()
}

/// Validate a spec by id from `.ito/specs/<id>/spec.md`.
pub fn validate_spec(ito_path: &Path, spec_id: &str, strict: bool) -> CoreResult<ValidationReport> {
    let path = paths::spec_markdown_path(ito_path, spec_id);
    let markdown = ito_common::io::read_to_string_std(&path)
        .map_err(|e| CoreError::io(format!("reading spec {}", spec_id), e))?;
    Ok(validate_spec_markdown(&markdown, strict))
}

/// Validate a change using schema-driven rules when available, with legacy
/// delta/task fallback for older schemas.
pub fn validate_change(
    change_repo: &(impl DomainChangeRepository + ?Sized),
    ito_path: &Path,
    change_id: &str,
    strict: bool,
) -> CoreResult<ValidationReport> {
    let mut rep = report(strict);

    let (ctx, schema_name) = resolve_validation_context(ito_path, change_id);

    let resolved = match resolve_schema(Some(&schema_name), &ctx) {
        Ok(s) => {
            rep.push(info(
                "schema",
                format!(
                    "Resolved schema '{}' from {}",
                    s.schema.name,
                    s.source.as_str()
                ),
            ));
            Some(s)
        }
        Err(e) => {
            rep.push(error(
                "schema",
                format!("Failed to resolve schema '{schema_name}': {e}"),
            ));
            None
        }
    };

    if let Some(resolved) = &resolved {
        match load_schema_validation(resolved) {
            Ok(Some(validation)) => {
                rep.push(info("schema.validation", "Using schema validation.yaml"));
                validate_change_against_schema_validation(
                    &mut rep,
                    change_repo,
                    ito_path,
                    change_id,
                    resolved,
                    &validation,
                    strict,
                )?;
                return Ok(rep.finish());
            }
            Ok(None) => {}
            Err(e) => {
                rep.push(error(
                    "schema.validation",
                    format!("Failed to load schema validation.yaml: {e}"),
                ));
                return Ok(rep.finish());
            }
        }

        if is_legacy_delta_schema(&resolved.schema.name) {
            validate_change_delta_specs(&mut rep, change_repo, change_id, strict)?;

            let tracks_rel = resolved
                .schema
                .apply
                .as_ref()
                .and_then(|a| a.tracks.as_deref())
                .unwrap_or("tasks.md");

            if !ito_domain::tasks::is_safe_tracking_filename(tracks_rel) {
                rep.push(error(
                    "tracking",
                    format!("Invalid tracking file path in apply.tracks: '{tracks_rel}'"),
                ));
                return Ok(rep.finish());
            }

            let report_path = format!("changes/{change_id}/{tracks_rel}");
            let abs_path = paths::change_dir(ito_path, change_id).join(tracks_rel);
            rep.extend(validate_tasks_tracking_path(
                &abs_path,
                &report_path,
                strict,
            ));
            return Ok(rep.finish());
        }

        rep.push(info(
            "schema.validation",
            "Schema has no validation.yaml; manual validation required",
        ));
        validate_apply_required_artifacts(&mut rep, ito_path, change_id, resolved);
        return Ok(rep.finish());
    }

    validate_change_delta_specs(&mut rep, change_repo, change_id, strict)?;
    Ok(rep.finish())
}

/// Returns true for built-in schemas that predate schema-driven `validation.yaml`.
fn is_legacy_delta_schema(schema_name: &str) -> bool {
    schema_name == "spec-driven" || schema_name == "tdd"
}

fn schema_artifact_ids(resolved: &ResolvedSchema) -> Vec<String> {
    let mut ids = Vec::new();
    for a in &resolved.schema.artifacts {
        ids.push(a.id.clone());
    }
    ids
}

fn validate_apply_required_artifacts(
    rep: &mut ReportBuilder,
    ito_path: &Path,
    change_id: &str,
    resolved: &ResolvedSchema,
) {
    let change_dir = paths::change_dir(ito_path, change_id);
    if !change_dir.exists() {
        rep.push(error(
            "change",
            format!("Change directory not found: changes/{change_id}"),
        ));
        return;
    }

    let required_ids: Vec<String> = match resolved.schema.apply.as_ref() {
        Some(apply) => apply
            .requires
            .clone()
            .unwrap_or_else(|| schema_artifact_ids(resolved)),
        None => schema_artifact_ids(resolved),
    };

    for id in required_ids {
        let Some(a) = resolved.schema.artifacts.iter().find(|a| a.id == id) else {
            rep.push(error(
                "schema.validation",
                format!("Schema apply.requires references unknown artifact id '{id}'"),
            ));
            continue;
        };
        if artifact_done(&change_dir, &a.generates) {
            continue;
        }
        rep.push(warning(
            format!("artifacts.{id}"),
            format!(
                "Apply-required artifact '{id}' is missing (expected output: {})",
                a.generates
            ),
        ));
    }
}

fn resolve_validation_context(ito_path: &Path, change_id: &str) -> (ConfigContext, String) {
    let schema_name = read_change_schema(ito_path, change_id);

    let mut ctx = ConfigContext::from_process_env();
    ctx.project_dir = ito_path.parent().map(|p| p.to_path_buf());

    (ctx, schema_name)
}

fn validate_change_against_schema_validation(
    rep: &mut ReportBuilder,
    change_repo: &(impl DomainChangeRepository + ?Sized),
    ito_path: &Path,
    change_id: &str,
    resolved: &ResolvedSchema,
    validation: &ValidationYaml,
    strict: bool,
) -> CoreResult<()> {
    let change_dir = paths::change_dir(ito_path, change_id);

    let missing_level = validation
        .defaults
        .missing_required_artifact_level
        .unwrap_or(ValidationLevelYaml::Warning)
        .as_level_str();

    for (artifact_id, cfg) in &validation.artifacts {
        let Some(schema_artifact) = resolved
            .schema
            .artifacts
            .iter()
            .find(|a| a.id == *artifact_id)
        else {
            rep.push(error(
                "schema.validation",
                format!("validation.yaml references unknown artifact id '{artifact_id}'"),
            ));
            continue;
        };

        let present = artifact_done(&change_dir, &schema_artifact.generates);
        if cfg.required && !present {
            rep.push(issue(
                missing_level,
                format!("artifacts.{artifact_id}"),
                format!(
                    "Missing required artifact '{artifact_id}' (expected output: {})",
                    schema_artifact.generates
                ),
            ));
        }

        if !present {
            if let Some(validator_id @ ValidatorId::DeltaSpecsV1) = cfg.validate_as {
                // Only delta-spec validation runs without a generated artifact because it
                // validates change-wide state; tasks-tracking validation is file-backed.
                let ctx = ArtifactValidatorContext {
                    ito_path,
                    change_id,
                    strict,
                };
                run_validator_for_artifact(
                    rep,
                    change_repo,
                    ctx,
                    artifact_id,
                    &schema_artifact.generates,
                    validator_id,
                )?;
                rules_engine::run_artifact_rules(
                    rep,
                    change_repo,
                    ctx,
                    validator_id,
                    artifact_id,
                    cfg.rules.as_ref(),
                )?;
            }
            continue;
        }

        let Some(validator_id) = cfg.validate_as else {
            continue;
        };
        let ctx = ArtifactValidatorContext {
            ito_path,
            change_id,
            strict,
        };
        run_validator_for_artifact(
            rep,
            change_repo,
            ctx,
            artifact_id,
            &schema_artifact.generates,
            validator_id,
        )?;
        rules_engine::run_artifact_rules(
            rep,
            change_repo,
            ctx,
            validator_id,
            artifact_id,
            cfg.rules.as_ref(),
        )?;
    }

    if let Some(proposal) = validation.proposal.as_ref() {
        let report_path = format!("changes/{change_id}/proposal.md");
        let abs_path = change_dir.join("proposal.md");
        let present = abs_path.exists();

        if proposal.required && !present {
            rep.push(issue(
                missing_level,
                "proposal",
                format!("Missing required proposal artifact: {report_path}"),
            ));
        }

        if present && let Some(validator_id) = proposal.validate_as {
            let ctx = ArtifactValidatorContext {
                ito_path,
                change_id,
                strict,
            };
            match validator_id {
                ValidatorId::DeltaSpecsV1 => {
                    rules_engine::run_proposal_rules(
                        rep,
                        change_repo,
                        ctx,
                        validator_id,
                        proposal.rules.as_ref(),
                    )?;
                }
                ValidatorId::TasksTrackingV1 => {
                    rep.push(error(
                        "schema.validation",
                        "Validator 'ito.tasks-tracking.v1' is not valid for proposal artifacts",
                    ));
                }
            }
        }
    }

    if let Some(tracking) = validation.tracking.as_ref() {
        match tracking.source {
            crate::templates::ValidationTrackingSourceYaml::ApplyTracks => {
                let tracks_rel = resolved
                    .schema
                    .apply
                    .as_ref()
                    .and_then(|a| a.tracks.as_deref());

                let Some(tracks_rel) = tracks_rel else {
                    if tracking.required {
                        rep.push(error(
                            "tracking",
                            "Schema tracking is required but schema apply.tracks is not set",
                        ));
                    }
                    return Ok(());
                };

                if !ito_domain::tasks::is_safe_tracking_filename(tracks_rel) {
                    rep.push(error(
                        "tracking",
                        format!("Invalid tracking file path in apply.tracks: '{tracks_rel}'"),
                    ));
                    return Ok(());
                }

                let report_path = format!("changes/{change_id}/{tracks_rel}");
                let abs_path = paths::change_dir(ito_path, change_id).join(tracks_rel);

                let present = abs_path.exists();
                if tracking.required && !present {
                    rep.push(error(
                        "tracking",
                        format!("Missing required tracking file: {report_path}"),
                    ));
                }
                if !present {
                    return Ok(());
                }

                match tracking.validate_as {
                    ValidatorId::TasksTrackingV1 => {
                        rep.extend(validate_tasks_tracking_path(
                            &abs_path,
                            &report_path,
                            strict,
                        ));
                        let ctx = ArtifactValidatorContext {
                            ito_path,
                            change_id,
                            strict,
                        };
                        rules_engine::run_tracking_rules(
                            rep,
                            change_repo,
                            ctx,
                            ValidatorId::TasksTrackingV1,
                            &abs_path,
                            &report_path,
                            tracking.rules.as_ref(),
                        )?;
                    }
                    ValidatorId::DeltaSpecsV1 => {
                        rep.push(error(
                            "schema.validation",
                            "Validator 'ito.delta-specs.v1' is not valid for tracking files",
                        ));
                    }
                }
            }
        }
    }

    Ok(())
}

/// Dispatch the configured validator for one artifact and append any findings.
fn run_validator_for_artifact(
    rep: &mut ReportBuilder,
    change_repo: &(impl DomainChangeRepository + ?Sized),
    ctx: ArtifactValidatorContext<'_>,
    artifact_id: &str,
    generates: &str,
    validator_id: ValidatorId,
) -> CoreResult<()> {
    match validator_id {
        ValidatorId::DeltaSpecsV1 => {
            validate_change_delta_specs(rep, change_repo, ctx.change_id, ctx.strict)?;
        }
        ValidatorId::TasksTrackingV1 => {
            use format_specs::TASKS_TRACKING_V1;

            if generates.contains('*') {
                rep.push(with_format_spec(
                    error(
                        format!("artifacts.{artifact_id}"),
                        format!(
                            "Validator '{}' requires a single file path; got pattern '{}'",
                            TASKS_TRACKING_V1.validator_id, generates
                        ),
                    ),
                    TASKS_TRACKING_V1,
                ));
                return Ok(());
            }

            let report_path = format!("changes/{}/{generates}", ctx.change_id);
            let abs_path = paths::change_dir(ctx.ito_path, ctx.change_id).join(generates);
            rep.extend(validate_tasks_tracking_path(
                &abs_path,
                &report_path,
                ctx.strict,
            ));
        }
    }
    Ok(())
}

#[derive(Debug, Clone, Copy)]
struct ArtifactValidatorContext<'a> {
    ito_path: &'a Path,
    change_id: &'a str,
    strict: bool,
}

fn validate_tasks_tracking_path(
    path: &Path,
    report_path: &str,
    strict: bool,
) -> Vec<ValidationIssue> {
    use format_specs::TASKS_TRACKING_V1;
    use ito_domain::tasks::{DiagnosticLevel, parse_tasks_tracking_file};

    let contents = match ito_common::io::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            return vec![with_format_spec(
                error(report_path, format!("Failed to read {report_path}: {e}")),
                TASKS_TRACKING_V1,
            )];
        }
    };

    let parsed = parse_tasks_tracking_file(&contents);
    let mut issues = Vec::new();

    if parsed.tasks.is_empty() {
        let msg = "Tracking file contains no recognizable tasks";
        let i = if strict {
            error(report_path, msg)
        } else {
            warning(report_path, msg)
        };
        issues.push(with_format_spec(i, TASKS_TRACKING_V1));
    }
    for d in &parsed.diagnostics {
        let level = match d.level {
            DiagnosticLevel::Error => LEVEL_ERROR,
            DiagnosticLevel::Warning => LEVEL_WARNING,
        };
        issues.push(with_format_spec(
            ValidationIssue {
                path: report_path.to_string(),
                level: level.to_string(),
                message: d.message.clone(),
                line: d.line.map(|l| l as u32),
                column: None,
                rule_id: None,
                metadata: None,
            },
            TASKS_TRACKING_V1,
        ));
    }
    issues
}

/// Validate a change's delta specs, including structural checks and traceability.
fn validate_change_delta_specs(
    rep: &mut ReportBuilder,
    change_repo: &(impl DomainChangeRepository + ?Sized),
    change_id: &str,
    strict: bool,
) -> CoreResult<()> {
    use format_specs::DELTA_SPECS_V1;

    let files = read_change_delta_spec_files(change_repo, change_id)?;
    if files.is_empty() {
        rep.push(with_format_spec(
            error("specs", "Change must have at least one delta"),
            DELTA_SPECS_V1,
        ));
        return Ok(());
    }

    let show = parse_change_show_json(change_id, &files);
    if show.deltas.is_empty() {
        rep.push(with_format_spec(
            error("specs", "Change must have at least one delta"),
            DELTA_SPECS_V1,
        ));
        return Ok(());
    }

    if show.deltas.len() > MAX_DELTAS_PER_CHANGE {
        rep.push(with_format_spec(
            info(
                "deltas",
                "Consider splitting changes with more than 10 deltas",
            ),
            DELTA_SPECS_V1,
        ));
    }

    for (idx, d) in show.deltas.iter().enumerate() {
        let base = format!("deltas[{idx}]");
        if d.description.trim().is_empty() {
            rep.push(with_format_spec(
                error(&base, "Delta description cannot be empty"),
                DELTA_SPECS_V1,
            ));
        } else if d.description.trim().len() < 20 {
            rep.push(with_format_spec(
                warning(&base, "Delta description is too brief"),
                DELTA_SPECS_V1,
            ));
        }

        if d.requirements.is_empty() {
            rep.push(with_format_spec(
                warning(&base, "Delta should include requirements"),
                DELTA_SPECS_V1,
            ));
        }

        for (ridx, req) in d.requirements.iter().enumerate() {
            let rp = format!("{base}.requirements[{ridx}]");
            if req.text.trim().is_empty() {
                rep.push(with_format_spec(
                    error(&rp, "Requirement text cannot be empty"),
                    DELTA_SPECS_V1,
                ));
            }
            let up = req.text.to_ascii_uppercase();
            if !up.contains("SHALL") && !up.contains("MUST") {
                rep.push(with_format_spec(
                    error(&rp, "Requirement must contain SHALL or MUST keyword"),
                    DELTA_SPECS_V1,
                ));
            }
            if req.scenarios.is_empty() {
                rep.push(with_format_spec(
                    error(&rp, "Requirement must have at least one scenario"),
                    DELTA_SPECS_V1,
                ));
            }
        }
    }

    // --- Traceability validation ---
    // Collect (title, id) pairs from all delta requirements.
    let mut delta_requirements: Vec<(String, Option<String>)> = Vec::new();
    for d in &show.deltas {
        for req in &d.requirements {
            delta_requirements.push((req.text.clone(), req.requirement_id.clone()));
        }
    }

    // Only run traceability if at least one requirement has an ID.
    let has_any_id = delta_requirements.iter().any(|(_, id)| id.is_some());
    if has_any_id {
        let change_data = change_repo.get(change_id).into_core()?;
        let trace_result =
            ito_domain::traceability::compute_traceability(&delta_requirements, &change_data.tasks);

        match &trace_result.status {
            ito_domain::traceability::TraceStatus::Invalid { missing_ids } => {
                for title in missing_ids {
                    rep.push(with_format_spec(
                        error(
                            "traceability",
                            format!(
                                "Requirement '{}' has no Requirement ID; all requirements must have IDs for traceability",
                                title
                            ),
                        ),
                        DELTA_SPECS_V1,
                    ));
                }
            }
            ito_domain::traceability::TraceStatus::Unavailable { reason } => {
                rep.push(with_format_spec(
                    info(
                        "traceability",
                        format!("Traceability unavailable: {reason}"),
                    ),
                    DELTA_SPECS_V1,
                ));
            }
            ito_domain::traceability::TraceStatus::Ready => {
                for diag in &trace_result.diagnostics {
                    rep.push(with_format_spec(
                        error("traceability", diag.clone()),
                        DELTA_SPECS_V1,
                    ));
                }
                for unresolved in &trace_result.unresolved_references {
                    rep.push(with_format_spec(
                        error(
                            "traceability",
                            format!(
                                "Task '{}' references unknown requirement ID '{}'",
                                unresolved.task_id, unresolved.requirement_id
                            ),
                        ),
                        DELTA_SPECS_V1,
                    ));
                }
                for uncovered in &trace_result.uncovered_requirements {
                    let i = if strict {
                        error(
                            "traceability",
                            format!(
                                "Requirement '{}' is not covered by any active task",
                                uncovered
                            ),
                        )
                    } else {
                        warning(
                            "traceability",
                            format!(
                                "Requirement '{}' is not covered by any active task",
                                uncovered
                            ),
                        )
                    };
                    rep.push(with_format_spec(i, DELTA_SPECS_V1));
                }
            }
        }
    }

    Ok(())
}

#[derive(Debug, Clone)]
/// A resolved module reference (directory + key paths).
pub struct ResolvedModule {
    /// 3-digit module id.
    pub id: String,
    /// Directory name under `.ito/modules/`.
    pub full_name: String,
    /// Full path to the module directory.
    pub module_dir: PathBuf,
    /// Full path to `module.md`.
    pub module_md: PathBuf,
}

/// Resolve a module directory name from user input.
pub fn resolve_module(
    module_repo: &(impl DomainModuleRepository + ?Sized),
    ito_path: &Path,
    input: &str,
) -> CoreResult<Option<ResolvedModule>> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }

    let module = module_repo.get(trimmed).into_core();
    match module {
        Ok(m) => {
            let full_name = format!("{}_{}", m.id, m.name);
            let module_dir = if m.path.as_os_str().is_empty() {
                let fallback = paths::modules_dir(ito_path).join(&full_name);
                if !fallback.exists() {
                    return Ok(None);
                }
                fallback
            } else {
                m.path
            };
            let module_md = module_dir.join("module.md");
            Ok(Some(ResolvedModule {
                id: m.id,
                full_name,
                module_dir,
                module_md,
            }))
        }
        Err(_) => Ok(None),
    }
}

/// Validate a module's `module.md` and any discovered sub-modules.
pub fn validate_module(
    module_repo: &(impl DomainModuleRepository + ?Sized),
    ito_path: &Path,
    module_input: &str,
    strict: bool,
) -> CoreResult<(String, ValidationReport)> {
    let resolved = resolve_module(module_repo, ito_path, module_input)?;
    let Some(r) = resolved else {
        let mut rep = report(strict);
        rep.push(error("module", "Module not found"));
        return Ok((module_input.to_string(), rep.finish()));
    };

    let mut rep = report(strict);
    let md = match ito_common::io::read_to_string_std(&r.module_md) {
        Ok(c) => c,
        Err(_) => {
            rep.push(error("file", "Module must have a Purpose section"));
            return Ok((r.full_name, rep.finish()));
        }
    };

    let purpose = extract_section(&md, "Purpose");
    if purpose.trim().is_empty() {
        rep.push(error("purpose", "Module must have a Purpose section"));
    } else if purpose.trim().len() < MIN_MODULE_PURPOSE_LENGTH {
        rep.push(error(
            "purpose",
            "Module purpose must be at least 20 characters",
        ));
    }

    let scope = extract_section(&md, "Scope");
    if scope.trim().is_empty() {
        rep.push(error(
            "scope",
            "Module must have a Scope section with at least one capability (use \"*\" for unrestricted)",
        ));
    }

    // Validate sub-modules.
    validate_sub_modules_under_module(&mut rep, module_repo, &r.module_dir, &r.id, strict);

    Ok((r.full_name, rep.finish()))
}

/// Validate all sub-modules belonging to a parent module.
fn validate_sub_modules_under_module(
    rep: &mut ReportBuilder,
    module_repo: &(impl DomainModuleRepository + ?Sized),
    module_dir: &Path,
    parent_id: &str,
    strict: bool,
) {
    let sub_dir = module_dir.join("sub");
    if !sub_dir.exists() {
        return;
    }

    // Retrieve sub-modules through the repository to avoid re-discovering
    // the same filesystem layout the repository already parsed.
    let module = match module_repo.get(parent_id) {
        Ok(m) => m,
        Err(_) => return, // Parent module not found; outer validation already handles this.
    };

    // Track which directory names the repository recognized as valid so we
    // can later flag any unrecognized entries.
    let mut recognized_dirs: std::collections::HashSet<String> =
        std::collections::HashSet::with_capacity(module.sub_modules.len());

    for sm in &module.sub_modules {
        let dir_name = sm
            .path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or(&sm.name)
            .to_string();
        recognized_dirs.insert(dir_name.clone());

        // Validate naming convention: sub_id must be exactly two ASCII digits.
        if sm.sub_id.len() != 2 || !sm.sub_id.bytes().all(|b| b.is_ascii_digit()) {
            rep.push(error(
                format!("sub-modules/{dir_name}"),
                format!("Sub-module directory '{dir_name}' does not follow the SS_name convention"),
            ));
            continue;
        }

        // Validate module.md presence.
        let module_md = sm.path.join("module.md");
        if !module_md.exists() {
            let level = if strict { LEVEL_ERROR } else { LEVEL_WARNING };
            rep.push(issue(
                level,
                format!("sub-modules/{dir_name}"),
                format!("Sub-module '{dir_name}' is missing module.md"),
            ));
            continue;
        }

        // Validate module.md content.
        let content = match ito_common::io::read_to_string_std(&module_md) {
            Ok(c) => c,
            Err(err) => {
                rep.push(error(
                    format!("sub-modules/{dir_name}/module.md"),
                    format!("Failed to read module.md: {err}"),
                ));
                continue;
            }
        };

        let purpose = extract_section(&content, "Purpose");
        if purpose.trim().is_empty() {
            rep.push(error(
                format!("sub-modules/{dir_name}/purpose"),
                format!("Sub-module '{dir_name}' module.md must have a Purpose section"),
            ));
        } else if purpose.trim().len() < MIN_MODULE_PURPOSE_LENGTH {
            rep.push(warning(
                format!("sub-modules/{dir_name}/purpose"),
                format!(
                    "Sub-module '{dir_name}' purpose is too brief (less than {MIN_MODULE_PURPOSE_LENGTH} characters)"
                ),
            ));
        }
    }

    // Report any sub/ entries that the repository silently skipped because
    // they do not follow the required naming convention.
    if let Ok(entries) = std::fs::read_dir(&sub_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }
            let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) else {
                continue;
            };
            if !recognized_dirs.contains(dir_name) {
                rep.push(error(
                    format!("sub-modules/{dir_name}"),
                    format!(
                        "Sub-module directory '{dir_name}' does not follow the SS_name convention"
                    ),
                ));
            }
        }
    }
}

fn extract_section(markdown: &str, header: &str) -> String {
    let mut in_section = false;
    let mut out = String::new();
    let normalized = markdown.replace('\r', "");
    for raw in normalized.split('\n') {
        let line = raw.trim_end();
        if let Some(h) = line.strip_prefix("## ") {
            let title = h.trim();
            if title.eq_ignore_ascii_case(header) {
                in_section = true;
                continue;
            }
            if in_section {
                break;
            }
        }
        if in_section {
            out.push_str(line);
            out.push('\n');
        }
    }
    out
}

/// Validate a change's tracking file and return any issues found.
pub fn validate_tasks_file(
    ito_path: &Path,
    change_id: &str,
    strict: bool,
) -> CoreResult<Vec<ValidationIssue>> {
    use crate::templates::{load_schema_validation, read_change_schema, resolve_schema};
    use ito_domain::tasks::tasks_path_checked;

    // `read_change_schema` uses `change_id` as a path segment; reject traversal.
    if tasks_path_checked(ito_path, change_id).is_none() {
        return Ok(vec![error(
            "tracking",
            format!("invalid change id path segment: \"{change_id}\""),
        )]);
    }

    let schema_name = read_change_schema(ito_path, change_id);
    let mut ctx = ConfigContext::from_process_env();
    ctx.project_dir = ito_path.parent().map(|p| p.to_path_buf());

    let mut issues: Vec<ValidationIssue> = Vec::new();

    let mut tracking_file = "tasks.md".to_string();
    let resolved = match resolve_schema(Some(&schema_name), &ctx) {
        Ok(r) => Some(r),
        Err(e) => {
            issues.push(error(
                "schema",
                format!("Failed to resolve schema '{schema_name}': {e}"),
            ));
            None
        }
    };

    if let Some(resolved) = resolved.as_ref() {
        // If schema validation declares a non-tasks tracking validator, this file is not a
        // tasks-tracking file that `ito validate` can interpret.
        if let Ok(Some(validation)) = load_schema_validation(resolved)
            && let Some(tracking) = validation.tracking.as_ref()
            && tracking.validate_as != ValidatorId::TasksTrackingV1
        {
            issues.push(error(
                "tracking",
                format!(
                    "Schema tracking validator '{}' is not valid for tasks tracking files",
                    tracking.validate_as.as_str()
                ),
            ));
            return Ok(issues);
        }

        if let Some(tracks) = resolved
            .schema
            .apply
            .as_ref()
            .and_then(|a| a.tracks.as_deref())
        {
            tracking_file = tracks.to_string();
        }
    }

    if !ito_domain::tasks::is_safe_tracking_filename(&tracking_file) {
        issues.push(error(
            "tracking",
            format!("Invalid tracking file path in apply.tracks: '{tracking_file}'"),
        ));
        return Ok(issues);
    }

    let path = paths::change_dir(ito_path, change_id).join(&tracking_file);
    let report_path = format!("changes/{change_id}/{tracking_file}");
    issues.extend(validate_tasks_tracking_path(&path, &report_path, strict));
    Ok(issues)
}