sbom-tools 0.2.0

Semantic SBOM diff and analysis tool
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
//! Quality command handler.
//!
//! Implements the `quality` subcommand for assessing SBOM quality.

use crate::config::EnrichmentConfig;
use crate::pipeline::{OutputTarget, exit_codes, parse_sbom_with_context, write_output};
use crate::quality::{QualityGrade, QualityReport, QualityScorer, ScoringProfile};
use crate::reports::ReportFormat;
use anyhow::Result;
use serde_json::json;
use std::path::PathBuf;

/// Output formats the `quality` command has a real renderer for.
/// `auto`/`summary` render the plain-text report; JSON, SARIF, and
/// sbomqs-json are dedicated emitters. All other [`ReportFormat`] values are
/// rejected up front instead of silently falling back to text.
pub const QUALITY_OUTPUT_FORMATS: &[ReportFormat] = &[
    ReportFormat::Auto,
    ReportFormat::Summary,
    ReportFormat::Json,
    ReportFormat::Sarif,
    ReportFormat::SbomqsJson,
];

/// Quality command configuration
pub struct QualityConfig {
    pub sbom_path: PathBuf,
    pub profile: ScoringProfile,
    pub output: ReportFormat,
    pub output_file: Option<PathBuf>,
    pub show_recommendations: bool,
    pub show_metrics: bool,
    pub min_score: Option<f32>,
    /// Exit non-zero when the compliance verdict is non-compliant (opt-in;
    /// the default gate is `--min-score` only, so existing scripts are
    /// unaffected).
    pub fail_on_noncompliant: bool,
    pub no_color: bool,
    /// Optional CRA sidecar metadata path (auto-discovered next to the SBOM
    /// when None). Supplements the embedded compliance check used by the
    /// `cra` scoring profile.
    pub cra_sidecar_path: Option<PathBuf>,
    /// CRA Annex III/IV product class (CLI string form). Sidecar value wins.
    pub cra_product_class: Option<String>,
    /// Pinned evaluation clock (raw `--as-of` CLI form). Deadline-sensitive
    /// compliance checks embedded in the report (CRA Art. 14 readiness, SBOM
    /// age, EUCC certificate expiry) evaluate against this instant instead of
    /// the wall clock, mirroring `validate --as-of`.
    pub as_of: Option<String>,
    /// Enrichment configuration (OSV / KEV / EOL / staleness / VEX). When any
    /// source is enabled the SBOM is enriched before scoring so the
    /// Lifecycle / `VulnDocs` categories reflect live data.
    pub enrichment: EnrichmentConfig,
}

/// Run the quality command, returning the desired exit code.
///
/// Gate codes (below-threshold / non-compliant) only apply to runs that
/// completed an assessment; usage/configuration errors propagate as `Err`,
/// which the binary's `main()` maps to process exit code 1.
///
/// The caller is responsible for calling `std::process::exit()` with the
/// returned code when it is non-zero.
#[allow(clippy::too_many_arguments)]
pub fn run_quality(
    sbom_path: PathBuf,
    profile: ScoringProfile,
    output: ReportFormat,
    output_file: Option<PathBuf>,
    show_recommendations: bool,
    show_metrics: bool,
    min_score: Option<f32>,
    fail_on_noncompliant: bool,
    no_color: bool,
    cra_sidecar_path: Option<PathBuf>,
    cra_product_class: Option<String>,
    as_of: Option<String>,
    enrichment: EnrichmentConfig,
) -> Result<i32> {
    let config = QualityConfig {
        sbom_path,
        profile,
        output,
        output_file,
        show_recommendations,
        show_metrics,
        min_score,
        fail_on_noncompliant,
        no_color,
        cra_sidecar_path,
        cra_product_class,
        as_of,
        enrichment,
    };

    run_quality_impl(config)
}

fn run_quality_impl(config: QualityConfig) -> Result<i32> {
    super::ensure_output_format_supported("quality", config.output, QUALITY_OUTPUT_FORMATS)?;

    // Pinned evaluation clock for deadline-sensitive compliance checks
    // (shared parser with `validate --as-of`). Parsed up front so a bad
    // value fails before the SBOM is read.
    let as_of: Option<chrono::DateTime<chrono::Utc>> = config
        .as_of
        .as_deref()
        .map(super::parse_as_of)
        .transpose()?;

    #[cfg_attr(not(feature = "enrichment"), allow(unused_mut))]
    let mut parsed = parse_sbom_with_context(&config.sbom_path, false)?;

    // Enrich before scoring so Lifecycle (staleness/EOL) and VulnDocs (OSV/KEV)
    // categories reflect live data rather than only the static SBOM contents.
    #[cfg(feature = "enrichment")]
    {
        let any_enrichment = config.enrichment.enabled
            || config.enrichment.enable_eol
            || config.enrichment.enable_kev
            || config.enrichment.enable_epss
            || config.enrichment.enable_staleness
            || config.enrichment.enable_huggingface
            || !config.enrichment.vex_paths.is_empty();
        if any_enrichment {
            let stats =
                crate::pipeline::enrich_sbom_full(parsed.sbom_mut(), &config.enrichment, false);
            for warning in &stats.warnings {
                tracing::warn!("{warning}");
            }
        }
    }

    let profile = config.profile;

    tracing::info!("Running quality assessment with {:?} profile", profile);

    // Honour explicit --cra-sidecar (hard error when broken); otherwise
    // auto-discover next to the SBOM (best-effort).
    let sidecar = super::load_cra_sidecar(config.cra_sidecar_path.as_deref(), &config.sbom_path)?;
    // An explicitly passed unrecognized class is a hard error (strict parse).
    let cli_class = super::parse_cra_product_class(config.cra_product_class.as_deref())?;
    let sidecar_class = sidecar.as_ref().and_then(|s| s.product_class);
    if let (Some(cli), Some(side)) = (cli_class, sidecar_class)
        && cli != side
    {
        tracing::warn!(
            "CRA product class mismatch: --cra-product-class={} but sidecar says {}; using sidecar.",
            cli.label(),
            side.label()
        );
    }
    let effective_class = sidecar_class.or(cli_class);

    let mut scorer = QualityScorer::new(profile);
    if let Some(sc) = sidecar {
        scorer = scorer.with_cra_sidecar(sc);
    }
    if let Some(c) = effective_class {
        scorer = scorer.with_cra_product_class(c);
    }
    if let Some(t) = as_of {
        scorer = scorer.with_as_of(t);
    }
    let report = scorer.score(parsed.sbom());

    // sbomqs-compat table for the human summary. Computed straight from the
    // NormalizedSbom (plus the raw document text for file-format /
    // data-license detection) — deliberately NOT from `report`: the
    // 0-100 pipeline and the sbomqs 0-10 model are not convertible, and the
    // compat path must never read `QualityReport.overall_score`.
    // The AI-readiness profile has its own dedicated layout and skips it.
    let sbomqs_input = crate::reports::sbomqs_compat::SbomqsCompatInput {
        sbom: parsed.sbom(),
        file_name: &config.sbom_path.to_string_lossy(),
        raw_content: Some(parsed.raw_content()),
    };

    // Build output based on format
    let output_text = match config.output {
        ReportFormat::Json => format_quality_json(&report, &config),
        ReportFormat::Sarif => format_quality_sarif(&report, &config),
        ReportFormat::SbomqsJson => crate::reports::sbomqs_compat::render_json(&sbomqs_input),
        _ => {
            let sbomqs_table = (config.profile != ScoringProfile::AiReadiness)
                .then(|| crate::reports::sbomqs_compat::render_summary_table(&sbomqs_input));
            format_quality_report(&report, &config, sbomqs_table.as_deref())
        }
    };

    // Write output
    let output_target = OutputTarget::from_option(config.output_file);
    write_output(&output_text, &output_target, false)?;

    // An N/A AI-readiness report (no ML components) has no meaningful score
    // and no rendered compliance verdict (text and SARIF both show "N/A"),
    // so NEITHER gate below may fire on it.
    let ai_not_applicable = report
        .ai_readiness_metrics
        .as_ref()
        .is_some_and(crate::quality::AiReadinessMetrics::is_not_applicable);

    // Check minimum score threshold.
    if let Some(threshold) = config.min_score
        && !ai_not_applicable
        && report.overall_score < threshold
    {
        tracing::error!(
            "Quality score {:.1} is below minimum threshold {:.1}",
            report.overall_score,
            threshold
        );
        return Ok(exit_codes::QUALITY_BELOW_THRESHOLD);
    }

    // Opt-in: fail the command when the compliance verdict is non-compliant,
    // so the printed "NON-COMPLIANT" cannot be paired with a success exit.
    // Off by default, so `quality --min-score` keeps its score-only contract.
    // Guarded by the same applicability rules as the score gate: an N/A run
    // (AI-readiness without ML components, or a not-applicable compliance
    // standard) renders no verdict and must not flip the exit code.
    if config.fail_on_noncompliant
        && !ai_not_applicable
        && report.compliance.is_applicable()
        && !report.compliance.is_compliant
    {
        tracing::error!(
            "SBOM is non-compliant with {} ({} error(s))",
            report.compliance.level.name(),
            report.compliance.error_count
        );
        return Ok(exit_codes::COMPLIANCE_ERRORS);
    }

    Ok(exit_codes::SUCCESS)
}

/// Format quality report as JSON
fn format_quality_json(report: &QualityReport, config: &QualityConfig) -> String {
    let not_applicable = report
        .ai_readiness_metrics
        .as_ref()
        .is_some_and(crate::quality::AiReadinessMetrics::is_not_applicable);

    // Serialize the report, then for an N/A AI-readiness result replace the
    // overall_score/grade so machine consumers don't read a 0.0 / "F" as a real
    // failing score (the standard 8-category pipeline did not run).
    let mut report_value = serde_json::to_value(report).unwrap_or_default();
    if not_applicable && let Some(obj) = report_value.as_object_mut() {
        obj.insert("overall_score".to_string(), serde_json::Value::Null);
        obj.insert(
            "grade".to_string(),
            serde_json::Value::String("N/A".to_string()),
        );
    }

    let output = json!({
        "tool": "sbom-tools",
        "version": env!("CARGO_PKG_VERSION"),
        "sbom": config.sbom_path.file_name().unwrap_or_default().to_string_lossy(),
        "profile": config.profile.to_string(),
        "applicable": !not_applicable,
        "report": report_value,
    });
    serde_json::to_string_pretty(&output).unwrap_or_default()
}

/// Format quality report as SARIF 2.1.0
fn format_quality_sarif(report: &QualityReport, config: &QualityConfig) -> String {
    // AI-readiness uses a dedicated SBOM-AIBOM-* SARIF rule family (one result per
    // failing model-card check), with a rule table and run-level properties.
    if report.profile == ScoringProfile::AiReadiness
        && let Some(metrics) = report.ai_readiness_metrics.as_ref()
    {
        let na = metrics.is_not_applicable();
        let score = if na { None } else { Some(report.overall_score) };
        let grade = if na { "N/A" } else { report.grade.letter() };
        return crate::reports::generate_ai_readiness_sarif(
            metrics,
            &config
                .sbom_path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy(),
            &config.profile.to_string(),
            score,
            grade,
        )
        .unwrap_or_else(|_| {
            serde_json::to_string_pretty(&serde_json::json!({ "runs": [] })).unwrap_or_default()
        });
    }

    // Everything else routes through the shared registry-driven SARIF layer:
    // the compliance violations carry the exact same external rule ids as
    // `validate -o sarif`, and recommendations are merged into the same run
    // as advisory (never `error`) results.
    crate::reports::generate_quality_sarif(
        report,
        &config
            .sbom_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy(),
        &config.profile.to_string(),
    )
    .unwrap_or_else(|_| {
        serde_json::to_string_pretty(&serde_json::json!({ "runs": [] })).unwrap_or_default()
    })
}

/// Format quality report for output.
///
/// `sbomqs_table` is the pre-rendered sbomqs-comparable score table (0-10),
/// appended verbatim at the end of the report. `None` for profiles with a
/// dedicated layout (AI-readiness) and for direct test callers.
fn format_quality_report(
    report: &QualityReport,
    config: &QualityConfig,
    sbomqs_table: Option<&str>,
) -> String {
    let mut lines = Vec::new();
    let use_color = !config.no_color && std::env::var("NO_COLOR").is_err();

    // AI-readiness uses a dedicated report layout (per-check pass/fail, not the
    // standard 8 category scores).
    if report.profile == ScoringProfile::AiReadiness {
        return format_ai_readiness_report(report, config, use_color);
    }

    // Color codes
    let (grade_color, reset) = if use_color {
        let color = match report.grade {
            QualityGrade::A | QualityGrade::B => "\x1b[32m", // Green
            QualityGrade::C | QualityGrade::D => "\x1b[33m", // Yellow
            QualityGrade::F => "\x1b[31m",                   // Red
        };
        (color, "\x1b[0m")
    } else {
        ("", "")
    };

    // Header
    lines.push(format!(
        "SBOM Quality Report: {}",
        config
            .sbom_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
    ));
    lines.push(format!("Profile: {}", config.profile));
    lines.push(String::new());

    // Overall score
    lines.push(format!(
        "Overall Score: {}{:.1}/100 (Grade: {}){}",
        grade_color,
        report.overall_score,
        report.grade.letter(),
        reset
    ));
    lines.push(String::new());

    // Category scores
    lines.push("Category Scores:".to_string());
    lines.push(format!(
        "  Completeness:    {:.1}/100",
        report.completeness_score
    ));
    lines.push(format!(
        "  Identifiers:     {:.1}/100",
        report.identifier_score
    ));
    lines.push(format!(
        "  Licenses:        {:.1}/100",
        report.license_score
    ));
    lines.push(match report.vulnerability_score {
        Some(score) => format!("  Vulnerabilities: {score:.1}/100"),
        None => "  Vulnerabilities: N/A".to_string(),
    });
    lines.push(format!(
        "  Dependencies:    {:.1}/100",
        report.dependency_score
    ));
    lines.push(String::new());

    // Compliance status
    let compliance_status = if report.compliance.is_compliant {
        format!(
            "{}COMPLIANT{}",
            if use_color { "\x1b[32m" } else { "" },
            reset
        )
    } else {
        format!(
            "{}NON-COMPLIANT{}",
            if use_color { "\x1b[31m" } else { "" },
            reset
        )
    };
    lines.push(format!(
        "Compliance ({}): {} ({} errors, {} warnings)",
        report.compliance.level.name(),
        compliance_status,
        report.compliance.error_count,
        report.compliance.warning_count
    ));
    lines.push(String::new());

    // Detailed metrics
    if config.show_metrics {
        lines.push("Detailed Metrics:".to_string());
        lines.push(format!(
            "  Total Components: {}",
            report.completeness_metrics.total_components
        ));
        lines.push(format!(
            "  With Version:     {:.1}%",
            report.completeness_metrics.components_with_version
        ));
        lines.push(format!(
            "  With PURL:        {:.1}%",
            report.completeness_metrics.components_with_purl
        ));
        lines.push(format!(
            "  With License:     {:.1}%",
            report.completeness_metrics.components_with_licenses
        ));
        lines.push(format!(
            "  With Supplier:    {:.1}%",
            report.completeness_metrics.components_with_supplier
        ));
        lines.push(format!(
            "  With Hashes:      {:.1}%",
            report.completeness_metrics.components_with_hashes
        ));
        lines.push(String::new());

        lines.push("  Identifier Quality:".to_string());
        lines.push(format!(
            "    Valid PURLs:    {}",
            report.identifier_metrics.valid_purls
        ));
        lines.push(format!(
            "    Valid CPEs:     {}",
            report.identifier_metrics.valid_cpes
        ));
        lines.push(format!(
            "    Missing IDs:    {}",
            report.identifier_metrics.missing_all_identifiers
        ));
        lines.push(format!(
            "    Ecosystems:     {}",
            report.identifier_metrics.ecosystems.join(", ")
        ));
        lines.push(String::new());

        lines.push("  Dependency Graph:".to_string());
        lines.push(format!(
            "    Total Edges:    {}",
            report.dependency_metrics.total_dependencies
        ));
        lines.push(format!(
            "    Orphan Nodes:   {}",
            report.dependency_metrics.orphan_components
        ));
        // Software complexity index
        if let Some(simplicity) = report.dependency_metrics.software_complexity_index {
            let level = report
                .dependency_metrics
                .complexity_level
                .as_ref()
                .map_or("N/A", |l| l.label());
            lines.push(format!("    Complexity:     {simplicity:.0}/100 ({level})"));
            if let Some(ref f) = report.dependency_metrics.complexity_factors {
                lines.push(format!(
                    "      Volume: {:.2}  Depth: {:.2}  Fanout: {:.2}  Cycles: {:.2}  Fragmentation: {:.2}",
                    f.dependency_volume, f.normalized_depth, f.fanout_concentration, f.cycle_ratio, f.fragmentation
                ));
            }
        } else {
            lines.push("    Complexity:     N/A (graph analysis skipped)".to_string());
        }
        lines.push(String::new());
    }

    // Recommendations
    if config.show_recommendations && !report.recommendations.is_empty() {
        lines.push("Recommendations:".to_string());
        for rec in report.recommendations.iter().take(10) {
            let priority_indicator = if use_color {
                match rec.priority {
                    1 => "\x1b[31m[P1]\x1b[0m",
                    2 => "\x1b[33m[P2]\x1b[0m",
                    3 => "\x1b[34m[P3]\x1b[0m",
                    _ => "[P4+]",
                }
            } else {
                match rec.priority {
                    1 => "[P1]",
                    2 => "[P2]",
                    3 => "[P3]",
                    _ => "[P4+]",
                }
            };
            lines.push(format!(
                "  {} {} ({} affected, +{:.1} impact)",
                priority_indicator, rec.message, rec.affected_count, rec.impact
            ));
        }
        lines.push(String::new());
    }

    // Compact sbomqs-comparable table (0-10 scores recomputed per-feature
    // with sbomqs' formulas — never overall_score/10).
    if let Some(table) = sbomqs_table {
        lines.push(table.to_string());
        lines.push(String::new());
    }

    lines.join("\n")
}

/// Render the AI-readiness profile as a per-check pass/fail report.
fn format_ai_readiness_report(
    report: &QualityReport,
    config: &QualityConfig,
    use_color: bool,
) -> String {
    let mut lines = Vec::new();
    let Some(metrics) = report.ai_readiness_metrics.as_ref() else {
        return String::new();
    };
    let reset = if use_color { "\x1b[0m" } else { "" };

    lines.push(format!(
        "SBOM Quality Report: {}",
        config
            .sbom_path
            .file_name()
            .unwrap_or_default()
            .to_string_lossy()
    ));
    lines.push(format!("Profile: {}", config.profile));
    lines.push(String::new());

    if metrics.is_not_applicable() {
        let muted = if use_color { "\x1b[33m" } else { "" };
        lines.push(format!("Overall Score: {muted}N/A{reset}"));
        lines.push(
            metrics
                .na_reason
                .clone()
                .unwrap_or_else(|| "AI readiness is not applicable for this SBOM".to_string()),
        );
        return lines.join("\n");
    }

    let grade_color = if use_color {
        match report.grade {
            QualityGrade::A | QualityGrade::B => "\x1b[32m",
            QualityGrade::C | QualityGrade::D => "\x1b[33m",
            QualityGrade::F => "\x1b[31m",
        }
    } else {
        ""
    };
    lines.push(format!(
        "Overall Score: {}{:.1}/100 (Grade: {}){}",
        grade_color,
        report.overall_score,
        report.grade.letter(),
        reset
    ));
    lines.push(format!(
        "ML Components: {} total, {} fully documented",
        metrics.ml_component_count, metrics.components_fully_documented
    ));
    lines.push(String::new());
    lines.push("AI Readiness Checks:".to_string());

    for check in &metrics.checks {
        let status = if check.passed { "PASS" } else { "FAIL" };
        let status_color = if use_color {
            if check.passed { "\x1b[32m" } else { "\x1b[31m" }
        } else {
            ""
        };
        lines.push(format!(
            "  {}{}{} {} ({:.0}%)",
            status_color,
            status,
            reset,
            check.id,
            check.weight * 100.0
        ));
        lines.push(format!("    {}", check.name));
        if config.show_metrics
            && let Some(detail) = &check.detail
        {
            lines.push(format!("    {detail}"));
        }
    }
    lines.push(String::new());

    if config.show_recommendations && !report.recommendations.is_empty() {
        lines.push("Recommendations:".to_string());
        for rec in report.recommendations.iter().take(10) {
            lines.push(format!(
                "  [P{}] {} ({} affected, +{:.1} impact)",
                rec.priority, rec.message, rec.affected_count, rec.impact
            ));
        }
        lines.push(String::new());
    }

    lines.join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Component, ComponentType, DocumentMetadata, MlModelInfo, NormalizedSbom};

    /// Contract test: every documented `--profile` spelling parses to the
    /// right profile through the single shared parser (clap uses the same
    /// name/alias table).
    #[test]
    fn every_documented_profile_alias_parses() {
        let table: &[(&str, ScoringProfile)] = &[
            ("minimal", ScoringProfile::Minimal),
            ("standard", ScoringProfile::Standard),
            ("security", ScoringProfile::Security),
            ("license-compliance", ScoringProfile::LicenseCompliance),
            ("license", ScoringProfile::LicenseCompliance),
            ("cra", ScoringProfile::Cra),
            ("cyber-resilience", ScoringProfile::Cra),
            ("bsi", ScoringProfile::BsiTr03183_2),
            ("tr-03183", ScoringProfile::BsiTr03183_2),
            ("tr03183", ScoringProfile::BsiTr03183_2),
            ("bsi-tr-03183-2", ScoringProfile::BsiTr03183_2),
            ("comprehensive", ScoringProfile::Comprehensive),
            ("full", ScoringProfile::Comprehensive),
            ("cbom", ScoringProfile::Cbom),
            ("cryptographic", ScoringProfile::Cbom),
            ("ai-readiness", ScoringProfile::AiReadiness),
            ("ai_readiness", ScoringProfile::AiReadiness),
        ];
        for (spelling, expected) in table {
            let parsed: ScoringProfile = spelling
                .parse()
                .unwrap_or_else(|e| panic!("'{spelling}' must parse: {e}"));
            assert_eq!(parsed, *expected, "'{spelling}' mapped to wrong profile");
        }
    }

    #[test]
    fn profile_parse_is_case_insensitive_and_rejects_unknown() {
        assert_eq!(
            "MINIMAL".parse::<ScoringProfile>().unwrap(),
            ScoringProfile::Minimal
        );
        assert_eq!(
            "Standard".parse::<ScoringProfile>().unwrap(),
            ScoringProfile::Standard
        );
        let err = "invalid".parse::<ScoringProfile>().unwrap_err();
        assert!(err.contains("Valid values"));
        assert!(err.contains("license-compliance"));
    }

    #[test]
    fn rejects_unsupported_output_format_before_reading_sbom() {
        // html/markdown/csv/oscal-json used to fall through to the text
        // renderer; they must now fail fast (before the SBOM is read — the
        // path here does not exist).
        for format in [
            ReportFormat::Html,
            ReportFormat::Markdown,
            ReportFormat::Csv,
            ReportFormat::OscalJson,
            ReportFormat::Ndjson,
            ReportFormat::Table,
            ReportFormat::SideBySide,
            ReportFormat::Tui,
        ] {
            let err = run_quality(
                PathBuf::from("/nonexistent/never-read.cdx.json"),
                ScoringProfile::Standard,
                format,
                None,
                false,
                false,
                None,
                false,
                true,
                None,
                None,
                None,
                EnrichmentConfig::default(),
            )
            .expect_err("unsupported format must be rejected");
            let msg = err.to_string();
            assert!(
                msg.contains("not supported by `sbom-tools quality`"),
                "unexpected error for {format}: {msg}"
            );
            assert!(
                msg.contains("sarif") && msg.contains("json"),
                "error must list the supported formats: {msg}"
            );
        }
    }

    #[test]
    fn sbomqs_json_output_emits_sbomqs_shaped_report() {
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","version":1,
                "components":[{"type":"library","name":"lodash","version":"4.17.21",
                               "purl":"pkg:npm/lodash@4.17.21"}]}"#,
        )
        .unwrap();
        let out_path = dir.path().join("out.json");
        let code = run_quality(
            sbom_path,
            ScoringProfile::Standard,
            ReportFormat::SbomqsJson,
            Some(out_path.clone()),
            false,
            false,
            None,
            false,
            true,
            None,
            None,
            None,
            EnrichmentConfig::default(),
        )
        .expect("sbomqs-json run must succeed");
        assert_eq!(code, exit_codes::SUCCESS);

        let value: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&out_path).unwrap())
                .expect("sbomqs-json output must be valid JSON");
        // Exact sbomqs score-report shape, honest identity.
        assert!(value["run_id"].is_string());
        assert_eq!(value["creation_info"]["name"], "sbom-tools");
        let file = &value["files"][0];
        assert_eq!(file["spec"], "cyclonedx");
        assert_eq!(file["file_format"], "json");
        assert!(file["avg_score"].is_number());
        let scores = file["scores"].as_array().expect("scores array");
        assert_eq!(scores.len(), 23);
        assert!(
            scores
                .iter()
                .any(|s| s["feature"] == "comp_with_name" && s["score"] == 10.0)
        );
    }

    #[test]
    fn summary_report_appends_sbomqs_compat_table() {
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = write_minimal_sbom(dir.path());
        let out_path = dir.path().join("out.txt");
        let code = run_quality(
            sbom_path,
            ScoringProfile::Standard,
            ReportFormat::Summary,
            Some(out_path.clone()),
            false,
            false,
            None,
            false,
            true,
            None,
            None,
            None,
            EnrichmentConfig::default(),
        )
        .expect("summary run must succeed");
        assert_eq!(code, exit_codes::SUCCESS);
        let text = std::fs::read_to_string(&out_path).unwrap();
        assert!(text.contains("sbomqs-Comparable Scores"));
        assert!(text.contains("NTIA-minimum-elements"));
        assert!(
            text.contains("not convertible"),
            "table must carry the non-convertibility note"
        );
    }

    #[test]
    fn explicit_missing_sidecar_is_a_hard_error() {
        // An explicitly passed --cra-sidecar that fails to load used to be
        // silently ignored (`.ok()`); it must now abort the command.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        let err = run_quality(
            sbom_path,
            ScoringProfile::Cra,
            ReportFormat::Summary,
            None,
            false,
            false,
            None,
            false,
            true,
            Some(dir.path().join("missing.cra.json")),
            None,
            None,
            EnrichmentConfig::default(),
        )
        .expect_err("broken explicit sidecar must be a hard error");
        assert!(err.to_string().contains("Failed to load CRA sidecar"));
    }

    fn write_minimal_sbom(dir: &std::path::Path) -> PathBuf {
        let sbom_path = dir.join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        sbom_path
    }

    #[test]
    fn fail_on_noncompliant_does_not_fire_on_na_ai_readiness_run() {
        // Regression: an N/A AI-readiness run (no ML components) used to
        // exit 1 on the hidden Comprehensive-level compliance check that no
        // renderer ever displays. Both gates are armed here; neither may fire.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = write_minimal_sbom(dir.path());
        let code = run_quality(
            sbom_path,
            ScoringProfile::AiReadiness,
            ReportFormat::Summary,
            Some(dir.path().join("out.txt")),
            false,
            false,
            Some(70.0), // --min-score: must not fire on N/A either (P0 guard)
            true,       // --fail-on-noncompliant
            true,
            None,
            None,
            None,
            EnrichmentConfig::default(),
        )
        .expect("an N/A AI-readiness run must not error");
        assert_eq!(
            code,
            exit_codes::SUCCESS,
            "N/A AI-readiness run must exit 0 with --fail-on-noncompliant"
        );
    }

    #[test]
    fn fail_on_noncompliant_still_fires_on_applicable_noncompliant_run() {
        // The empty SBOM is genuinely non-compliant with the CRA profile's
        // embedded check, so the opt-in gate must still flip the exit code.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = write_minimal_sbom(dir.path());
        let code = run_quality(
            sbom_path,
            ScoringProfile::Cra,
            ReportFormat::Summary,
            Some(dir.path().join("out.txt")),
            false,
            false,
            None,
            true, // --fail-on-noncompliant
            true,
            None,
            None,
            None,
            EnrichmentConfig::default(),
        )
        .expect("the run itself must succeed");
        assert_eq!(code, exit_codes::COMPLIANCE_ERRORS);
    }

    #[test]
    fn typod_cra_product_class_is_a_hard_error() {
        // Regression: a typo'd --cra-product-class was silently dropped,
        // scoring a critical-class product as Default.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = write_minimal_sbom(dir.path());
        let err = run_quality(
            sbom_path,
            ScoringProfile::Cra,
            ReportFormat::Summary,
            None,
            false,
            false,
            None,
            false,
            true,
            None,
            Some("critcal".to_string()),
            None,
            EnrichmentConfig::default(),
        )
        .expect_err("typo'd --cra-product-class must be a hard error");
        let msg = err.to_string();
        assert!(msg.contains("critcal"), "must name the bad value: {msg}");
        assert!(
            msg.contains("critical"),
            "must list the valid values: {msg}"
        );
    }

    #[test]
    fn invalid_as_of_is_a_hard_error_before_reading_the_sbom() {
        let err = run_quality(
            PathBuf::from("/nonexistent/never-read.cdx.json"),
            ScoringProfile::Cra,
            ReportFormat::Summary,
            None,
            false,
            false,
            None,
            false,
            true,
            None,
            None,
            Some("not-a-date".to_string()),
            EnrichmentConfig::default(),
        )
        .expect_err("invalid --as-of must be rejected");
        assert!(err.to_string().contains("invalid --as-of"));
    }

    #[test]
    fn auto_discovered_broken_sidecar_hard_fails() {
        // A discovered-but-broken sidecar is a hard error, matching the
        // explicit --cra-sidecar contract: silently scoring without it would
        // shift the CRA verdict with only a stderr warning.
        let dir = tempfile::tempdir().unwrap();
        let sbom_path = dir.path().join("app.cdx.json");
        std::fs::write(
            &sbom_path,
            r#"{"bomFormat":"CycloneDX","specVersion":"1.5","components":[]}"#,
        )
        .unwrap();
        std::fs::write(dir.path().join("app.cra.json"), "{ not json").unwrap();
        let err = run_quality(
            sbom_path,
            ScoringProfile::Cra,
            ReportFormat::Json,
            Some(dir.path().join("out.json")),
            false,
            false,
            None,
            false,
            true,
            None,
            None,
            None,
            EnrichmentConfig::default(),
        )
        .expect_err("a discovered-but-broken sidecar must hard-error");
        assert!(
            err.to_string().contains("CRA sidecar"),
            "error must name the sidecar: {err}"
        );
    }

    fn ai_config(output: ReportFormat, min_score: Option<f32>) -> QualityConfig {
        QualityConfig {
            sbom_path: PathBuf::from("model.cdx.json"),
            profile: ScoringProfile::AiReadiness,
            output,
            output_file: None,
            show_recommendations: true,
            show_metrics: true,
            min_score,
            fail_on_noncompliant: false,
            no_color: true,
            cra_sidecar_path: None,
            cra_product_class: None,
            as_of: None,
            enrichment: EnrichmentConfig::default(),
        }
    }

    fn fully_documented_ml_sbom() -> NormalizedSbom {
        let mut sbom = NormalizedSbom::new(DocumentMetadata::default());
        let mut component = Component::new("bert-base".to_string(), "ml-model-1".to_string())
            .with_version("1.0.0".to_string());
        component.component_type = ComponentType::MachineLearningModel;
        component.ml_model = Some(MlModelInfo {
            architecture_family: Some("transformer".to_string()),
            training_datasets: vec![crate::model::DatasetRef {
                reference: None,
                name: Some("dataset".to_string()),
                purl: None,
            }],
            energy_kwh_training: Some(20.0),
            model_card_url: Some("https://example.test/model-card".to_string()),
            limitations: Some("Only validated for English text".to_string()),
            ..MlModelInfo::default()
        });
        // A weight hash satisfies the AI-010 integrity check.
        component.hashes.push(crate::model::Hash::new(
            crate::model::HashAlgorithm::Sha256,
            "d".repeat(64),
        ));
        component.extensions.raw = Some(json!({
            "mlModel": { "modelCard": {
                "quantitativeAnalysis": { "performanceMetrics": [{ "type": "accuracy", "value": 0.97 }] },
                "considerations": {
                    "fairnessConsiderations": ["Reviewed"],
                    "useCases": ["Classification"],
                    "ethicalConsiderations": ["Human review required"]
                }
            }}
        }));
        sbom.add_component(component);
        sbom
    }

    #[test]
    fn test_format_quality_report_ai_readiness_shows_checks() {
        let sbom = fully_documented_ml_sbom();
        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let output = format_quality_report(&report, &ai_config(ReportFormat::Summary, None), None);
        assert!(output.contains("AI Readiness Checks:"));
        assert!(output.contains("PASS AI-001"));
        assert!(!output.contains("Category Scores:"));
    }

    #[test]
    fn test_format_quality_report_ai_readiness_na_shows_na() {
        let sbom = NormalizedSbom::new(DocumentMetadata::default());
        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let output =
            format_quality_report(&report, &ai_config(ReportFormat::Summary, Some(70.0)), None);
        assert!(output.contains("Overall Score: N/A"));
        assert!(output.contains("No machine-learning-model components found"));
    }

    #[test]
    fn test_format_quality_json_ai_readiness_na_is_not_misleading() {
        let sbom = NormalizedSbom::new(DocumentMetadata::default());
        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let out = format_quality_json(&report, &ai_config(ReportFormat::Json, None));
        let value: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
        // N/A must not serialize as a real 0.0 / "F" score.
        assert_eq!(value["applicable"], json!(false));
        assert!(value["report"]["overall_score"].is_null());
        assert_eq!(value["report"]["grade"], json!("N/A"));
    }

    #[test]
    fn test_format_quality_sarif_routes_compliance_through_registry_rule_ids() {
        // Non-AI profiles route through the shared SARIF layer: violations
        // carry registry SARIF rule ids (never invented QUALITY-* ids) and
        // every emitted ruleId has a reportingDescriptor.
        let sbom = NormalizedSbom::new(DocumentMetadata::default());
        let report = QualityScorer::new(ScoringProfile::Cra).score(&sbom);
        let mut config = ai_config(ReportFormat::Sarif, None);
        config.profile = ScoringProfile::Cra;
        let out = format_quality_sarif(&report, &config);
        let value: serde_json::Value = serde_json::from_str(&out).expect("valid SARIF JSON");
        let run = &value["runs"][0];
        let results = run["results"].as_array().expect("results array");
        assert!(!results.is_empty(), "empty SBOM must fire CRA violations");
        assert!(
            results.iter().all(|r| r["ruleId"]
                .as_str()
                .is_some_and(|id| id.starts_with("SBOM-"))),
            "quality SARIF must not invent QUALITY-* rule ids"
        );
        assert!(
            run["tool"]["driver"]["rules"]
                .as_array()
                .is_some_and(|rules| !rules.is_empty()),
            "quality SARIF must declare its rule catalogue"
        );
        assert_eq!(run["properties"]["compliant"], json!(false));
    }

    #[test]
    fn test_format_quality_sarif_ai_readiness_na_is_not_misleading() {
        let sbom = NormalizedSbom::new(DocumentMetadata::default());
        let report = QualityScorer::new(ScoringProfile::AiReadiness).score(&sbom);
        let out = format_quality_sarif(&report, &ai_config(ReportFormat::Sarif, None));
        let value: serde_json::Value = serde_json::from_str(&out).expect("valid SARIF JSON");
        let run = &value["runs"][0];
        let props = &run["properties"];
        assert_eq!(props["applicable"], json!(false));
        // The serialized key is camelCase and *omitted* for the unscored N/A
        // case — indexing `props["overall_score"]` would return Null for any
        // absent key, so assert on the real key's absence.
        assert!(
            props.get("overallScore").is_none(),
            "unscored N/A run must omit overallScore entirely"
        );
        assert!(
            props["notApplicableReason"]
                .as_str()
                .is_some_and(|r| r.contains("No machine-learning-model components")),
            "N/A run must carry the metrics' human-readable reason"
        );
        assert_eq!(props["grade"], json!("N/A"));
        // The dedicated SBOM-AIBOM-* rule family is now emitted (was absent before),
        // and N/A yields no findings.
        let rules = run["tool"]["driver"]["rules"]
            .as_array()
            .expect("rules array");
        assert!(
            rules.iter().any(|r| r["id"] == json!("SBOM-AIBOM-001")),
            "expected SBOM-AIBOM rule table"
        );
        assert!(run["results"].as_array().expect("results array").is_empty());
    }
}