affidavit 26.6.22

Provenance Layer — receipt assembly and certification (verify a witness against a format standard; never decide honesty).
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
//! OCEL (Object-Centric Event Logs) integration for SBOM supply-chain provenance.
//!
//! This module bridges the canonical SBOM model (see [`crate::sbom`]) with the
//! OCEL standard, projecting a Software Bill of Materials into an immutable,
//! auditable chain of operation-events and object references. It mirrors the
//! quality OCEL integration (see [`crate::quality_ocel`]) in style and doctrine:
//! it *certifies what was catalogued* — it never decides whether the SBOM is
//! truthful.
//!
//! # Object taxonomy
//!
//! Every facet of an SBOM becomes an OCEL object with a stable, typed id:
//!
//! - **`sbom-document`** — the document itself (id = serial number or address)
//! - **`sbom-component:<type.tag()>`** — each catalogued component (id = `bom_ref`)
//! - **`sbom-license:<label>`** — each distinct license label
//! - **`sbom-supplier:<name>`** — each distinct supplier
//! - **`sbom-vulnerability:<id>`** — a vulnerability (id supplied by the caller;
//!   this module never depends on the vulnerability subsystem)
//!
//! # Event taxonomy
//!
//! A fixed `&'static str` set of event types (see [`supported_event_types`]):
//!
//! - `sbom:import` — a document was imported / normalized
//! - `sbom:generate` — a document was generated by a tool
//! - `sbom:component-catalogued` — a component entered the catalogue
//! - `sbom:dependency-resolved` — a dependency edge was resolved
//! - `sbom:license-detected` — a license was attached to a component
//! - `sbom:supplier-attested` — a supplier was attested for a component
//! - `sbom:attest` — the document was attested as a whole
//!
//! Each event commits to a small canonical JSON payload via
//! [`crate::ocel::build_event`], so a verifier can check the commitment without
//! ever seeing the payload bytes.
//!
//! # Determinism
//!
//! The event stream relies on the already-canonical ordering of
//! [`Sbom::components`](crate::sbom::Sbom) and
//! [`Sbom::dependencies`](crate::sbom::Sbom). Nothing here reads the wall clock
//! or sorts by time, so a fixed SBOM always yields the same ordered stream and
//! the same BLAKE3 commitments.

use crate::ocel::{build_event, object_ref, qualified_object_ref, SeqCounter};
use crate::sbom::{Component, Sbom};
use crate::types::OperationEvent;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;

/// Errors raised while projecting an SBOM into an OCEL event stream.
#[derive(Debug, thiserror::Error)]
pub enum SbomOcelError {
    /// The SBOM carried no components, so there is nothing to catalogue.
    #[error("sbom document is empty: no components to project")]
    EmptyDocument,

    /// A `bom_ref` was referenced (e.g. as a causal root) but not catalogued.
    #[error("unknown component: {0}")]
    UnknownComponent(String),

    /// An underlying OCEL event could not be built or validated.
    #[error(transparent)]
    Ocel(#[from] crate::error::OcelError),
}

// ---------------------------------------------------------------------------
// Event-type taxonomy
// ---------------------------------------------------------------------------

/// Event type: a source document was imported and normalized.
pub const EVENT_IMPORT: &str = "sbom:import";
/// Event type: a document was generated by a tool.
pub const EVENT_GENERATE: &str = "sbom:generate";
/// Event type: a component was catalogued.
pub const EVENT_COMPONENT_CATALOGUED: &str = "sbom:component-catalogued";
/// Event type: a dependency edge was resolved.
pub const EVENT_DEPENDENCY_RESOLVED: &str = "sbom:dependency-resolved";
/// Event type: a license was detected on a component.
pub const EVENT_LICENSE_DETECTED: &str = "sbom:license-detected";
/// Event type: a supplier was attested for a component.
pub const EVENT_SUPPLIER_ATTESTED: &str = "sbom:supplier-attested";
/// Event type: the whole document was attested.
pub const EVENT_ATTEST: &str = "sbom:attest";

/// The canonical, ordered list of supported SBOM OCEL event-type strings.
///
/// The order here is the documented taxonomy order, not an execution order.
pub fn supported_event_types() -> &'static [&'static str] {
    &[
        EVENT_IMPORT,
        EVENT_GENERATE,
        EVENT_COMPONENT_CATALOGUED,
        EVENT_DEPENDENCY_RESOLVED,
        EVENT_LICENSE_DETECTED,
        EVENT_SUPPLIER_ATTESTED,
        EVENT_ATTEST,
    ]
}

// ---------------------------------------------------------------------------
// Object-type helpers
// ---------------------------------------------------------------------------

/// The OCEL object type for a component, e.g. `sbom-component:library`.
pub fn component_object_type(component: &Component) -> String {
    format!("sbom-component:{}", component.component_type.tag())
}

/// The OCEL object type for a license label, e.g. `sbom-license:MIT`.
pub fn license_object_type(label: &str) -> String {
    format!("sbom-license:{label}")
}

/// The OCEL object type for a supplier, e.g. `sbom-supplier:serde-rs`.
pub fn supplier_object_type(name: &str) -> String {
    format!("sbom-supplier:{name}")
}

/// The OCEL object type for a vulnerability id, e.g.
/// `sbom-vulnerability:CVE-2024-0001`. The id is supplied by the caller; this
/// module does not depend on any vulnerability subsystem.
pub fn vulnerability_object_type(id: &str) -> String {
    format!("sbom-vulnerability:{id}")
}

/// The OCEL object type for the SBOM document itself.
pub const OBJECT_DOCUMENT: &str = "sbom-document";

// ---------------------------------------------------------------------------
// Event wrapper
// ---------------------------------------------------------------------------

/// An SBOM-specific OCEL event extending the base [`OperationEvent`].
///
/// Wraps an [`OperationEvent`] with the SBOM event category and the canonical
/// JSON payload the event committed to. Mirrors `OcelQualityEvent`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomOcelEvent {
    /// Base OCEL operation event (carries id, seq, objects, commitment).
    pub event: OperationEvent,

    /// SBOM event category (one of [`supported_event_types`]).
    pub sbom_event_type: String,

    /// The canonical JSON payload this event committed to.
    pub payload: serde_json::Value,
}

impl SbomOcelEvent {
    /// Build an SBOM OCEL event, committing to the canonical bytes of `payload`.
    ///
    /// The payload is serialized deterministically (serde_json preserves the
    /// insertion order of the `json!` macro, and all keys here are fixed), so
    /// the resulting commitment is stable across runs.
    fn build(
        sbom_event_type: &str,
        objects: Vec<crate::types::ObjectRef>,
        payload: serde_json::Value,
        counter: &mut SeqCounter,
    ) -> Result<Self, SbomOcelError> {
        let payload_bytes = serde_json::to_vec(&payload).unwrap_or_default();
        let event = build_event(sbom_event_type, objects, &payload_bytes, counter)?;
        Ok(SbomOcelEvent {
            event,
            sbom_event_type: sbom_event_type.to_string(),
            payload,
        })
    }
}

// ---------------------------------------------------------------------------
// Projection: SBOM -> ordered OCEL event stream
// ---------------------------------------------------------------------------

/// Object references contributed by a single component: the component object,
/// each of its licenses, and its supplier (if any).
fn component_objects(component: &Component) -> Vec<crate::types::ObjectRef> {
    let mut objects = vec![object_ref(
        component.bom_ref.clone(),
        component_object_type(component),
    )];
    for license in &component.licenses {
        let label = license.label();
        objects.push(qualified_object_ref(
            label.clone(),
            license_object_type(&label),
            "licensed-under",
        ));
    }
    if let Some(supplier) = &component.supplier {
        objects.push(qualified_object_ref(
            supplier.name.clone(),
            supplier_object_type(&supplier.name),
            "supplied-by",
        ));
    }
    objects
}

/// Project a canonical SBOM into a deterministic, ordered OCEL event stream.
///
/// The stream is, in order:
///
/// 1. One `sbom:import` document event whose objects are the `sbom-document`
///    plus the primary component (if one is declared and catalogued).
/// 2. One `sbom:component-catalogued` event per component, in the SBOM's
///    already-canonical component order. Its objects are the component, each of
///    its licenses, and its supplier.
/// 3. One `sbom:dependency-resolved` event per dependency edge, in the SBOM's
///    already-canonical dependency order. Its objects are the dependent plus
///    each `depends_on` target as a qualified ref with qualifier `depends-on`.
///
/// # Errors
///
/// Returns [`SbomOcelError::EmptyDocument`] if the SBOM has no components.
pub fn sbom_to_ocel_events(
    sbom: &Sbom,
    counter: &mut SeqCounter,
) -> Result<Vec<SbomOcelEvent>, SbomOcelError> {
    if sbom.components.is_empty() {
        return Err(SbomOcelError::EmptyDocument);
    }

    let mut events = Vec::new();
    let document_id = sbom
        .serial_number
        .clone()
        .unwrap_or_else(|| sbom.content_address().as_hex().to_string());

    // 1. Import document event.
    let mut import_objects = vec![object_ref(document_id.clone(), OBJECT_DOCUMENT)];
    if let Some(primary_ref) = &sbom.metadata.primary_component {
        if let Some(primary) = sbom.component(primary_ref) {
            import_objects.push(qualified_object_ref(
                primary.bom_ref.clone(),
                component_object_type(primary),
                "primary-component",
            ));
        }
    }
    let import_payload = serde_json::json!({
        "document_id": document_id,
        "format": sbom.format.tag(),
        "family": sbom.format.family(),
        "spec_version": sbom.spec_version,
        "version": sbom.version,
        "component_count": sbom.components.len(),
        "dependency_count": sbom.dependencies.len(),
    });
    events.push(SbomOcelEvent::build(
        EVENT_IMPORT,
        import_objects,
        import_payload,
        counter,
    )?);

    // 2. One component-catalogued event per component.
    for component in &sbom.components {
        let payload = serde_json::json!({
            "bom_ref": component.bom_ref,
            "name": component.name,
            "version": component.version,
            "component_type": component.component_type.tag(),
            "purl": component.purl,
            "cpe": component.cpe,
            "has_unique_identifier": component.has_unique_identifier(),
            "license_labels": component
                .licenses
                .iter()
                .map(|l| l.label())
                .collect::<Vec<_>>(),
        });
        events.push(SbomOcelEvent::build(
            EVENT_COMPONENT_CATALOGUED,
            component_objects(component),
            payload,
            counter,
        )?);
    }

    // 3. One dependency-resolved event per dependency edge.
    for dependency in &sbom.dependencies {
        let mut objects = vec![object_ref(
            dependency.dependent.clone(),
            dependent_object_type(sbom, &dependency.dependent),
        )];
        for target in &dependency.depends_on {
            objects.push(qualified_object_ref(
                target.clone(),
                dependent_object_type(sbom, target),
                "depends-on",
            ));
        }
        let payload = serde_json::json!({
            "dependent": dependency.dependent,
            "depends_on": dependency.depends_on,
            "edge_count": dependency.depends_on.len(),
        });
        events.push(SbomOcelEvent::build(
            EVENT_DEPENDENCY_RESOLVED,
            objects,
            payload,
            counter,
        )?);
    }

    Ok(events)
}

/// Resolve the object type for a `bom_ref` appearing in a dependency edge.
///
/// Catalogued components get their precise `sbom-component:<type>` tag; a
/// `bom_ref` not present in the catalogue falls back to the generic
/// `sbom-component:library` tag so the ref still carries a valid, non-empty
/// object type.
fn dependent_object_type(sbom: &Sbom, bom_ref: &str) -> String {
    sbom.component(bom_ref)
        .map(component_object_type)
        .unwrap_or_else(|| "sbom-component:library".to_string())
}

// ---------------------------------------------------------------------------
// Causal chain
// ---------------------------------------------------------------------------

/// A causal chain linking the import event through the root component's
/// catalogue event to every dependency event reachable from the root.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SbomCausalChain {
    /// Event id of the `sbom:import` document event.
    pub document_event_id: String,

    /// Event id of the `sbom:component-catalogued` event for the root component.
    pub component_event_id: String,

    /// Event ids of the dependency events reachable from the root component.
    pub dependency_event_ids: Vec<String>,

    /// The root component's `bom_ref`.
    pub root_component: String,

    /// Count of transitive components reachable from the root.
    pub transitive_component_count: usize,
}

/// Build a causal chain from the import event through the root component's
/// catalogue event to every dependency event reachable from the root.
///
/// Reachability uses [`Sbom::transitive_dependencies`], so a dependency event
/// is included if its `dependent` is the root or any transitively reachable
/// component.
///
/// # Errors
///
/// - [`SbomOcelError::EmptyDocument`] if there is no import event.
/// - [`SbomOcelError::UnknownComponent`] if `root_bom_ref` is not catalogued or
///   has no catalogue event in `events`.
pub fn build_sbom_causal_chain(
    events: &[SbomOcelEvent],
    sbom: &Sbom,
    root_bom_ref: &str,
) -> Result<SbomCausalChain, SbomOcelError> {
    if sbom.component(root_bom_ref).is_none() {
        return Err(SbomOcelError::UnknownComponent(root_bom_ref.to_string()));
    }

    let document_event = events
        .iter()
        .find(|e| e.sbom_event_type == EVENT_IMPORT)
        .ok_or(SbomOcelError::EmptyDocument)?;

    // Locate the catalogue event whose primary component object is the root.
    let component_event = events
        .iter()
        .find(|e| {
            e.sbom_event_type == EVENT_COMPONENT_CATALOGUED
                && e.event
                    .objects
                    .first()
                    .is_some_and(|o| o.id == root_bom_ref)
        })
        .ok_or_else(|| SbomOcelError::UnknownComponent(root_bom_ref.to_string()))?;

    // The set of components in scope: the root plus its transitive deps.
    let transitive = sbom.transitive_dependencies(root_bom_ref);
    let mut in_scope: BTreeMap<String, ()> = BTreeMap::new();
    in_scope.insert(root_bom_ref.to_string(), ());
    for t in &transitive {
        in_scope.insert(t.clone(), ());
    }

    let dependency_event_ids = events
        .iter()
        .filter(|e| e.sbom_event_type == EVENT_DEPENDENCY_RESOLVED)
        .filter(|e| {
            e.payload
                .get("dependent")
                .and_then(|v| v.as_str())
                .is_some_and(|d| in_scope.contains_key(d))
        })
        .map(|e| e.event.id.clone())
        .collect();

    Ok(SbomCausalChain {
        document_event_id: document_event.event.id.clone(),
        component_event_id: component_event.event.id.clone(),
        dependency_event_ids,
        root_component: root_bom_ref.to_string(),
        transitive_component_count: transitive.len(),
    })
}

// ---------------------------------------------------------------------------
// Correlation
// ---------------------------------------------------------------------------

/// A correlation grouping objects of one object type across events.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ObjectCorrelation {
    /// The shared object type (e.g. `sbom-license:MIT`).
    pub object_type: String,

    /// Object ids that participate in this correlation (e.g. component refs).
    pub object_ids: Vec<String>,

    /// Event ids that contributed to this correlation.
    pub event_ids: Vec<String>,
}

/// Correlate components that share a license label.
///
/// Walks the `sbom:component-catalogued` events and groups, per license object
/// type, the component refs that declare that license and the events in which
/// the correlation was observed. The result is ordered deterministically by
/// license object type.
pub fn correlate_components_by_license(
    events: &[SbomOcelEvent],
    sbom: &Sbom,
) -> Vec<ObjectCorrelation> {
    // bom_ref -> the component's first object id (which is the bom_ref).
    let mut by_type: BTreeMap<String, ObjectCorrelation> = BTreeMap::new();

    for event in events
        .iter()
        .filter(|e| e.sbom_event_type == EVENT_COMPONENT_CATALOGUED)
    {
        // The first object of a catalogue event is always the component.
        let component_ref = match event.event.objects.first() {
            Some(o) => o.id.clone(),
            None => continue,
        };
        let component = match sbom.component(&component_ref) {
            Some(c) => c,
            None => continue,
        };
        for license in &component.licenses {
            let object_type = license_object_type(&license.label());
            let entry = by_type
                .entry(object_type.clone())
                .or_insert_with(|| ObjectCorrelation {
                    object_type,
                    object_ids: Vec::new(),
                    event_ids: Vec::new(),
                });
            if !entry.object_ids.contains(&component_ref) {
                entry.object_ids.push(component_ref.clone());
            }
            if !entry.event_ids.contains(&event.event.id) {
                entry.event_ids.push(event.event.id.clone());
            }
        }
    }

    by_type.into_values().collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sbom::{Dependency, License, SbomFormat, Supplier};

    /// Build a small but rich SBOM: app -> serde -> log, with licenses and a
    /// supplier on each library, and `app` as the primary component.
    fn sample_sbom() -> Sbom {
        let mut sbom = Sbom::new(SbomFormat::CycloneDx16, "1.6");
        sbom.serial_number = Some("urn:uuid:test".to_string());
        sbom.metadata.primary_component = Some("app".to_string());
        sbom.metadata.author = Some("Build Bot".to_string());
        sbom.metadata.timestamp = 1_700_000_000;

        let mut app = Component::library("app", "app", "1.0");
        app.licenses.push(License::id("Apache-2.0"));

        let mut serde_c = Component::library("serde", "serde", "1.0.0");
        serde_c.purl = Some("pkg:cargo/serde@1.0.0".to_string());
        serde_c.licenses.push(License::id("MIT"));
        serde_c.supplier = Some(Supplier {
            name: "serde-rs".to_string(),
            url: None,
            contact: None,
        });

        let mut log_c = Component::library("log", "log", "0.4.0");
        log_c.purl = Some("pkg:cargo/log@0.4.0".to_string());
        log_c.licenses.push(License::id("MIT"));
        log_c.supplier = Some(Supplier {
            name: "rust-lang".to_string(),
            url: None,
            contact: None,
        });

        sbom.components.push(app);
        sbom.components.push(serde_c);
        sbom.components.push(log_c);

        sbom.dependencies.push(Dependency {
            dependent: "app".to_string(),
            depends_on: vec!["serde".to_string()],
        });
        sbom.dependencies.push(Dependency {
            dependent: "serde".to_string(),
            depends_on: vec!["log".to_string()],
        });

        sbom.canonicalize();
        sbom
    }

    #[test]
    fn supported_event_types_is_non_empty_and_well_formed() {
        let types = supported_event_types();
        assert!(!types.is_empty());
        assert_eq!(types.len(), 7);
        assert!(types.iter().all(|t| t.starts_with("sbom:")));
        assert!(types.contains(&EVENT_IMPORT));
        assert!(types.contains(&EVENT_ATTEST));
    }

    #[test]
    fn projection_event_count_matches_taxonomy() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();
        // 1 import + 3 components + 2 dependencies = 6.
        assert_eq!(events.len(), 6);
    }

    #[test]
    fn projection_event_ordering_is_deterministic() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        assert_eq!(events[0].sbom_event_type, EVENT_IMPORT);
        // After canonicalize, components sort by bom_ref: app, log, serde.
        assert_eq!(events[1].sbom_event_type, EVENT_COMPONENT_CATALOGUED);
        assert_eq!(events[2].sbom_event_type, EVENT_COMPONENT_CATALOGUED);
        assert_eq!(events[3].sbom_event_type, EVENT_COMPONENT_CATALOGUED);
        assert_eq!(events[4].sbom_event_type, EVENT_DEPENDENCY_RESOLVED);
        assert_eq!(events[5].sbom_event_type, EVENT_DEPENDENCY_RESOLVED);

        // seq values are monotonic from 0.
        for (i, e) in events.iter().enumerate() {
            assert_eq!(e.event.seq, i as u64);
        }
    }

    #[test]
    fn import_event_references_document_and_primary() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();
        let import = &events[0];

        let doc = &import.event.objects[0];
        assert_eq!(doc.obj_type, OBJECT_DOCUMENT);
        assert_eq!(doc.id, "urn:uuid:test");

        let primary = &import.event.objects[1];
        assert_eq!(primary.id, "app");
        assert_eq!(primary.qualifier.as_deref(), Some("primary-component"));
        assert_eq!(primary.obj_type, "sbom-component:library");
    }

    #[test]
    fn component_object_carries_typed_tag() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let catalogue: Vec<&SbomOcelEvent> = events
            .iter()
            .filter(|e| e.sbom_event_type == EVENT_COMPONENT_CATALOGUED)
            .collect();
        for e in catalogue {
            let comp = &e.event.objects[0];
            assert_eq!(comp.obj_type, "sbom-component:library");
        }
    }

    #[test]
    fn catalogue_event_includes_license_and_supplier_objects() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        // Find the serde catalogue event.
        let serde_evt = events
            .iter()
            .find(|e| {
                e.sbom_event_type == EVENT_COMPONENT_CATALOGUED && e.event.objects[0].id == "serde"
            })
            .unwrap();

        // component + 1 license + 1 supplier = 3.
        assert_eq!(serde_evt.event.objects.len(), 3);
        assert!(serde_evt
            .event
            .objects
            .iter()
            .any(|o| o.obj_type == "sbom-license:MIT"));
        assert!(serde_evt
            .event
            .objects
            .iter()
            .any(|o| o.obj_type == "sbom-supplier:serde-rs"));
    }

    #[test]
    fn dependency_event_uses_depends_on_qualifier() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let dep = events
            .iter()
            .find(|e| {
                e.sbom_event_type == EVENT_DEPENDENCY_RESOLVED && e.event.objects[0].id == "app"
            })
            .unwrap();

        assert_eq!(dep.event.objects[0].qualifier, None);
        assert_eq!(dep.event.objects[1].id, "serde");
        assert_eq!(
            dep.event.objects[1].qualifier.as_deref(),
            Some("depends-on")
        );
    }

    #[test]
    fn empty_document_is_rejected() {
        let sbom = Sbom::new(SbomFormat::Spdx23, "2.3");
        let mut counter = SeqCounter::new();
        let result = sbom_to_ocel_events(&sbom, &mut counter);
        assert!(matches!(result, Err(SbomOcelError::EmptyDocument)));
    }

    #[test]
    fn commitments_are_deterministic_across_runs() {
        let sbom = sample_sbom();
        let mut c1 = SeqCounter::new();
        let mut c2 = SeqCounter::new();
        let e1 = sbom_to_ocel_events(&sbom, &mut c1).unwrap();
        let e2 = sbom_to_ocel_events(&sbom, &mut c2).unwrap();

        assert_eq!(e1.len(), e2.len());
        for (a, b) in e1.iter().zip(e2.iter()) {
            assert_eq!(
                a.event.payload_commitment, b.event.payload_commitment,
                "commitment must be deterministic for identical inputs"
            );
            assert_eq!(a.event.id, b.event.id);
        }
    }

    #[test]
    fn causal_chain_links_document_component_and_deps() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let chain = build_sbom_causal_chain(&events, &sbom, "app").unwrap();
        assert_eq!(chain.document_event_id, events[0].event.id);
        assert_eq!(chain.root_component, "app");

        // The component event id must point at app's catalogue event.
        let app_evt = events
            .iter()
            .find(|e| {
                e.sbom_event_type == EVENT_COMPONENT_CATALOGUED && e.event.objects[0].id == "app"
            })
            .unwrap();
        assert_eq!(chain.component_event_id, app_evt.event.id);

        // Both dependency edges (app->serde, serde->log) are reachable.
        assert_eq!(chain.dependency_event_ids.len(), 2);
    }

    #[test]
    fn causal_chain_transitive_count_matches() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let chain = build_sbom_causal_chain(&events, &sbom, "app").unwrap();
        // app -> serde -> log: two transitive components.
        assert_eq!(chain.transitive_component_count, 2);

        let leaf = build_sbom_causal_chain(&events, &sbom, "log").unwrap();
        assert_eq!(leaf.transitive_component_count, 0);
        assert_eq!(leaf.dependency_event_ids.len(), 0);
    }

    #[test]
    fn causal_chain_rejects_unknown_root() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let result = build_sbom_causal_chain(&events, &sbom, "does-not-exist");
        assert!(matches!(result, Err(SbomOcelError::UnknownComponent(_))));
    }

    #[test]
    fn license_correlation_groups_shared_licenses() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let correlations = correlate_components_by_license(&events, &sbom);

        // Apache-2.0 (app) and MIT (serde, log).
        let mit = correlations
            .iter()
            .find(|c| c.object_type == "sbom-license:MIT")
            .unwrap();
        assert_eq!(mit.object_ids.len(), 2);
        assert!(mit.object_ids.contains(&"serde".to_string()));
        assert!(mit.object_ids.contains(&"log".to_string()));

        let apache = correlations
            .iter()
            .find(|c| c.object_type == "sbom-license:Apache-2.0")
            .unwrap();
        assert_eq!(apache.object_ids, vec!["app".to_string()]);
    }

    #[test]
    fn license_correlation_is_deterministically_ordered() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();

        let first = correlate_components_by_license(&events, &sbom);
        let second = correlate_components_by_license(&events, &sbom);
        let types1: Vec<&str> = first.iter().map(|c| c.object_type.as_str()).collect();
        let types2: Vec<&str> = second.iter().map(|c| c.object_type.as_str()).collect();
        assert_eq!(types1, types2);
        // BTreeMap ordering: Apache-2.0 before MIT.
        assert_eq!(types1, vec!["sbom-license:Apache-2.0", "sbom-license:MIT"]);
    }

    #[test]
    fn object_type_helpers_format_tags() {
        assert_eq!(license_object_type("MIT"), "sbom-license:MIT");
        assert_eq!(supplier_object_type("acme"), "sbom-supplier:acme");
        assert_eq!(
            vulnerability_object_type("CVE-2024-0001"),
            "sbom-vulnerability:CVE-2024-0001"
        );
        let c = Component::library("x", "x", "1");
        assert_eq!(component_object_type(&c), "sbom-component:library");
    }

    #[test]
    fn import_event_commits_to_format_payload() {
        let sbom = sample_sbom();
        let mut counter = SeqCounter::new();
        let events = sbom_to_ocel_events(&sbom, &mut counter).unwrap();
        let import = &events[0];
        assert_eq!(
            import.payload.get("format").and_then(|v| v.as_str()),
            Some("cyclonedx-1.6")
        );
        assert_eq!(
            import
                .payload
                .get("component_count")
                .and_then(|v| v.as_u64()),
            Some(3)
        );
    }
}