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
//! CycloneDX 1.7 JSON emitter.
//!
//! Synthesizes a fresh CycloneDX 1.7 document from a [`NormalizedSbom`]:
//! component identity (`bom-ref`) from [`CanonicalId`], `dependencies` from the
//! edge list, and licenses/hashes/purls/etc. from the typed model. Where a
//! component carries preserved same-format source JSON (see
//! [`super::preserve_source_json`]), format-specific blocks that the canonical
//! model can't fully round-trip (`cryptoProperties`, `evidence`) are spliced
//! back verbatim.
//!
//! The `mlModel.modelCard` AI bridge (populated by the SPDX-3 parser into
//! `extensions.raw`) is preserved so converting an AI-BOM does not regress AI
//! scoring.

use serde_json::{Map, Value, json};

use crate::model::{
    Component, ComponentType, Creator, CreatorType, DependencyType, Hash, LicenseExpression,
    NormalizedSbom,
};

use super::EmitError;
use super::fidelity::FidelityReport;

/// CycloneDX spec version emitted by this module.
const SPEC_VERSION: &str = "1.7";

/// Emit `sbom` as a CycloneDX 1.7 JSON document plus a fidelity report.
///
/// # Errors
///
/// Returns [`EmitError::Serialize`] if the synthesized document fails to
/// serialize (not expected for well-formed models).
pub fn emit_cyclonedx(sbom: &NormalizedSbom) -> Result<(String, FidelityReport), EmitError> {
    let mut report = FidelityReport::new(sbom.document.format.to_string(), "CycloneDX 1.7");

    // Stable bom-ref per component = canonical id value. Canonical ids are
    // unique keys in the components map, so refs never collide.
    let bom_ref_of = |id: &crate::model::CanonicalId| id.value().to_string();

    let mut components_json = Vec::with_capacity(sbom.components.len());
    let mut primary_component_json: Option<Value> = None;

    for (id, component) in &sbom.components {
        let comp_json = emit_component(component, &bom_ref_of(id), &mut report);
        if sbom.primary_component_id.as_ref() == Some(id) {
            primary_component_json = Some(comp_json);
        } else {
            components_json.push(comp_json);
        }
    }

    // Metadata block.
    let mut metadata = Map::new();
    metadata.insert(
        "timestamp".to_string(),
        json!(sbom.document.created.to_rfc3339()),
    );
    if let Some(tools) = emit_tools(sbom) {
        metadata.insert("tools".to_string(), tools);
    }
    if let Some(authors) = emit_authors(sbom) {
        metadata.insert("authors".to_string(), authors);
        report.synthesized("metadata.authors from person creators");
    }
    if let Some(manufacturer) = emit_manufacturer(sbom) {
        metadata.insert("manufacturer".to_string(), manufacturer);
        report.synthesized("metadata.manufacturer from organization creator");
    }
    if let Some(primary) = primary_component_json {
        metadata.insert("component".to_string(), primary);
        report.synthesized("metadata.component from primary component");
    }

    let mut doc = Map::new();
    doc.insert("bomFormat".to_string(), json!("CycloneDX"));
    doc.insert("specVersion".to_string(), json!(SPEC_VERSION));
    // Round-trip the source document's revision counter when it was
    // captured; 1 is the CycloneDX default for a first revision.
    doc.insert(
        "version".to_string(),
        json!(sbom.document.doc_version.unwrap_or(1)),
    );
    if let Some(serial) = &sbom.document.serial_number {
        doc.insert("serialNumber".to_string(), json!(serial));
    }
    doc.insert("metadata".to_string(), Value::Object(metadata));
    doc.insert("components".to_string(), Value::Array(components_json));

    let dependencies = emit_dependencies(sbom, &mut report);
    if !dependencies.is_empty() {
        doc.insert("dependencies".to_string(), Value::Array(dependencies));
        report.synthesized("dependencies from edge list");
    }

    // Note canonical-model fields with no CycloneDX 1.7 home so the report is honest.
    note_unmappable(sbom, &mut report);

    let serialized = serde_json::to_string_pretty(&Value::Object(doc))?;
    Ok((serialized, report))
}

/// Synthesize a single CycloneDX component object.
fn emit_component(component: &Component, bom_ref: &str, report: &mut FidelityReport) -> Value {
    let mut obj = Map::new();

    obj.insert(
        "type".to_string(),
        json!(emit_component_type(&component.component_type)),
    );
    obj.insert("bom-ref".to_string(), json!(bom_ref));
    report.synthesized("bom-ref from canonical id");
    obj.insert("name".to_string(), json!(component.name));

    if let Some(version) = &component.version {
        obj.insert("version".to_string(), json!(version));
    }
    if let Some(group) = &component.group {
        obj.insert("group".to_string(), json!(group));
    }
    if let Some(author) = &component.author {
        obj.insert("author".to_string(), json!(author));
    }
    if let Some(desc) = &component.description {
        obj.insert("description".to_string(), json!(desc));
    }
    if let Some(copyright) = &component.copyright {
        obj.insert("copyright".to_string(), json!(copyright));
    }
    if let Some(purl) = &component.identifiers.purl {
        obj.insert("purl".to_string(), json!(purl));
    }
    if let Some(cpe) = component.identifiers.cpe.first() {
        obj.insert("cpe".to_string(), json!(cpe));
    }
    if !component.identifiers.swhid.is_empty() {
        let swhids: Vec<Value> = component
            .identifiers
            .swhid
            .iter()
            .map(|s| json!(s.to_string()))
            .collect();
        obj.insert("swhid".to_string(), Value::Array(swhids));
    }

    if let Some(supplier) = &component.supplier {
        obj.insert("supplier".to_string(), json!({ "name": supplier.name }));
    }

    if let Some(licenses) = emit_licenses(component) {
        obj.insert("licenses".to_string(), licenses);
    }
    if let Some(hashes) = emit_hashes(&component.hashes) {
        obj.insert("hashes".to_string(), hashes);
    }
    if let Some(ext_refs) = emit_external_refs(component) {
        obj.insert("externalReferences".to_string(), ext_refs);
    }
    if !component.extensions.properties.is_empty() {
        let props: Vec<Value> = component
            .extensions
            .properties
            .iter()
            .map(|p| json!({ "name": p.name, "value": p.value }))
            .collect();
        obj.insert("properties".to_string(), Value::Array(props));
    }

    // ML model card: synthesize from typed model and splice the AI bridge so
    // AI-readiness scoring survives a round-trip conversion of an AI-BOM.
    if let Some(model_card) = emit_model_card(component, report) {
        obj.insert("modelCard".to_string(), model_card);
    }

    // Dataset componentData (typed model).
    if let Some(data) = emit_dataset(component) {
        obj.insert("data".to_string(), data);
        report.synthesized("data componentData from dataset model");
    }

    // 1.7 external-component flags.
    if component.is_external {
        obj.insert("isExternal".to_string(), json!(true));
        if let Some(vr) = &component.version_range {
            obj.insert("versionRange".to_string(), json!(vr));
        }
    }

    // Splice format-specific blocks the typed model can't fully reconstruct,
    // only when preserved same-format source JSON carries them.
    splice_preserved_blocks(component, &mut obj, report);

    Value::Object(obj)
}

/// Splice verbatim CycloneDX-only blocks from preserved source JSON.
///
/// Limited to blocks the canonical model genuinely can't reconstruct losslessly
/// (`cryptoProperties`, `evidence`). Never overwrites a synthesized key.
fn splice_preserved_blocks(
    component: &Component,
    obj: &mut Map<String, Value>,
    report: &mut FidelityReport,
) {
    let Some(src) = component.extensions.source_json.as_deref() else {
        return;
    };
    // Only splice from a CycloneDX-shaped source object (has bom-ref or purl).
    let looks_cdx = src.get("bom-ref").is_some()
        || src.get("purl").is_some()
        || src.get("cryptoProperties").is_some();
    if !looks_cdx {
        return;
    }
    for key in ["cryptoProperties", "evidence", "pedigree"] {
        if let Some(block) = src.get(key)
            && !obj.contains_key(key)
        {
            obj.insert(key.to_string(), block.clone());
            report.preserved(format!("component.{key}"));
        }
    }
}

/// Map a [`ComponentType`] to its CycloneDX `type` string.
fn emit_component_type(ty: &ComponentType) -> String {
    // ComponentType::Display already yields CycloneDX spelling
    // (e.g. "machine-learning-model", "operating-system").
    ty.to_string()
}

/// Emit a `licenses` array from declared + concluded expressions.
///
/// A concluded expression identical to a declared one (common for SPDX inputs
/// where `licenseConcluded == licenseDeclared`) is not emitted twice.
fn emit_licenses(component: &Component) -> Option<Value> {
    let mut seen: Vec<&str> = Vec::new();
    let mut items = Vec::new();
    for expr in &component.licenses.declared {
        if !seen.contains(&expr.expression.as_str()) {
            seen.push(&expr.expression);
            items.push(license_choice(expr));
        }
    }
    if let Some(concluded) = &component.licenses.concluded
        && !seen.contains(&concluded.expression.as_str())
    {
        items.push(license_choice(concluded));
    }
    if items.is_empty() {
        None
    } else {
        Some(Value::Array(items))
    }
}

/// Build one CycloneDX license-choice object.
///
/// Valid single SPDX ids use `{license:{id}}`; compound valid expressions use
/// the `{expression}` form, matching CycloneDX semantics. A bare
/// `LicenseRef-*`/`DocumentRef-*` token parses as a valid SPDX *expression* but
/// is not a valid SPDX *identifier*, so it must not go in `license.id`: it is
/// emitted as `{license:{name}}`, preferring the human-readable name resolved
/// from the source document (SPDX `hasExtractedLicensingInfos`) over the raw
/// ref string.
fn license_choice(expr: &LicenseExpression) -> Value {
    let raw = expr.expression.as_str();
    let is_compound = raw.contains(" OR ") || raw.contains(" AND ") || raw.contains(" WITH ");
    let is_local_ref =
        !is_compound && (raw.starts_with("LicenseRef-") || raw.starts_with("DocumentRef-"));
    if expr.is_valid_spdx && !is_compound && !is_local_ref {
        json!({ "license": { "id": raw } })
    } else if expr.is_valid_spdx && is_compound {
        json!({ "expression": raw })
    } else {
        json!({ "license": { "name": expr.display_name() } })
    }
}

/// Emit a `hashes` array, dropping hashes whose algorithm has no CycloneDX
/// spelling (recorded by the caller via `note_unmappable`).
fn emit_hashes(hashes: &[Hash]) -> Option<Value> {
    if hashes.is_empty() {
        return None;
    }
    let items: Vec<Value> = hashes
        .iter()
        .map(|h| json!({ "alg": h.algorithm.to_string(), "content": h.value }))
        .collect();
    Some(Value::Array(items))
}

/// Emit an `externalReferences` array.
fn emit_external_refs(component: &Component) -> Option<Value> {
    if component.external_refs.is_empty() {
        return None;
    }
    let items: Vec<Value> = component
        .external_refs
        .iter()
        .map(|r| {
            let mut o = json!({ "type": r.ref_type.to_string(), "url": r.url });
            if let Some(comment) = &r.comment {
                o["comment"] = json!(comment);
            }
            o
        })
        .collect();
    Some(Value::Array(items))
}

/// Emit a `modelCard`, merging the typed ML model with any preserved AI-bridge
/// `extensions.raw` data so AI scoring survives conversion.
fn emit_model_card(component: &Component, report: &mut FidelityReport) -> Option<Value> {
    let ml = component.ml_model.as_ref();

    // Pull a pre-shaped modelCard from the SPDX-3 AI bridge if present.
    // Layout: extensions.raw = { "mlModel": { "modelCard": { ... } } }.
    let bridged = component
        .extensions
        .raw
        .as_ref()
        .and_then(|raw| raw.pointer("/mlModel/modelCard"))
        .cloned();

    if ml.is_none() && bridged.is_none() {
        return None;
    }

    let mut model_card = bridged
        .and_then(|v| v.as_object().cloned())
        .unwrap_or_default();
    if !model_card.is_empty() {
        report.preserved("modelCard AI bridge (extensions.raw)");
    }

    if let Some(ml) = ml {
        // modelParameters from typed fields.
        let mut params = model_card
            .get("modelParameters")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        if let Some(approach) = &ml.approach {
            params.insert("approach".to_string(), json!({ "type": approach }));
        }
        if let Some(task) = &ml.task {
            params.insert("task".to_string(), json!(task));
        }
        if let Some(family) = &ml.architecture_family {
            params.insert("architectureFamily".to_string(), json!(family));
        }
        if let Some(arch) = &ml.architecture_name {
            params.insert("modelArchitecture".to_string(), json!(arch));
        }
        if !ml.training_datasets.is_empty() {
            let datasets: Vec<Value> = ml
                .training_datasets
                .iter()
                .map(|d| match (&d.reference, &d.name) {
                    (Some(r), _) => json!({ "ref": r }),
                    (None, Some(n)) => json!({ "type": "dataset", "name": n }),
                    (None, None) => json!({ "type": "dataset" }),
                })
                .collect();
            params.insert("datasets".to_string(), Value::Array(datasets));
        }
        if !params.is_empty() {
            model_card.insert("modelParameters".to_string(), Value::Object(params));
        }

        // considerations from typed limitations + energy + the AI-readiness
        // fields (fairness / ethics / use-cases). These mirror the exact spec
        // field names + shapes the CycloneDX parser reads so an AI-BOM round-trips
        // without regressing AI-005/007/009 scoring.
        let mut considerations = model_card
            .get("considerations")
            .and_then(Value::as_object)
            .cloned()
            .unwrap_or_default();
        if let Some(limits) = &ml.limitations {
            considerations.insert("technicalLimitations".to_string(), json!([limits]));
        }
        if let Some(energy) = ml.energy_kwh_training {
            considerations.insert(
                "environmentalConsiderations".to_string(),
                json!({
                    "energyConsumptions": [{
                        "activity": "training",
                        "activityEnergyCost": { "value": energy, "unit": "kWh" }
                    }]
                }),
            );
        }
        // considerations.fairnessAssessments[] — spec object shape
        // { groupAtRisk, benefits, harms, mitigationStrategy } (camelCase, the
        // parser's CdxFairnessObj). Only non-null fields are emitted.
        if !ml.fairness.is_empty() {
            let assessments: Vec<Value> = ml
                .fairness
                .iter()
                .map(|f| {
                    let mut o = Map::new();
                    if let Some(group) = &f.group_at_risk {
                        o.insert("groupAtRisk".to_string(), json!(group));
                    }
                    if let Some(benefits) = &f.benefits {
                        o.insert("benefits".to_string(), json!(benefits));
                    }
                    if let Some(harms) = &f.harms {
                        o.insert("harms".to_string(), json!(harms));
                    }
                    if let Some(mitigation) = &f.mitigation_strategy {
                        o.insert("mitigationStrategy".to_string(), json!(mitigation));
                    }
                    Value::Object(o)
                })
                .collect();
            considerations.insert("fairnessAssessments".to_string(), Value::Array(assessments));
        }
        // considerations.ethicalConsiderations[] — spec object shape
        // { name, mitigationStrategy } (the parser's CdxEthicalObj).
        if !ml.ethical_considerations.is_empty() {
            let ethics: Vec<Value> = ml
                .ethical_considerations
                .iter()
                .map(|e| {
                    let mut o = Map::new();
                    if let Some(name) = &e.name {
                        o.insert("name".to_string(), json!(name));
                    }
                    if let Some(mitigation) = &e.mitigation_strategy {
                        o.insert("mitigationStrategy".to_string(), json!(mitigation));
                    }
                    Value::Object(o)
                })
                .collect();
            considerations.insert("ethicalConsiderations".to_string(), Value::Array(ethics));
        }
        // considerations.useCases — spec string array.
        if !ml.use_cases.is_empty() {
            considerations.insert("useCases".to_string(), json!(ml.use_cases));
        }
        if !considerations.is_empty() {
            model_card.insert("considerations".to_string(), Value::Object(considerations));
        }

        // modelCard.quantitativeAnalysis.performanceMetrics[] — spec object shape
        // { type, value, slice } (the parser's CdxPerformanceMetric).
        if !ml.performance_metrics.is_empty() {
            let metrics: Vec<Value> = ml
                .performance_metrics
                .iter()
                .map(|m| {
                    let mut o = Map::new();
                    if let Some(metric_type) = &m.metric_type {
                        o.insert("type".to_string(), json!(metric_type));
                    }
                    if let Some(value) = &m.value {
                        o.insert("value".to_string(), json!(value));
                    }
                    if let Some(slice) = &m.slice {
                        o.insert("slice".to_string(), json!(slice));
                    }
                    Value::Object(o)
                })
                .collect();
            let mut quant = model_card
                .get("quantitativeAnalysis")
                .and_then(Value::as_object)
                .cloned()
                .unwrap_or_default();
            quant.insert("performanceMetrics".to_string(), Value::Array(metrics));
            model_card.insert("quantitativeAnalysis".to_string(), Value::Object(quant));
        }
        report.synthesized("modelCard from ml_model");
    }

    if model_card.is_empty() {
        None
    } else {
        Some(Value::Object(model_card))
    }
}

/// Emit a `data` componentData array from typed dataset metadata.
fn emit_dataset(component: &Component) -> Option<Value> {
    let dataset = component.dataset.as_ref()?;
    let mut entry = Map::new();
    entry.insert(
        "type".to_string(),
        json!(
            dataset
                .dataset_type
                .clone()
                .unwrap_or_else(|| "dataset".to_string())
        ),
    );
    if !dataset.sensitivity_classifications.is_empty() {
        entry.insert(
            "sensitiveData".to_string(),
            json!(dataset.sensitivity_classifications),
        );
    }
    if !dataset.governance_owners.is_empty() {
        let owners: Vec<Value> = dataset
            .governance_owners
            .iter()
            .map(|o| json!({ "organization": { "name": o } }))
            .collect();
        entry.insert("governance".to_string(), json!({ "owners": owners }));
    }
    Some(json!([Value::Object(entry)]))
}

/// Emit a `metadata.tools` array from document creators of tool type.
fn emit_tools(sbom: &NormalizedSbom) -> Option<Value> {
    let tools: Vec<Value> = sbom
        .document
        .creators
        .iter()
        .filter(|c| matches!(c.creator_type, CreatorType::Tool))
        .map(|c| json!({ "name": c.name }))
        .collect();
    if tools.is_empty() {
        None
    } else {
        Some(Value::Array(tools))
    }
}

/// Render a creator as a CycloneDX `organizationalContact` object.
fn contact_json(creator: &Creator) -> Value {
    let mut o = Map::new();
    o.insert("name".to_string(), json!(creator.name));
    if let Some(email) = &creator.email {
        o.insert("email".to_string(), json!(email));
    }
    Value::Object(o)
}

/// Emit `metadata.authors` (CycloneDX 1.5+) from Person creators — the inverse
/// of the parser's `metadata.authors` → Person mapping. Organization creators
/// beyond the one emitted as `metadata.manufacturer` are folded in as well so
/// no document creator is silently dropped (manufacturer is single-valued).
fn emit_authors(sbom: &NormalizedSbom) -> Option<Value> {
    let mut authors: Vec<Value> = sbom
        .document
        .creators
        .iter()
        .filter(|c| matches!(c.creator_type, CreatorType::Person))
        .map(contact_json)
        .collect();
    authors.extend(
        sbom.document
            .creators
            .iter()
            .filter(|c| matches!(c.creator_type, CreatorType::Organization))
            .skip(1)
            .map(contact_json),
    );
    if authors.is_empty() {
        None
    } else {
        Some(Value::Array(authors))
    }
}

/// Emit `metadata.manufacturer` (CycloneDX 1.5+) from the first Organization
/// creator — the inverse of the parser's manufacturer → Organization mapping
/// (BSI TR-03183-2 Table 8's "Creator of the SBOM").
fn emit_manufacturer(sbom: &NormalizedSbom) -> Option<Value> {
    let org = sbom
        .document
        .creators
        .iter()
        .find(|c| matches!(c.creator_type, CreatorType::Organization))?;
    let mut o = Map::new();
    o.insert("name".to_string(), json!(org.name));
    if let Some(email) = &org.email {
        o.insert("contact".to_string(), json!([{ "email": email }]));
    }
    Some(Value::Object(o))
}

/// Emit the `dependencies` array from the edge list.
///
/// CycloneDX groups edges by source `ref` with a `dependsOn` list. `Provides`
/// edges (1.7) become a `provides` list. Other relationship kinds (SPDX-style
/// CONTAINS/GENERATES/etc.) have no CycloneDX dependency representation and are
/// recorded as dropped by the caller.
fn emit_dependencies(sbom: &NormalizedSbom, report: &mut FidelityReport) -> Vec<Value> {
    use indexmap::IndexMap;

    // ref -> (dependsOn refs, provides refs)
    let mut grouped: IndexMap<String, (Vec<String>, Vec<String>)> = IndexMap::new();
    let mut dropped_rel = false;

    for edge in &sbom.edges {
        let from = edge.from.value().to_string();
        let to = edge.to.value().to_string();
        let entry = grouped.entry(from).or_default();
        match edge.relationship {
            DependencyType::DependsOn
            | DependencyType::OptionalDependsOn
            | DependencyType::DevDependsOn
            | DependencyType::BuildDependsOn
            | DependencyType::TestDependsOn
            | DependencyType::RuntimeDependsOn
            | DependencyType::ProvidedDependsOn
            | DependencyType::Describes => entry.0.push(to),
            DependencyType::Provides => entry.1.push(to),
            _ => {
                dropped_rel = true;
                // Best-effort: still record as a plain dependency so the graph
                // edge is not silently lost.
                entry.0.push(to);
            }
        }
    }

    if dropped_rel {
        report.dropped("non-CycloneDX relationship kind (mapped to dependsOn)");
    }

    grouped
        .into_iter()
        .map(|(ref_id, (depends_on, provides))| {
            let mut o = Map::new();
            o.insert("ref".to_string(), json!(ref_id));
            if !depends_on.is_empty() {
                o.insert("dependsOn".to_string(), json!(depends_on));
            }
            if !provides.is_empty() {
                o.insert("provides".to_string(), json!(provides));
            }
            Value::Object(o)
        })
        .collect()
}

/// Record canonical-model data that has no CycloneDX 1.7 home, for the report.
fn note_unmappable(sbom: &NormalizedSbom, report: &mut FidelityReport) {
    for component in sbom.components.values() {
        if !component.extensions.annotations.is_empty() {
            report.dropped("SPDX annotations");
        }
        for hash in &component.hashes {
            if let crate::model::HashAlgorithm::Other(_) = hash.algorithm {
                report.dropped("non-standard hash algorithm");
            }
        }
        if component.crypto_properties.is_some() && component.extensions.source_json.is_none() {
            // Crypto properties are deep; without preserved source JSON we can't
            // reconstruct the full cryptoProperties block from the typed model.
            report.dropped("cryptoProperties (no preserved source)");
        }
    }
    if matches!(sbom.document.format, crate::model::SbomFormat::Spdx)
        && sbom.document.serial_number.is_none()
    {
        // SPDX namespace becomes serialNumber only when it is a URN/UUID.
        report.synthesized("no serialNumber (SPDX namespace not URN form)");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parsers::parse_sbom_str;

    const CDX: &str = r#"{
        "bomFormat": "CycloneDX", "specVersion": "1.5", "version": 1,
        "metadata": {"component": {"type": "application", "bom-ref": "root",
                                   "name": "app", "version": "1.0.0"}},
        "components": [
            {"type": "library", "bom-ref": "lodash@4.17.21", "name": "lodash",
             "version": "4.17.21", "purl": "pkg:npm/lodash@4.17.21",
             "hashes": [{"alg": "SHA-256", "content": "abc"}],
             "licenses": [{"license": {"id": "MIT"}}]}
        ],
        "dependencies": [{"ref": "root", "dependsOn": ["lodash@4.17.21"]}]
    }"#;

    #[test]
    fn emits_valid_cyclonedx_that_reparses() {
        let sbom = parse_sbom_str(CDX).unwrap();
        let (json, _report) = emit_cyclonedx(&sbom).unwrap();
        let reparsed = parse_sbom_str(&json).expect("emitted CDX must re-parse");
        // root (primary) + lodash
        assert_eq!(reparsed.components.len(), 2);
        assert_eq!(reparsed.document.format_version, "1.7");
    }

    /// SPDX input with a resolved LicenseRef (hasExtractedLicensingInfos), an
    /// unresolved LicenseRef, and a plain SPDX id.
    const SPDX_LICENSE_REFS: &str = r#"{
        "spdxVersion": "SPDX-2.3", "dataLicense": "CC0-1.0",
        "SPDXID": "SPDXRef-DOCUMENT", "name": "license-ref-doc",
        "documentNamespace": "https://example.com/license-ref-doc",
        "creationInfo": {"created": "2024-01-01T00:00:00Z",
                         "creators": ["Tool: sbom-gen-1.0"]},
        "packages": [
            {"SPDXID": "SPDXRef-Package-a", "name": "pkg-a", "versionInfo": "1.0",
             "downloadLocation": "NOASSERTION",
             "licenseDeclared": "LicenseRef-foo", "licenseConcluded": "LicenseRef-foo"},
            {"SPDXID": "SPDXRef-Package-b", "name": "pkg-b", "versionInfo": "1.0",
             "downloadLocation": "NOASSERTION", "licenseDeclared": "LicenseRef-bar"},
            {"SPDXID": "SPDXRef-Package-c", "name": "pkg-c", "versionInfo": "1.0",
             "downloadLocation": "NOASSERTION", "licenseDeclared": "MIT"}
        ],
        "hasExtractedLicensingInfos": [
            {"licenseId": "LicenseRef-foo", "name": "Foo Proprietary License",
             "extractedText": "Proprietary terms."}
        ]
    }"#;

    /// Find the single license-choice object of the named emitted component.
    fn license_of<'a>(doc: &'a Value, name: &str) -> &'a Value {
        let comp = doc["components"]
            .as_array()
            .unwrap()
            .iter()
            .find(|c| c["name"] == name)
            .unwrap_or_else(|| panic!("component {name} not emitted"));
        &comp["licenses"][0]
    }

    #[test]
    fn license_ref_emits_resolved_name_never_id() {
        let sbom = parse_sbom_str(SPDX_LICENSE_REFS).unwrap();
        let (json, _report) = emit_cyclonedx(&sbom).unwrap();
        let doc: Value = serde_json::from_str(&json).unwrap();

        // (a) resolved LicenseRef -> name form with the resolved human name.
        assert_eq!(
            license_of(&doc, "pkg-a")["license"]["name"],
            json!("Foo Proprietary License")
        );
        // (b) unresolved LicenseRef -> name form keeping the raw ref string.
        assert_eq!(
            license_of(&doc, "pkg-b")["license"]["name"],
            json!("LicenseRef-bar")
        );
        // (c) valid SPDX id keeps the id form.
        assert_eq!(license_of(&doc, "pkg-c")["license"]["id"], json!("MIT"));

        // LicenseRef-* must never appear as a license `id` anywhere.
        fn assert_no_license_ref_id(v: &Value) {
            match v {
                Value::Object(o) => {
                    if let Some(Value::String(id)) = o.get("id") {
                        assert!(
                            !id.starts_with("LicenseRef-"),
                            "LicenseRef emitted as license id: {id}"
                        );
                    }
                    o.values().for_each(assert_no_license_ref_id);
                }
                Value::Array(a) => a.iter().for_each(assert_no_license_ref_id),
                _ => {}
            }
        }
        assert_no_license_ref_id(&doc);
    }

    #[test]
    fn person_creators_emit_metadata_authors() {
        let cdx_with_authors: &str = r#"{
            "bomFormat": "CycloneDX", "specVersion": "1.6", "version": 1,
            "metadata": {
                "authors": [{"name": "Jane Doe", "email": "jane@example.com"}],
                "manufacturer": {"name": "Acme Corp",
                                 "contact": [{"email": "sbom@acme.example"}]},
                "tools": [{"name": "gen", "version": "1.0"}]
            },
            "components": [{"type": "library", "bom-ref": "x", "name": "x",
                            "version": "1.0"}]
        }"#;
        let sbom = parse_sbom_str(cdx_with_authors).unwrap();
        let (json, _report) = emit_cyclonedx(&sbom).unwrap();
        let doc: Value = serde_json::from_str(&json).unwrap();

        // (d) Person creator with email round-trips into metadata.authors.
        assert_eq!(
            doc["metadata"]["authors"],
            json!([{ "name": "Jane Doe", "email": "jane@example.com" }])
        );
        // Organization creator round-trips into metadata.manufacturer.
        assert_eq!(
            doc["metadata"]["manufacturer"],
            json!({ "name": "Acme Corp", "contact": [{ "email": "sbom@acme.example" }] })
        );
        // Tool creators stay in metadata.tools, not authors.
        assert_eq!(doc["metadata"]["tools"], json!([{ "name": "gen 1.0" }]));
    }

    #[test]
    fn preserves_component_counts_and_edges() {
        let sbom = parse_sbom_str(CDX).unwrap();
        let (json, _report) = emit_cyclonedx(&sbom).unwrap();
        let reparsed = parse_sbom_str(&json).unwrap();
        assert_eq!(reparsed.components.len(), sbom.components.len());
        assert_eq!(reparsed.edges.len(), sbom.edges.len());
        // license + hash survive on lodash
        let lodash = reparsed
            .components
            .values()
            .find(|c| c.name == "lodash")
            .unwrap();
        assert_eq!(lodash.hashes.len(), 1);
        assert!(!lodash.licenses.declared.is_empty());
    }
}